Bikarhêner:Balyozxane/skrîpt/js/updateWDLabel.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.
$(document).ready(function() {

    var APIoptions = {
        ajax: {
            headers: {
                'Api-User-Agent': 'Update wikidata w:ku:User:Balyozxane'
            }
        }
    };
    var API = new mw.Api(APIoptions);
    var wikidataAPI = new mw.ForeignApi('https://www.wikidata.org/w/api.php', APIoptions);

    // Function to retrieve entity information from Wikidata
    var getWikidataEntity = function(qid) {
        return mw.loader.using('mediawiki.ForeignApi').then(function() {
            return wikidataAPI.get({
                action: 'wbgetentities',
                ids: qid,
                props: "claims",
                format: 'json'
            }).then(function(data) {
                // Extract the entity information from the response
                var entities = data.entities;
                var entity = entities[qid];
                return entity;
            });
        });
    };
    // Function to retrieve the English label for a given entity ID
    var getWikidataEntityLabel = function(entityId, language) {
        return mw.loader.using('mediawiki.ForeignApi').then(function() {
            return wikidataAPI.get({
                action: 'wbgetentities',
                ids: entityId,
                languages: language,
                props: 'labels',
                format: 'json'
            }).then(function(data) {
                // Extract the label from the response
                var labels = data.entities[entityId]?.labels;
                var label = labels?.[language]?.value;
                return label;
            });
        });
    };

    mw.loader.using("mediawiki.api").done(function() {

        // Function to open a single modal with multiple input boxes
        function openSingleModal(propertyValues) {
            // Create a modal dialog
            var modal = $('<div>', {
                id: 'property-modal',
                title: 'Update Values'
            });
            // Add a tab character between submit and cancel button
            var tabCharacter = $('<span>', {
                text: '\u00a0\u00a0' // Unicode representation of a tab character
            });

            // Create an input box for each property value
            var inputBoxes = propertyValues.map(function(property) {
                // Determine the label to display based on the language
                var labelToDisplay = property.value;
                var defaultVal;
                if (property.kuLabel !== null) {
                    // If the language is Kurdish, prioritize kuLabel, fallback to enLabel, or QID
                    labelToDisplay = property.kuLabel || property.enLabel || property.value;
                    defaultVal = property.kuLabel;
                }

                // Create a label element
                var labelElement = $('<label>', {
                    text: labelToDisplay
                });

                // Create an input element
                var inputBox = $('<input>', {
                    type: 'text',
                    value: defaultVal,
                    placeholder: 'Enter new value',
                    id: 'input-' + property.value, // unique id for each input
                    css: {
                        width: '300px', // Set the width
                        height: '30px', // Set the height
                        border: '1px solid #ccc', // Add a border for visibility
                        borderRadius: '5px' // Optional: Add rounded corners
                    }
                });

                // Create a line break element
                var lineBreak = $('<br>');
                // Return an array containing label, input box, and line break
                return [labelElement, " ", inputBox, lineBreak];
            });

            // Flatten the array to ensure correct structure when appending
            inputBoxes = [].concat.apply([], inputBoxes);

            var submitButton = $('<button>', {
                text: 'Submit',
                click: function() {
                    // Iterate through input boxes and get the new values
                    propertyValues.forEach(function(property, index) {
                        var newValue = $('#' + 'input-' + property.value).val();
                        // Update the label in Wikidata using the API for each property value
                        if (newValue !== property.kuLabel || newValue.trim() !== ""){
                        	updateWikidataLabel(property.value, 'ku', newValue);
                        }else {
                        	mw.notify("Jixwe ev danasîn heye!");
                        }
                    });

                    // Close the modal when done
                    modal.dialog('close');
                },
                css: {
                    width: '150px', // Set the width
                    height: '30px', // Set the height
                    border: '1px solid #ccc', // Add a border for visibility
                    borderRadius: '5px', // Optional: Add rounded corners
                    marginRight: '10px' // Optional: Add some margin between buttons
                }
            });

            // Create a cancel button
            var cancelButton = $('<button>', {
                text: 'Cancel',
                click: function() {
                    // Close the modal when canceling
                    modal.dialog('close');
                },
                css: {
                    width: '150px', // Set the width
                    height: '30px', // Set the height
                    border: '1px solid #ccc', // Add a border for visibility
                    borderRadius: '5px' // Optional: Add rounded corners
                }
            });


            // Append the input boxes, buttons, and tab character to the modal
            modal.append(inputBoxes, submitButton, tabCharacter, cancelButton);

            // Append the modal to the container (e.g., the body)
            $(document.body).append(modal);

            // Initialize the modal as a jQuery UI dialog
            modal.dialog({
                modal: true,
                width: 'auto',
                close: function() {
                    // Remove the modal from the DOM when closed
                    $(this).dialog('destroy').remove();
                }
            });
        }

		function updateWikidataLabel(qid, language, updatedLabel) {
            console.log(`Updating label for QID: ${qid}, Language: ${language}, Label: ${updatedLabel}`);
			    var summary = 'Adding label for ' + language + ' via ([[:w:ku:User:Balyozxane/updateWD.js|updateWD.js]])';
		    wikidataAPI.postWithEditToken({
		        action: 'wbsetlabel',
		        id: qid,
		        language: language,
		        summary: summary,
		        value: updatedLabel
		    }).then(function (response) {
		        mw.notify('Etîket li Wîkîdaneyê hat qeydkirin');
		    }).catch(function (error) {
		        console.error('Qeydkirina rûpela Wîkîdaneyê têkçû:', error);
		        mw.notify('Qeydkirina rûpela Wîkîdaneyê têkçû. Binêre konsolê.');
		    });
		}

        // Find all elements with the class "penicon autoconfirmed-show" or "noprint wikidata-linkback"
        var elements = $('.penicon.autoconfirmed-show, .noprint.wikidata-linkback');

        // Iterate through each element
        elements.each(function() {
            var linkElement = $(this).find('a');

            // Extract the href attribute value
            var hrefValue = linkElement.attr('href');

            // Use regular expressions to extract QID and P31 values
            var match = hrefValue.match(/\/wiki\/[qQ](\d+)\?uselang=ku#[Pp](\d+)/);
            if (match) {
                var qid = "Q" + match[1];
                var property = "P" + match[2];
                console.log('Qid: ' + qid + '\nProperty: ' + property);

                // Create a pencil icon element
                var pencilIcon = $('<span>✏️</span>').css({
                    cursor: 'pointer',
                    marginLeft: '5px'
                });

                // Append the pencil icon to the element
                $(this).append(pencilIcon);

                // Handle the click event on the pencil icon
                pencilIcon.on('click', function() {
					mw.notify("Tê barkirin...");
                    getWikidataEntity(qid).then(function(entity) {
                        // Log the entire entity response
                        console.log('Entity Information:', entity);

                        // Check if the 'claims' property exists in the entity
                        if (entity && entity.claims) {
                            // Access the retrieved property information
                            var propertyData = entity.claims[property];
                            console.log('Property ' + property + ' Information:', propertyData);
                            var propertyValues = [];
                            propertyData.forEach(function(propertyValue) {

								if (propertyValue.mainsnak.datavalue.type !== 'wikibase-entityid') {
								    // Display an error message using mw.notify
								    mw.notify('Tenê ji bo etîketan (label) tê bikaranîn. Ev ne etîketek e.');
								    return; // Exit the function or handle the error as needed
								}
								
                                // Extract the entity information from the property value

                                var entityInfo = propertyValue.mainsnak.datavalue.value;

                                // Retrieve the English label for the entity
                                getWikidataEntityLabel(entityInfo.id, 'en').then(function(enLabel) {
                                	console.log('enLabel:', enLabel);
                                    // Retrieve the Kurdish label for the entity
                                    getWikidataEntityLabel(entityInfo.id, 'ku').then(function(kuLabel) {
                                    	console.log('kuLabel:', kuLabel);

                                        // Add the label and value to the propertyValues array
                                        propertyValues.push({
                                            enLabel: enLabel,
                                            kuLabel: kuLabel,
                                            value: entityInfo.id
                                        });

                                        // Check if all property values have been processed
                                        if (propertyValues.length === propertyData.length) {
                                            // Once all values are collected, open a single modal with multiple input boxes
                                            openSingleModal(propertyValues);
                                        }
                                    });
                                });
                            });

                        }else {
                        	mw.notify('Daneyên QIDyê kêm e.');
                        }
                    }).catch(function(error) {
                        console.error('Wergirtina daneyên QIDyê têk çû:', error);
                        mw.notify('Wergirtina daneyên QIDyê têk çû. Binêre konsolê.');
                    });
                });
            }
        });
    });
});