Bikarhêner:Balyozxane/CreateTranslation.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>
// Kurdish alphabet
const kurdishAlphabet = "ABCCÇDEÊFGHIÎJKLÎMNOPQRSŞTUÛVWXYZabccçdeêfghiîjklîmnopqrsştuûvwxyzǃǀǁǂ";
function customSort(langNameA, langNameB) {
langNameA = langNameA.toLowerCase();
langNameB = langNameB.toLowerCase();
const minLength = Math.min(langNameA.length, langNameB.length);
for (let i = 0; i < minLength; i++) {
const indexA = kurdishAlphabet.indexOf(langNameA[i]);
const indexB = kurdishAlphabet.indexOf(langNameB[i]);
if (indexA < indexB) {
return -1;
} else if (indexA > indexB) {
return 1;
}
}
return langNameA.length - langNameB.length;
}
function page_exists(lang_code, page) {
var domain;
var wm_liens = {
'cmn': 'zh',
'fra-nor': 'nrm',
'gsw': 'als',
'ko-Hani': 'ko',
'lzh': 'zh-classical',
'nan': 'zh-min-nan',
'nb': 'no',
'rup': 'roa-rup',
'yue': 'zh-yue',
};
var wiktios = [
'en', 'mg', 'fr', 'zh', 'lt', 'ru', 'es', 'el', 'pl', 'sv', 'ko',
'nl', 'de', 'tr', 'ku', 'ta', 'io', 'kn', 'fi', 'vi', 'hu', 'pt',
'chr', 'no', 'ml', 'my', 'id', 'it', 'li', 'ro', 'et', 'ja', 'te',
'jv', 'fa', 'cs', 'ca', 'ar', 'eu', 'gl', 'lo', 'uk', 'br', 'fj',
'eo', 'bg', 'hr', 'th', 'oc', 'is', 'vo', 'ps', 'zh-min-nan',
'simple', 'cy', 'uz', 'scn', 'sr', 'af', 'ast', 'az', 'da', 'sw',
'fy', 'tl', 'he', 'nn', 'wa', 'ur', 'la', 'sq', 'hy', 'sm', 'sl',
'ka', 'pnb', 'nah', 'hi', 'tt', 'bs', 'lb', 'lv', 'tk', 'sk', 'hsb',
'nds', 'kk', 'ky', 'be', 'km', 'mk', 'ga', 'wo', 'ms', 'ang', 'co',
'sa', 'gn', 'mr', 'csb', 'ug', 'st', 'ia', 'sd', 'sh', 'si', 'mn',
'tg', 'or', 'kl', 'vec', 'jbo', 'an', 'ln', 'fo', 'zu', 'gu', 'kw',
'gv', 'rw', 'qu', 'ss', 'ie', 'mt', 'om', 'bn', 'pa', 'roa-rup',
'iu', 'so', 'am', 'su', 'za', 'gd', 'mi', 'tpi', 'ne', 'yi', 'ti',
'sg', 'na', 'dv', 'tn', 'ts', 'ha', 'ks', 'ay',
];
var keepApos = [
'fr', 'de',
];
if (wm_liens.hasOwnProperty(lang_code)) {
domain = wm_liens[lang_code] + '.wiktionary';
} else if (lang_code === 'navz') {
domain = 'species.wikimedia';
} else if ($.inArray(lang_code, wiktios) !== -1) {
domain = lang_code + '.wiktionary';
}
// Si le Wiktionnaire n'existe pas, inutile de faire une requête HTTP
if (!domain) {
return Promise.resolve(false);
}
// traiter l'apostrophe typographique comme une apostrophe dactylographique
// dans les liens interwikis, les autres wiktionnaires privilégiant la seconde
if ($.inArray(lang_code, keepApos) === -1) {
page = page.replace('’', "'");
page = page.replace('ʼ', "'");
}
// Check if rupelaNu starts with "^" and remove it
if (page.startsWith("^")) {
page = page.replace(/\^/g, '');
}
return new Promise(function(resolve, reject) {
$.ajax({
url: '//' + domain + '.org/w/api.php?origin=' + location.protocol + '//' + location.host,
data: {
action: 'query',
titles: page,
format: 'json'
},
dataType: 'json'
}).fail(function() {
resolve(false);
}).then(function(data) {
// If the AJAX request succeeds, check if the page exists in the API response.
// If it exists, resolve the promise with true (indicating existence).
// Otherwise, resolve the promise with false (indicating non-existence).
resolve(data.query.pages[-1] ? false : true);
});
});
}
function checkPageExistence(page) {
const apiUrl = 'https://ku.wiktionary.org/w/api.php';
const params = new URLSearchParams({
action: 'query',
titles: page,
format: 'json',
origin: '*'
});
return fetch(`${apiUrl}?${params}`)
.then(response => response.json())
.then(data => {
const pages = data.query.pages;
const pageId = Object.keys(pages)[0];
return pageId !== '-1'; // If pageId is not -1, the page exists
})
.catch(error => {
console.error('An error occurred:', error);
return false;
});
}
function editWikiPage(pageTitle, newWikicode, langCode, callback) {
const priorityLangs = ["ku", "kmr", "navz", "ckb", "lki", "sdh", "zza"];
if (!pageTitle) {
console.log("No page name provided. Editing cancelled.");
callback("Ti ziman nehat dîtin. Guhartin betal kir.");
return;
}
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: pageTitle,
rvprop: "content",
format: "json"
});
fetch(apiUrl + "?" + params.toString())
.then(response => response.json())
.then(data => {
try {
const pageId = Object.keys(data.query.pages)[0];
const content = data.query.pages[pageId].revisions[0]['*'];
const zimanCheck = new RegExp(`==\\s*?{{ziman\\|${langCode}}}\\s*?==`);
if (zimanCheck.test(content)) {
callback(new Error(`Di rûpelê de beşeke bi zimanê '${langCode}' jixwe heye.`));
mw.notify(`Di rûpelê de beşeke bi zimanê '${langCode}' jixwe heye.`);
return;
}
const sections = content.split(/(?=== \{\{ziman\|[a-z-]+\}\} ==)/); // Split by section headers
let sortedSections = [];
let addedTopSections = false;
for (let i = 0; i < sections.length; i++) {
const langMatch = sections[i].match(/\{\{ziman\|([a-z-]+)\}\}/);
if (!langMatch) {
sortedSections.push(sections[i]);
continue;
}
const lang = langMatch[1];
if (!addedTopSections && priorityLangs.includes(lang)) {
sortedSections.push({
lang,
content: sections[i]
});
} else {
addedTopSections = true;
sortedSections.push({
lang,
content: sections[i]
});
}
}
async function insertAndSort() {
await insertNewSection(sortedSections, newWikicode, langCode, priorityLangs);
const sortedContent = await sortSections(sortedSections, priorityLangs);
const editedContent = sortedContent.join("\n\n");
const rupel = mw.config.get('wgPageName').replace(/_/g, " ");
const summary = "+" + langCode + ":" + pageTitle + " Bi [[Bikarhêner:Balyozxane/CreateTranslation.js|amûrê]] ji wergerên [[" + rupel + "]]";
const editParams = new URLSearchParams({
action: "edit",
title: pageTitle,
text: editedContent,
token: editToken,
summary: summary, // Add summary
format: "json"
});
fetch(apiUrl, {
method: "POST",
body: editParams
})
.then(response => response.json())
.then(data => {
if (data.edit.result === "Success") {
console.log("Guhartina rûpelê bi ser ket: +" + langCode + ":" + pageTitle)
callback(null);
} else {
console.error("Têkçûyîna guhartina rûpelê.");
callback("Têkçûyîna guhartina rûpelê.");
}
})
.catch(error => {
console.error("An error occurred during editing:", error);
callback("Xeletiyek di guhartina rûpelê de çêbû.");
});
}
insertAndSort().catch(error => {
console.error("An error occurred during insertion:", error);
callback("Xeletiyek di lêzêdekirina zimanî de çêbû.");
});
} catch (error) {
console.error("An error occurred during page content retrieval:", error);
callback("Xeletiyek di wergera zimanan de çêbû.");
}
})
.catch(error => {
console.error("An error occurred during API request:", error);
callback("Xeletiyek di pirsîna API de çêbû.");
});
})
.catch(error => {
console.error("An error occurred during token retrieval:", error);
callback("Xeletiyek di qonaxa guhartinê de çêbû.");
});
}
function insertNewSection(sortedSections, newWikicode, langCode, priorityLangs) {
// Insert the new section at the appropriate position
let insertionIndex = sortedSections.length;
for (let i = 0; i < sortedSections.length; i++) {
const langMatch = sortedSections[i].content.match(/\{\{ziman\|([a-z-]+)\}\}/);
if (langMatch) {
const lang = langMatch[1];
if (!priorityLangs.includes(lang)) {
insertionIndex = i;
break;
}
}
}
sortedSections.splice(insertionIndex, 0, {
lang: langCode,
content: newWikicode
});
}
function fetchLanguageName(langCode) {
return new Promise(function(resolve, reject) {
$.ajax({
url: "https://ku.wiktionary.org/w/index.php?title=MediaWiki:Gadget-translation editor.js/ziman.json&action=raw",
dataType: "json",
success: function(data) {
if (data.hasOwnProperty(langCode)) {
resolve(data[langCode]);
} else {
reject("Language code not found: " + langCode);
}
},
error: function(xhr, status, error) {
reject(error);
}
});
});
}
async function sortSections(sortedSections, priorityLangs) {
await Promise.all(sortedSections.map(async section => {
const langMatch = section.content.match(/\{\{ziman\|([a-z-]+)\}\}/);
if (langMatch) {
const lang = langMatch[1];
section.lang = lang; // Store the lang code in the section object
try {
const canonicalName = await fetchLanguageName(lang);
section.canonicalName = canonicalName;
} catch (error) {
console.error("Error fetching language name:", error);
// Handle the error as needed, e.g., set a default value for section.canonicalName
}
}
}));
sortedSections.sort((sectionA, sectionB) => {
// If either section contains a priorityLang, preserve their relative order
if (priorityLangs.includes(sectionA.lang) || priorityLangs.includes(sectionB.lang)) {
return 0;
}
if (sectionA.canonicalName && sectionB.canonicalName) {
return customSort(sectionA.canonicalName, sectionB.canonicalName);
}
return 0;
});
return sortedSections.map(section => section.content.trim());
}
function removeDiacritics(lang, word) {
var api = new mw.Api();
return api.get({
action: 'expandtemplates',
format: 'json',
text: `{{#invoke:ziman/şablon|makeEntryName|${lang}|${word}}}`,
prop: 'wikitext'
}).then(function(data) {
return data.expandtemplates.wikitext;
});
}
function createNewWikicode(page, translation, langCode, wordtype, mane, transcription, dif, label, gender, mijarCheckbox, script) {
var newWikicode = "== {{ziman|" + langCode + "}} ==\n\n";
var capitalizedWordtype = wordtype.charAt(0).toUpperCase() + wordtype.substring(1);
var lowerWordtype = wordtype.charAt(0).toLowerCase() + wordtype.substring(1);
newWikicode += "=== " + capitalizedWordtype + " ===\n";
newWikicode += "{{" + lowerWordtype + "|" + langCode;
if (dif && dif.length > 0)
newWikicode += "|" + dif;
if (transcription && transcription.length > 0)
newWikicode += "|tr=" + transcription;
if (script && script.length > 0)
newWikicode += "|sc=" + script;
if ((lowerWordtype === "navdêr" || lowerWordtype === "serenav") && (gender === "n" || gender === "m" || gender === "nt") && gender.length > 0)
newWikicode += "|z=" + gender;
newWikicode += "}}";
newWikicode += "\n";
if (label.length > 0) {
if (mijarCheckbox) {
newWikicode += "# {{mijar|" + langCode + "|" + label + "}} ";
} else {
newWikicode += "# {{f|" + langCode + "|" + label + "}} ";
}
newWikicode += mane;
} else {
newWikicode += "# " + mane;
}
newWikicode += "\n#* {{bêmînak|" + langCode + "}}\n\n";
newWikicode += "=== Çavkanî ===\n{{rûpela wergerê|" + langCode + "|" + page + "}}";
newWikicode += "\n\n";
return newWikicode;
}
$(document).ready(function() {
// Find all translation sections
var translationSections = $('.translations');
// Add a button before each translation section
translationSections.each(function(index) {
var translationSection = $(this);
var buttonNumber = index + 1;
// Add a button before the translation section
var buttonHTML = '<button class="startProcessBtn" data-section="' + index + '">Hemû Çêke ' + buttonNumber + '</button>';
translationSection.prepend(buttonHTML);
});
// Attach a click event handler to the button
$(document).on('click', '.startProcessBtn', function() {
var button = $(this);
var sectionIndex = button.data('section');
var translationSection = translationSections.eq(sectionIndex);
if (button.hasClass('cancelBtn')) {
// Revert back to the start state
translationSection.find('.wordTypeForm').remove();
button.removeClass('cancelBtn').text('Hemû Çêke');
} else {
// Create and show the form
var rupelMane = mw.config.get('wgPageName').replace(/_/g, " ");
newRupelMane = '{{g|ku|' + rupelMane + '}}';
var formHTML = '<form class="wordTypeForm">' +
' <label for="wordType">Cureyê peyvê hilbijêre:</label>' +
' <select id="wordType" name="wordType">' +
' <option value="Navdêr">Navdêr</option>' +
' <option value="Lêker">Lêker</option>' +
' <option value="Serenav">Serenav</option>' +
' <option value="Rengdêr">Rengdêr</option>' +
' <option value="Hoker">Hoker</option>' +
' <option value="Cînav">Cînav</option>' +
' <option value="Artîkel">Artîkel</option>' +
' <option value="Baneşan">Baneşan</option>' +
' <option value="Bazinedaçek">Bazinedaçek</option>' +
' <option value="Biwêj">Biwêj</option>' +
' <option value="Daçek">Daçek</option>' +
' <option value="Girêdek">Girêdek</option>' +
' <option value="Gotineke pêşiyan">Gotineke pêşiyan</option>' +
' <option value="Hejmar">Hejmar</option>' +
' <option value="Hevok">Hevok</option>' +
' <option value="Kurtenav">Kurtenav</option>' +
' <option value="Navgir">Navgir</option>' +
' <option value="Paşdaçek">Paşdaçek</option>' +
' <option value="Paşgir">Paşgir</option>' +
' <option value="Pêşdaçek">Pêşdaçek</option>' +
' <option value="Pêşgir">Pêşgir</option>' +
' <option value="Pirtik">Pirtik</option>' +
' <option value="Reh">Reh</option>' +
' <option value="Sembol">Sembol</option>' +
' <option value="Tîp">Tîp</option>' +
' </select>' +
' <label for="mane">Maneya wergerê:</label>' +
' <input type="text" id="mane" name="mane" value="' + newRupelMane + '">' +
' <label for="label">Etîket:</label>' +
' <input type="text" id="label" name="label">' +
' <label for="mijarCheckbox">Etîketê veşêre?</label>' +
' <input type="checkbox" id="mijarCheckbox" name="mijarCheckbox">' +
' <button type="submit">Bişîne</button>' +
'</form>';
translationSection.prepend(formHTML);
button.addClass('cancelBtn').text('Betal bike');
document.getElementById('mane').style.width = "400px";
}
});
$(document).on('submit', '.wordTypeForm', function(event) {
event.preventDefault();
var form = $(this);
var translationSection = form.closest('.translations');
var button = translationSection.find('.startProcessBtn');
var wordType = form.find('#wordType').val();
var mane = form.find('#mane').val();
var label = form.find('#label').val();
var mijarCheckbox = form.find('#mijarCheckbox').prop('checked'); // Check if the checkbox is checked
// Show confirmation alert
var confirmationText = "Bi rastî dixwazî rûpelê bi van agahiyan çêkî?:\n\n" +
"Cureyê peyvê: " + wordType + "\n" +
"Maneya wergerê: " + mane + "\n" +
"Etîket: " + label;
if (window.confirm(confirmationText)) {
initiateTranslationProcess(translationSection, wordType, mane, label, mijarCheckbox);
// Hide the form after confirmation
form.remove();
button.removeClass('cancelBtn').text('Hemû Çêke');
}
});
// Function to initiate the translation process
function initiateTranslationProcess(translationSection, wordType, mane, label, mijarCheckbox) {
// Create the progress indicator element
var progressIndicator = $('<div id="progressIndicator" style="display: none;">Werger tên çêkirin... <span id="progressCount">0</span> / <span id="totalCount">0</span></div>');
var loadingSpinner = $('<div class="loading-spinner"></div>');
progressIndicator.prepend(loadingSpinner);
// prepend the progress indicator to the translation section
translationSection.prepend(progressIndicator);
// Fetch and process translations from the specified section
fetchAndProcessTranslations(translationSection, wordType, mane, label, mijarCheckbox);
}
function fetchAndProcessTranslations(translationSection, wordType, mane, label, mijarCheckbox) {
var sectionIndex = $('.translations').index(translationSection);
var currentPageTitle = mw.config.get('wgPageName');
var apiUrl = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php';
$.ajax({
url: apiUrl,
method: 'GET',
data: {
action: 'query',
format: 'json',
prop: 'revisions',
titles: currentPageTitle,
rvprop: 'content'
},
success: function(data) {
var pages = data.query.pages;
var currentPage = pages[Object.keys(pages)[0]];
var content = currentPage.revisions[0]['*'];
var wergerPattern = /\{\{werger-ser.*?\}\}(.*?)\{\{werger-bin\}\}/gs;
var matches;
var currentIndex = 0;
var newTranslation;
var translationWithoutDiacritics;
while ((matches = wergerPattern.exec(content)) !== null) {
if (currentIndex === sectionIndex) {
var sectionContent = matches[1];
var templatePattern = /\{\{W[-+]*\|([^|]+)\|([^|}]*)?\|?(.*?)(?=\}\})\}\}/g;
var innerMatches;
var translations = [];
while ((innerMatches = templatePattern.exec(sectionContent)) !== null) {
var langCode = innerMatches[1];
var translation = innerMatches[2];
var argumentString = innerMatches[3] || '';
var args = argumentString.split('|');
var gender = null;
var transliteration = null;
var dif = null;
var script = null;
args.forEach(arg => {
if (arg.startsWith('tr=')) {
transliteration = arg.substr(3);
} else if (arg.startsWith('cuda=')) {
dif = arg.substr(5);
} else if (arg.startsWith('sc=')) {
script = arg.substr(3);
} else {
gender = arg;
}
});
translations.push({
langCode: langCode,
translation: translation,
gender: gender,
transliteration: transliteration,
dif: dif,
script: script
});
}
if (translations.length > 0) {
console.log("Found translations:", translations);
var totalCount = translations.length;
$('#totalCount').text(totalCount);
$('#progressIndicator').show(); // Show the progress indicator
var translationsList = [];
translations.forEach(function(translation) {
// Apply removeDiacritics to the translation and check if diacritics were removed
removeDiacritics(translation.langCode, translation.translation).then(function(result) {
if (translation.translation !== result) {
// Diacritics were removed, set the dif to the translation with diacritics
translation.dif = translation.translation;
} else {
// No diacritics were removed, set dif to null
translation.dif = null;
}
// Add the translation to the list
translationsList.push(translation);
if (translationsList.length === translations.length) {
// All translations are processed, start processing sequentially
processTranslationsSequentially(translationsList, 0, wordType, mane, label, mijarCheckbox);
}
});
});
}
break;
}
currentIndex++; // Move to the next section
}
if (currentIndex !== sectionIndex) {
console.log("Beş tune ye.");
}
},
error: function(xhr, status, error) {
console.error('Error fetching page content:', error);
}
});
}
var activeTimeout = null; // Track the active timeout for notifications
function processTranslationsSequentially(translationsList, currentIndex, wordType, mane, label, mijarCheckbox) {
if (currentIndex < translationsList.length) {
var translation = translationsList[currentIndex];
console.log('Creating translation page for:', translation.translation);
var page = mw.config.get('wgPageName').replace(/_/g, " ");
try {
var newWikicode = createNewWikicode(
page,
translation.translation,
translation.langCode,
wordType,
mane,
translation.transliteration,
translation.dif, // Use translation without diacritics as page title
label,
translation.gender,
mijarCheckbox,
translation.script
);
createTranslationPage(translation.translation, translation.langCode, newWikicode, function(error) {
if (error) {
// Handle the error (e.g., display a message)
console.error('Error creating translation page:', error);
mw.notify('Xeletî di çêkirina rûpelê de çêbû:', error);
} else {
// Handle success (e.g., display a success message)
console.log('Translation page created successfully:', translation.translation);
}
// Move to the next translation
setTimeout(function() {
$('#progressCount').text(currentIndex + 1); // Update the progress count
processTranslationsSequentially(translationsList, currentIndex + 1, wordType, mane, label, mijarCheckbox);
}, 100); // Wait for 0.1 seconds before moving to the next translation
});
} catch (error) {
// Handle the error (e.g., display a message)
console.error('Error processing translation:', error);
// Move to the next translation
setTimeout(function() {
$('#progressCount').text(currentIndex + 1); // Update the progress count
processTranslationsSequentially(translationsList, currentIndex + 1, wordType, mane, label, mijarCheckbox);
}, 100); // Wait for 0.1 seconds before moving to the next translation
}
} else {
// All translations are processed
console.log('Hemû werger hatin çêkirin.');
mw.notify('Hemû werger hatin çêkirin.', {
tag: 'all-translations-processed'
});
$('#progressIndicator').hide(); // Hide the progress indicator after all translations are created
}
}
function createTranslationPage(translation, langCode, newWikicode, callback) {
var rupel = mw.config.get('wgPageName').replace(/_/g, " ");
// Remove diacritics from the translation
removeDiacritics(langCode, translation).then(function(translationWithoutDiacritics) {
var rupelaNu = translationWithoutDiacritics;
// Check if rupelaNu starts with "^" and remove it
if (rupelaNu.startsWith("^")) {
rupelaNu = rupelaNu.replace(/\^/g, '');
}
var summary = "+" + langCode + ":" + rupelaNu + " Bi [[Bikarhêner:Balyozxane/CreateTranslation.js|amûrê]] ji wergerên [[" + rupel + "]]";
page_exists("en", rupelaNu).then(function(enpageExists) {
page_exists(langCode, rupelaNu).then(function(pageExists) {
if (!(enpageExists || pageExists)) {
// Notify that translation does not exist
mw.notify("[[" + langCode + ":" + rupelaNu + "]] li ser wîkiya îngilîzî an jî ya zimanê xwe tine ye.");
callback(null);
} else {
// User-provided page name
checkPageExistence(rupelaNu).then(exists => {
if (exists) {
editWikiPage(rupelaNu, newWikicode, langCode, function(error) {
if (error) {
mw.notify("Xeletî di guhartina rûpelê de çêbû", error);
callback(error); // Call the callback function with the error
} else {
mw.notify("Guhartina rûpelê bi ser ket! " + langCode + ":" + rupelaNu);
callback(null); // Call the callback function with no error
}
});
} else {
// Create the translation page using AJAX
var api = new mw.Api();
api.postWithToken('csrf', {
action: 'edit',
title: rupelaNu,
text: newWikicode,
summary: summary,
createonly: true
}).done(function(data) {
// Page saved successfully
mw.notify("Rûpel hat çêkirin: +" + langCode + ":" + rupelaNu);
console.log('Page saved successfully:', data);
callback(null); // Call the callback function with no error
}).fail(function(err) {
// Error occurred while saving the page
console.error('Error while saving the page:', err);
callback(err); // Call the callback function with the error
});
console.log('The page does not exist on Kurdish Wiktionary.');
}
});
}
});
});
});
}
});
//</nowiki>