Bikarhêner:Balyozxane/test.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.
/** Ji [[fr:Mediawiki:Gadget-wikt.add-examples.js]] hatiye girtin.
* (fr)
* Ce gadget permet l’ajout d’exemples sans passer en mode édition. Un bouton pour
* ouvrir le formulaire devrait apparaitre à la fin de chaque série d’exemples pour
* chaque définition (seulement si le modèle [[Şablon:bêmînak]] / [[Şablon:jêgirtin?]] / [[Şablon:jêder]] est utilisé).
* ------------------------------------------------------------------------------------
* (en)
* This gadget allows to add examples without entering edit mode. A button to open the
* form should appear at the end of each series of examples for each definition
* (only if [[Şablon:bêmînak]] / [[Şablon:jêgirtin?]] / [[Şablon:jêder]] template is used).
* ------------------------------------------------------------------------------------
* v1.0 2021-09-12 Initial version
* v1.1 2021-09-16 Added input field for "lien" parameter.
* v1.1.1 2021-09-17 Fixed bug when text or translation contained the "=" sign.
* v1.1.2 2021-09-20 Restricted to main and “Reconstruction” namespaces.
* v1.2 2022-11-29 Better handling of multiline examples. Added checkbox to disable
* the translation. Link instead of button to show the form.
* ------------------------------------------------------------------------------------
* [[Catégorie:JavaScript du Wiktionnaire|add-examples.js]]
* <nowiki>
*/
// Polyfill Beşa li jêr ji [[:fr:MediaWiki:Gadget-CommonWikt.js]] hatiye girtin
if (!String.prototype.format) {
/**
* Formats a string.
* @param var_args {...Object} The list of values to insert into the string.
* @return {string} The formatted string.
*/
String.prototype.format = function(var_args) {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] !== "undefined" ? args[number] : match;
});
};
}
/*Beşa li jêr ji [[:fr:MediaWiki:Gadget-CommonWikt.js]] hatiye girtin
* Cookies
*/
window.wikt = window.wikt || {};
wikt.cookie = {};
/**
* Crée un cookie.
* @param name {string} Le nom du cookie.
* @param value {string} La valeur du cookie.
* @param days {number} La durée de vie en jours.
*/
function CommonWikt_AjouteCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + days * 86400000);
// noinspection JSUnresolvedFunction
document.cookie = "{0}={1}; expires={2}; path=/".format(name, value, date.toGMTString());
}
wikt.cookie.create = CommonWikt_AjouteCookie;
/**
* Lit la valeur d’un cookie.
* @param name {string} Le nom du cookie.
* @return {string|null} La valeur du cookie ou null s’il n’existe pas.
*/
function CommonWikt_LitCookie(name) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var valueIndex = cookie.indexOf(name + "=");
if (valueIndex >= 0) {
return cookie.substr(valueIndex + name.length + 1);
}
}
return null;
}
wikt.cookie.read = CommonWikt_LitCookie;
/**
* Supprime un cookie.
* @param name {string} Le nom du cookie.
*/
function CommonWikt_SupprimeCookie(name) {
wikt.cookie.create(name, "", -1);
}
wikt.cookie.delete = CommonWikt_SupprimeCookie;
$(function() {
"use strict";
if (mw.config.get("wgNamespaceNumber") !== 108 && mw.config.get("wgNamespaceNumber") !== 0 && mw.config.get("wgPageName") !== "Wîkîferheng:ceribandin") return;
console.log("Chargement de Gadget-wikt.add-examples.js…");
var NAME = "[[Mediawiki:Gadget-wikt.add-examples|Nimûne zêde bike]]";
var VERSION = "1.2";
var COOKIE_KEY_TEXT = "add_examples_text";
var COOKIE_KEY_SOURCE = "add_examples_source";
var COOKIE_KEY_SOURCE_URL = "add_examples_source_url";
var COOKIE_KEY_TRANSLATION = "add_examples_translation";
var COOKIE_KEY_TRANSCRIPTION = "add_examples_transcription";
var api = new mw.Api();
api.get({
action: "query",
titles: mw.config.get("wgPageName"),
prop: "revisions",
rvprop: "content",
rvslots: "main",
}).then(function(data) {
var pageContent;
for (var pageID in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageID)) {
// noinspection JSUnresolvedVariable
pageContent = data.query.pages[pageID].revisions[0].slots.main["*"];
break;
}
}
if (pageContent.includes("{{maneid")) {
console.log("Amûra 'Nimûne zêde bike' di rûpelên ku tê de 'maneid' hene, nikare were bikaranîn. (for now)");
return;
}
var languages = {};
var sectionNames = {
"Navdêr": ["Navdêr"],
"Formeke navdêrê": ["Formeke navdêrê"],
"Lêker": ["Lêker"],
"Formeke lêkerê": ["Formeke lêkerê"],
"Rengdêr": ["Rengdêr"],
"Formeke rengdêrê": ["Formeke rengdêrê"],
"Hoker": ["Hoker"],
"Formeke hokerê": ["Formeke hokerê"],
"Serenav": ["Serenav"],
"Formeke serenavê": ["Formeke serenavê"],
"Artîkel": ["Artîkel"],
"Baneşan": ["Baneşan"],
"Bazinedaçek": ["Bazinedaçek"],
"Biwêj": ["Biwêj"],
"Cînav": ["Cînav"],
"Daçek": ["Daçek"],
"Girêdek": ["Girêdek"],
"Gotineke pêşiyan": ["Gotineke pêşiyan"],
"Hejmar": ["Hejmar"],
"Hevok": ["Hevok"],
"Kurtenav": ["Kurtenav"],
"Navgir": ["Navgir"],
"Paşdaçek": ["Paşdaçek"],
"Paşgir": ["Paşgir"],
"Pêşdaçek": ["Pêşdaçek"],
"Pêşgir": ["Pêşgir"],
"Pirtik": ["Pirtik"],
"Reh": ["Reh"],
"Sembol": ["Sembol"],
"Tîp": ["Tîp"]
};
// Get names of all defined languages
api.get({
action: "query",
format: "json",
titles: "MediaWiki:Gadget-translation editor.js/ziman.json",
prop: "revisions",
rvprop: "content",
rvslots: "main",
}).then(function(data) {
for (var pageID in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageID)) {
// noinspection JSUnresolvedVariable
languages = JSON.parse(data.query.pages[pageID].revisions[0].slots.main["*"]);
break;
}
}
});
$("ul > li > .example").each(function() {
var $element = $(this);
var $item = $element.parent();
if (!$item.next().length) {
// Get example’s language
var language = $item.find("bdi[lang]")[0].lang;
if (language === "ku-Latn") {
language = "ku";
}
console.log('Language:', language);
// Get section and indices of associated definition
var definitionLevel = [];
var $definitionItem = $item.parent().parent();
var $topItem;
do {
definitionLevel.splice(0, 0, $definitionItem.index());
$topItem = $definitionItem;
$definitionItem = $definitionItem.parent().parent();
} while ($definitionItem.prop("tagName") === "LI");
var $section = $($topItem.parent().prevAll("h3").get(0)).find(".mw-headline");
definitionLevel.splice(0, 0, $section.attr("id"));
if (typeof definitionLevel === "undefined") {
return;
}
// Remove default edit link if present
var $defaultEditLink = $item.find("span.example > span.stubedit");
if ($defaultEditLink.length) {
$defaultEditLink.remove();
}
// Add a nice button to open the form
var $formItem = $("<li>");
var $button = $("<a href='#'>Nimûneyeke bikaranînê lê zêde bike</a>");
$button.css("color", "#777777");
$button.on("click", function() {
if (!$button.form) {
$formItem.append(new Form($item, $button, language, definitionLevel).$element);
console.log("$item", $item);
console.log("$button", $button);
console.log("language", language);
console.log("definitionLevel", definitionLevel);
}
$button.form.setVisible(true);
return false;
});
$item.after($formItem.append($button));
}
});
/**
* Constructor for the edit form.
* @param $lastExample {jQuery} The element corresponding to the example right above the button.
* @param $button {jQuery} The button that shows this form.
* @param language {string} Language for the example.
* @param definitionLevel {Array<string|number>} Indices of the associated definition.
* @constructor
*/
function Form($lastExample, $button, language, definitionLevel) {
var self = this;
this._language = language;
this._definitionLevel = definitionLevel;
this._$lastExample = $lastExample;
this._$button = $button;
this._$button.form = this;
this._textInput = new OO.ui.MultilineTextInputWidget();
var textInputLayout = new OO.ui.FieldLayout(this._textInput, {
label: "Nivîsa nimûneyê",
align: "top",
});
this._textInput.on("change", function(value) {
self._applyButton.setDisabled(!value);
});
this._sourceInput = new OO.ui.MultilineTextInputWidget();
var sourceInputLayout = new OO.ui.FieldLayout(this._sourceInput, {
label: "Çavkaniya nimûneyê",
align: "top",
});
this._sourceURLInput = new OO.ui.TextInputWidget();
var sourceURLInputLayout = new OO.ui.FieldLayout(this._sourceURLInput, {
label: "Adresa webê ya nimûneyê",
align: "top",
help: "Tenê binivîse ger girêdan jixwe di referansa çavkaniyê de tinebe.",
helpInline: true,
});
this._translationInput = new OO.ui.MultilineTextInputWidget();
var translationInputLayout = new OO.ui.FieldLayout(this._translationInput, {
label: "Wergera kurmancî ya nimûneyê",
align: "top",
});
this._transcriptionInput = new OO.ui.MultilineTextInputWidget();
var transcriptionInputLayout = new OO.ui.FieldLayout(this._transcriptionInput, {
label: "Transkrîpsiyona nimûneyê",
align: "top",
help: "Tenê lê zêde bike ger nivîsa di nimûneyê de bi alfabeya latînî nehatibe nivîsandin.",
helpInline: true,
});
this._applyButton = new OO.ui.ButtonWidget({
label: "Biweşîne",
title: "Nimûneyê ji bo vê tarîfê nimûneyê lê zêde bike",
flags: ["progressive", "primary"],
disabled: true,
});
this._applyButton.on("click", this.submit.bind(this));
this._cancelButton = new OO.ui.ButtonWidget({
label: "Betal bike",
title: "Formê bigire",
flags: ["destructive"],
});
this._cancelButton.on("click", function() {
self.setVisible(false);
});
this._loadingImage = new OO.ui.LabelWidget({
label: $('<img src="https://upload.wikimedia.org/wikipedia/commons/7/7a/Ajax_loader_metal_512.gif" alt="loading" style="width: 1.5em">'),
});
this._loadingImage.toggle(false);
var content = [textInputLayout, sourceInputLayout, sourceURLInputLayout];
if (language !== "ku") {
content.push(translationInputLayout, transcriptionInputLayout);
}
var fieldsLayout = new OO.ui.FieldsetLayout({
label: "Nimûneyeke bi " + (languages[this._language] || "zimanekî nenas") + " lê zêde dikî.",
items: content,
classes: ["add-example-fieldset"],
});
var buttonsLayout = new OO.ui.HorizontalLayout({
items: [
this._applyButton,
this._cancelButton,
this._loadingImage,
]
});
this._frame = new OO.ui.PanelLayout({
id: "add-example-definition-{0}-form".format(this._definitionLevel.join("-")),
classes: ["add-example-form"],
expanded: false,
content: [
fieldsLayout,
buttonsLayout,
],
});
}
Form.prototype = {
/**
* Returns the jQuery object for this form.
* @return {jQuery}
*/
get $element() {
return this._frame.$element;
},
/**
* Toggles the visibility of this form.
* @param visible {boolean}
*/
setVisible: function(visible) {
this._$button.toggle(!visible);
this._frame.toggle(visible);
if (visible) {
if (!this._textInput.getValue() && $.cookie(COOKIE_KEY_TEXT)) {
this._textInput.setValue($.cookie(COOKIE_KEY_TEXT));
}
if (!this._sourceInput.getValue() && $.cookie(COOKIE_KEY_SOURCE)) {
this._sourceInput.setValue($.cookie(COOKIE_KEY_SOURCE));
}
if (!this._sourceURLInput.getValue() && $.cookie(COOKIE_KEY_SOURCE_URL)) {
this._sourceURLInput.setValue($.cookie(COOKIE_KEY_SOURCE_URL));
}
if (!this._translationInput.getValue() && $.cookie(COOKIE_KEY_TRANSLATION)) {
this._translationInput.setValue($.cookie(COOKIE_KEY_TRANSLATION));
}
if (!this._transcriptionInput.getValue() && $.cookie(COOKIE_KEY_TRANSCRIPTION)) {
this._transcriptionInput.setValue($.cookie(COOKIE_KEY_TRANSCRIPTION));
}
}
},
/**
* Clears all fields contained in this forms.
*/
clear: function() {
this._textInput.setValue("");
this._sourceInput.setValue("");
this._sourceURLInput.setValue("");
this._translationInput.setValue("");
this._transcriptionInput.setValue("");
},
/**
* Generates and submits the wikicode then inserts the resulting HTML element if no errors occured.
*/
submit: function() {
var self = this;
self._textInput.setDisabled(true);
self._sourceInput.setDisabled(true);
self._sourceURLInput.setDisabled(true);
self._translationInput.setDisabled(true);
self._transcriptionInput.setDisabled(true);
// self._disableTranslationChk.setDisabled(true);
this._applyButton.setDisabled(true);
this._loadingImage.toggle(true);
var source = this._sourceInput.getValue().trim();
var sourceURL = this._sourceURLInput.getValue().trim();
var text = this._textInput.getValue().trim();
var minakAnNa, sablon;
if (source || sourceURL) {
minakAnNa = "*";
sablon = "jêder";
} else {
minakAnNa = ":";
sablon = "mk";
}
var listMarker = "".padStart(this._definitionLevel.length - 1, "#") + minakAnNa;
var title = mw.config.get('wgTitle');
//şablona jêder/mînak
var code = listMarker + " {{" + sablon;
// 1= koda zimanî
code += "|" + this._language;
//2= çavkanî
if (source) {
code += "|2=" + source;
}
if (sourceURL) {
code += "|url=" + sourceURL;
}
//jêgirtin/mînak
code += "|";
if (sablon === "jêder") {
code += "jêgirtin=";
}
//navê rûpelê bike stûr
code += text.replace(new RegExp("(" + title + "([^( |,|;|\?|\.|\!)]+)?)", "ig"), "'''$1'''");
if (this._language !== "ku") {
var translation = this._translationInput.getValue().trim();
var transcription = this._transcriptionInput.getValue().trim();
if (translation) {
code += "|werger=" + translation;
}
if (transcription) {
code += "|tr=" + transcription;
}
}
code += "}}";
// var escapedLangCode = languages[this._language].charAt(0).toUpperCase() + languages[this._language].slice(1);
// console.log("escapedLangCode: ", escapedLangCode);
var sectionIDPattern = new RegExp("^([\\wîêçş_]+?)_?(\\d+)?_?(\\d+)?$");
console.log("this._definitionLevel[0]: ", this._definitionLevel[0]);
var matchSectionID = sectionIDPattern.exec(this._definitionLevel[0]);
var isInflection;
var sectionType = matchSectionID[1].replace(/_/, ' ');
sectionType = sectionType.replace(/_\d+$/, '');
console.log("sectionType: ", sectionType);
var sectionNum = matchSectionID[2] ? parseInt(matchSectionID[2]) : "";
console.log("Section Number:", sectionNum);
// Insert new example into page’s code
api.get({
action: "query",
titles: mw.config.get("wgPageName"),
prop: "revisions",
rvprop: "content",
rvslots: "main",
}).then(function(data) {
var pageContent;
for (var pageID in data.query.pages) {
if (data.query.pages.hasOwnProperty(pageID)) {
// noinspection JSUnresolvedVariable
pageContent = data.query.pages[pageID].revisions[0].slots.main["*"];
break;
}
}
// Look for correct language section
var langSectionRegex = new RegExp("==\\s*{{ziman\\|{0}}}\\s*==".format(self._language));
var langSectionIndex = pageContent.search(langSectionRegex);
console.log("langSectionIndex:", langSectionIndex);
if (langSectionIndex === -1) {
console.log("langSectionIndex === -1");
error("Xeletiyeke bi koda zimanî heye. Koda zimanî:" + self._language);
return;
}
// Look for correct word type section
var lines = pageContent.slice(langSectionIndex).split("\n");
var sectionNamesRegex = Object.keys(sectionNames).join('|');
var sectionRegex = new RegExp('^===\\s(' + sectionNamesRegex + ')\\s*(\\d+)?');
var targetLineIndex;
for (targetLineIndex = 0; targetLineIndex < lines.length; targetLineIndex++) {
var line = lines[targetLineIndex];
console.log("line:", line);
var matchSection = sectionRegex.exec(line);
if (matchSection) {
console.log("matchSection:", matchSection[1]);
// Extract section name and number from the matched result
var matchedSectionName = matchSection[1];
var matchedSectionNum = matchSection[2]; // It could be undefined
if (!sectionNames[sectionType]) {
error('Navê beşê xelet e. Di beşên "Ji wêjêyê" û "Ji wêjêya klasîk" ev amûr nayê bikaranîn.');
return; // Exit the function
}
// Check if the matched section name is in the expected list
if (sectionNames[sectionType].includes(matchedSectionName)) {
// Check if the line includes the section number (if present)
if (!matchedSectionNum || line.includes(" " + matchedSectionNum)) {
// Add more conditions if needed for inflection, e.g., (isInflection === line.includes("Formeke "))
break;
}
}
}
}
if (targetLineIndex === lines.length) {
console.log("targetLineIndex === lines.length");
error("Di navê beşê de xeletî heye. Îhtimalen bi vî navê beşê çend heb hene.");
return;
}
// Look for correct definition
var defIndex = -1;
var level = 1;
for (; targetLineIndex < lines.length; targetLineIndex++) {
var m = /^(#+)[^*#:]/.exec(lines[targetLineIndex]);
console.log("lines[targetLineIndex]:", lines[targetLineIndex]);
if (m) {
console.log("m:", m);
if (level === m[1].length) {
console.log("m[1]:", m[1]);
defIndex++;
console.log("defIndex:", defIndex);
if (self._definitionLevel[level] === defIndex) {
console.log("self._definitionLevel[level] === defIndex");
console.log("self._definitionLevel[level]", self._definitionLevel[level]);
if (level === self._definitionLevel.length - 1) {
console.log("level:", level);
break;
} else {
level++;
defIndex = -1;
}
}
}
}
}
// Look for last example of current definition
var inExample = false;
var stack = 0;
for (targetLineIndex += 1; targetLineIndex < lines.length; targetLineIndex++) {
var line_ = lines[targetLineIndex];
// Check if the current line is a potential insertion point based on the template type
var isInsertionPoint = (
(line_.startsWith("#:") || line_.startsWith("#*")) &&
!line_.includes("{{hevmane") &&
!line_.includes("{{dijmane") &&
!line_.includes("{{jornav")
);
if (isInsertionPoint) {
// Insert new example based on the template type
if (sablon === "jêder") {
// Insert after the #: block or after all #*
while (targetLineIndex < lines.length && (lines[targetLineIndex].startsWith("#:") || lines[targetLineIndex].startsWith("#*"))) {
targetLineIndex++;
}
// Insert new example into page content
var emptyTemplate = /#+(\*|\:)\s*{{b?ê?(mînak|jêgirtin)\??\s*\|\s*\|?\s*[^|}]+}}/.test(lines[targetLineIndex - 1]);
if (emptyTemplate) {
console.log("empty Template found", sablon);
// Replace empty template with new example
lines.splice(targetLineIndex - 1, 1, code);
} else {
console.log("empty Template not found", sablon);
// Insert new example
lines.splice(targetLineIndex, 0, code);
}
} else if (sablon === "mk") {
// Insert before the #* and at the end of #: block
if (line_.startsWith("#*")) {
// Insert new example into page content
emptyTemplate = /#+(\*|\:)\s*{{b?ê?(mînak|jêgirtin)\??\s*\|\s*\|?\s*[^|}]+}}/.test(lines[targetLineIndex - 1]);
if (emptyTemplate) {
console.log("empty Template found", sablon);
// Replace empty template with new example
lines.splice(targetLineIndex - 1, 1, code);
} else {
console.log("empty Template not found", sablon);
// Insert new example
lines.splice(targetLineIndex, 0, code);
}
} else {
while (targetLineIndex < lines.length && lines[targetLineIndex].startsWith("#:")) {
targetLineIndex++;
}
// Insert new example into page content
emptyTemplate = /#+(\*|\:)\s*{{b?ê?(mînak|jêgirtin)\??\s*\|\s*\|?\s*[^|}]+}}/.test(lines[targetLineIndex - 1]);
if (emptyTemplate) {
console.log("empty Template found", sablon);
// Replace empty template with new example
lines.splice(targetLineIndex - 1, 1, code);
} else {
console.log("empty Template not found", sablon);
// Insert new example
lines.splice(targetLineIndex, 0, code);
}
}
}
break; // Break out of the loop after inserting the example
}
}
// Submit new page content
api.edit(mw.config.get("wgPageName"), function(_) {
return {
text: pageContent.slice(0, langSectionIndex) + lines.join("\n"),
summary: "+nimûneya bikaranînê bi amûra «\u00a0{0}\u00a0» (v{1}).".format(NAME, VERSION),
};
}).then(function() {
api.parse(code).done(function(data) {
var $renderedExample = $(data).find("ul > li").html();
var $item;
// Insert rendered example into page
if (emptyTemplate) {
self._$lastExample.html($renderedExample);
$item = self._$lastExample;
} else {
self._$lastExample.after($item = $("<li>").append($renderedExample));
}
$item.css("background-color", "lightgreen");
setTimeout(function() {
$item.css("background-color", "inherit");
}, 1000);
self._$lastExample = $item;
});
self.setVisible(false);
self.clear();
$.removeCookie(COOKIE_KEY_TEXT);
$.removeCookie(COOKIE_KEY_SOURCE);
$.removeCookie(COOKIE_KEY_SOURCE_URL);
$.removeCookie(COOKIE_KEY_TRANSLATION);
$.removeCookie(COOKIE_KEY_TRANSCRIPTION);
reenable();
});
});
function error(errorMessage) {
mw.notify(errorMessage || "Nimûne nehat weşandin, îhtimalen rûpel hate guhartin. Ji kerema xwe re rûpelê dîsa bar bike û dîsa biceribîne.");
$.cookie(COOKIE_KEY_TEXT, self._textInput.getValue());
$.cookie(COOKIE_KEY_SOURCE, self._sourceInput.getValue());
$.cookie(COOKIE_KEY_SOURCE_URL, self._sourceURLInput.getValue());
$.cookie(COOKIE_KEY_TRANSLATION, self._translationInput.getValue());
$.cookie(COOKIE_KEY_TRANSCRIPTION, self._transcriptionInput.getValue());
reenable();
}
function reenable() {
self._textInput.setDisabled(false);
self._sourceInput.setDisabled(false);
self._sourceURLInput.setDisabled(false);
self._translationInput.setDisabled(false);
self._transcriptionInput.setDisabled(false);
// self._disableTranslationChk.setDisabled(false);
self._applyButton.setDisabled(false);
self._cancelButton.setDisabled(false);
self._loadingImage.toggle(false);
}
},
};
});
});
// </nowiki>