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-sortwerger { font-weight: normal; }');
        $(mw.util.addPortletLink('p-tb', '#', 'Sort-werger', 't-sortwerger', 'Sort language codes in Werger')).click(init);
    });

    function init() {
        sortWerger();
    }

    // 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 removeDiacritics(lang, word) {
	    var api = new mw.Api();
	
	    return api.get({
	        action: 'expandtemplates',
	        format: 'json',
	        text: `{{#invoke:ziman/şablon|makeEntryName|${lang}|${word}}}`,
	        prop: 'wikitext'
	    }).then(function(data) {
	        return data.expandtemplates.wikitext;
	    });
	}

    function page_exists(lang_code, page) {
        var domain;
    	var normalizedPageTitle; // Declare it here
        var wm_liens = {
            'cmn': 'zh',
            'fra-nor': 'nrm',
            'gsw': 'als',
            'ko-Hani': 'ko',
            'lzh': 'zh-classical',
            'nan': 'zh-min-nan',
            'nb': 'no',
            'rup': 'roa-rup',
            'yue': 'zh-yue',
        };
        var wiktios = [
            'en', 'mg', 'fr', 'zh', 'lt', 'ru', 'es', 'el', 'pl', 'sv', 'ko',
            'nl', 'de', 'tr', 'ku', 'ta', 'io', 'kn', 'fi', 'vi', 'hu', 'pt',
            'chr', 'no', 'ml', 'my', 'id', 'it', 'li', 'ro', 'et', 'ja', 'te',
            'jv', 'fa', 'cs', 'ca', 'ar', 'eu', 'gl', 'lo', 'uk', 'br', 'fj',
            'eo', 'bg', 'hr', 'th', 'oc', 'is', 'vo', 'ps', 'zh-min-nan',
            'simple', 'cy', 'uz', 'scn', 'sr', 'af', 'ast', 'az', 'da', 'sw',
            'fy', 'tl', 'he', 'nn', 'wa', 'ur', 'la', 'sq', 'hy', 'sm', 'sl',
            'ka', 'pnb', 'nah', 'hi', 'tt', 'bs', 'lb', 'lv', 'tk', 'sk', 'hsb',
            'nds', 'kk', 'ky', 'be', 'km', 'mk', 'ga', 'wo', 'ms', 'ang', 'co',
            'sa', 'gn', 'mr', 'csb', 'ug', 'st', 'ia', 'sd', 'sh', 'si', 'mn',
            'tg', 'or', 'kl', 'vec', 'jbo', 'an', 'ln', 'fo', 'zu', 'gu', 'kw',
            'gv', 'rw', 'qu', 'ss', 'ie', 'mt', 'om', 'bn', 'pa', 'roa-rup',
            'iu', 'so', 'am', 'su', 'za', 'gd', 'mi', 'tpi', 'ne', 'yi', 'ti',
            'sg', 'na', 'dv', 'tn', 'ts', 'ha', 'ks', 'ay',
        ];
        var keepApos = [
            'fr', 'de',
        ];


        if (wm_liens.hasOwnProperty(lang_code)) {
            domain = wm_liens[lang_code] + '.wiktionary';
        } else if (lang_code === 'navz') {
            domain = 'species.wikimedia';
        } else if ($.inArray(lang_code, wiktios) !== -1) {
            domain = lang_code + '.wiktionary';
        }

        // Si le Wiktionnaire n'existe pas, inutile de faire une requête HTTP
        if (!domain) {
            return $.Deferred().resolve('W-').promise();
        }

        // traiter l'apostrophe typographique comme une apostrophe dactylographique
        // dans les liens interwikis, les autres wiktionnaires privilégiant la seconde
        if ($.inArray(lang_code, keepApos) === -1) {
            page = page.replace('’', "'");
            page = page.replace('ʼ', "'");
        }
        // Check if rupelaNu starts with "^" and remove it
        if (page.startsWith("^")) {
        	page = page.replace(/\^/g, '');
        }
	    // Call removeDiacritics here to remove diacritics from 'page'
	    return removeDiacritics(lang_code, page).then(function (result) {
	        if (page !== result) {
	            normalizedPageTitle = result;
	        } else {
	            normalizedPageTitle = page;
	        }
	
	        var def = $.Deferred();
	        $.ajax({
	            url: '//' + domain + '.org/w/api.php?origin=' + location.protocol + '//' + location.host,
	            data: {
	                action: 'query',
	                titles: normalizedPageTitle,
	                format: 'json'
	            },
	            dataType: 'json'
	        }).fail(function () {
	            def.resolve('W-');
	        }).then(function (data) {
	            // The page title is already normalized, so no need to normalize again.
	            // We can directly use the data to check for existence.
	            // If the AJAX request succeeds, check if the page exists in the API response.
	            // If it exists, resolve the promise with 'W+' (indicating existence).
	            // Otherwise, resolve the promise with 'W-' (indicating non-existence).
	            def.resolve(data.query.pages[-1] ? 'W-' : 'W+');
	        });
	
	        return def.promise();
	    });
	}
    function fetchLanguageNames(langCodes) {
        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) {
                    const languageNames = {};
                    for (const langCode of langCodes) {
                        if (data.hasOwnProperty(langCode)) {
                            languageNames[langCode] = data[langCode];
                        }
                    }
                    resolve(languageNames);
                },
                error: function(xhr, status, error) {
                    reject(error);
                }
            });
        });
    }

    function sortAlphabetically(content) {
        const wergerSections = extractWergerSections(content);

        if (wergerSections.length > 0) {
            const fetchPromises = wergerSections.map(wergerSection => {
                const lines = wergerSection.trim().split("\n");
                const langCodeRegex = /\{\{Z\|([a-zA-Z-]+)(\|[^\}]+)?/;
                const langSet = [];

                let currentMainLang = null;

                for (let i = 0; i < lines.length; i++) {
                    const line = lines[i];
                    const langCodeMatches = line.match(langCodeRegex);
                    if (langCodeMatches !== null) {
                        const langCode = langCodeMatches[1]?.toLowerCase() || "";
                        if (!line.startsWith("*:")) { // Lines that don't start with "*:" are normal lines
                            if (currentMainLang) {
                                langSet.push(currentMainLang);
                            }
                            currentMainLang = {
                                type: 'mainLang',
                                line,
                                langCode,
                                subsets: [],
                            };
                        } else if (currentMainLang) {
                            currentMainLang.subsets.push(line);
                        }
                    } else {
                        if (currentMainLang) {
                            currentMainLang.subsets.push(line);
                        } else {
                            langSet.push({
                                type: 'unknown', // Mark unknown lines to distinguish from subsets
                                line,
                            });
                        }
                    }
                }

                if (currentMainLang) {
                    langSet.push(currentMainLang);
                }

                return fetchLanguageNames(langSet.filter(item => item.type === 'mainLang').map(item => item.langCode)).then(function(languageNames) {
                    // Inside the sortAlphabetically function, use the customSort function
                    langSet.sort((a, b) => {
                        if (a.type === 'mainLang' && b.type === 'mainLang') {
                            const langNameA = languageNames[a.langCode] || "";
                            const langNameB = languageNames[b.langCode] || "";
                            return customSort(langNameA, langNameB);
                        } else {
                            return a.type === 'mainLang' ? -1 : 1; // Preserve the order of unknown lines and subsets
                        }
                    });
                    const sortedLines = langSet.reduce((result, item) => {
                        if (item.type === 'mainLang') {
                            result.push(item.line, ...item.subsets);
                        } else {
                            result.push(item.line);
                        }
                        return result;
                    }, []);

                    const sortedContent = "" + sortedLines.join("\n") + "";
                    content = content.replace(new RegExp(escapeRegExp(wergerSection), "g"), sortedContent); // Escape RegExp characters

                    return content;
                });
            });

            return Promise.all(fetchPromises).then(() => {
                return content;
            });
        }

        return Promise.resolve(content);
    }

    function extractWergerSections(content) {
        const wergerSections = [];
        const wergerSerRegex = /\{\{werger-ser(?:\|[^}]+)?}}/gi; // Regular expression to match {{werger-ser}} with optional arguments

        let match;
        while ((match = wergerSerRegex.exec(content)) !== null) {
            const startIndex = match.index;
            const endIndex = content.indexOf("{{werger-bin}}", startIndex);
            if (endIndex !== -1) {
                const sectionContent = content.substring(startIndex + match[0].length, endIndex).trim();
                wergerSections.push(sectionContent);
            } else {
                break;
            }
        }

        return wergerSections;
    }

    function updateWTemplateOutcome($textBox) {
        const langCodeRegex = /\{\{W(\+|-)?\|([^\|]+)\|([^\|\}]+)/g;

        let match;
        let promises = [];

        while ((match = langCodeRegex.exec($textBox.val())) !== null) {
            const fullMatch = match[0];
            const sign = match[1] || '+';
            const langCode = match[2].toLowerCase();
            const page = match[3];

            const promise = page_exists(langCode, page).then(function(outcome) {
                const newTemplate = `{{W${outcome === 'W+' ? '+' : '-'}|${langCode}|${page}`;
                $textBox.val($textBox.val().replace(fullMatch, newTemplate));
            });

            promises.push(promise);
        }

        return Promise.all(promises);
    }

    window.sortWerger = function() {
        const $textBox = $("#wpTextbox1");

        if ($textBox.length > 0 && $textBox.val().includes("{{werger-ser") && $textBox.val().includes("{{werger-bin}}")) {
            sortAlphabetically($textBox.val()).then(function(sortedContent) {
                $textBox.val(sortedContent);
                mw.notify("Hatine rêzkirin");
                return updateWTemplateOutcome($textBox); // Pass the $textBox as an argument
            }).then(function() {
                mw.notify("Sererastkirinên W-/+ çêbû.");
                mw.notify("Xilas.");
            }).catch(function(error) {
                mw.notify("Failed to fetch language names or update W templates: " + error);
            });
        } else {
            mw.notify("Required templates not found on page: " + mw.config.get("wgTitle"));
        }
    }

    function escapeRegExp(string) {
        return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    function flatten(arr) {
        return arr.reduce((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten), []);
    }
});
// </nowiki>