Karber:Balyozxane/CreateTranslation.js

Wikiqısebend ra

Note: Qeydi ra dıme, gani viriya cıgeyrayoği pak bo ke vurnayışi bıvêniyê.

  • Gışta şıma ke niya ro gocega Firefox / Safari: Shift ser, bıtıknê ra newe ra bar kerên ya zi Ctrl-F5 ya zi Ctrl-R bıtıknê (seba Mac ra ⌘-R).
  • Google Chrome: Ctrl-Shift-R ro nê. (seba Mac ra ⌘-Shift-R)
  • Internet Explorer / Edge: Ctrl ke niyo ro cı, Newe ke bıtıknê ya zi Ctrl-F5 bıkerê.
  • Opera: Ctrl-F5 bıtıknê.
//<nowiki>
function newGetLang() {
    const langNameToLangCodePromise = new mw.Api().get({
        "action": "expandtemplates",
        "format": "json",
        "text": "{{#invoke:languages/javascript-interface|AllCanonicalToCode}}",
        "prop": "wikitext"
    }).then(function(response) {
        return JSON.parse(response.expandtemplates.wikitext);
    });

    const langCodeToLangNamePromise = langNameToLangCodePromise.then(function(name2code) {
        const code2name = {};
        for (const name in name2code) {
            code2name[name2code[name]] = name;
        }
        return code2name;
    });

    function getWiktionaryCodeByCanonicalName(canonicalName) {
        return langNameToLangCodePromise.then(function(r) {
            return r[canonicalName];
        });
    }

    function getCanonicalNameByWiktionaryCode(langcode) {
        return langCodeToLangNamePromise.then(function(r) {
            return r[langcode];
        });
    }

    return {
        getWiktionaryCodeByCanonicalName,
        getCanonicalNameByWiktionaryCode
    };
}

const getLangNew = newGetLang();

const zazakiAlphabet = "ABCÇDEÊFGĞHIİJKLMNOPQRSŞTUÛVWXYZǃǀǁǂ";
    
function customSort(langNameA, langNameB) {

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

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

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

    return langNameA.length - langNameB.length;
}

function checkPageExistence(page) {
    const apiUrl = 'https://diq.wiktionary.org/w/api.php';

    const params = new URLSearchParams({
        action: 'query',
        titles: page,
        format: 'json',
        origin: '*'
    });

    return fetch(`${apiUrl}?${params}`)
        .then(response => response.json())
        .then(data => {
            const pages = data.query.pages;
            const pageId = Object.keys(pages)[0];
            return pageId !== '-1'; // If pageId is not -1, the page exists
        })
        .catch(error => {
            console.error('An error occurred:', error);
            return false;
        });
}

