Bikarhêner:Balyozxane/etîket-çêke.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() {

    //CSS loader
    mw.loader.addStyleTag('.help { font-size: 12px }');
    mw.loader.addStyleTag('.button { display: inline-block; text-align: center; margin-top: 10px; margin-bottom: 10px }');
    mw.loader.addStyleTag('.etiket-box { font: 12px sans-serif; margin-left: 1rem; margin: 1px; width: 100%; padding:0px; }');

    // It is important to make sure that OOUI is loaded before we can make use of it.
    mw.loader.using("oojs-ui", "mediawiki.api").done(function() {

        let etiketInput, displayInput, danasinInput, parentsInput, interwikiInput, naveDinInput;
        let inSerkategori, isHidden, umbrella;

        // Initialize form input variables
        etiketInput = new OO.ui.TextInputWidget({
            id: 'etiket',
            placeholder: 'Etîket',
            classes: ['etiket-box']
        });

        displayInput = new OO.ui.TextInputWidget({
            id: 'display',
            placeholder: '[[etîket]]',
            classes: ['etiket-box']
        });


        danasinInput = new OO.ui.TextInputWidget({
            id: 'danasin',
            placeholder: 'Danasîn',
            classes: ['etiket-box']
        });

        danasinInput.setValue('default');

        parentsInput = new OO.ui.TextInputWidget({
            id: 'parents',
            placeholder: 'Serkategorî',
            classes: ['etiket-box']
        });

        interwikiInput = new OO.ui.TextInputWidget({
            id: 'interwiki',
            placeholder: 'Înterwîkî',
            classes: ['etiket-box']
        });

        naveDinInput = new OO.ui.TextInputWidget({
            id: 'naveDin',
            placeholder: 'Navê din bo etîketê',
            classes: ['etiket-box']
        });

        inSerkategoriInput = new OO.ui.CheckboxInputWidget({
            id: 'inSerkategori',
            label: 'Li !Serkategorî ye?'
        });

        isHiddenInput = new OO.ui.CheckboxInputWidget({
            id: 'isHidden',
            label: 'Veşêre?'
        });

        umbrellaInput = new OO.ui.CheckboxInputWidget({
            id: 'umbrella',
            label: 'Li gorî zimanan çêke?',
        });

        etiketInput.on('change', function(value) {
            if (value.trim() !== '') {
                fetchExistingContentAndSearch(value).then(existingContent => {
                    if (existingContent) {

                        mw.notify('Etîketeke bi vî navî jixwe heye!', {
                            type: 'warn'
                        });

                        // Clear and reset input fields
                        resetInputs();
                    } else {
                        // Enable the submit button
                        submitButton.setDisabled(false);
                        // Copy the value to displayInput
                        danasinInput.setValue('default');
                        displayInput.setValue('[[' + value + ']]');
                    }
                });
            } else {
                // Clear and reset input fields
                resetInputs();
            }
        });


        // Create the submit button
        const submitButton = new OO.ui.ButtonInputWidget({
            label: 'Bişîne',
            classes: ["button"],
            flags: ['primary', 'progressive'],
            disabled: true // Initially disable the button
        });
        // Create the "Bigre" button
        const cancelButton = new OO.ui.ButtonInputWidget({
            label: 'Bigre',
            classes: ["button"],
            flags: ['destructive']
        });

        // Add click event to the "Bigre" button
        cancelButton.on('click', function() {
            popUp.toggle();
            resetInputs(); // Reset input fields when cancelling
        });
        // Create a FieldsetLayout for better organization
        fieldset = new OO.ui.FieldsetLayout({
            label: 'Etîket çêke',
            id: 'new-label-fieldset',
            classes: ["help"],
            items: [
                new OO.ui.FieldLayout(etiketInput, {
                    label: 'Etîket',
                    align: 'left',
                    help: 'Navê etîketa ku di şablona {{ş|f}} de tê bikaranîn. Navê kategoriyê li gorî vê etîketê tê çêkirin wekî "Etîket + bi kurdî"'
                }),
                new OO.ui.FieldLayout(displayInput, {
                    label: 'Nîşankirin',
                    align: 'left',
                    help: 'Dema şablona {{ş|f}} li rûpelê zêde kirin, li gorî formata li vir dê xuya bibe. Etîketeke wekî "Mîtolojiya kurdî" wek [[mîtolojî|mîtolojiya]] [[kurdî]] dikare were nîşankirin.'
                }),
                new OO.ui.FieldLayout(danasinInput, {
                    label: 'Danasîn',
                    align: 'left',
                    help: 'Danasîna kategoriya vê etîketê li ser rûpela kategoriyê. Dema "default" tê nivisîn, encam wekî "Peyvên {{{langname}}} têkildarî [[etîket]]ê" derdikeve. Heke dixwazin tiştek din binivîsin li cihê ku ziman were "{{{langname}}" binivîsin.'
                }),
                new OO.ui.FieldLayout(parentsInput, {
                    label: 'Serkategorî',
                    align: 'left',
                    help: 'Serkategoriyên vê kategoriyê, nimûne Kategorî:Zanist bi kurdî serkategoriya Kategorî:Biyolojî bi kurdî ye, Kategorî:Biyolojî bi kurdî jî serkategoriya Kategorî:Anatomî bi kurdî ye, ji yekî zêdetir serkategorî dikare hebe. Di navbera her serkategoriyê de vîrgulekê bi kar bînin. Wekî "biyolojî, zanist".'
                }),
                new OO.ui.FieldLayout(interwikiInput, {
                    label: 'Înterwîkî',
                    align: 'left',
                    help: 'Navê kategoriyê li ser en.wiktionaryê. Heke Kategorî:Zanist bi kurdî li en.wiktê wekî Category:kmr:Sciences hebe, vê demê li vir "sciences" binivîsin, peyva yekê hûrdek yan girdek be ferq nake.'
                }),
                new OO.ui.FieldLayout(naveDinInput, {
                    label: 'Navê din bo etîketê',
                    align: 'left',
                    help: 'Ji bo her etîketê hûn dikarin ji yekî zêdetir navên din lê zêde bikin. Nimûne, ji bo etîketa "behr", mirov dikare "derya" wekî navê din lê zêde bike. Ji yekî zêdetir navên din dikare hebin. Di navbera her navî de vîrgulekê bi kar bînin.'
                }),
                new OO.ui.FieldLayout(inSerkategoriInput, {
                    label: 'Li !Serkategorî ye?',
                    align: 'left',
                    help: 'Kategorî:!Serkategorî kategoriya sereke ya Wîkîferhengê ye. Ger ev etîket divê bikeve vê kategoriyê, pê li vê qutiyê bikin.'
                }),
                new OO.ui.FieldLayout(isHiddenInput, {
                    label: 'Veşêre?',
                    align: 'left',
                    help: 'Heger divê ev kategorî veşartî be, pê li qutiyê bikin.'
                }),
                new OO.ui.FieldLayout(umbrellaInput, {
                    label: 'Li gorî zimanan çêke?',
                    align: 'left',
                    help: 'Gelek binkategoriyên Kategorî:Zanist wekî Bîyolojî, Psîkolojî, Fizîk û hwd. hene loma ji bo veqetandina "Zanist bi zimanekî" ji binkategoriyên din, Kategorî:Zanist li gorî zimanan tê çêkirin. Ji bo vê etîketê "li gorî zimanan" hewce be, vê qutiyê bitikînin.'
                })
            ]
        });

        // Add click event to the submit button
        submitButton.on('click', function() {
            if (!isFormValid()) {
                mw.notify('Please fill in all required fields before submitting.', {
                    type: 'warn'
                });
                return; // Do not submit if form is not valid
            }

            submitForm();
            popUp.toggle();
            resetInputs(); // Reset input fields when cancelling
        });

        // Add form fields and submit button to the form
        fieldset.addItems([submitButton, cancelButton]);

        // Function to reset input fields
        function resetInputs() {
            etiketInput.setValue('');
            displayInput.setValue('');
            danasinInput.setValue('');
            parentsInput.setValue('');
            interwikiInput.setValue('');
            naveDinInput.setValue('');
            inSerkategoriInput.setValue(false);
            isHiddenInput.setValue(false);
            umbrellaInput.setValue(false);
        }

        function isFormValid() {
            const requiredFields = [
                etiketInput.getValue(),
                displayInput.getValue(),
                danasinInput.getValue(),
                parentsInput.getValue()
            ];

            return requiredFields.every(value => value.trim() !== ''); // Check if all values are non-empty
        }

        // Function to handle form submission
        function submitForm() {
            const etiket = etiketInput.getValue();
            const display = displayInput.getValue();
            const danasin = danasinInput.getValue();
            const parents = parentsInput.getValue();
            const interwiki = interwikiInput.getValue();
            const naveDin = naveDinInput.getValue();
            const inSerkategori = inSerkategoriInput.isSelected() ? 'true' : 'false';
            const isHidden = isHiddenInput.isSelected() ? 'true' : 'false';
            const umbrella = umbrellaInput.isSelected() ? 'true' : 'false';

            // Generate new etiket content using newetiket function
            const newEtiketContent = newEtiket(etiket, display, danasin, parents, interwiki, naveDin, inSerkategori, isHidden, umbrella);

            editWikiPage(etiket, newEtiketContent);
        }

        function newEtiket(etiket, display, danasin, parents, interwiki, naveDin, inSerkategori, isHidden, umbrella) {
            let etiket_new = 'labels["' + etiket + '"] = {\n';
            etiket_new += '    display = "' + display + '",\n';
            etiket_new += '    topical_categories = {"' + etiket + '"},\n';
            etiket_new += '    description = "' + danasin + '",\n';
	
		    // Split parents input by comma and add each value to the parents array
		    const parentsArray = parents.split(',').map(value => value.trim());
		    etiket_new += '    parents = {' + parentsArray.map(parent => '"' + parent + '"').join(', ') + '},\n';
		    
            if (inSerkategoriInput.isSelected()) {
                etiket_new += '    inSerkategori = true,\n';
            }

            if (isHiddenInput.isSelected()) {
                etiket_new += '    isHidden = true,\n';
            }

            if (umbrellaInput.isSelected()) {
                etiket_new += '    umbrella = true,\n';
            }

            etiket_new += '}\n';

            if (interwiki && interwiki.length > 0)
                etiket_new += 'interwiki["' + etiket + '"] = "' + interwiki + '"\n';

		    if (naveDin && naveDin.length > 0) {
		        const naveDinArray = naveDin.split(',').map(value => value.trim());
		        etiket_new += naveDinArray.map(nave => 'aliases["' + nave + '"] = "' + etiket + '"').join('\n') + '\n';
		    }

            return etiket_new;
        }

        function sortContentAlphabetically(content) {
            const lines = content.split("\n");
            const kurdishAlphabet = "aAbBcCçÇdDeEêÊfFgGhHiIîÎjJkKlLmMnNoOpPqQrRsSşŞtTuUûÛvVwWxXyYzZ";
            let currentLabel = null;
            const labels = {};
            const sortedLabels = {};
            let sortedContent = "";

            lines.forEach((line) => {
                const match = line.match(/^\s*labels\["(.*?)"\]\s*=/);
                if (match) {
                    currentLabel = match[1];
                    labels[currentLabel] = [];
                    sortedLabels[currentLabel] = line;
                } else if (currentLabel !== null) {
                    labels[currentLabel].push(line);
                } else {
                    sortedContent += line + "\n";
                }
            });

            Object.keys(labels).sort((a, b) => {
                const indexA = kurdishAlphabet.indexOf(a.charAt(0));
                const indexB = kurdishAlphabet.indexOf(b.charAt(0));
                return indexA - indexB;
            }).forEach((label) => {
                sortedContent += sortedLabels[label] + "\n" + labels[label].join("\n") + "\n";
            });

            // Trim extra empty lines
            sortedContent = sortedContent.replace(/\n{3,}/g, "\n\n");

            return sortedContent;
        }

        // Function to fetch existing Lua module content and search for label or alias
        function fetchExistingContentAndSearch(label) {
            const apiUrl = "https://ku.wiktionary.org/w/api.php";
            const params = new URLSearchParams({
                action: "query",
                prop: "revisions",
                titles: "Modul:dara kategoriyan/ferhengokkatbike/dane/ferhengok",
                rvprop: "content",
                format: "json"
            });

            return 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]['*'];

                    // Search for the label or alias's existing content in the Lua module
                    const labelPattern = new RegExp(`labels\\["${label}"\\]\\s*=\\s*\\{[\\s\\S]*?\\}`);
                    const aliasPattern = new RegExp(`aliases\\["${label}"\\]\\s*=\\s*\\{[\\s\\S]*?\\}`);
                    const existingLabelContent = content.match(labelPattern);
                    const existingAliasContent = content.match(aliasPattern);

                    return existingLabelContent || existingAliasContent ? true : false;
                });
        }


        function editWikiPage(etiket, newWikiCode) {
            var etiketceke;
            etiketceke = etiket;
            if (newWikiCode) {
                fetch("https://ku.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://ku.wiktionary.org/w/api.php";
                        const params = new URLSearchParams({
                            action: "query",
                            prop: "revisions",
                            titles: "Modul:dara kategoriyan/ferhengokkatbike/dane/ferhengok",
                            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]['*'];

                                console.log(newWikiCode);
                                // Get the existing Lua module content
                                const existingContent = content.replace(/return {[\s\S]*}/, '');

                                // Construct the new content
                                const newContent = existingContent + "\n\n" + newWikiCode;

                                // Usage example:
                                const sortedNewContent = sortContentAlphabetically(newContent);

                                const sortedContent = sortedNewContent + "\n\n" + "return {LABELS = labels, HANDLERS = handlers, aliases = aliases, interwiki = interwiki, deprecated = deprecated}";
                                const summary = "[[Bikarhêner:Balyozxane/etîket-çêke.js|Etîket-çêke]]: +" + etiketceke;

                                const editParams = new URLSearchParams({
                                    action: "edit",
                                    title: "Modul:dara kategoriyan/ferhengokkatbike/dane/ferhengok",
                                    text: sortedContent,
                                    token: editToken,
                                    summary: summary,
                                    format: "json"
                                });

                                fetch(apiUrl, {
                                        method: "POST",
                                        body: editParams
                                    })
                                    .then(response => response.json())
                                    .then(data => {

                                        // Check if the edit property exists and contains the expected result
                                        if (data.edit && data.edit.result === "Success") {
                                            console.log("Page edited successfully!");
                                            mw.notify("Etîketa " + etiketceke + " hat çêkirin.");
                                        } else {
                                            mw.notify("Xeletî çêbû!");
                                            console.error("Failed to edit page.");
                                        }
                                    });
                            });
                    });
            } else {
                console.log("No page name provided. Editing cancelled.");
            }
        }

        // To add the edit wizard tab on the top navigation bar
        var node = mw.util.addPortletLink('p-tb', '#', 'Etîket çêke', 't-etîket', 'Etîketeke nû çêke bo şablona f');

        // A popup widget is instantiated
        var popUp = new OO.ui.PopupWidget({
            align: "forwards",
            $floatableContainer: $(node),
            $content: fieldset.$element,
            padded: true,
            popup: false,
            width: 400,
            height: 1200,
            head: true,
            // hideWhenOutOfView: false,
            // autoClose: false,
            hideCloseButton: true,
        });


        $(node).on('click', function(e) {
            popUp.toggle();
            e.preventDefault();
        });

        $(document.body).append(popUp.$element);
    });
});

// </nowiki>