Bikarhêner:Balyozxanetest/raterafeqiran.js

Ji Wîkîpediya, ensîklopediya azad.

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>
$.when(
    mw.loader.using(['mediawiki.api', 'mediawiki.util', 'jquery.ui']),
    $.ready
).done(function () {

    // Dynamically inject styles for the modal
    var modalStyles = `
        <style>
            /* Add your modal styles here */
            .myModal {
                display: none;
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: white;
                padding: 20px;
                border: 1px solid #ccc;
                z-index: 9999; /* Ensure modals appear on top of other content */
                box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); /* Add a shadow effect */
                max-width: 100%; /* Adjust maximum width as needed */
            }
        </style>
    `;
    $('head').append(modalStyles);

    // Array to store template names and aliases
    var templates = {
        "Wîkîproje Kurdistan": ["WPKU", "WPKURDISTAN"],
        "Wîkîproje Fransa": ["WPFR"],
    };

function addNewTemplateToModal() {
    var newTemplateHtml = `
        <div>
            <label for="newTemplateName">Enter the name of the new Wîkîproje template:</label>
            <input type="text" id="newTemplateName">
            <br>
            <label for="newTemplateMuhimi">Enter the value for the parameter "muhîmî":</label>
            <input type="text" id="newTemplateMuhimi">
            <br>
            <label for="newTemplateSinif">Select the value for the parameter "sinif":</label>
            <select id="newTemplateSinif">
                <option value="">Select</option>
                <option value="şitil">Şitil</option>
                <option value="destpêkî">Destpêkî</option>
                <option value="c">C</option>
                <option value="b">B</option>
                <option value="gba">GBA</option>
                <option value="gb">GB</option>
                <option value="lîste">Lîste</option>
                <option value="cudakirin">Cudakirin</option>
                <option value="beralîkirin">Beralîkirin</option>
            </select>
            <br>
            <button id="addTemplateBtn">Add Template</button>
        </div>
    `;
    $('#modalContent').html(newTemplateHtml);
}


function getTemplateParameters(pageTitle) {
    mw.notify('getTemplateParameters called for: ' + pageTitle);
    new mw.Api().get({
        action: 'query',
        prop: 'revisions',
        rvprop: 'content',
        titles: 'Talk:' + pageTitle,
        formatversion: 2,
    }).done(function (data) {
        // Check if the talk page exists and has content
        if (data.query && data.query.pages && data.query.pages[0] && data.query.pages[0].revisions && data.query.pages[0].revisions[0]) {
            var content = data.query.pages[0].revisions[0].content;
            var matches = [];

            // Regular expression to match "Kalika wîkîprojeyê" template
            var kalikaRegex = /\{\{Kalika wîkîprojeyê([^}]*)?\}\}/g;

            // Find matches for Kalika wîkîprojeyê template
            var kalikaMatch = kalikaRegex.exec(content);
            if (kalikaMatch) {
                // Check if there are any { in the matched content
                console.log("kalikaMatch[1]:", kalikaMatch[1]);
                if (kalikaMatch[1] && kalikaMatch[1].includes('{')) {
                    console.log("kalikaMatch[1].includes");
                    // If there are, use a different regex to match content until {
                    var nestedKalikaRegex = /\{\{Kalika wîkîprojeyê([^{]+)/;
                    var nestedMatch = nestedKalikaRegex.exec(content);
                    if (nestedMatch) {
                        console.log("nestedMatch");
                        matches.push({ templateName: "Kalika wîkîprojeyê", params: nestedMatch[1] });
                    }
                } else {
                    // If there are no {, use the original match
                    matches.push({ templateName: "Kalika wîkîprojeyê", params: kalikaMatch[1] });
                }
            }

            // Current logic to match Wîkîproje templates
            for (var template in templates) {
                var aliases = templates[template];
                for (var i = 0; i < aliases.length; i++) {
                    var alias = aliases[i];
                    // Construct the regular expression to match the template and its parameters
                    var regex = new RegExp("\\{\\{(" + template + "|" + alias + ")([^}]+)?\\}\\}", "g");
                    var match;
                    // Find all matches in the content
                    while ((match = regex.exec(content)) !== null) {
                        // Push the matched template name and parameters into the matches array
                        matches.push({ templateName: match[1], params: match[2] });
                    }
                }
            }

            // Filter out duplicate matches
            var uniqueMatches = matches.filter((match, index, self) =>
                index === self.findIndex((m) => (
                    m.templateName === match.templateName && m.params === match.params
                ))
            );

            if (uniqueMatches.length > 0) {
                mw.notify('Retrieved parameters for matched templates: ' + JSON.stringify(uniqueMatches));
                showSingleModal(uniqueMatches); // Call showSingleModal with the matched templates
            } else {
                mw.notify('No matching templates found.');
                // Load the modal if no templates found
                loadModal();
            }
        } else {
            mw.notify('Talk page does not exist.');
            // Load the modal if talk page doesn't exist
            loadModal();
        }
    }).fail(function (error) {
        mw.notify('Error fetching data from API: ' + error);
        // Load the modal if there's an error
        loadModal();
    });
}

function loadModal() {
    // Create and show the modal
    var modalHtml = `
        <div class="myModal" id="myModal">
            <h2>No Templates Found</h2>
            <p>No Wîkîproje templates or Kalika wîkîprojeyê template found on the talk page.</p>
            <button id="addTemplateButton">Lê zêde bike</button>
            <button id="closeButton">Bigre</button>
        </div>
    `;
    $('body').append(modalHtml);

    // Make the modal draggable
    $('#myModal').draggable();

    // Show the modal
    $('#myModal').show();

    // Event listener for the close button
    $('#closeButton').on('click', function () {
        $('#myModal').hide(); // Hide the modal when the close button is clicked
    });

    // Event listener for the "Lê zêde bike" button
    $('#addTemplateButton').on('click', function () {
        // Call the function to add new template to the modal
        addNewTemplateToModal();
    });
}

// Function to show a single modal for all matched templates
function showSingleModal(matches) {
    var modalHtml = `
        <div class="myModal" id="myModal">
            <h2>Templates</h2>
            <div id="modalContent">
                <!-- Template content will be appended here -->
            </div>
            <button id="addTemplateButton">Lê zêde bike</button>
            <button class="saveButton" data-modal-id="1">Save</button>
            <button id="closeButton">Bigre</button> <!-- Added close button -->
        </div>
    `;
    $('body').append(modalHtml);

    // Make the modal draggable
    $('#myModal').draggable();

    // Show the modal
    $('#myModal').show();

    // Event listener for the close button
    $('#closeButton').on('click', function () {
        $('#myModal').hide(); // Hide the modal when the close button is clicked
        $('#modalContent').empty(); // Clear the content of the modal when closing
    });

    // Event listener for the "Lê zêde bike" button
    $('#addTemplateButton').on('click', function () {
        addNewTemplateToModal(); // Call the function to add new template to the modal
    });

    // Concatenate template content into one HTML string
    var templateContentHtml = '';
    for (var i = 0; i < matches.length; i++) {
        var match = matches[i];
        var templateName = match.templateName;
        var paramsStr = match.params;

        // Splitting params by '|' to get individual parameters
        var paramsArray = paramsStr.split('|');

        // Creating HTML for each parameter
        var paramsHtml = '';
        for (var j = 0; j < paramsArray.length; j++) {
            var param = paramsArray[j].trim();
            var paramName = param.split('=')[0].trim();
            var paramValue = '';

            // Check if the parameter contains an equal sign
            if (param.includes('=')) {
                paramValue = param.split('=')[1].trim();
            }

            // Convert paramValue to lowercase for case insensitivity
            var paramValueLower = paramValue.toLowerCase();

            // Check if the parameter name is not empty
            if (paramName !== '') {
                // Creating input fields based on parameter type
                if (paramName === 'sinif') {
                    // For 'sinif' parameter, create dropdown menu
                    paramsHtml += `
                        <div>
                            <label for="${paramName}">${paramName}:</label>
                            <select id="${paramName}">
                                <option value="">Select</option> <!-- Default option -->
                                <option value="şitil" ${paramValueLower === 'şitil' ? 'selected' : ''}>Şitil</option>
                                <option value="destpêkî" ${paramValueLower === 'destpêkî' ? 'selected' : ''}>Destpêkî</option>
                                <option value="c" ${paramValueLower === 'c' ? 'selected' : ''}>C</option>
                                <option value="b" ${paramValueLower === 'b' ? 'selected' : ''}>B</option>
                                <option value="gba" ${paramValueLower === 'gba' ? 'selected' : ''}>GBA</option>
                                <option value="gb" ${paramValueLower === 'gb' ? 'selected' : ''}>GB</option>
                                <option value="lîste" ${paramValueLower === 'lîste' ? 'selected' : ''}>Lîste</option>
                                <option value="cudakirin" ${paramValueLower === 'cudakirin' ? 'selected' : ''}>Cudakirin</option>
                                <option value="beralîkirin" ${paramValueLower === 'beralîkirin' ? 'selected' : ''}>Beralîkirin</option>
                                <!-- Add options here -->
                            </select>
                        </div>
                    `;
                } else if (paramName === 'muhîmî') {
                    // For 'muhîmî' parameter, create dropdown menu
                    paramsHtml += `
                        <div>
                            <label for="${paramName}">${paramName}:</label>
                            <select id="${paramName}">
                                <option value="">Select</option> <!-- Default option -->
                                <option value="herî zêde" ${paramValueLower === 'herî zêde' ? 'selected' : ''}>Herî zêde</option>
                                <option value="zêde" ${paramValueLower === 'zêde' ? 'selected' : ''}>Zêde</option>
                                <option value="navîn" ${paramValueLower === 'navîn' ? 'selected' : ''}>Navîn</option>
                                <option value="kêm" ${paramValueLower === 'kêm' ? 'selected' : ''}>Kêm</option>
                                <option value="na" ${paramValueLower === 'na' ? 'selected' : ''}>NA</option>
                                <!-- Add options here -->
                            </select>
                        </div>
                    `;
                } else {
                    // For other parameters, create input box
                    paramsHtml += `
                        <div>
                            <label for="${paramName}">${paramName}:</label>
                            <input type="text" id="${paramName}" value="${paramValue}">
                        </div>
                    `;
                }
            }
        }

        // Appending template content HTML if there are parameters
        if (paramsHtml !== '') {
            templateContentHtml += `
                <div>
                    <h3>${templateName}</h3>
                    ${paramsHtml}
                    <br>
                </div>
            `;
        }
    }

    // Append the concatenated template content to the modal
    $('#modalContent').append(templateContentHtml);
}

    // Function to update template parameters on talk page using MediaWiki API
    function updateTemplateParametersOnTalkPage(pageTitle, updatedParam1, updatedParam2) {
        mw.notify('updateTemplateParametersOnTalkPage called for: ' + pageTitle);

        // Manually retrieve CSRF token
        new mw.Api().get({
            action: 'query',
            meta: 'tokens',
            type: 'csrf'
        }).done(function (tokenData) {
            var token = tokenData.query.tokens.csrftoken;

            // Fetch existing content of the talk page
            new mw.Api().get({
                action: 'query',
                prop: 'revisions',
                rvprop: 'content',
                titles: 'Talk:' + pageTitle,
                formatversion: 2,
                token: token // Include token in the request
            }).done(function (data) {
                var content = data.query.pages[0].revisions[0].content;

                // Update the template parameters in the existing content
                var updatedContent = content.replace(/\{\{Wîkîproje Kurdistan\|.+?\|.+?\}\}/, '{{Wîkîproje Kurdistan|' + updatedParam1 + '|' + updatedParam2 + '}}');

                // Manually include CSRF token in the API request
                var apiRequestParams = {
                    action: 'edit',
                    title: 'Talk:' + pageTitle,
                    summary: '+' + updatedParam1,
                    text: updatedContent,
                    formatversion: 2,
                    token: token // Include token in the request
                };

                // Make the API request to save the updated content
                $.ajax({
                    url: mw.util.wikiScript('api'),
                    type: 'POST',
                    dataType: 'json',
                    data: apiRequestParams,
                    success: function (data) {
                        if (data.edit && data.edit.result === 'Success') {
                            mw.notify('Edit successful!');
                        } else {
                            mw.notify('Error editing page: ' + JSON.stringify(data));
                        }
                    },
                    error: function (error) {
                        console.log('Error making edit API request: ' + JSON.stringify(error));
                    }
                });
            }).fail(function (error) {
                mw.notify('Error fetching data from API: ' + error);
            });
        }).fail(function (error) {
            mw.notify('Error getting CSRF token: ' + error);
        });
    }

    // Document ready function
    $(function () {
        var targetContainer = mw.config.get('skin') === 'vector' ? 'p-views' : 'p-cactions';
        var node = mw.util.addPortletLink(targetContainer, '#', 'ratera feqîran', 't-rater', 'rater');

        // Click event for the "rater" button
        $(node).on('click', function (event) {
            event.preventDefault();
            mw.notify('Rater button clicked');
            var pageTitle = mw.config.get('wgTitle');
            getTemplateParameters(pageTitle);
        });

// Click event for the "Lê zêde bike" button
$('body').on('click', '#addTemplateButton', function () {
    console.log("Lê zêde bike button clicked");
    addNewTemplateToModal();
});

        // Click event for the "Add Template" button
        $('body').on('click', '#addTemplateBtn', function () {
            var newTemplateName = $('#newTemplateName').val();
            var newTemplateMuhimi = $('#newTemplateMuhimi').val();
            if (newTemplateName && newTemplateMuhimi) {
                // Add logic here to construct the HTML for the new template and append it to the modal
                var newTemplateHtml = `
                    <div>
                        <h3>${newTemplateName}</h3>
                        <div>
                            <label for="muhimiInput">muhîmî:</label>
                            <input type="text" id="muhimiInput" value="${newTemplateMuhimi}">
                        </div>
                    </div>
                `;
                $('#modalContent').append(newTemplateHtml);
                $('#newTemplateName').val('');
                $('#newTemplateMuhimi').val('');
            } else {
                alert('Please enter both template name and muhîmî value.');
            }
        });

        // Call the updateTemplateParametersOnTalkPage function when the "save" button is clicked
        $('body').on('click', '.saveButton', function () {
            var modalId = $(this).data('modal-id');
            var pageTitle = mw.config.get('wgTitle');
            var updatedParam1 = $('#modalParam1' + modalId).val();
            var updatedParam2 = $('#modalParam2' + modalId).val();
            updateTemplateParametersOnTalkPage(pageTitle, updatedParam1, updatedParam2);
            $('#myModal' + modalId).hide();
        });
    });

});
//</nowiki>