function editWikiPage(pageTitle, newWikicode, langCode, callback) {
    const priorityLangs = ["mul", "zza"];

    if (!pageTitle) {
        console.log("No page name provided. Editing cancelled.");
        callback("Ti ziman nehat dîtin. Guhartin betal kir.");
        return;
    }

    fetch("https://diq.wiktionary.org/w/api.php?action=query&meta=tokens&type=csrf&format=json")
        .then(response => response.json())
        .then(data => {
            const editToken = data.query.tokens.csrftoken;

            const apiUrl = "https://diq.wiktionary.org/w/api.php";
            const params = new URLSearchParams({
                action: "query",
                prop: "revisions",
                titles: pageTitle,
                rvprop: "content",
                format: "json"
            });

            fetch(apiUrl + "?" + params.toString())
                .then(response => response.json())
                .then(data => {
                    const pageId = Object.keys(data.query.pages)[0];
                    const content = data.query.pages[pageId].revisions[0]['*'];

                    const zimanCheck = "== {{zıwan|" + langCode + "}} ==";
					
					if (content.includes(zimanCheck)) {
					    callback("Di rûpelê de beşeke bi zimanê '" + langCode + "' jixwe heye.");
					    return;
					}
					
                    const sections = content.split(/(?=== \{\{zıwan\|.{2,3}\} ==)/); // Split by section headers

                    let sortedSections = [];
                    let addedTopSections = false;

                    for (let i = 0; i < sections.length; i++) {
                        const langMatch = sections[i].match(/\{\{zıwan\|(.{2,3})\}\}/);
                        if (!langMatch) {
                            sortedSections.push(sections[i]);
                            continue;
                        }
                        const lang = langMatch[1];
                        if (!addedTopSections && priorityLangs.includes(lang)) {
                            sortedSections.push({
                                lang,
                                content: sections[i]
                            });
                        } else {
                            addedTopSections = true;
                            sortedSections.push({
                                lang,
                                content: sections[i]
                            });
                        }
                    }

                    async function insertAndSort() {
                        await insertNewSection(sortedSections, newWikicode, langCode, priorityLangs);
                        const sortedContent = await sortSections(sortedSections, priorityLangs);

                        const editedContent = sortedContent.join("\n\n");
                        const rupel = mw.config.get('wgPageName').replace(/_/g, " ");
                        const summary = "[[Karber:Balyozxane/CreateTranslation.js|CreateTranslation]] from  [[" + rupel + "]]";
                        
                        const editParams = new URLSearchParams({
                            action: "edit",
                            title: pageTitle,
                            text: editedContent,
                            token: editToken,
                            summary: summary, // Add summary
                            format: "json"
                        });

                        fetch(apiUrl, {
                                method: "POST",
                                body: editParams
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.edit.result === "Success") {
                                    console.log("Guhartina rûpelê bi ser ket!");
                                    callback(null);
                                } else {
                                    console.error("Têkçûyîna guhartina rûpelê.");
                                    callback("Têkçûyîna guhartina rûpelê.");
                                }
                            })
                            .catch(error => {
                                console.error("An error occurred during editing:", error);
                                callback("Xeletiyek di guhartina rûpelê de çêbû.");
                            });
                    }

                    insertAndSort().catch(error => {
                        console.error("An error occurred during insertion:", error);
                        callback("Xeletiyek di lêzêdekirina zimanî de çêbû.");
                    });
                });
        });
}

function insertNewSection(sortedSections, newWikicode, langCode, priorityLangs) {
    // Insert the new section at the appropriate position
    let insertionIndex = sortedSections.length;

    for (let i = 0; i < sortedSections.length; i++) {
        const langMatch = sortedSections[i].content.match(/\{\{ziman\|(.{2,3})\}\}/);
        if (langMatch) {
            const lang = langMatch[1];
            if (!priorityLangs.includes(lang)) {
                insertionIndex = i;
                break;
            }
        }
    }

    sortedSections.splice(insertionIndex, 0, {
        lang: langCode,
        content: newWikicode
    });
}

async function sortSections(sortedSections, priorityLangs) {
    await Promise.all(sortedSections.map(async section => {
        const langMatch = section.content.match(/\{\{zıwan\|(.{2,3})\}\}/);
        if (langMatch) {
            const lang = langMatch[1];
            section.lang = lang; // Store the lang code in the section object
            const canonicalName = await getLangNew.getCanonicalNameByWiktionaryCode(lang);
            section.canonicalName = canonicalName;
        }
    }));

    sortedSections.sort((sectionA, sectionB) => {
        // If either section contains a priorityLang, preserve their relative order
        if (priorityLangs.includes(sectionA.lang) || priorityLangs.includes(sectionB.lang)) {
            return 0;
        }

        if (sectionA.canonicalName && sectionB.canonicalName) {
            return customSort(sectionA.canonicalName, sectionB.canonicalName);
        }
        return 0;
    });

    return sortedSections.map(section => section.content.trim());
}

function removeDiacritics(lang, word) {
    var api = new mw.Api();

    return api.get({
        action: 'expandtemplates',
        format: 'json',
        text: `{{#invoke:languages/templates|makeEntryName|${lang}|${word}}}`,
        prop: 'wikitext'
    }).then(function(data) {
        return data.expandtemplates.wikitext;
    });
}

