Bikarhêner:Balyozbot/test.js

Ji Wîkîferhengê

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() {
    console.log('Document ready');

    mw.loader.using("oojs-ui", "mediawiki.api").done(function() {
        console.log('Dependencies loaded');

        mw.loader.addStyleTag('.container { width: 415px; height:150px }');

        var node = mw.util.addPortletLink(
            'p-views',
            "#",
            'Şablon lêke',
            'sablon-leke-link',
            'Şablon lêke',
            "",
            "#ca-history"
        );

        var templateSelect = new OO.ui.DropdownInputWidget({
            options: [{
                    data: '',
                    label: 'Select Template'
                },
                {
                    data: 'bêçavkanî',
                    label: 'bêçavkanî'
                },
                {
                    data: 'jêbirin',
                    label: 'jêbirin'
                },
                {
                    data: 'ds',
                    label: 'ds'
                }
            ]
        });
        var addTopCheckbox = new OO.ui.CheckboxInputWidget({
            selected: false,
        });

        // Wrap the checkbox in a FieldLayout with a label
        var addTopField = new OO.ui.FieldLayout(addTopCheckbox, {
            label: 'Add to the top?',
        });

        var alertCheckbox = new OO.ui.CheckboxInputWidget({
            selected: false,
        });

        // Wrap the checkbox in a FieldLayout with a label
        var alertField = new OO.ui.FieldLayout(alertCheckbox, {
            label: 'Do you want to alert the page creator?',
        });

        var addTemplateButton = new OO.ui.ButtonWidget({
            label: 'Add Template'
        });

        welcomepanel = new OO.ui.PanelLayout({
            content: [
                templateSelect,
                addTopField,
                alertField,
                addTemplateButton,
            ],
            padded: true,
        });
        var stack = new OO.ui.StackLayout({
            classes: ["container"],
            items: [welcomepanel]
        });

        var popUp = new OO.ui.PopupWidget({
            align: "forwards",
            $floatableContainer: $(node),
            $content: stack.$element,
            padded: true,
            popup: false,
            width: 450,
            height: 250,
            head: true,
            hideCloseButton: false,
        });

        $(node).on('click', function(e) {
            console.log('Popup button clicked');
            popUp.toggle();
            e.preventDefault();
        });

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

        addTemplateButton.on('click', function() {
            console.log('Add Template button clicked');
            const selectedTemplate = templateSelect.getValue();
            const alertCreator = alertCheckbox.isSelected();
            const pageTitle = mw.config.get('wgPageName'); // Retrieve the page title from the URL
            const addToTop = addTopCheckbox.isSelected(); // Check if "Add to the top?" is checked

            if (selectedTemplate) {
                console.log('Selected template:', selectedTemplate);

                if (addToTop) {
                    // If "Add to the top?" is checked, no need to prompt for language header
                    const langHeaderId = null;
                    editPageWithTemplate(pageTitle, selectedTemplate, addToTop, langHeaderId);
                } else {
                    const langHeaderId = prompt("Please enter the ID of the language header:", "");
                    if (langHeaderId) {
                        console.log('Language header ID:', langHeaderId);
                        editPageWithTemplate(pageTitle, selectedTemplate, addToTop, langHeaderId);
                    } else {
                        console.log('No language header ID provided.');
                        mw.notify("No language header ID provided.");
                    }
                }
            } else {
                console.log('No template selected.');
                alert("Please select a template.");
            }
        });
    });
});

