Bikarhêner:Balyozxane/skrîpt/js/deprecate-params.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() {
	mw.loader.using("mediawiki.api").done(function() {
		function getTemplateData(template_title) {
			const url = "https://ku.wikipedia.org/w/api.php";
			const encodedTemplateTitle = encodeURIComponent(template_title);

			const params = {
				action: "templatedata",
				titles: encodedTemplateTitle,
				format: "json"
			};

			const queryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
			const apiUrl = url + '?' + queryString;

			console.log("API URL:", apiUrl);

			fetch(apiUrl)
				.then(response => {
					if (!response.ok) {
						mw.notify("Network response was not ok");
						throw new Error("Network response was not ok");
					}
					return response.json();
				})
				.then(data => {

					const pagesData = data.pages;
					const pageId = Object.keys(pagesData)[0];
					const paramsData = pagesData[pageId].params;

					// Check if 'params' key exists
					if (!paramsData) {
						mw.notify("Params data not found in response");
						throw new Error("Params data not found in response");
					}

					const aliasDict = {};
					for (const param in paramsData) {
						const aliases = paramsData[param].aliases;
						if (aliases && aliases.length > 0) {
							aliases.forEach(alias => {
								aliasDict[alias] = param;
							});
						}
					}

					console.log("Alias Dictionary:", aliasDict);

					// Display modal with aliasDict content
					displayModal(aliasDict);
				})
				.catch(error => {
					console.error("Error:", error);
				});
		}

		// Function to open the modal
		function openModal() {
			$('#myModal').dialog('open');
		}

		// Function to close the modal
		function closeModal() {
			$('#myModal').dialog('close');
		}

		// Function to display content in the modal
		function displayModal(aliasDict) {
			var templateName = mw.config.get('wgTitle');
			var modalContent = '<textarea id="modal-textbox" rows="20" cols="100">';

			modalContent += `\n\n== [[Şablon:${templateName}|${templateName}]] ==\n`;

			// Construct modal content using aliasDict
			for (const key in aliasDict) {
				modalContent += `* <code>{{AWB rename template parameter|${templateName}|${key}|${aliasDict[key]}}}</code>\n`;
			}
			modalContent += '</textarea>';

			// Add a button to the modal
			modalContent += '<button id="appendButton">Append to Page</button>';

			$('#modal-content').html(modalContent);
			openModal(); // Open modal after setting content

			// Attach an event listener to the button
			$('#appendButton').on('click', function() {
				appendToPage(templateName, $('#modal-textbox').val());
			});
		}


function appendToPage(template_title, newSection) {
    // Fetch current content of the page
    fetch("https://ku.wikipedia.org/w/api.php?action=query&titles=Wîkîpediya:AutoWikiBrowser/Rename_template_parameters&prop=revisions&rvprop=content&format=json")
        .then(response => response.json())
        .then(data => {
            const pages = data.query.pages;
            const pageId = Object.keys(pages)[0];
            const currentPageContent = pages[pageId].revisions[0]['*'];

            // Combine current content with new section
            const combinedContent = currentPageContent;
            console.log("combinedContent:", combinedContent)
			let removingContent = combinedContent
            // Regular expression to split content into sections
            const sections = combinedContent.split(/\n(?===\s*([^=]+?)==)/).filter(section => section.trim() !== "");

            // Create an object to hold sections
            const sectionDictionary = {};
			newsectionheader = "[[Şablon:" + template_title + "|" + template_title + "]]"
			sectionDictionary[newsectionheader] = newSection
            // Iterate through sections and populate the dictionary
            for (let i = 1; i < sections.length; i += 2) {
                const sectionHeader = sections[i].trim();
                console.log("sectionHeader:", sectionHeader)
                const sectionContent = sections[i + 1]; // Handle the last section without content
                console.log("sectionContent:", sectionContent)
                removingContent = removingContent.replace(sectionContent, '').trim();
                console.log("removingContent:", removingContent)
                sectionDictionary[sectionHeader] = sectionContent;
            }


            // Sort the dictionary by section headers
            const sortedSections = Object.fromEntries(Object.entries(sectionDictionary).sort(([a], [b]) => a.localeCompare(b)));

            // Construct the sorted content
            let sortedContent = removingContent;

            for (const [header, content] of Object.entries(sortedSections)) {
                sortedContent += `\n${content}\n`;
            }
console.log("Sections:", sections);
console.log("Section Dictionary:", sectionDictionary);
            // Debugging: Log sorted content
			sortedContent = sortedContent.replace(/^\s*[\r\n]/gm, '\n');

            console.log("Sorted Content:", sortedContent);

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

                      // Construct edit parameters
                     const apiUrl = "https://ku.wikipedia.org/w/api.php";
                     const editParams = new URLSearchParams({
                         action: "edit",
                         title: "Wîkîpediya:AutoWikiBrowser/Rename template parameters",
                         //title: "Bikarhêner:Balyozxane/ceribandin",
                         token: editToken,
                         summary: "Parametreyên [[Şablon:" + template_title + "]] lê hat zêdekirin (bi [[Bikarhêner:Balyozxane/skrîpt/js/deprecate-params.js|deprecate-params.js]])",
                         text: sortedContent,
                         format: "json"
                     });

            //          Send POST request to edit the page
                     fetch(apiUrl, {
                             method: "POST",
                             body: editParams
                         })
                         .then(response => response.json())
                         .then(data => {
                             if (data.edit && data.edit.result === "Success") {
                                 console.log("Content appended and sorted successfully");
                                 mw.notify("Şablon lê hat zêdekirin");
                                 closeModal(); // Close the modal after appending and sorting content
                             } else {
                                 console.error("Failed to append and sort content:", data);
                                 mw.notify("Xeletî çêbû", data);
                             }
                         })
                         .catch(error => {
                             console.error("Error appending and sorting content:", error);
                             mw.notify("Xeletî çêbû", error);
                         });
                 })
                 .catch(error => {
                     console.error("Error retrieving CSRF token:", error);
                     mw.notify("Xeletî çêbû", error);
                 });
        })
        .catch(error => {
            console.error("Error retrieving current page content:", error);
            mw.notify("Xeletî çêbû", error);
        });
}


		// Create the modal dialog
		const modal = $('<div>', {
			id: 'myModal',
			title: 'TemplateData',
			style: 'display: none;'
		});

		// Modal content area
		const modalContent = $('<div>', {
			id: 'modal-content'
		});
		modal.append(modalContent);

		// Append modal to the document body
		$(document.body).append(modal);

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

		// Define the function to handle the click event
		function handleTemplateDataClick(event) {
			event.preventDefault(); // Prevent the default action of following the link

			// Get the current page title
			var pageTitle = mw.config.get('wgPageName');

			// Call the getTemplateData function with the current page title
			getTemplateData(pageTitle);
		}

	if (mw.config.get('wgNamespaceNumber') === 10 ){
		// Create the link using mw.util.addPortletLink
		var targetContainer = mw.config.get('skin') === 'vector-2022' ? 'p-cactions' : 'p-tb';
		var link = mw.util.addPortletLink(targetContainer, '#', 'Deprecate params', 't-Deprecateparams', 'Deprecate params');

		// Attach an event listener to the link
		link.addEventListener('click', handleTemplateDataClick);
	}
	});
});