function createNewWikicode(translation, langCode, wordtype, mane, transcription, dif, label, gender) {

    var newWikicode = "== {{zıwan|" + langCode + "}} ==\n\n";
    var capitalizedWordtype = wordtype.charAt(0).toUpperCase() + wordtype.substring(1);
    var lowerWordtype = wordtype.charAt(0).toLowerCase() + wordtype.substring(1);

    newWikicode += "=== " + capitalizedWordtype + " ===\n";
    newWikicode += "{{ser|" + langCode  + "|" + lowerWordtype ;

    if (dif && dif.length > 0)
        newWikicode += "|ser=" + dif;

    if (transcription && transcription.length > 0)
        newWikicode += "|tr=" + transcription;

if ((lowerWordtype === "name" || lowerWordtype === "nameyê xısusiyi") && (gender === "n" || gender === "m" || gender === "nt") && gender.length > 0)
        newWikicode += "|c=" + gender;

    newWikicode += "}}";
    newWikicode += "\n";


    if (label.length > 0)
        newWikicode += "# " + mane + " {{terimi|" + langCode + "|" + label + "}}\n\n";
    else
        newWikicode += "# " + mane + "\n\n";

    return newWikicode;
}

$(document).ready(function() {

    // Find all translation sections
    var translationSections = $('.translations');

    // Add a button before each translation section
    translationSections.each(function(index) {
        var translationSection = $(this);
        var buttonNumber = index + 1;

        // Add a button before the translation section
        var buttonHTML = '<button class="startProcessBtn" data-section="' + index + '">Create ' + buttonNumber + '</button>';
        translationSection.prepend(buttonHTML);
    });

    // Attach a click event handler to the button
    $(document).on('click', '.startProcessBtn', function() {
        var button = $(this);
        var sectionIndex = button.data('section');
        var translationSection = translationSections.eq(sectionIndex);

        if (button.hasClass('cancelBtn')) {
            // Revert back to the start state
            translationSection.find('.wordTypeForm').remove();
            button.removeClass('cancelBtn').text('Create');
        } else {
            // Create and show the form
            var rupelMane = mw.config.get('wgPageName').replace(/_/g, " ");
            newRupelMane = '{{g|diq|' + rupelMane + '}}';
            var formHTML = '<form class="wordTypeForm">' +
                '  <label for="wordType">Select Word Type:</label>' +
                '  <select id="wordType" name="wordType">' +
                '    <option value="name">name</option>' +
                '    <option value="nameyê xısusiyi">nameyê xısusiyi</option>' +
                '    <option value="sıfet">sıfet</option>' +
                '    <option value="zerfe">zerfe</option>' +
                '    <option value="akronim">akronim</option>' +
                '    <option value="amar">amar</option>' +
                '    <option value="artikel">artikel</option>' +
                '    <option value="balnişan">balnişan</option>' +
                '    <option value="bend">bend</option>' +
                '    <option value="bestoğ">bestoğ</option>' +
                '    <option value="cumle">cumle</option>' +
                '    <option value="çıftçekuye">çıftçekuye</option>' +
                '    <option value="herfi">herfi</option>' +
                '    <option value="kılmname">kılmname</option>' +
                '    <option value="miyanbend">miyanbend</option>' +
                '    <option value="peybend">peybend</option>' +
                '    <option value="rıçık">rıçık</option>' +
                '    <option value="sembol">sembol</option>' +
                '    <option value="vate">vate</option>' +
                '    <option value="vatenê verênan">vatenê verênan</option>' +
                '    <option value="verbend">verbend</option>' +
                '    <option value="wextqıse">wextqıse</option>' +
                '    <option value="zemir">zemir</option>' +
                '    <option value="edat">edat</option>' +
                '    <option value="nameyo pêrabeste">nameyo pêrabeste</option>' +
                '    <option value="qıse">qıse</option>' +
                '    <option value="wextqıseyo pêrabeste">wextqıseyo pêrabeste</option>' +
                '  </select>' +
                '  <label for="mane">Maneya çarnayış:</label>' +
                '  <input type="text" id="mane" name="mane" value="' + newRupelMane + '">' +
                '  <label for="label">Terimi:</label>' +
                '  <input type="text" id="label" name="label">' +
                '  <button type="submit">Submit</button>' +
                '</form>';

            translationSection.prepend(formHTML);
            button.addClass('cancelBtn').text('Betal bike');
            document.getElementById('mane').style.width = "400px";
        }
    });

    // Attach a submit event handler to the form
    $(document).on('submit', '.wordTypeForm', function(event) {
        event.preventDefault();
        var form = $(this);
        var translationSection = form.closest('.translations');
        var button = translationSection.find('.startProcessBtn');
        var wordType = form.find('#wordType').val();
        var mane = form.find('#mane').val();
        var label = form.find('#label').val(); // Get the label value

        // Show confirmation alert
        var confirmationText = "Bi rastî dixwazî rûpelê bi van agahiyan çêkî?:\n\n" +
            "Cureyê peyvê: " + wordType + "\n" +
            "Maneya wergerê: " + mane + "\n" +
            "Etîket: " + label;

        if (window.confirm(confirmationText)) {
            initiateTranslationProcess(translationSection, wordType, mane, label);

            // Hide the form after confirmation
            form.remove();
            button.removeClass('cancelBtn').text('Create');
        }
    });
    // Function to initiate the translation process
    function initiateTranslationProcess(translationSection, wordType, mane, label) {

        // Create the progress indicator element
        var progressIndicator = $('<div id="progressIndicator" style="display: none;">Creating translations... <span id="progressCount">0</span> / <span id="totalCount">0</span></div>');
        var loadingSpinner = $('<div class="loading-spinner"></div>');
        progressIndicator.prepend(loadingSpinner);

        // prepend the progress indicator to the translation section
        translationSection.prepend(progressIndicator);

        // Fetch and process translations from the specified section
        fetchAndProcessTranslations(translationSection, wordType, mane, label);

    }

    function fetchAndProcessTranslations(translationSection, wordType, mane, label) {
        var sectionIndex = $('.translations').index(translationSection);
        var currentPageTitle = mw.config.get('wgPageName');
        var apiUrl = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php';

        $.ajax({
            url: apiUrl,
            method: 'GET',
            data: {
                action: 'query',
                format: 'json',
                prop: 'revisions',
                titles: currentPageTitle,
                rvprop: 'content'
            },
            success: function(data) {
                var pages = data.query.pages;
                var currentPage = pages[Object.keys(pages)[0]];
                var content = currentPage.revisions[0]['*'];

                var wergerPattern = /\{\{ç-ser.*?\}\}(.*?)\{\{ç-bın\}\}/gs;
                var matches;
                var currentIndex = 0;
                var newTranslation;
                var translationWithoutDiacritics;
                while ((matches = wergerPattern.exec(content)) !== null) {
                    if (currentIndex === sectionIndex) {
                        var sectionContent = matches[1];

                        var templatePattern = /\{\{ç[-+]*\|([^|]+)\|([^|}]*)?\|?(.*?)(?=\}\})\}\}/g;
                        var innerMatches;
                        var translations = [];

                        while ((innerMatches = templatePattern.exec(sectionContent)) !== null) {
                            var langCode = innerMatches[1];
                            var translation = innerMatches[2];
                            var argumentString = innerMatches[3] || '';

                            var args = argumentString.split('|');

                            var gender = null;
                            var transliteration = null;
                            var dif = null;
                            var script = null;

                            args.forEach(arg => {
                                if (arg.startsWith('tr=')) {
                                    transliteration = arg.substr(3);
                                } else if (arg.startsWith('alt=')) {
                                    dif = arg.substr(5);
                                } else if (arg.startsWith('sc=')) {
                                    script = arg.substr(3);
                                } else {
                                    gender = arg;
                                }
                            });

                            translations.push({
                                langCode: langCode,
                                translation: translation,
                                gender: gender,
                                transliteration: transliteration,
                                dif: dif,
                                script: script
                            });
                        }

                        if (translations.length > 0) {
                            console.log("Found translations:", translations);
                            var totalCount = translations.length;
                            $('#totalCount').text(totalCount);
                            $('#progressIndicator').show(); // Show the progress indicator

                            var translationsList = [];

                            translations.forEach(function(translation) {
                                // Apply removeDiacritics to the translation and check if diacritics were removed
                                removeDiacritics(translation.langCode, translation.translation).then(function(result) {
                                    if (translation.translation !== result) {
                                        // Diacritics were removed, set the dif to the translation with diacritics
                                        translation.dif = translation.translation;
                                    } else {
                                        // No diacritics were removed, set dif to null
                                        translation.dif = null;
                                    }

                                    // Add the translation to the list
                                    translationsList.push(translation);

                                    if (translationsList.length === translations.length) {
                                        // All translations are processed, start processing sequentially
                                        processTranslationsSequentially(translationsList, 0, wordType, mane, label);
                                    }
                                });
                            });
                        }

                        break;
                    }
                    currentIndex++; // Move to the next section
                }

                if (currentIndex !== sectionIndex) {
                    console.log("Beş tune ye.");
                }
            },
            error: function(xhr, status, error) {
                console.error('Error fetching page content:', error);
            }
        });
    }

    var activeTimeout = null; // Track the active timeout for notifications

    function processTranslationsSequentially(translationsList, currentIndex, wordType, mane, label) {
        if (currentIndex < translationsList.length) {
            var translation = translationsList[currentIndex];
            console.log('Creating translation page for:', translation.translation);

            var newWikicode = createNewWikicode(
                translation.translation,
                translation.langCode,
                wordType,
                mane,
                translation.transliteration,
                translation.dif, // Use translation without diacritics as page title
                label,
                translation.gender
            );

            // Display notification for page creation and waiting
            createTranslationPage(translation.translation, translation.langCode, newWikicode, function(error) {
                if (error) {
                    // Clear the active timeout before showing new notifications
                    if (activeTimeout !== null) {
                        clearTimeout(activeTimeout);
                        activeTimeout = null;
                    }

                    // Show error notification
                    mw.notify('Xeletî di çêkirina rûpelê de çêbû: ' + error, {
                        tag: 'page-creation-error'
                    });

                    // Move to the next translation immediately
                    activeTimeout = setTimeout(function() {
                        mw.notify('Derbasî wergera din dibe');
                        $('#progressCount').text(currentIndex + 1); // Update the progress count
                        processTranslationsSequentially(translationsList, currentIndex + 1, wordType, mane, label); // Move to the next translation
                    }, 100); // Wait for 0.1 seconds before moving to the next translation
                } else {
                    // Show success notification
                    mw.notify('Rûpel hat çêkirin: ' + translation.langCode + ':' +translation.translation, {
                        tag: 'page-created'
                    });

                    // Wait for 5 seconds before processing the next translation
                    activeTimeout = setTimeout(function() {
                        // Show waiting notification
                        mw.notify('Bo 5 saniye disekine');

                        $('#progressCount').text(currentIndex + 1); // Update the progress count
                        activeTimeout = setTimeout(function() {
                            // Show moving to next translation notification
                            mw.notify('Derbasî wergera din dibe');

                            processTranslationsSequentially(translationsList, currentIndex + 1, wordType, mane, label); // Move to the next translation
                        }, 5000); // Wait for 5 seconds before processing the next translation
                    }, 100); // Wait for 0.1 seconds before showing the "Waiting for 10 seconds" notification
                }
            });
        } else {
            // All translations are processed
            mw.notify('Hemû werger hatin çêkirin.', {
                tag: 'all-translations-processed'
            });
            $('#progressIndicator').hide(); // Hide the progress indicator after all translations are created
        }
    }

    function createTranslationPage(translation, langCode, newWikicode, callback) {
        var rupel = mw.config.get('wgPageName').replace(/_/g, " ");
        var summary = "[[Karber:Balyozxane/CreateTranslation.js|CreateTranslation]] from  [[" + rupel + "]]";

        // Remove diacritics from the translation
        removeDiacritics(langCode, translation).then(function(translationWithoutDiacritics) {
            var rupelaNu = translationWithoutDiacritics;

            // User-provided page name
            checkPageExistence(rupelaNu)
                .then(exists => {
                    if (exists) {

                        editWikiPage(rupelaNu, newWikicode, langCode, function(error) {
                            if (error) {
                                mw.notify("Xeletî di guhartina rûpelê de çêbû:", error);
                                callback(error); // Call the callback function with the error
                            } else {
                                mw.notify("Guhartina rûpelê bi ser ket!");
                                callback(null); // Call the callback function with no error
                            }
                        });

                    } else {

                        // Create the translation page using AJAX
                        var api = new mw.Api();
                        api.postWithToken('csrf', {
                            action: 'edit',
                            title: rupelaNu,
                            text: newWikicode,
                            summary: summary,
                            createonly: true
                        }).done(function(data) {
                            // Page saved successfully
                            console.log('Page saved successfully:', data);
                            callback(null); // Call the callback function with no error
                        }).fail(function(err) {
                            // Error occurred while saving the page
                            console.error('Error while saving the page:', err);
                            callback(err); // Call the callback function with the error
                        });
                        console.log('The page does not exist on Kurdish Wiktionary.');
                    }
                });

        });
    }

});
//</nowiki>