Jump to content

MediaWiki:Common.js

From Garmin Wiki

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.
/* Any JavaScript here will be loaded for all users on every page load. */

/* Mobile header spacing - more room after hamburger, 3 dots away from edge */
(function() {
    if (window.innerWidth <= 768) {
        var logo = document.querySelector('.mw-logo');
        var headerEnd = document.querySelector('.vector-header-end');
        if (logo) {
            logo.style.marginLeft = '12px';
        }
        if (headerEnd) {
            headerEnd.style.paddingRight = '12px';
        }
    }
})();


/* Random article image link fix - make infobox images link to article instead of file page */
(function() {
    var box = document.querySelector('.featured-article-content');
    if (box) {
        var article = box.getAttribute('data-article');
        if (article) {
            var images = box.querySelectorAll('.infobox a img');
            images.forEach(function(img) {
                var link = img.closest('a');
                if (link && link.href && link.href.indexOf('/File:') !== -1) {
                    link.href = '/' + article;
                }
            });
        }
    }
})();

/* ============================================================================
 * Explore Rail — fixed left tray with Explore/Contents toggle
 * ========================================================================== */
(function () {
    'use strict';

    if (typeof mw === 'undefined' || !mw.config) return;

    var cfg = mw.config.get([
        'wgPageName', 'wgNamespaceNumber', 'wgAction',
        'wgIsMainPage', 'wgArticleId', 'wgTitle', 'wgSiteName'
    ]);

    if (cfg.wgNamespaceNumber !== 0) return;
    if (cfg.wgIsMainPage) return;
    if (cfg.wgAction !== 'view') return;
    if (!cfg.wgArticleId) return;

    var MAX_RESULTS = 12;
    var CACHE_VER = 'v5';
    var CACHE_KEY = 'gr-related-' + CACHE_VER + '-' + cfg.wgPageName;
    var CACHE_TTL_MS = 1000 * 60 * 60 * 6;
    var SUBTITLE = (cfg.wgSiteName || 'Garmin Wiki');
    var META_CATS = /^(Pages|Articles|Stub|Stubs|Redirects|Disambiguation|Discontinued|Devices|Garmin)$/i;

    function getCached() {
        try {
            var raw = sessionStorage.getItem(CACHE_KEY);
            if (!raw) return null;
            var obj = JSON.parse(raw);
            if (!obj || !obj.ts || (Date.now() - obj.ts) > CACHE_TTL_MS) return null;
            return obj.data;
        } catch (e) { return null; }
    }
    function setCached(data) {
        try { sessionStorage.setItem(CACHE_KEY, JSON.stringify({ ts: Date.now(), data: data })); }
        catch (e) {}
    }

    var api;

    function rankCategories(cats) {
        var names = (cats || []).map(function (c) {
            return (typeof c === 'string' ? c : (c.title || '')).replace(/^Category:/, '');
        }).filter(Boolean);

        var ranked = names.map(function (name) {
            var score = 0;
            if (/series$/i.test(name)) score += 9;
            if (/releases?$/i.test(name)) score += 8;
            if (/(watches?|devices?)$/i.test(name)) score += 4;
            if (/(features|health|fitness|sensors|software|connectivity|training)/i.test(name)) score += 3;
            if (META_CATS.test(name)) score -= 15;
            return { name: name, score: score };
        }).sort(function (a, b) {
            if (b.score !== a.score) return b.score - a.score;
            return a.name.localeCompare(b.name);
        });

        return ranked.map(function (r) { return r.name; });
    }

    function seriesPageRank(title, catBareName) {
        var name = String(title || '').replace(/_/g, ' ');
        var cat = String(catBareName || '').replace(/_/g, ' ');
        var group = 1;
        if (name === cat) group = 0;
        else if (/software updates|comparison/i.test(name)) group = 2;
        var nums = name.match(/\d+/g);
        var gen = nums ? parseInt(nums[0], 10) : -1;
        var pro = /pro/i.test(name) ? 1 : 0;
        var plus = /plus/i.test(name) ? 1 : 0;
        return { group: group, gen: gen, pro: pro, plus: plus, name: name };
    }

    function compareSeriesPages(a, b, catBareName) {
        var A = seriesPageRank(a.title, catBareName);
        var B = seriesPageRank(b.title, catBareName);
        if (A.group !== B.group) return A.group - B.group;
        if (A.gen !== B.gen) return B.gen - A.gen;
        if (A.pro !== B.pro) return B.pro - A.pro;
        if (A.plus !== B.plus) return B.plus - A.plus;
        return A.name.localeCompare(B.name);
    }

    function fetchCategoryItems(catBareName) {
        if (!catBareName) return Promise.resolve([]);
        return api.get({
            action: 'query',
            generator: 'categorymembers',
            gcmtitle: 'Category:' + catBareName,
            gcmnamespace: 0,
            gcmlimit: 100,
            gcmtype: 'page',
            prop: 'pageimages|pageprops',
            piprop: 'thumbnail',
            pithumbsize: 240,
            ppprop: 'description',
            format: 'json',
            formatversion: 2
        }).then(function (res) {
            var pages = (res && res.query && res.query.pages) || [];
            var current = cfg.wgPageName.replace(/_/g, ' ');
            pages = pages.filter(function (p) {
                return p.title && p.title !== current && p.title !== cfg.wgTitle;
            });
            pages.sort(function (a, b) { return compareSeriesPages(a, b, catBareName); });
            pages = pages.slice(0, MAX_RESULTS);
            return pages.map(function (p) {
                var desc = (p.pageprops && p.pageprops.description) || '';
                if (desc.length > 90) desc = desc.slice(0, 87).replace(/\s+\S*$/, '') + '...';
                return {
                    title: p.title,
                    href: mw.util.getUrl(p.title),
                    thumb: (p.thumbnail && p.thumbnail.source) || null,
                    extract: desc
                };
            });
        });
    }

    function fetchRelated() {
        return api.get({
            action: 'query',
            prop: 'categories',
            titles: cfg.wgPageName,
            cllimit: 'max',
            clshow: '!hidden',
            format: 'json',
            formatversion: 2
        }).then(function (res) {
            var page = res && res.query && res.query.pages && res.query.pages[0];
            var cats = page && page.categories ? page.categories : [];
            if (!cats.length) return { cat: null, cats: [], items: [] };

            var rankedAll = rankCategories(cats);
            var nonMeta = rankedAll.filter(function (name) { return !META_CATS.test(name); });
            var catChoices = nonMeta.length ? nonMeta : rankedAll;
            var defaultCat = catChoices[0] || null;
            if (!defaultCat) return { cat: null, cats: [], items: [] };

            return fetchCategoryItems(defaultCat).then(function (items) {
                return {
                    cat: defaultCat,
                    cats: catChoices,
                    items: items
                };
            });
        });
    }

    function collectTocItems() {

        var content = document.getElementById('mw-content-text');
        if (!content) return [];

        var raw = content.querySelectorAll('h2, h3, .mw-heading2 > h2, .mw-heading3 > h3');
        var seen = Object.create(null);
        var out = [];

        for (var i = 0; i < raw.length; i++) {
            var h = raw[i];
            var id = h.id;
            if (!id) {
                var mh = h.querySelector && h.querySelector('.mw-headline[id]');
                id = mh && mh.id;
            }
            if (!id || seen[id]) continue;
            seen[id] = true;

            var text = (h.textContent || '').replace(/\[\s*edit\s*\]/ig, '').trim();
            if (!text) continue;
            if (/^(references|external links|see also)$/i.test(text)) {
                // keep these too; no continue
            }

            var tag = (h.tagName || '').toUpperCase();
            var level = tag === 'H3' ? 3 : 2;
            out.push({ id: id, text: text, level: level });
        }

        return out;
    }

    function escapeHtml(s) {
        return String(s).replace(/[&<>"']/g, function (c) {
            return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
        });
    }

    function buildExplorePanel(payload) {
        var wrap = document.createElement('div');
        wrap.className = 'gr-rail-panel gr-rail-panel-explore';

        var filter = document.createElement('div');
        filter.className = 'gr-rail-filter';
        filter.innerHTML =
            '<label class="gr-rail-filter-label" for="grRailCategory">Related by</label>' +
            '<select id="grRailCategory" class="gr-rail-category"></select>';
        var catSelect = filter.querySelector('.gr-rail-category');

        var list = document.createElement('div');
        list.className = 'gr-rail-list';

        var foot = document.createElement('div');
        foot.className = 'gr-rail-foot';

        wrap._setCategoryOptions = function (cats, currentCat) {
            var options = (cats && cats.length) ? cats.slice(0, 12) : (currentCat ? [currentCat] : []);
            catSelect.innerHTML = options.map(function (name) {
                var sel = name === currentCat ? ' selected' : '';
                return '<option value="' + escapeHtml(name) + '"' + sel + '>' + escapeHtml(name) + '</option>';
            }).join('');
            filter.style.display = options.length > 1 ? '' : 'none';
        };

        wrap._setItems = function (items, catName) {
            list.innerHTML = '';
            if (!items || !items.length) {
                var empty = document.createElement('div');
                empty.className = 'gr-rail-empty';
                empty.textContent = 'No related pages found for this category.';
                list.appendChild(empty);
            } else {
                items.forEach(function (item) {
                    var card = document.createElement('a');
                    card.className = 'gr-card';
                    card.href = item.href;

                    var thumbHtml = item.thumb
                        ? '<img class="gr-card-thumb" src="' + escapeHtml(item.thumb) + '" alt="" loading="lazy" />'
                        : '<span class="gr-card-thumb gr-card-thumb-ph" aria-hidden="true"></span>';

                    card.innerHTML =
                        thumbHtml +
                        '<span class="gr-card-text">' +
                            '<span class="gr-card-name">' + escapeHtml(item.title) + '</span>' +
                        '</span>';
                    list.appendChild(card);
                });
            }

            if (catName) {
                var catUrl = mw.util.getUrl('Category:' + catName);
                foot.innerHTML = '<a href="' + escapeHtml(catUrl) + '">More from ' +
                    escapeHtml(catName) + ' →</a>';
                foot.style.display = '';
            } else {
                foot.innerHTML = '';
                foot.style.display = 'none';
            }
        };

        wrap._categorySelect = catSelect;

        wrap.appendChild(filter);
        wrap.appendChild(list);
        wrap.appendChild(foot);

        wrap._setCategoryOptions(payload.cats || [], payload.cat || null);
        wrap._setItems(payload.items || [], payload.cat || null);

        return wrap;
    }

    function buildContentsPanel(items) {

        var wrap = document.createElement('div');
        wrap.className = 'gr-rail-panel gr-rail-panel-contents';

        var list = document.createElement('div');
        list.className = 'gr-rail-toc-list';

        if (!items.length) {
            var empty = document.createElement('div');
            empty.className = 'gr-rail-empty';
            empty.textContent = 'No section headings found on this page.';
            list.appendChild(empty);
        } else {
            items.forEach(function (it) {
                var a = document.createElement('a');
                a.className = 'gr-rail-toc-item ' + (it.level === 3 ? 'gr-toc-l3' : 'gr-toc-l2');
                a.href = '#' + encodeURIComponent(it.id).replace(/%3A/g, ':');
                a.setAttribute('data-target-id', it.id);
                a.textContent = it.text;
                a.addEventListener('click', function (e) {
                    var target = document.getElementById(it.id);
                    if (!target) return;
                    e.preventDefault();
                    target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    try { history.replaceState(null, '', '#' + it.id); } catch (_) {}
                });
                list.appendChild(a);
            });
        }

        wrap.appendChild(list);
        return wrap;
    }

    function buildRail(payload) {
        if (!payload || ((!payload.items || !payload.items.length) && (!payload.cats || !payload.cats.length))) return null;

        var rail = document.createElement('aside');
        rail.className = 'gr-rail';
        rail.setAttribute('role', 'complementary');
        rail.setAttribute('aria-label', 'Explore related articles');

        var currentExploreCat = payload.cat || ((payload.cats && payload.cats[0]) || null);
        var currentMode = 'explore';

        var head = document.createElement('div');
        head.className = 'gr-rail-head';
        head.innerHTML =
            '<span class="gr-rail-title">Explore</span>' +
            '<span class="gr-rail-subhead"></span>';
        rail.appendChild(head);

        var tocItems = collectTocItems();

        var modeBar = document.createElement('div');
        modeBar.className = 'gr-rail-modes';
        modeBar.innerHTML =
            '<button type="button" class="gr-rail-mode is-active" data-mode="explore">Explore</button>' +
            '<button type="button" class="gr-rail-mode" data-mode="contents">Contents</button>';
        rail.appendChild(modeBar);

        var panelExplore = buildExplorePanel(payload);
        var panelContents = buildContentsPanel(tocItems);
        panelExplore.classList.add('is-active');

        rail.appendChild(panelExplore);
        rail.appendChild(panelContents);

        var tocActiveId = null;
        var tocTicking = false;
        var tocListEl = panelContents.querySelector('.gr-rail-toc-list');

        function setActiveToc(id, keepVisible) {
            if (!id || id === tocActiveId) return;
            tocActiveId = id;
            var links = panelContents.querySelectorAll('.gr-rail-toc-item');
            for (var i = 0; i < links.length; i++) {
                var link = links[i];
                var active = link.getAttribute('data-target-id') === id;
                link.classList.toggle('is-active', active);
                if (active) {
                    link.setAttribute('aria-current', 'true');
                    if (keepVisible && tocListEl) {
                        var top = link.offsetTop;
                        var bottom = top + link.offsetHeight;
                        var viewTop = tocListEl.scrollTop + 8;
                        var viewBottom = tocListEl.scrollTop + tocListEl.clientHeight - 8;
                        if (top < viewTop || bottom > viewBottom) {
                            link.scrollIntoView({ block: 'nearest' });
                        }
                    }
                } else {
                    link.removeAttribute('aria-current');
                }
            }
        }

        function currentHeadingId() {
            if (!tocItems.length) return null;
            var railTop = parseInt((getComputedStyle(document.documentElement).getPropertyValue('--gr-rail-top') || '0'), 10) || 0;
            var threshold = Math.max(96, railTop + 18);
            var bestId = null;
            var bestTop = -Infinity;
            var firstAfterId = null;
            var firstAfterTop = Infinity;

            for (var i = 0; i < tocItems.length; i++) {
                var item = tocItems[i];
                var el = document.getElementById(item.id);
                if (!el) continue;
                var top = el.getBoundingClientRect().top;

                if (top <= threshold && top > bestTop) {
                    bestTop = top;
                    bestId = item.id;
                } else if (top > threshold && top < firstAfterTop) {
                    firstAfterTop = top;
                    firstAfterId = item.id;
                }
            }
            return bestId || firstAfterId || tocItems[0].id;
        }

        function updateActiveTocFromScroll() {
            var id = currentHeadingId();
            setActiveToc(id, true);
        }

        function queueActiveTocUpdate() {
            if (tocTicking) return;
            tocTicking = true;
            window.requestAnimationFrame(function () {
                tocTicking = false;
                updateActiveTocFromScroll();
            });
        }

        if (tocItems.length) {
            panelContents.addEventListener('click', function (e) {
                var link = e.target && e.target.closest('.gr-rail-toc-item');
                if (!link) return;
                var id = link.getAttribute('data-target-id');
                if (id) setActiveToc(id, true);
            });
            window.addEventListener('scroll', queueActiveTocUpdate, { passive: true });
            window.addEventListener('resize', queueActiveTocUpdate);
            window.addEventListener('hashchange', queueActiveTocUpdate);
            queueActiveTocUpdate();
        }

        var tab = document.createElement('button');
        tab.type = 'button';
        tab.className = 'gr-rail-tab';
        tab.setAttribute('aria-label', 'Collapse Explore');
        tab.setAttribute('aria-expanded', 'true');
        tab.innerHTML = '<span class="gr-rail-tab-arrow" aria-hidden="true"></span>';
        rail.appendChild(tab);

        function refreshHead() {
            var titleEl = head.querySelector('.gr-rail-title');
            var subEl = head.querySelector('.gr-rail-subhead');
            if (!titleEl || !subEl) return;
            if (currentMode === 'contents') {
                titleEl.textContent = 'Contents';
                subEl.textContent = cfg.wgTitle || 'This page';
            } else {
                titleEl.textContent = 'Explore';
                subEl.textContent = currentExploreCat || 'Related pages';
            }
        }

        function setMode(mode) {
            currentMode = mode;
            var explore = mode !== 'contents';
            panelExplore.classList.toggle('is-active', explore);
            panelContents.classList.toggle('is-active', !explore);

            var btns = modeBar.querySelectorAll('.gr-rail-mode');
            for (var i = 0; i < btns.length; i++) {
                var b = btns[i];
                b.classList.toggle('is-active', b.getAttribute('data-mode') === mode);
            }

            refreshHead();
            if (!explore) queueActiveTocUpdate();
            try { localStorage.setItem('gr-rail-mode', mode); } catch (e) {}
        }

        var catRequestSeq = 0;
        var catSelect = panelExplore._categorySelect;
        if (catSelect) {
            catSelect.addEventListener('change', function () {
                var selected = catSelect.value;
                if (!selected || selected === currentExploreCat) return;

                var reqId = ++catRequestSeq;
                panelExplore.classList.add('is-loading');
                catSelect.disabled = true;

                Promise.resolve(fetchCategoryItems(selected)).then(function (items) {
                    if (reqId !== catRequestSeq) return;
                    currentExploreCat = selected;
                    panelExplore._setItems(items, currentExploreCat);
                    panelExplore._setCategoryOptions(payload.cats || [], currentExploreCat);
                    refreshHead();
                }, function (err) {
                    if (reqId !== catRequestSeq) return;
                    if (window.console) console.warn('[gr-rail] category fetch failed', err);
                    var liveSelect = panelExplore._categorySelect || catSelect;
                    if (liveSelect && currentExploreCat) liveSelect.value = currentExploreCat;
                }).then(function () {
                    if (reqId !== catRequestSeq) return;
                    panelExplore.classList.remove('is-loading');
                    var liveSelect = panelExplore._categorySelect || catSelect;
                    if (liveSelect) liveSelect.disabled = false;
                });
            });
        }

        modeBar.addEventListener('click', function (e) {
            var b = e.target && e.target.closest('.gr-rail-mode');
            if (!b) return;
            var mode = b.getAttribute('data-mode');
            if (!mode) return;
            setMode(mode);
        });

        try {
            var savedMode = localStorage.getItem('gr-rail-mode');
            if (savedMode === 'contents') setMode('contents');
            else refreshHead();
        } catch (e) {
            refreshHead();
        }

        tab.addEventListener('click', function () {
            var collapsed = rail.classList.toggle('gr-rail-collapsed');
            document.documentElement.classList.toggle('gr-rail-is-collapsed', collapsed);
            tab.setAttribute('aria-expanded', collapsed ? 'false' : 'true');
            tab.setAttribute('aria-label', collapsed ? 'Expand Explore' : 'Collapse Explore');
            try { localStorage.setItem('gr-rail-collapsed', collapsed ? '1' : '0'); } catch (e) {}
        });

        try {
            if (localStorage.getItem('gr-rail-collapsed') === '1') {
                rail.classList.add('gr-rail-collapsed');
                document.documentElement.classList.add('gr-rail-is-collapsed');
                tab.setAttribute('aria-expanded', 'false');
                tab.setAttribute('aria-label', 'Expand Explore');
            }
        } catch (e) {}

        return rail;
    }



    function updateRailTop() {
        var root = document.documentElement;
        if (!root) return;

        var top = 0;
        var stickyVisible = false;
        var scrollY = Math.max(window.pageYOffset || 0, window.scrollY || 0);

        // Use actual sticky-header geometry instead of class state so the rail
        // doesn't keep a stale offset once the sticky header is out of view.
        var sticky = document.querySelector('.vector-sticky-header-container');
        if (sticky) {
            var stickyRect = sticky.getBoundingClientRect();
            if (stickyRect && stickyRect.height > 0 && stickyRect.bottom > 0 && stickyRect.top < 140) {
                top = Math.max(top, Math.round(stickyRect.bottom));
                stickyVisible = true;
            }
        }

        var header = document.querySelector('.vector-header-container');
        var headerHeight = 0;
        if (header) {
            var headerRect = header.getBoundingClientRect();
            headerHeight = Math.round(headerRect.height || header.offsetHeight || 0);
            if (!stickyVisible && headerRect.bottom > 0 && scrollY < (headerHeight + 32)) {
                top = Math.max(top, Math.round(headerRect.bottom));
            }
        }

        var page = document.querySelector('.mw-page-container');
        if (page) {
            var pageTop = Math.round(page.getBoundingClientRect().top || 0);

            if (pageTop > 0 && pageTop < 220) {
                top = Math.max(top, pageTop);
            }

            // When the article reaches the viewport top and sticky header is hidden,
            // the rail should fully dock to the top (no gray gap).
            if (pageTop <= 0 && !stickyVisible) {
                top = 0;
            }
        } else if (!stickyVisible && scrollY > (headerHeight + 32)) {
            top = 0;
        }

        root.style.setProperty('--gr-rail-top', Math.max(0, top) + 'px');
    }

    function ensureRailTopSync() {
        if (ensureRailTopSync._bound) return;
        ensureRailTopSync._bound = true;
        window.addEventListener('scroll', updateRailTop, { passive: true });
        window.addEventListener('resize', updateRailTop);
        window.addEventListener('orientationchange', updateRailTop);
    }

    function buildInline(payload) {
        if (!payload || !payload.items || !payload.items.length) return null;
        var section = document.createElement('section');
        section.className = 'gr-inline';
        section.setAttribute('aria-label', 'Explore related articles');

        var h = document.createElement('h2');
        h.className = 'gr-inline-head';
        h.textContent = 'Explore';
        section.appendChild(h);

        if (payload.cat) {
            var sub = document.createElement('div');
            sub.className = 'gr-inline-sub';
            sub.textContent = 'More from ' + payload.cat;
            section.appendChild(sub);
        }

        var grid = document.createElement('div');
        grid.className = 'gr-inline-grid';
        payload.items.slice(0, 6).forEach(function (item) {
            var card = document.createElement('a');
            card.className = 'gr-card gr-card-inline';
            card.href = item.href;
            var thumbHtml = item.thumb
                ? '<img class="gr-card-thumb" src="' + escapeHtml(item.thumb) + '" alt="" loading="lazy" />'
                : '<span class="gr-card-thumb gr-card-thumb-ph" aria-hidden="true"></span>';
            card.innerHTML =
                thumbHtml +
                '<span class="gr-card-text">' +
                    '<span class="gr-card-name">' + escapeHtml(item.title) + '</span>' +
                '</span>';
            grid.appendChild(card);
        });
        section.appendChild(grid);
        return section;
    }

    function buildMobile(payload) {
        if (!payload || ((!payload.items || !payload.items.length) && (!payload.cats || !payload.cats.length))) return null;

        var root = document.createElement('div');
        root.className = 'gr-mobile-root';

        var launcher = document.createElement('button');
        launcher.type = 'button';
        launcher.className = 'gr-mobile-launcher';
        launcher.setAttribute('aria-haspopup', 'dialog');
        launcher.setAttribute('aria-expanded', 'false');
        launcher.innerHTML = '<span class="gr-mobile-launcher-label">Explore</span>';
        root.appendChild(launcher);

        var overlay = document.createElement('div');
        overlay.className = 'gr-mobile-overlay';
        overlay.innerHTML =
            '<div class="gr-mobile-backdrop" aria-hidden="true"></div>' +
            '<aside class="gr-mobile-panel" role="dialog" aria-modal="true" aria-label="Explore related articles"></aside>';
        root.appendChild(overlay);

        var panel = overlay.querySelector('.gr-mobile-panel');
        var currentExploreCat = payload.cat || ((payload.cats && payload.cats[0]) || null);
        var currentMode = 'explore';
        var catRequestSeq = 0;
        var alive = true;
        var tocTicking = false;
        var tocActiveId = null;

        var head = document.createElement('div');
        head.className = 'gr-mobile-head';
        head.innerHTML =
            '<div class="gr-mobile-head-main">' +
                '<span class="gr-mobile-title">Explore</span>' +
                '<span class="gr-mobile-subhead"></span>' +
            '</div>' +
            '<button type="button" class="gr-mobile-close" aria-label="Close Explore">\u00d7</button>';
        panel.appendChild(head);

        var modeBar = document.createElement('div');
        modeBar.className = 'gr-rail-modes';
        modeBar.innerHTML =
            '<button type="button" class="gr-rail-mode is-active" data-mode="explore">Explore</button>' +
            '<button type="button" class="gr-rail-mode" data-mode="contents">Contents</button>';
        panel.appendChild(modeBar);

        var panelExplore = buildExplorePanel(payload);
        var tocItems = collectTocItems();
        var panelContents = buildContentsPanel(tocItems);
        panelExplore.classList.add('is-active');
        panel.appendChild(panelExplore);
        panel.appendChild(panelContents);

        var tocListEl = panelContents.querySelector('.gr-rail-toc-list');

        function refreshHead() {
            var titleEl = head.querySelector('.gr-mobile-title');
            var subEl = head.querySelector('.gr-mobile-subhead');
            if (!titleEl || !subEl) return;
            if (currentMode === 'contents') {
                titleEl.textContent = 'Contents';
                subEl.textContent = cfg.wgTitle || 'This page';
            } else {
                titleEl.textContent = 'Explore';
                subEl.textContent = currentExploreCat || 'Related pages';
            }
        }

        function setMode(mode) {
            currentMode = mode;
            var explore = mode !== 'contents';
            panelExplore.classList.toggle('is-active', explore);
            panelContents.classList.toggle('is-active', !explore);

            var btns = modeBar.querySelectorAll('.gr-rail-mode');
            for (var i = 0; i < btns.length; i++) {
                var b = btns[i];
                b.classList.toggle('is-active', b.getAttribute('data-mode') === mode);
            }

            refreshHead();
            if (!explore) queueActiveTocUpdate();
            try { localStorage.setItem('gr-mobile-mode', mode); } catch (e) {}
        }

        function setActiveToc(id, keepVisible) {
            if (!id || id === tocActiveId) return;
            tocActiveId = id;
            var links = panelContents.querySelectorAll('.gr-rail-toc-item');
            for (var i = 0; i < links.length; i++) {
                var link = links[i];
                var active = link.getAttribute('data-target-id') === id;
                link.classList.toggle('is-active', active);
                if (active) {
                    link.setAttribute('aria-current', 'true');
                    if (keepVisible && tocListEl && overlay.classList.contains('is-open')) {
                        var top = link.offsetTop;
                        var bottom = top + link.offsetHeight;
                        var viewTop = tocListEl.scrollTop + 8;
                        var viewBottom = tocListEl.scrollTop + tocListEl.clientHeight - 8;
                        if (top < viewTop || bottom > viewBottom) {
                            link.scrollIntoView({ block: 'nearest' });
                        }
                    }
                } else {
                    link.removeAttribute('aria-current');
                }
            }
        }

        function currentHeadingId() {
            if (!tocItems.length) return null;
            var panelTop = parseInt((getComputedStyle(root).getPropertyValue('--gr-mobile-panel-top') || '72'), 10) || 72;
            var threshold = panelTop + 14;
            var bestId = null;
            var bestTop = -Infinity;
            var firstAfterId = null;
            var firstAfterTop = Infinity;

            for (var i = 0; i < tocItems.length; i++) {
                var item = tocItems[i];
                var el = document.getElementById(item.id);
                if (!el) continue;
                var top = el.getBoundingClientRect().top;
                if (top <= threshold && top > bestTop) {
                    bestTop = top;
                    bestId = item.id;
                } else if (top > threshold && top < firstAfterTop) {
                    firstAfterTop = top;
                    firstAfterId = item.id;
                }
            }
            return bestId || firstAfterId || tocItems[0].id;
        }

        function updateActiveTocFromScroll() {
            var id = currentHeadingId();
            setActiveToc(id, true);
        }

        function queueActiveTocUpdate() {
            if (tocTicking || !alive) return;
            tocTicking = true;
            window.requestAnimationFrame(function () {
                tocTicking = false;
                if (!alive) return;
                updateActiveTocFromScroll();
            });
        }

        function openOverlay() {
            if (!alive) return;
            overlay.classList.add('is-open');
            launcher.setAttribute('aria-expanded', 'true');
            document.documentElement.classList.add('gr-mobile-open');
            queueActiveTocUpdate();
        }

        function closeOverlay() {
            overlay.classList.remove('is-open');
            launcher.setAttribute('aria-expanded', 'false');
            document.documentElement.classList.remove('gr-mobile-open');
        }

        function updateMobileLayout() {
            if (!alive) return;
            var minTop = 96;
            var header = document.querySelector('.vector-header-container');
            if (header) {
                var headerBottom = Math.round(header.getBoundingClientRect().bottom || 0);
                if (headerBottom > 0) minTop = Math.max(minTop, headerBottom + 14);
            }
            var vh = window.innerHeight || 800;
            var ideal = Math.round(vh * 0.48);
            var maxTop = Math.max(minTop + 24, vh - 90);
            var launcherTop = Math.min(maxTop, Math.max(minTop, ideal));
            root.style.setProperty('--gr-mobile-launcher-top', launcherTop + 'px');
            root.style.setProperty('--gr-mobile-panel-top', Math.max(58, minTop - 4) + 'px');
        }

        var catSelect = panelExplore._categorySelect;
        if (catSelect) {
            catSelect.addEventListener('change', function () {
                var selected = catSelect.value;
                if (!selected || selected === currentExploreCat) return;

                var reqId = ++catRequestSeq;
                panelExplore.classList.add('is-loading');
                catSelect.disabled = true;

                Promise.resolve(fetchCategoryItems(selected)).then(function (items) {
                    if (reqId !== catRequestSeq) return;
                    currentExploreCat = selected;
                    panelExplore._setItems(items, currentExploreCat);
                    panelExplore._setCategoryOptions(payload.cats || [], currentExploreCat);
                    refreshHead();
                }, function (err) {
                    if (reqId !== catRequestSeq) return;
                    if (window.console) console.warn('[gr-mobile] category fetch failed', err);
                    var liveSelect = panelExplore._categorySelect || catSelect;
                    if (liveSelect && currentExploreCat) liveSelect.value = currentExploreCat;
                }).then(function () {
                    if (reqId !== catRequestSeq) return;
                    panelExplore.classList.remove('is-loading');
                    var liveSelect = panelExplore._categorySelect || catSelect;
                    if (liveSelect) liveSelect.disabled = false;
                });
            });
        }

        modeBar.addEventListener('click', function (e) {
            var b = e.target && e.target.closest('.gr-rail-mode');
            if (!b) return;
            var mode = b.getAttribute('data-mode');
            if (!mode) return;
            setMode(mode);
        });

        launcher.addEventListener('click', function () {
            if (overlay.classList.contains('is-open')) closeOverlay();
            else openOverlay();
        });

        var closeBtn = head.querySelector('.gr-mobile-close');
        if (closeBtn) closeBtn.addEventListener('click', closeOverlay);

        overlay.addEventListener('click', function (e) {
            if (e.target === overlay || (e.target && e.target.classList.contains('gr-mobile-backdrop'))) {
                closeOverlay();
            }
        });

        panel.addEventListener('click', function (e) {
            var link = e.target && e.target.closest('.gr-card, .gr-rail-toc-item');
            if (link) closeOverlay();
        });

        if (tocItems.length) {
            panelContents.addEventListener('click', function (e) {
                var link = e.target && e.target.closest('.gr-rail-toc-item');
                if (!link) return;
                var id = link.getAttribute('data-target-id');
                if (id) setActiveToc(id, true);
            });
        }

        function onScroll() {
            if (!alive) return;
            updateMobileLayout();
            queueActiveTocUpdate();
        }
        function onResize() {
            if (!alive) return;
            updateMobileLayout();
            queueActiveTocUpdate();
        }
        function onHashChange() {
            if (!alive) return;
            queueActiveTocUpdate();
        }
        function onKeyDown(e) {
            if (!alive) return;
            if (e.key === 'Escape' && overlay.classList.contains('is-open')) closeOverlay();
        }

        window.addEventListener('scroll', onScroll, { passive: true });
        window.addEventListener('resize', onResize);
        window.addEventListener('orientationchange', onResize);
        window.addEventListener('hashchange', onHashChange);
        document.addEventListener('keydown', onKeyDown);

        try {
            var savedMode = localStorage.getItem('gr-mobile-mode');
            if (savedMode === 'contents') setMode('contents');
            else refreshHead();
        } catch (e) {
            refreshHead();
        }

        updateMobileLayout();
        queueActiveTocUpdate();

        root._destroy = function () {
            alive = false;
            document.documentElement.classList.remove('gr-mobile-open');
            window.removeEventListener('scroll', onScroll);
            window.removeEventListener('resize', onResize);
            window.removeEventListener('orientationchange', onResize);
            window.removeEventListener('hashchange', onHashChange);
            document.removeEventListener('keydown', onKeyDown);
        };

        return root;
    }

    function mount(payload) {
        if (!payload || ((!payload.items || !payload.items.length) && (!payload.cats || !payload.cats.length))) return;
        if (document.querySelector('.gr-rail') || document.querySelector('.gr-inline') || document.querySelector('.gr-mobile-root')) return;

        var WIDE = 1100;
        var inlineHost = document.querySelector('.mw-parser-output')
            || document.getElementById('mw-content-text')
            || document.getElementById('bodyContent');

        var current = null;
        var currentType = '';

        function clearCurrent() {
            if (!current) return;
            if (typeof current._destroy === 'function') current._destroy();
            current.remove();
            current = null;
            currentType = '';
        }

        function place() {
            var wide = window.innerWidth >= WIDE;
            if (wide) {
                if (currentType === 'desktop') return;
                clearCurrent();
                current = buildRail(payload);
                if (current) {
                    document.body.appendChild(current);
                    ensureRailTopSync();
                    updateRailTop();
                    currentType = 'desktop';
                }
                document.documentElement.classList.add('gr-has-rail');
                document.documentElement.classList.remove('gr-mobile-open');
            } else {
                if (currentType === 'mobile' || currentType === 'inline') return;
                clearCurrent();
                document.documentElement.classList.remove('gr-has-rail');
                document.documentElement.style.removeProperty('--gr-rail-top');
                current = buildMobile(payload);
                if (current) {
                    document.body.appendChild(current);
                    currentType = 'mobile';
                } else {
                    current = buildInline(payload);
                    if (current && inlineHost) {
                        inlineHost.appendChild(current);
                        currentType = 'inline';
                    }
                }
            }
        }
        place();

        var t;
        window.addEventListener('resize', function () {
            clearTimeout(t);
            t = setTimeout(place, 150);
        });
    }

    var cached = getCached();
    if (cached && cached.items && cached.items.length) {
        mount(cached);
        return;
    }

    mw.loader.using(['mediawiki.api', 'mediawiki.util']).then(function () {
        api = new mw.Api();
        fetchRelated().then(function (payload) {
            if (payload && payload.items && payload.items.length) setCached(payload);
            mount(payload);
        }).catch(function (err) {
            if (window.console) console.warn('[gr-rail] fetch failed', err);
        });
    });
})();

