MediaWiki:Gadget-TimelinePreview.js

From Angelina Jordan Wiki
Revision as of 18:17, 11 November 2025 by Most2dot0 (talk | contribs) (test older approch again, with increased timer for fallcack (180 ->1000ms))

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
// Gadget: Timeline hover previews (no suppression; system-popup replace + fallback custom popup)
// Requires: mediawiki.api, jquery, mediawiki.util

mw.loader.using(['mediawiki.api', 'jquery', 'mediawiki.util']).then(function () {
    var api = new mw.Api();
    var timelineCache = null;

    // Custom popup (fallback) - simple white box that won't try to hide system popups
    var customPopup = $('<div>')
        .attr('id', 'timeline-preview-fallback')
        .css({
            position: 'absolute',
            zIndex: 1100,
            background: '#fff',
            border: '1px solid #a2a9b1',
            borderRadius: '2px',
            padding: '0.75em 1em',
            boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
            maxWidth: '360px',
            display: 'none'
        })
        .appendTo(document.body);

    function loadTimeline() {
        if (timelineCache) return $.Deferred().resolve();
        return api.get({
            action: 'parse',
            page: 'Timeline',
            prop: 'text',
            formatversion: 2
        }).then(function (data) {
            var html = $('<div>').html(data.parse.text);
            timelineCache = {};
            html.find('dt').each(function () {
                var dt = $(this);
                var id = dt.find('span[id]').attr('id');
                if (!id) return;
                var ddList = [];
                var el = dt.next();
                while (el.length && el.prop('tagName') === 'DD') {
                    var clone = el.clone();
                    // strip citation superscripts
                    clone.find('sup.reference').remove();
                    // replace links with their text
                    clone.find('a').replaceWith(function () {
                        return $(this).text();
                    });
                    ddList.push(clone.html());
                    el = el.next();
                }
                timelineCache[id] = ddList.join('<br>');
            });
        });
    }

    // Heuristic: identify system popup elements when they are added
    function replaceSystemPopupContent(popupNode, html) {
        try {
            var $p = $(popupNode);
            var extract = $p.find('.mwe-popups-extract, .popups-extract, .mwe-popups-container').first();
            if (extract && extract.length) {
                extract.html(html);
            } else {
                // fallback: try replace an inner container, otherwise replace entire popup
                var inner = $p.find('*').first();
                if (inner && inner.length) inner.html(html);
                else $p.html(html);
            }
        } catch (e) {
            // ignore
        }
    }

    // Observe once for system popup nodes being added; disconnect after first match or timeout
    function watchForSystemPopupOnce(html, timeoutMs, onFound) {
        timeoutMs = timeoutMs || 1500;
        var found = false;
        var observer = new MutationObserver(function (mutations, obs) {
            for (var i = 0; i < mutations.length; i++) {
                var m = mutations[i];
                for (var j = 0; j < m.addedNodes.length; j++) {
                    var node = m.addedNodes[j];
                    if (node.nodeType !== 1) continue;
                    var cls = node.className || '';
                    if (/\bmwe-popups\b/.test(cls) || /\bpopups\b/.test(cls) || /\bpopups-container\b/.test(cls)) {
                        found = true;
                        replaceSystemPopupContent(node, html);
                        if (typeof onFound === 'function') onFound(node);
                        obs.disconnect();
                        return;
                    }
                    var $node = $(node);
                    var foundEl = $node.find('.mwe-popups, .popups, .popups-container, .mwe-popups-extract, .popups-extract').first();
                    if (foundEl && foundEl.length) {
                        found = true;
                        replaceSystemPopupContent(foundEl.get(0), html);
                        if (typeof onFound === 'function') onFound(foundEl.get(0));
                        obs.disconnect();
                        return;
                    }
                }
            }
        });
        observer.observe(document.body, { childList: true, subtree: true });
        var to = setTimeout(function () {
            if (!found) {
                try { observer.disconnect(); } catch (e) {}
            }
        }, timeoutMs);
        return {
            disconnect: function () { clearTimeout(to); try { observer.disconnect(); } catch (e) {} }
        };
    }

    function showFallbackPopup($link, html) {
        customPopup.html(html).show();
        var offset = $link.offset();
        customPopup.css({
            top: offset.top + $link.outerHeight() + 6,
            left: offset.left
        });
    }
    function hideFallbackPopup() { customPopup.hide(); }

    function onLinkEnter() {
        var $link = $(this);
        var href = $link.attr('href') || '';
        var match = href.match(/\/Timeline#(\d{4}-\d{2}-\d{2})$/) || href.match(/^#(\d{4}-\d{2}-\d{2})$/);
        if (!match) return;
        var id = match[1];

        loadTimeline().then(function () {
            var content = timelineCache && timelineCache[id];
            if (!content) return;

            // Start watching for a system popup to replace. If found, we replace it and hide the fallback.
            var handle = watchForSystemPopupOnce(content, 2000, function () {
                hideFallbackPopup();
            });

            // Fallback: show our custom popup after a short delay if no system popup yet
            var fallbackTimer = setTimeout(function () {
                // if the observer already found a popup it would have disconnected; still show unless replaced
                showFallbackPopup($link, content);
            }, 1000);

            // cleanup on leave
            $link.one('mouseleave.timelineCleanup', function () {
                clearTimeout(fallbackTimer);
                try { handle.disconnect(); } catch (e) {}
                hideFallbackPopup();
                $link.off('mouseleave.timelineCleanup');
            });
        });
    }

    function onLinkLeave() {
        hideFallbackPopup();
        // remove any one-time cleanup that may not have fired
        $(this).off('mouseleave.timelineCleanup');
    }

    var timelineLinkSelector = 'a[href*="Timeline#"], a[href^="#"]';

    function bindTimelineLinks(context) {
        $(context).find(timelineLinkSelector).each(function () {
            var $link = $(this);
            var href = $link.attr('href') || '';
            if (!(href.match(/Timeline#\d{4}-\d{2}-\d{2}$/) || href.match(/^#\d{4}-\d{2}-\d{2}$/))) return;
            if ($link.data('timeline-bound')) return;
            $link.data('timeline-bound', true);
            $link.off('.timelinePreview')
                .on('mouseenter.timelinePreview', onLinkEnter)
                .on('mouseleave.timelinePreview', onLinkLeave);
        });
    }

    // initial binding
    mw.hook('wikipage.content').add(function (context) { bindTimelineLinks(context); });

    // observe added nodes to bind links that appear later
    var mo = new MutationObserver(function (mutations) {
        for (var i = 0; i < mutations.length; i++) {
            var m = mutations[i];
            for (var j = 0; j < m.addedNodes.length; j++) {
                var node = m.addedNodes[j];
                if (node.nodeType === 1) bindTimelineLinks(node);
            }
        }
    });
    mo.observe(document.body, { childList: true, subtree: true });
});