function getRupelCeker(pageTitle) {
    return new Promise((resolve, reject) => {
        const encodedPageTitle = encodeURIComponent(pageTitle);
        const apiUrl = `https://ku.wiktionary.org/w/api.php?action=query&format=json&prop=revisions&titles=${encodedPageTitle}&rvprop=user|timestamp&rvlimit=max&origin=*`;

        $.ajax({
            url: apiUrl,
            dataType: 'json',
            success: function(data) {
                const pages = data.query.pages;
                const pageId = Object.keys(pages)[0];
                const revisions = pages[pageId].revisions;

                if (revisions.length > 0) {
                    const oldestRevision = revisions[revisions.length - 1];
                    const creatorName = oldestRevision.user;
                    resolve(creatorName);
                } else {
                    resolve(null); // No revisions found
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                reject(errorThrown); // Reject the promise in case of error
            }
        });
    });
}


function editPage(info) {
    var api = new mw.Api();
    api.postWithToken("csrf", {
        action: 'edit',
        title: info.title,
        text: info.text,
        summary: info.summary
    }).then(function(data) {
        OO.ui.alert('Edit Request sent to talk page..!');
    }).catch(function(code, data) {
        console.log(api.getErrorMessage(data).text());
    });
}

function insertTemplateAfterLanguageHeader(content, langHeaderId, templateText, addToTop) {
    if (addToTop) {
        const bnrHeaderRegex = /{{\s*(?:Binêre herwiha|bnr\s*herwiha|bnr-h|bnr-hrw|bnr\s*h)\s*(?:\|.*?)*\s*}}/i;
        const bnrMatch = content.match(bnrHeaderRegex);

        if (bnrMatch) {
            const insertionIndex = bnrMatch.index + bnrMatch[0].length;
            const insertedContent = content.slice(0, insertionIndex) + '\n\n' + templateText + content.slice(insertionIndex);
            return insertedContent;
        }

        // If Binêre herwiha variations are not found, prepend the template
        const insertedContent = templateText + '\n\n' + content;
        return insertedContent;
    } else {
        const langHeaderRegex = new RegExp(`==\\s*{{ziman\\|${langHeaderId}}}\\s*==`, 'i');
        const match = content.match(langHeaderRegex);

        if (match) {
            console.log('Language header found.');
            // Find the insertion point after the language header
            const insertionIndex = match.index + match[0].length;
            console.log('Insertion index:', insertionIndex);
            const insertedContent = content.slice(0, insertionIndex) + '\n' + templateText + content.slice(insertionIndex);
            return insertedContent;
        }
    }

    return content;
}

function fetchPageContent(pageTitle) {
    const api = new mw.Api();
    return api.get({
        action: 'query',
        prop: 'revisions',
        titles: pageTitle,
        rvprop: 'content',
        formatversion: '2',
        format: 'json'
    }).then(function(data) {
        console.log('API response:', data);
        const pageContent = data.query.pages[0].revisions[0].content;
        console.log('Current page content:', pageContent);
        return pageContent;
    }).catch(function(error) {
        console.error('Error fetching page content:', error);
        mw.notify("Error fetching page content.");
        return null;
    });
}

function editPageWithTemplate(pageTitle, selectedTemplate, addToTop, langHeaderId) {
    console.log('Editing current page:', pageTitle);

    fetchPageContent(pageTitle).then(function(pageContent) {
        if (pageContent !== null) {
        	if (selectedTemplate !== 'ds') {
            const editedContent = insertTemplateAfterLanguageHeader(pageContent, langHeaderId, `{{${selectedTemplate}}}`, addToTop);
            console.log('Edited content for current page:', editedContent);

            const editInfo = {
                title: pageTitle,
                text: editedContent,
                summary: `Added template: {{${selectedTemplate}}}`
            };
            editPage(editInfo);
        	}

            // Edit other pages using templateMap
            const templateMap = {
                'bêçavkanî': {
                    title: "Bikarhêner:Balyozbot/test1",
                    newData: `== [[${pageTitle}]] ==\n`,
                    summary: "Bêçavkanî: +[[" + pageTitle + "]]",
                    sirove: "''[[Wîkîferheng:Pîvekên tevlîkirinê|Çavkanî hewce ye]].''",
                },
                'ds': {
                    title: "Bikarhêner:Balyozbot/test2",
                    newData: `== [[${pageTitle}]] ==\n`,
                    summary: "Standardkirin: +[[" + pageTitle + "]]",
                    sirove: "",

                },
                'jêbirin': {
                    title: "Bikarhêner:Balyozbot/test3",
                    newData: "testing",
                    summary: "Jêbirin: +" + pageTitle,

                }
            };
            console.log('şablon:', selectedTemplate);

            if (selectedTemplate in templateMap) {
                const templateInfo = templateMap[selectedTemplate];
                if (selectedTemplate === 'ds') {
                    const rupelenDin = prompt("Please enter other pages to be edited (comma-separated):", pageTitle + ', ');
                    if (rupelenDin !== null) {
                        const otherTitles = rupelenDin.split(",").map(title => title.trim());
                        if (otherTitles.length > 0) {
                            // Fetch content of other pages and construct new content
                            const dsTemplate = `{{ds|${otherTitles.join('|')}}}`;
                            newNewData = templateInfo.newData + rupelenDin.split(",").map(title => "[[" + title.trim() + "]]") + '\n\n';
                            const fetchAndEditPromises = otherTitles.map(title => {
                                return fetchPageContent(title).then(content => {
                                	
                                    const newContent =  insertTemplateAfterLanguageHeader(content, null, dsTemplate, true);
                                    const editInfo = {
                                        title: title,
                                        text: newContent,
                                        summary: `Daxwaza standardkirinê: ${dsTemplate}`
                                    };
                                    return editPage(editInfo);
                                });
                            });

                        } else {
                            // If no other titles, edit only the current page
                            const editInfo = {
                                title: pageTitle,
                                text: dsTemplate + pageContent,
                                summary: `Daxwaza standardkirinê: ${dsTemplate}`
                            };
                            editPage(editInfo);
                        }

                    } else {
                        console.log('No other titles provided.');
                    }
		        getRupelCeker(pageTitle).then(creatorName => {
		            const siroveyaNu = prompt("Şiroveyekê ji bo rûpela daxwazê binivîse:", `@[[Bikarhêner:${creatorName}|${creatorName}]] ` + templateInfo.sirove);

                fetchPageContent(templateInfo.title).then(function(templatePageContent) {
                    if (templatePageContent !== null) {
                        const newContent = templatePageContent + '\n\n' + newNewData + siroveyaNu + " —~~~~" + `\n\n'''Gotûbêj:''' <!--Li jêr fikrên xwe binivîsin. {{şirove}} -->\n\n{{şirove}}`;

                        console.log('New content for template page:', newContent);

                        const editInfo = {
                            title: templateInfo.title,
                            text: newContent,
                            summary: templateInfo.summary
                        };
                        editPage(editInfo);
                    }
                });

		        }).catch(error => {
		            console.error('Error fetching user:', error);
		        });
                } else if  (selectedTemplate === 'bêçavkanî') {

		        getRupelCeker(pageTitle).then(creatorName => {
		            const siroveyaNu = prompt("Şiroveyekê ji bo rûpela daxwazê binivîse:", `@[[Bikarhêner:${creatorName}|${creatorName}]] ` + templateInfo.sirove);

                fetchPageContent(templateInfo.title).then(function(templatePageContent) {
                    if (templatePageContent !== null) {
                        const newContent = templatePageContent + '\n\n' + templateInfo.newData + siroveyaNu + " —~~~~";

                        console.log('New content for template page:', newContent);

                        const editInfo = {
                            title: templateInfo.title,
                            text: newContent,
                            summary: templateInfo.summary
                        };
                        editPage(editInfo);
                    }
                });
		        }).catch(error => {
		            console.error('Error fetching user:', error);
		        });
                } else if  (selectedTemplate === 'jêbirin') {
}
            } else {
                console.log('Selected template not found in templateMap.');
            }
        }
    });
}
//</nowiki>