Bikarhêner:Balyozxane/sort-langheaders.js

Zanibe: Piştî weşandinê, ji bo dîtina guhartinan dibe ku hewce be "cache"ya geroka xwe paqij bikî.

  • Firefox / Safari: Pê li Shift û Reload bike an jî Ctrl-F5 an Ctrl-R bike (ji bo Mac: ⌘-R)
  • Google Chrome: Pê li Ctrl-Shift-R (ji bo Mac: ⌘-Shift-R) bike
  • Internet Explorer / Edge: Pê li Ctrl û Refresh bike, an jî Ctrl-F5 bike
  • Opera: Pê li Ctrl-F5 bike.
//<nowiki>
$(document).ready(function () {
    mw.loader.using(['jquery.ui'], function () {
        mw.util.addCSS('#t-sortcontent{ font-weight: normal; }');
        $(mw.util.addPortletLink('p-tb', '#', 'Sort-content', 't-sortcontent', 'Sort Content')).click(function () {
            handleButtonClick(); // Wrap the async function in a non-async function
        });
    });

    // Kurdish alphabet
    const kurdishAlphabet = "ABCCÇDEÊFGHIÎJKLÎMNOPQRSŞTUÛVWXYZabccçdeêfghiîjklîmnopqrsştuûvwxyzǃǀǁǂ";

    function customSort(langNameA, langNameB) {
        langNameA = langNameA.toLowerCase();
        langNameB = langNameB.toLowerCase();

        const minLength = Math.min(langNameA.length, langNameB.length);

        for (let i = 0; i < minLength; i++) {
            const indexA = kurdishAlphabet.indexOf(langNameA[i]);
            const indexB = kurdishAlphabet.indexOf(langNameB[i]);

            if (indexA < indexB) {
                return -1;
            } else if (indexA > indexB) {
                return 1;
            }
        }

        return langNameA.length - langNameB.length;
    }

    // Function to find language sections in the page content
    async function findLanguageSections() {
        const $textBox = $("#wpTextbox1");
        const content = $textBox.val();
        const sections = content.split(/(== \{\{ziman\|[a-z-]+\}\} ==)/);
        const languageSections = [];

        for (let i = 1; i < sections.length; i += 2) {
            const langMatch = sections[i].match(/\{\{ziman\|([a-z-]+)\}\}/);
            if (langMatch) {
                const lang = langMatch[1];
                if (lang.trim() !== '') { // Check if langCode is not empty
                    try {
                        const canonicalName = await fetchLanguageName(lang);
                        languageSections.push({
                            lang,
                            canonicalName,
                            content: sections[i + 1]
                        });
                    } catch (error) {
                        console.error("Error fetching language name:", error);
                        mw.notify("Error fetching language name:", error);
                        // Handle the error as needed, e.g., set a default value for canonicalName
                    }
                }
            }
        }

        console.log("Language sections:", languageSections); // Log language sections
        mw.notify("Language sections:", sections.length); // Log language sections
        return languageSections;
    }

    // Function to sort sections by language names using custom sorting
    async function sortSections(sections) {
        // Define priority languages
        const priorityLangs = ["ku", "kmr", "ckb"]; // Add more if needed

        // Sort the sections using customSort function
        sections.sort((sectionA, sectionB) => {
            if (priorityLangs.includes(sectionA.lang) || priorityLangs.includes(sectionB.lang)) {
                // Preserve relative order of priority languages
                return 0;
            }
            return customSort(sectionA.canonicalName, sectionB.canonicalName);
        });

        console.log("Sorted sections:", sections); // Log sorted sections
        mw.notify("Sorted sections"); // Log sorted sections
        return sections;
    }

    // Function to update the page content with sorted sections
    function updatePageContent(sortedSections) {
        // Reconstruct the sorted content
        const sortedContent = sortedSections.map(section => `== {{ziman|${section.lang}}} ==${section.content}`).join('');

        console.log("Updated content:", sortedContent); // Log updated content
        mw.notify("Updated content"); // Log updated content

        // Update the page content with the sorted content
        const $wpTextbox1 = $('#wpTextbox1');
        $wpTextbox1.val(sortedContent);
        
        $("#wpDiff").click();
    }

    // Function to fetch language names for langCode
    function fetchLanguageName(langCode) {
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: "https://ku.wiktionary.org/w/index.php?title=MediaWiki:Gadget-translation editor.js/ziman.json&action=raw",
                dataType: "json",
                success: function (data) {
                    if (data.hasOwnProperty(langCode)) {
                        resolve(data[langCode]);
                    } else {
                        reject("Language code not found: " + langCode);
                    }
                },
                error: function (xhr, status, error) {
                    reject(error);
                }
            });
        });
    }

    // Function to handle the "Sort-content" link click
    async function handleButtonClick() {
        mw.notify("Sort-content link clicked."); // Log button click

        // Find all language sections in the page content
        const languageSections = await findLanguageSections();

        // Sort the sections by language names, considering priority languages and using custom sorting
        const sortedSections = await sortSections(languageSections);

        // Update the page content with the sorted sections
        updatePageContent(sortedSections);
    }
});
//</nowiki>