/* Persist the Vector color theme (day/night/os) across page loads.
   Vector remembers anonymous users' choice via cookie, but logged-in users
   were reverting to light on every refresh/navigation. This mirrors the
   effective theme into localStorage and re-applies it on each load. */
(function () {
    var KEY = 'gr-skin-theme';
    var H = document.documentElement;
    var TOKENS = ['day', 'night', 'os'];
    function currentToken() {
        for (var i = 0; i < TOKENS.length; i++) {
            if (H.classList.contains('skin-theme-clientpref-' + TOKENS[i])) return TOKENS[i];
        }
        return null;
    }
    function save() {
        try { var t = currentToken(); if (t) localStorage.setItem(KEY, t); } catch (e) {}
    }
    function applySaved() {
        try {
            var v = localStorage.getItem(KEY);
            if (!v || TOKENS.indexOf(v) < 0) return;
            if (!H.classList.contains('skin-theme-clientpref-' + v)) {
                TOKENS.forEach(function (t) { H.classList.remove('skin-theme-clientpref-' + t); });
                H.classList.add('skin-theme-clientpref-' + v);
            }
        } catch (e) {}
    }
    applySaved();
    try { if (!localStorage.getItem(KEY)) save(); } catch (e) {}
    try {
        new MutationObserver(save).observe(H, { attributes: true, attributeFilter: ['class'] });
    } catch (e) {}
})();

