Jump to content

User:Anne drew/TidyTools.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//<nowiki>
mw.loader.using(['mediawiki.util', 'jquery'], function () {
    'use strict';

    const targetMenus = ['p-tb'];
    const debounceDelay = 50;
    let debounceTimer;

    function sortMenu(menuId, observer) {
        const $menu = $('#' + menuId);
        const listNode = $menu.find('ul')[0];
        if (!listNode) return;

        if (observer) observer.disconnect();

        const items = Array.from(listNode.children);
        
        const itemsWithText = items.map(node => ({
            node: node,
            text: node.textContent.trim().toUpperCase()
        }));

        itemsWithText.sort((a, b) => a.text.localeCompare(b.text));

        const fragment = document.createDocumentFragment();
        itemsWithText.forEach(item => fragment.appendChild(item.node));
        
        listNode.appendChild(fragment);

        if (observer) {
            observer.observe(listNode, { childList: true });
        }
    }

    function handleMutation(mutations, observer) {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            targetMenus.forEach(menuId => sortMenu(menuId, observer));
        }, debounceDelay);
    }

    function init() {
        targetMenus.forEach(menuId => {
            const menuNode = document.getElementById(menuId);
            if (!menuNode) return;
            
            const listNode = menuNode.querySelector('ul');
            if (!listNode) return;

            sortMenu(menuId, null);

            const observer = new MutationObserver(handleMutation);
            observer.observe(listNode, { childList: true });
        });
    }

    $(init);
});
//</nowiki>