/* === GR-TIMELINE START (managed) === */
/* Garmin software-update timeline — self-contained renderer (no libraries).
 * Renders <div class="gr-timeline" data-platform="Fenix 7"></div> from the
 * per-platform wiki data page MediaWiki:GarminTimeline-<slug>. Maintained by the
 * bot; no WordPress involved.
 *  - Always horizontal. Year labels live in a fixed left gutter; the lanes sit
 *    in a horizontal-scroll area, so scrolling clips cleanly (no overlap).
 *  - On a narrow viewport the year does not fit, so the track opens scrolled
 *    to the latest release (earlier months are a swipe away).
 *  - Focal zoom: pinch (touch), Ctrl/Cmd + wheel (desktop) zoom about the
 *    pointer; the +/-/Fit buttons zoom about the viewport centre.
 *  - Round HTML dots; colours use MediaWiki Codex theme tokens (dark/light). */
( function () {
	'use strict';
	var MONTHS = [ 'Jan', '', 'Mar', '', 'May', '', 'Jul', '', 'Sep', '', 'Nov', '' ];
	var MON3 = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
	var cache = {};
	var tipEl = null;

	function slugify( s ) { return s.replace( /[^A-Za-z0-9]+/g, '-' ); }

	function loadPlatform( platform, node ) {
		if ( cache[ platform ] ) { return cache[ platform ]; }
		var jsonUrl = node && node.getAttribute( 'data-json' );
		var source = ( node && node.getAttribute( 'data-source' ) ) || '';
		var url;
		if ( jsonUrl || source === 'wp' ) {
			url = jsonUrl || ( ( window.grTimelineWp && window.grTimelineWp.rest ) || '' ) + encodeURIComponent( slugify( platform ) );
		} else {
			url = mw.config.get( 'wgScript' ) + '?title=' +
				encodeURIComponent( 'MediaWiki:GarminTimeline-' + slugify( platform ) ) +
				'&action=raw&ctype=application/json&maxage=0&smaxage=0';
		}
		cache[ platform ] = fetch( url, { credentials: 'same-origin', cache: 'no-cache' } ).then( function ( r ) {
			if ( !r.ok ) { throw new Error( 'timeline ' + r.status ); }
			return r.json();
		} );
		return cache[ platform ];
	}

	function parseDate( s ) {
		var d = new Date( s + 'T00:00:00' );
		return isNaN( d.getTime() ) ? null : d;
	}

	function yearFrac( d ) {
		var y = d.getFullYear();
		var start = new Date( y, 0, 1 ).getTime();
		var end = new Date( y + 1, 0, 1 ).getTime();
		return ( d.getTime() - start ) / ( end - start );
	}

	function niceDate( s ) {
		var d = parseDate( s );
		return d ? ( MON3[ d.getMonth() ] + ' ' + d.getDate() + ', ' + d.getFullYear() ) : s;
	}

	function el( tag, cls, txt ) {
		var e = document.createElement( tag );
		if ( cls ) { e.className = cls; }
		if ( txt != null ) { e.textContent = txt; }
		return e;
	}

	function kind( u ) { return u.t === 'stable' ? 'stable' : 'beta'; }
	function kindLabel( u ) {
		if ( u.t === 'stable' ) { return 'Stable'; }
		return u.t === 'alpha' ? 'Alpha' : 'Beta';
	}

	function wikiUrl( platform, anchor ) {
		var title = ( platform + ' Software Updates' ).replace( / /g, '_' );
		var url;
		if ( window.mw && mw.config && mw.config.get ) {
			var base = mw.config.get( 'wgArticlePath' ) || ( mw.config.get( 'wgScript' ) + '?title=$1' );
			url = base.replace( '$1', encodeURIComponent( title ).replace( /%2F/g, '/' ) );
		} else {
			var wikiBase = ( window.grTimelineWp && window.grTimelineWp.wikiBase ) || 'https://wiki.garminrumors.com/';
			url = wikiBase.replace( /\/?$/, '/' ) + title;
		}
		return anchor ? url + '#' + anchor : url;
	}

	/* ---- hover/focus tooltip ---- */
	function tipNode() {
		if ( !tipEl ) { tipEl = el( 'div', 'grtl-tip' ); document.body.appendChild( tipEl ); }
		return tipEl;
	}
	function showTip( anchor, u ) {
		var t = tipNode();
		t.className = 'grtl-tip grtl-' + kind( u );
		t.textContent = '';
		var row = el( 'div', 'grtl-tip-row' );
		row.appendChild( el( 'span', 'grtl-pill grtl-' + kind( u ), kindLabel( u ) ) );
		row.appendChild( el( 'span', 'grtl-tip-ver', 'v' + u.v ) );
		t.appendChild( row );
		t.appendChild( el( 'div', 'grtl-tip-date', niceDate( u.d ) ) );
		var r = anchor.getBoundingClientRect();
		t.style.left = ( r.left + r.width / 2 ) + 'px';
		t.style.top = ( r.top - 10 ) + 'px';
		t.classList.add( 'grtl-show' );
	}
	function hideTip() { if ( tipEl ) { tipEl.classList.remove( 'grtl-show' ); } }

	/* ---- details modal ---- */
	function openModal( u, platform ) {
		hideTip();
		var overlay = el( 'div', 'grtl-overlay' );
		var modal = el( 'div', 'grtl-modal grtl-' + kind( u ) );

		var head = el( 'div', 'grtl-mhead' );
		var close = el( 'button', 'grtl-close', '\u00d7' );
		close.type = 'button';
		close.setAttribute( 'aria-label', 'Close' );
		head.appendChild( close );
		var top = el( 'div', 'grtl-mtop' );
		top.appendChild( el( 'span', 'grtl-mver', 'v' + u.v ) );
		top.appendChild( el( 'span', 'grtl-pill grtl-' + kind( u ), kindLabel( u ) ) );
		head.appendChild( top );
		head.appendChild( el( 'div', 'grtl-msub', platform + ' \u00b7 ' + niceDate( u.d ) ) );
		modal.appendChild( head );

		var body = el( 'div', 'grtl-mbody' );
		if ( u.c && u.c.length ) {
			var ul = null;
			u.c.forEach( function ( line ) {
				line = ( line || '' ).trim();
				if ( !line ) { return; }
				if ( line.charAt( line.length - 1 ) === ':' ) {
					body.appendChild( el( 'div', 'grtl-sub', line ) );
					ul = null;
				} else {
					if ( !ul ) { ul = el( 'ul' ); body.appendChild( ul ); }
					ul.appendChild( el( 'li', null, line ) );
				}
			} );
		} else {
			body.appendChild( el( 'p', 'grtl-empty', 'No changelog recorded for this build.' ) );
		}
		modal.appendChild( body );

		var foot = el( 'div', 'grtl-mfoot' );
		var a = el( 'a', 'grtl-btn', 'View full release notes on the wiki' );
		a.href = wikiUrl( platform, u.w );
		foot.appendChild( a );
		modal.appendChild( foot );

		overlay.appendChild( modal );
		document.body.appendChild( overlay );

		function done() { overlay.remove(); document.removeEventListener( 'keydown', onKey ); }
		function onKey( e ) { if ( e.key === 'Escape' ) { done(); } }
		close.addEventListener( 'click', done );
		a.addEventListener( 'click', done );
		overlay.addEventListener( 'click', function ( e ) { if ( e.target === overlay ) { done(); } } );
		document.addEventListener( 'keydown', onKey );
	}

	/* ---- focal zoom ---- */
	function setupZoom( box, scroll, track, wrap, onChange ) {
		var z = 1, MIN = 1, MAX = 6;
		var minus = el( 'button', 'grtl-zbtn', '\u2212' );
		var fit = el( 'button', 'grtl-zbtn grtl-zfit', 'Fit' );
		var plus = el( 'button', 'grtl-zbtn', '+' );
		minus.type = fit.type = plus.type = 'button';
		minus.setAttribute( 'aria-label', 'Zoom out' );
		plus.setAttribute( 'aria-label', 'Zoom in' );
		fit.setAttribute( 'aria-label', 'Reset zoom' );
		wrap.appendChild( minus ); wrap.appendChild( fit ); wrap.appendChild( plus );

		function refresh() {
			fit.textContent = z <= 1.001 ? 'Fit' : ( Math.round( z * 10 ) / 10 ) + '\u00d7';
			minus.disabled = z <= MIN;
			plus.disabled = z >= MAX;
		}
		function applyAt( nz, focalX ) {
			nz = Math.min( MAX, Math.max( MIN, nz ) );
			var rect = scroll.getBoundingClientRect();
			var fx = ( focalX == null ) ? rect.left + rect.width / 2 : focalX;
			var before = track.getBoundingClientRect().width;
			var ratio = before > 0 ? ( scroll.scrollLeft + ( fx - rect.left ) ) / before : 0;
			z = Math.round( nz * 100 ) / 100;
			box.style.setProperty( '--grtl-zoom', z );
			var after = track.getBoundingClientRect().width;
			scroll.scrollLeft = ratio * after - ( fx - rect.left );
			refresh();
			if ( onChange ) { onChange(); }
		}
		minus.addEventListener( 'click', function () { applyAt( z - 0.5, null ); } );
		plus.addEventListener( 'click', function () { applyAt( z + 0.5, null ); } );
		fit.addEventListener( 'click', function () {
			applyAt( 1, null );
			if ( onChange ) { onChange( 'fit' ); }
		} );

		scroll.addEventListener( 'wheel', function ( e ) {
			if ( e.ctrlKey || e.metaKey ) {
				e.preventDefault();
				applyAt( z * ( e.deltaY < 0 ? 1.12 : 0.89 ), e.clientX );
			}
		}, { passive: false } );

		var pinch = null;
		function tdist( t ) { return Math.hypot( t[ 0 ].clientX - t[ 1 ].clientX, t[ 0 ].clientY - t[ 1 ].clientY ); }
		function tmid( t ) { return ( t[ 0 ].clientX + t[ 1 ].clientX ) / 2; }
		scroll.addEventListener( 'touchstart', function ( e ) {
			if ( e.touches.length === 2 ) { pinch = { d: tdist( e.touches ), z: z }; }
		}, { passive: true } );
		scroll.addEventListener( 'touchmove', function ( e ) {
			if ( pinch && e.touches.length === 2 ) {
				e.preventDefault();
				applyAt( pinch.z * tdist( e.touches ) / pinch.d, tmid( e.touches ) );
			}
		}, { passive: false } );
		scroll.addEventListener( 'touchend', function ( e ) { if ( e.touches.length < 2 ) { pinch = null; } } );

		refresh();
	}

	function buildLane( items, platform ) {
		var lane = el( 'div', 'grtl-lane' );
		items.forEach( function ( u ) {
			var dot = el( 'button', 'grtl-dot grtl-' + kind( u ) );
			dot.type = 'button';
			dot.style.left = ( u._frac * 100 ) + '%';
			dot.setAttribute( 'aria-label', 'v' + u.v + ' ' + kindLabel( u ) + ' ' + u.d );
			( function ( upd, d ) {
				d.addEventListener( 'mouseenter', function () { showTip( d, upd ); } );
				d.addEventListener( 'mouseleave', hideTip );
				d.addEventListener( 'focus', function () { showTip( d, upd ); } );
				d.addEventListener( 'blur', hideTip );
				d.addEventListener( 'click', function () { openModal( upd, platform ); } );
			}( u, dot ) );
			lane.appendChild( dot );
		} );
		var months = el( 'div', 'grtl-months' );
		MONTHS.forEach( function ( m, i ) {
			if ( !m ) { return; }
			var s = el( 'span', 'grtl-mlabel', m );
			s.style.left = ( ( i / 12 ) * 100 ) + '%';
			months.appendChild( s );
		} );
		lane.appendChild( months );
		return lane;
	}

	function render( node, platform, updates ) {
		node.textContent = '';
		var box = el( 'div', 'grtl-box' );

		var byYear = {};
		updates.forEach( function ( u ) {
			var d = parseDate( u.d );
			if ( !d ) { return; }
			u._frac = yearFrac( d );
			u._t = d.getTime();
			( byYear[ d.getFullYear() ] = byYear[ d.getFullYear() ] || [] ).push( u );
		} );
		var years = Object.keys( byYear ).map( Number ).sort( function ( a, b ) { return b - a; } );
		years.forEach( function ( y ) { byYear[ y ].sort( function ( a, b ) { return a._t - b._t; } ); } );

		var head = el( 'div', 'grtl-head' );
		var leg = el( 'div', 'grtl-legend' );
		var l1 = el( 'span', 'grtl-leg' );
		l1.appendChild( el( 'span', 'grtl-swatch grtl-stable' ) );
		l1.appendChild( el( 'span', null, 'Stable' ) );
		var l2 = el( 'span', 'grtl-leg' );
		l2.appendChild( el( 'span', 'grtl-swatch grtl-beta' ) );
		l2.appendChild( el( 'span', null, 'Beta' ) );
		leg.appendChild( l1 ); leg.appendChild( l2 );
		head.appendChild( leg );
		var zoomWrap = el( 'div', 'grtl-zoom' );
		head.appendChild( zoomWrap );
		box.appendChild( head );

		if ( !years.length ) {
			box.appendChild( el( 'p', 'grtl-empty', 'No dated updates for ' + platform + '.' ) );
			node.appendChild( box );
			return;
		}

		var bodyEl = el( 'div', 'grtl-body' );
		var gutter = el( 'div', 'grtl-gutter' );
		var scroll = el( 'div', 'grtl-scroll' );
		var track = el( 'div', 'grtl-track' );
		years.forEach( function ( y ) {
			gutter.appendChild( el( 'div', 'grtl-gcell', String( y ) ) );
			track.appendChild( buildLane( byYear[ y ], platform ) );
		} );
		scroll.appendChild( track );
		scroll.addEventListener( 'scroll', hideTip );
		bodyEl.appendChild( gutter );
		bodyEl.appendChild( scroll );
		box.appendChild( bodyEl );

		var foot = el( 'div', 'grtl-foot' );
		foot.appendChild( el( 'span', null, updates.length + ' updates \u00b7 ' + platform ) );
		var hint = el( 'span', 'grtl-foot-hint', '\u00b7 scroll sideways for earlier months' );
		foot.appendChild( hint );
		box.appendChild( foot );
		node.appendChild( box );

		function latestFrac() {
			var bestT = 0, frac = 1;
			years.forEach( function ( y ) {
				byYear[ y ].forEach( function ( u ) {
					if ( u._t >= bestT ) { bestT = u._t; frac = u._frac; }
				} );
			} );
			return frac;
		}
		function scrollToLatest() {
			var W = track.getBoundingClientRect().width;
			var V = scroll.clientWidth;
			if ( !( W > V + 4 ) ) { return; }
			// Put the newest release ~80% across the viewport so recent months
			// are in view; earlier months stay a swipe away.
			var target = latestFrac() * W - V * 0.8;
			scroll.scrollLeft = Math.max( 0, Math.min( W - V, target ) );
		}
		function updateHint( why ) {
			// Compare the (zoomable) track width to the viewport rather than
			// scrollWidth, which is inflated a constant ~50px by edge dots.
			var over = track.getBoundingClientRect().width > scroll.clientWidth + 4;
			hint.style.display = over ? '' : 'none';
			if ( why === 'fit' ) { scrollToLatest(); }
		}
		setupZoom( box, scroll, track, zoomWrap, updateHint );
		function afterLayout() {
			updateHint();
			scrollToLatest();
		}
		if ( window.requestAnimationFrame ) {
			requestAnimationFrame( function () { requestAnimationFrame( afterLayout ); } );
		} else { afterLayout(); }
		window.addEventListener( 'resize', updateHint );
	}

	function init( root ) {
		var nodes = ( root || document ).querySelectorAll( '.gr-timeline:not(.grtl-ready)' );
		nodes.forEach( function ( n ) {
			n.classList.add( 'grtl-ready' );
			n.textContent = 'Loading update timeline\u2026';
			var plat = n.getAttribute( 'data-platform' );
			loadPlatform( plat, n ).then( function ( arr ) {
				render( n, plat, arr || [] );
			} ).catch( function () { n.textContent = 'Timeline failed to load.'; } );
		} );
	}

	function boot() { init( document ); }
	if ( window.mw && mw.hook ) { mw.hook( 'wikipage.content' ).add( function ( $c ) { init( $c && $c[ 0 ] ); } ); }
	if ( window.jQuery ) { jQuery( boot ); } else if ( document.readyState !== 'loading' ) { boot(); } else { document.addEventListener( 'DOMContentLoaded', boot ); }
	setTimeout( boot, 400 );
}() );
/* === GR-TIMELINE END === */
/* === GR-WATCH-TIMELINE-START === */
/* List of Garmin watches: open the year table on the newest columns. */
(function () {
    if (typeof mw === 'undefined' || !mw.config) return;
    if (mw.config.get('wgPageName') !== 'List_of_Garmin_watches') return;

    function pinRight() {
        var wrap = document.getElementById('gr-watch-timeline');
        if (!wrap) {
            wrap = document.querySelector('#mw-content-text .mw-parser-output div[style*="overflow-x"]');
        }
        if (!wrap) return;
        wrap.scrollLeft = wrap.scrollWidth;
    }

    function run() {
        pinRight();
        if (window.requestAnimationFrame) {
            requestAnimationFrame(pinRight);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', run);
    } else {
        run();
    }
    window.addEventListener('load', pinRight);
    if (mw.hook) {
        mw.hook('wikipage.content').add(pinRight);
    }
}());
/* === GR-WATCH-TIMELINE-END === */
Garmin Wiki
A project by GarminRumors.com