Jump to content

User:Redaking/ArticleTranslator.js: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Redaking (talk | contribs)
No edit summary
Tags: Reverted Disambiguation links added
Redaking (talk | contribs)
No edit summary
Line 1: Line 1:
//[[:en:User:Ebraminio/ArticleTranslator.js]]; [[ويكيبيديا:الميدان/تقنية/05/2012#مترجم]]
// <nowiki> DO NOT COPY IT FOR TRANSLATION, READ THE DOCUMENTATION [[:en:User talk:Ebraminio/ArticleTranslator.js]]
/*global jQuery, mediaWiki*/
// <nowiki>
(function ($, mw) {
/*jslint regexp: true */
'use strict';
/*browser: true*/
/*global $: false, wgNamespaceNumber: false, wgAction: false, mw: false,
wgScriptPath: false, wgPageContentLanguage: false, window: false */


// prevent double execution of the tool
if (window.globalTranslatorConfigs === undefined) {
if (window.isArticletranslatorInitialized && location.hash === '#tofawikiframe') { return; }
var globalTranslatorConfigs = {
window.isArticletranslatorInitialized = true;
'homeWiki': window.homeWiki,
'fromLang': window.fromLang,
'translatorBarFormat': window.translatorBarFormat,
'templateTranslatorText': window.templateTranslatorText,
'removeLinksAliasesText': window.removeLinksAliasesText,
'doneText': window.doneText
};
}


var action = mw.config.get('wgAction');
var translatorConfigs = {
if (action === 'history') {
'homeWiki': 'arz',
return;
'fromLang': 'en',
}
'translatorBarFormat': '$1ترجم$2 الوصلات $4&nbsp;⇒&nbsp;$3',
'templateTranslatorText': 'ترجم القوالب',
'removeLinksAliasesText': 'أخف عناوين الوصلات',
'doneText': 'تم',
'enableTemplateTranslation': true,
'removeLinksAliases': true,
'enableNeedingShow': false,
'name': 'اسم الصفحة',
'interwikiCount': 'عدد وصلات اللغات فيها',
'linkedTo': 'عدد الوصلات فيها',
'listOfUnavailablePagesOn': 'الصفحات غير الموجودة في '
};


var conf = {
$.extend(translatorConfigs, globalTranslatorConfigs);
homeWiki: 'arz',
fromLang: mw.config.get('wgPageContentLanguage'),
translatorBarFormat: '$1translate$2 links from $3 to $4 $5',
templateTranslatorText: 'Template translation',
removeLinksAliasesText: 'Remove Links Aliases',
enableTemplateTranslation: true,
removeLinksAliases: true,
name: 'Name',
interwikiCount: 'Language links count',
linkedTo: 'Linked to',
listOfUnavailablePagesOn: 'List of not present pages on',
definedTemplates: ['Flag icon', 'flagicon', 'Flag', 'Portal', 'About', 'ADB', 'Alsoknown', 'Alternateuses', 'Cat main',
'Cat main article', 'Category disambiguation', 'Category main', 'Catmain', 'Consider disambiguation', 'Contrast',
'Dabprefixes', 'Detail', 'Details', 'Disambiguation needed', 'Distinguish', 'Distinguish2', 'For', 'For other uses',
'For2', 'In title', 'Introductory article', 'Look from', 'Main', 'Main cat', 'Main category', 'Maincat', 'More', 'Moredetails',
'Navbox hatnote *Templates', 'Other', 'Other hurricanes', 'Other meanings', 'Other people', 'Other people2', 'Other people3',
'Other people5', 'Other places', 'Other places3', 'Other ships', 'Other use', 'Other uses', 'Other uses of', 'Other uses1',
'Other uses2', 'Other uses-section', 'Othermeanings', 'Otheruse', 'OtherUses', 'Otheruses1', 'Otheruses3', 'OtherusesSubtopic',
'Othervalues', 'Outline', 'Previously', 'Redirect', 'Redirect10', 'Redirect2', 'Redirect3', 'Redirect4', 'Redirect6', 'Redirect-distinguish2',
'Redirect-synonym', 'See introduction', 'See Wiktionary', 'Seesubarticle', 'Selfref', 'Srlink', 'Surname links', 'Technical reasons',
'Template ambiguous', 'Template shortcut', 'This user talk', 'Three other uses', 'Two other uses', 'WikiProject Disambiguation'],
blacklistedTemplatePattern: /Template:(cite|citation|infobox) [a-z]+/i,
};


$.extend(conf, window.articleTranslatorConf);
// getting the last translator preference from the cookie
if ($.cookie('homeWiki') !== null) {
translatorConfigs.homeWiki = $.cookie('homeWiki');
}


// getting the last translator preference from the cookie
if ($.cookie('fromLang') !== null) {
translatorConfigs.fromLang = $.cookie('fromLang');
if ($.cookie && $.cookie('homeWiki') !== null) { conf.homeWiki = $.cookie('homeWiki'); }
if ($.cookie && $.cookie('fromLang') !== null) { conf.fromLang = $.cookie('fromLang'); }
}
//
function translate(links, showMissings) {
// unique titles
links = Object.keys(links.reduce(function (object, item) {
object[item] = true;
return object;
}, {}));
var request = {
from: conf.fromLang,
to: conf.homeWiki,
missings: !!showMissings,
p: links.join('|')
};
// https://github.com/ebraminio/linkstranslator
return $.post('https://tools.wmflabs.org/linkstranslator/', request).then(null, function () {
return $.post('https://fa-tts.wmflabs.org/linkstranslator/', request);
});
}


function hasNotPersianCharacter(x) {
// Regexp.escape() from: http://80.68.89.23/2006/Jan/20/escape/
return !/[كﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴً-ِْٰء-ٕپچژگکكڪﻙﻚیﻱﻲٔ۱۲۳۴۵۶۷۸۹۰]/.test(x);
RegExp.escape = function (text) {
}
'use strict';
return text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
};


function Translator() {
function editboxTranslator() {
var translationTextArea;
'use strict';


if (conf.fromLang === mw.config.get('wgPageContentLanguage')) {
var translationTextArea,
$('#wpTextbox2').remove();
progressCount,
translationTextArea = $('#wpTextbox1').clone().attr({
itemsCount,
'id': 'wpTextbox2'
ajaxUrl;
}).css({
'background-color': '#CCCEFF'
}).val($('#wpTextbox1').val());
$('#wpTextbox1').before(translationTextArea);
} else {
translationTextArea = $('#wpTextbox1');
}
var raw = translationTextArea.val();
if (raw.match(/\{\{(Navbox|Sidebar|Campaignbox)/)) {
raw = raw.replace(/(\|\s*name\s*=\s*)([^\n\|\}]*)/, '$1' + mw.config.get('wgTitle'));
}
$.Deferred().resolve().then(function () {
var links = (raw.match(/\[\[.*?[|\]]/g) || []).map(function (x) { return x.split(/\[\[:?/)[1].split(/[|\]]/)[0]; });


if (links.length === 0) {
function getOrigin() {
return;
var result = window.location.protocol + '//' + window.location.host;
}
if (window.location.port !== '') {
result = result + ':' + window.location.port;
}
return result;
}


if (conf.homeWiki === 'arz') {
function getOriginOfWikiLang(lang) {
links = links.filter(hasNotPersianCharacter);
return getOrigin().replace(mw.config.get('wgPageContentLanguage'), lang);
}
}


function setAjaxUrl() {
return translate(links).then(function (result) {
Object.keys(result).forEach(function (from) {
var tailOfApiUrl = '/api.php?action=query&prop=langlinks&redirects=&format=json&lllimit=500&titles=';
raw = raw.replace(
if (translatorConfigs.enableNeedingShow === true) {
new RegExp('(\\[\\[:?)' + mw.RegExp.escape(from) + '((?:\\|[^\\]]*)?)(\\]\\])', 'g'),
tailOfApiUrl = '/api.php?action=query&prop=langlinks|links&redirects=&format=json&pllimit=500&lllimit=500&titles=';
'$1' + result[from] + (conf.removeLinksAliases ? '' : '$2') + '$3'
}
);
ajaxUrl = getOriginOfWikiLang(translatorConfigs.fromLang) + mw.config.get('wgScriptPath') + tailOfApiUrl;
});
}
});


function getSelectedTextLinks() {
}).then(function () {
var templateLinksRegexp = new RegExp('(\\{\\{\\s*(?:Template:)?(?:' + conf.definedTemplates.join('|') + ')\\|)([^\n|]+?)((?:\\|[^\n\}]*?)?\\}\\})', 'ig');
// borrowed from: http://stackoverflow.com/questions/4220478 :)
var links = (raw.match(templateLinksRegexp) || []).map(function (x) { return x.split('|')[1].split('}')[0]; });
var selection,
selectionAncestor,
range,
allWithinRangeParent,
allSelected,
i,
el;


if (links.length === 0) {
// if `window.getSelection` is not defined (on IE) return nothing.
return;
if (window.getSelection === undefined) {
}
return [];
}
selection = window.getSelection();


return translate(links).then(function (result) {
// if nothing is selected, return empty array
raw = raw.replace(templateLinksRegexp, function ($0, $1, $2, $3) {
if (selection.isCollapsed) {
return $1 + (result[$2] || $2) + $3;
return [];
});
}
});


}).then(function () {
range = selection.getRangeAt(0);
if (!conf.enableTemplateTranslation) { return; }
selectionAncestor = range.commonAncestorContainer;
if (selectionAncestor.getElementsByTagName === undefined) { // if it is not a formal HTML selection
var templatesRegexp = /((?:[^{]|^)\{\{\s*(?:Template:|))([^\n|{]+?)([|}\n])/ig;
return [];
var links = (raw.match(templatesRegexp) || [])
}
.map(function (x) { return 'Template:' + x.split(/\{\{/)[1].split(/[|}\n]/)[0]; })
allWithinRangeParent = selectionAncestor.getElementsByTagName('a');
.filter(function (x) { return !conf.blacklistedTemplatePattern.test(x); });


if (links.length === 0) {
allSelected = [];
return;
for (i = 0; (el = allWithinRangeParent[i]) !== undefined; i += 1) {
}
// The second parameter says to include the element
// even if it's not fully selected
if (selection.containsNode(el, true)) {
allSelected.push(el);
}
}
return allSelected;
}


if (conf.homeWiki === 'arz') {
links = links.filter(hasNotPersianCharacter);
}


return translate(links).then(function (result) {
/*jslint unparam: true*/ // I don't want use key parameter in closures!
raw = raw.replace(templatesRegexp, function ($0, $1, $2, $3) {
function increaseProgressCount() {
return result['Template:' + $2] ? ($1 + result['Template:' + $2].replace(/[^:]*:/, '') + $3) : $0;
progressCount = progressCount + 1;
});
$('#translatorProgress').attr('value', progressCount);
});


}).then(function () {
if (progressCount === itemsCount) {
// Persian specific cleanings, disabled: https://fa.wikipedia.org/؟diff=18668571
$('#translatorProgress').hide('slow');
//if (conf.homeWiki === 'fa')
$('#translatorStatus').css('font-weight', 'bold').text(translatorConfigs.doneText).show('slow');
// raw = raw.replace(/\]\]s/g, ']]').replace(/, /g, '، ');
$( ".translatorAddedcontent" ).prev().css( "color", "lightblue" );
if (translatorConfigs.enableNeedingShow) {
translationTextArea.val(raw);
var links = [],
});
result,
}
linksCount,
titleExistance = {},
title;
$('.translatorNeededLink').each(function (k, v) {
title = $(v).attr('data-title');
if (titleExistance[title] === true) {
return;
}
titleExistance[title] = true;
linksCount = $(v).attr('data-links-to-count');
if (parseInt(linksCount, 10) === 500) {
linksCount = '500+';
}
links.push([title, parseInt($(v).attr('data-interwikis'), 10), linksCount]);
});
links = links.sort(function (x, y) { return y[1] - x[1]; });
result = '<table class="wikitable sortable" ><tr><th>' + translatorConfigs.name + '</th><th>' + translatorConfigs.interwikiCount + '</th><th>' + translatorConfigs.linkedTo + '</th></tr>' + links.map(function (x) { return '<tr><td style="unicode-bidi: plaintext;"><a href="' + x[0] + '">' + x[0] + '</a></td><td>' + x[1] + '</td><td>' + x[2] + '</tr>'; }).join('') + '</table>';
$('#translatorPlusContainer').remove();
$('<li style="line-height: 1.25;" id="translatorPlusContainer">' + translatorConfigs.listOfUnavailablePagesOn + ' ' + translatorConfigs.homeWiki + '.wiki:\n<div style="white-space: pre-line;">' + result + '</div></li>').appendTo('#translatorBar');
}
}
}


function queryTranslationFromData(data) {
function linkFromWikiLang(page, lang) {
if (lang === 'imdb')
var languageLinks,
return 'http://www.imdb.com/title/' + page + '/';
linksToCount = 0,
if (lang === 'wikidata')
translation;
return 'https://wikidata.org' + mw.util.getUrl(page);
return 'https://' + lang + '.wikipedia.org' + mw.util.getUrl(page);
}
var wgUserLanguage = mw.config.get('wgUserLanguage');
function showTables(result) {
var missings = result['#missings'];
// Red nodes inserted after the missing pages
Object.keys(missings).map(function (page) {
if (!missings[page].langlinks) return;
$('#bodyContent a[href$="' + mw.util.getUrl(page) + '"]').after(
$('<span>', {
'class': 'linkstranslator-added-content'
}).append('(', $('<bdi>', {
style: 'color: red',
'class': 'translatorNeededLink'
}).text(missings[page].langlinks), ')')
);
});


// Missings table
if (data.query === undefined || data.query.pages === undefined) {
var links = Object.keys(missings).map(function (page) {
return null;
return [page, missings[page].langlinks, missings[page].links];
}
}).filter(function (x) { return x[1]; });
$.each(data.query.pages, function (key, value) { // for retrieving first object index
languageLinks = value.langlinks;
if (value.links !== undefined) {
linksToCount = value.links.length;
}
});
if (languageLinks === undefined) {
return null;
}
$.each(languageLinks, function (key, value) { // we can also use .filter here
if (value.lang === translatorConfigs.homeWiki) {
translation = value['*'];
}
});
return {
translation: translation,
linksToCount: linksToCount,
interwikis: languageLinks.length
};
}
/*jslint unparam: false*/


links = links.sort(function (x, y) { return y[1] - x[1]; });
function commonAjaxRunner(title, translatorFunction) {
var start = document.dir === 'ltr' ? 'left' : 'right';
$.ajax({
$('#translatorBar').after($('<div>', {
url: ajaxUrl + encodeURIComponent(title),
style: 'line-height: 1.25; font-size: 50%;',
complete: function () {
id: 'linkstranslator-missings-wrapper'
increaseProgressCount();
}).append(
},
conf.listOfUnavailablePagesOn + ' ' + conf.homeWiki + '.wiki: ',
success: function (data) {
$('<div>', {
var translation = queryTranslationFromData(data);
style: 'height: 10em; overflow-y: scroll; overflow-x: hidden; width: 100em;'
if (translation !== null) {
}).append(
translatorFunction(translation);
$('<div>', { style: 'float: ' + start }).append(
}
$('<table>', { 'class': 'wikitable sortable' }).append(
},
$('<tr>').append(
dataType: 'jsonp'
$('<th>').text(conf.name),
});
$('<th>').text(conf.interwikiCount),
}
$('<th>').text(conf.linkedTo)
)
).append(links.map(function (x) {
return $('<tr>').append(
$('<td>').append($('<a>', {
href: linkFromWikiLang(x[0], conf.fromLang),
text: x[0]
})),
$('<td>').text(x[1].toLocaleString(wgUserLanguage)),
$('<td>').text(x[2].toLocaleString(wgUserLanguage))
);
}))
),
$('<div>', { style: 'width: 2em; float: ' + start }).append('<br>'),
$('<div>', { style: 'float: ' + start }).append(
$('<table>', { 'class': 'wikitable sortable' }).append(
$('<tr>').append(
$('<th>').text(conf.fromLang),
$('<th>').text(conf.homeWiki)
)
).append(Object.keys(result).map(function (x) {
if (x.indexOf('#') === 0) return '';
return $('<tr>').append(
$('<td>', { dir: 'auto' }).append($('<a>', {
href: linkFromWikiLang(x, conf.fromLang),
text: x
})),
$('<td>', { dir: 'auto' }).append($('<a>', {
href: linkFromWikiLang(result[x], conf.homeWiki),
text: result[x]
}))
);
}))
)
)
));
}


function addTranslationToNode(node, translation) {
function viewTranslator(showMissings) {
$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove();
if (translation.translation !== undefined) {
$('#translator-button, #translator-plus').css('color', 'lightgray');
node.after('<span class="translatorAddedcontent">' + '(<a href="' + getOriginOfWikiLang(translatorConfigs.homeWiki) + mw.util.getUrl(translation.translation) + '">' + translation.translation + '</a>)</span>');
var titles = {};
} else if (translatorConfigs.enableNeedingShow === true) {
$('#bodyContent a').get().forEach(function (x) {
node.after('<span class="translatorAddedcontent">(<span style="color: red;" class="translatorNeededLink" data-title="' + node.attr('title') + '" data-interwikis="' + translation.interwikis + '" data-links-to-count="' + translation.linksToCount + '">' + translation.interwikis + '</span>)</span>');
var href = x.getAttribute('href');
}
if (!href || href.indexOf('/wiki/') === -1) return;
}


var title = decodeURI(href.replace(/.*?\/wiki\//, ''))
function translateFromLanguageLinkNode(title, node) {
.replace(/_/g, ' ').replace(/#.*$/g, '');
commonAjaxRunner(title, function (translation) {
addTranslationToNode(node, translation);
});
}


if (title) {
// for [[Link]]s in textareas
titles[title] = true;
function addTranslationToTextareaLink(title, translation) {
}
translationTextArea.val(translationTextArea.val().replace(
});
new RegExp('(\\[\\[:?)' + RegExp.escape(title) + '((?:\\|[^\\]]*)?)(\\]\\])'),
titles = Object.keys(titles);
'$1' + translation + (translatorConfigs.removeLinksAliases ? '' : '$2') + '$3'
translate(titles, showMissings).then(function (result) {
));
$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove();
}


$('#translator-button, #translator-plus').css('color', '#808b96');
function translateFromLanguageLinks(title) {
commonAjaxRunner(title, function (translation) {
if (translation.translation !== undefined) {
addTranslationToTextareaLink(title, translation.translation);
}
});
}


Object.keys(result).forEach(function (from) {
// for {{TemplateLink}}s in textareas
if (from.indexOf('#') === 0) return;
function addTranslationToTextareaTemplateLink(title, translation) {
var to = result[from];
translationTextArea.val(translationTextArea.val().replace(
$('#bodyContent a[href$="' + mw.util.getUrl(from) + '"]').after(
new RegExp('(\\{\\{\\s*(?:[Tt]emplate:)?)' + RegExp.escape(title) + '([\\n\\|\\}])'),
$('<span>', {
'$1' + translation + '$2'
'class': 'linkstranslator-added-content'
));
}).append('(', $('<a>', {
}
href: '#',
'class': 'linkstranslator-link-copytext',
style: 'font-size: 140%; font-weight: normal; line-height: 0;',
title: 'Copy to clipboard',
text: '⎘'
}), ' ', $('<bdi>').append(
$('<a>', {
lang: conf.homeWiki,
href: linkFromWikiLang(to, conf.homeWiki),
text: to
})
), ')')
);
});
$('#bodyContent').after($('<textarea id="linkstranslator-link-textarea"></textarea>').css({
// http://stackoverflow.com/a/30810322
position: 'fixed', top: 0, right: '-2em', width: '2em', height: '2em',
padding: 0, border: 'none', outline: 'none', boxShadow: 'none',
background: 'transparent'
}));
$('.linkstranslator-link-copytext').click(function (event) {
event.preventDefault();
var el = event.target;
var text = el.nextElementSibling.firstChild.innerText;


if (location.hash === '#tofawikiframe')
function translateFromLanguageTemplateLinks(title) {
text = '[[' + text + ']]';
commonAjaxRunner('Template:' + title, function (translation) {
if (translation.translation !== undefined) {
addTranslationToTextareaTemplateLink(title, translation.translation.replace(/^.*?:/, ''));
}
});
}


$('#linkstranslator-link-textarea').val(text)[0].select();
function parseUrl(url) {
if (url === undefined) {
var success = false;
return undefined;
try { success = document.execCommand('copy'); } catch (e) { }
}
var match = url.match(/\/wiki\/([^#]*)/);
if (match === null) {
match = url.match(/\/w\/index\.php\?title=([^&#]*).*redlink=1/);
}


if (!success) return;
if (match !== null) {
return decodeURI(match[1]); // returns () matched text
}
return undefined;
}


$(el).animate({ fontSize: '200%' }, 20)
function getLinkTitle(link) { // previously it was link.attr("title")
.animate({ fontSize: '140%' }, 200);
return parseUrl(link.attr('href'));
});
}


if (showMissings) showTables(result);
this.run = function () {
setAjaxUrl();
if (result['#debug']) console.log('Server debug:', result['#debug']);
progressCount = 0;
});
itemsCount = 0;
}
$('#translatorStatus').hide(0);
$('#translatorProgress').removeAttr('max').removeAttr('value');
function saveLanguageConfigs() {
$('.translatorAddedcontent').remove();
if ($('#translator-from').text().trim() === '') {
$('#translator-from').text(conf.fromLang || 'arz');
}
conf.fromLang = $('#translator-from').text();
$.cookie('fromLang', conf.fromLang);
if ($('#translator-to').text().trim() === '') {
$('#translator-to').text(conf.homeWiki || 'en');
}
conf.homeWiki = $('#translator-to').text();
$.cookie('homeWiki', conf.homeWiki);
}


$(function () {
var links,
$('#translatorBar').remove();
templates,
i,
title;


var h1 = $('h1.firstHeading:first');
if (mw.config.get('wgAction') === 'view' || mw.config.get('wgAction') === 'purge' || mw.config.get('wgAction') === 'historysubmit') {
links = getSelectedTextLinks();
if (h1.width() === 0 && mw.config.get('wgContentLanguage') === 'en') {
if (links.length === 0) {
h1 = $('<span>').prependTo($('#mw-content-text'));
links = $('#bodyContent a');
}
}
$(links).filter('a').each(function () {
var iter = $(this),
title = getLinkTitle(iter);
if (title !== undefined) {
itemsCount = itemsCount + 1;
translateFromLanguageLinkNode(title, iter);
}
});
$('#translatorProgress').show().attr('max', itemsCount);
} else if (mw.config.get('wgAction') === 'edit' || mw.config.get('wgAction') === 'submit') {
$('#wpTextbox2').remove(); // remove translation textarea if exists


h1.append($('<span>', {
if (translatorConfigs.fromLang === mw.config.get('wgPageContentLanguage')) {
style: 'font-size: 40%; margin: 0 2em; display: inline-block',
translationTextArea = $('#wpTextbox1').clone().attr({
id: 'translatorBar',
'id': 'wpTextbox2'
'class': 'noprint'
}).css({ // new color for translation textarea
}).append(
'background-color': 'whitesmoke'
$('<span contenteditable>'),
}).val($('#wpTextbox1').val()); // this something that clone must do
conf.translatorBarFormat
$('#wpTextbox1').before(translationTextArea); // put translation textarea before old
.replace('$1', '<sub>' + (action === 'view' ? '<a id="translator-equ" href="#">=</a> <a id="translator-equ-play" href="#">▶️</a> <a id="translator-equ-frovo" target="_blank" href="https://forvo.com/search/' + encodeURI(mw.config.get('wgTitle')) + '">f</a> ' : '') + '<span id="translator-equ-links"></span></sub><a id="translator-button" href="#">')
} else {
.replace('$2', '</a>' + (action === 'view' ? '<sup><a id="translator-plus" href="#">+</a></sup>' : ''))
translationTextArea = $('#wpTextbox1');
.replace('$3', '<span id="translator-from" spellcheck="false" style="display: inline-block" contenteditable>' + conf.fromLang + '</span>')
}
.replace('$4', '<span id="translator-to" spellcheck="false" style="display: inline-block" contenteditable>' + conf.homeWiki + '</span>')
.replace('$5', '<a id="translator-switch" href="#">⇄</a>')
));
if (action === 'edit' || action === 'submit') {
$('#translatorBar').append(
' ',
$('<input>', { type: 'checkbox', name: 'enableTemplateTranslation', id: 'enableTemplateTranslation' }),
$('<label>', { 'for': 'enableTemplateTranslation', text: conf.templateTranslatorText }),
' ',
$('<input>', { type: 'checkbox', name: 'removeLinksAliases', id: 'removeLinksAliases' }),
$('<label>', { 'for': 'removeLinksAliases', text: conf.removeLinksAliasesText })
);
}


$('#translator-button, #translator-plus').click(function (event) {
// for links
event.preventDefault();
links = translationTextArea.val().match(/\[\[.*?\]\]/g);
saveLanguageConfigs();
templates = translationTextArea.val().match(/\{\{.*?[\n\|\}]/g);
if (action === 'edit' || action === 'submit') {
editboxTranslator();
} else {
viewTranslator(this.id === 'translator-plus');
}
});


// run translator if is in tofawiki context
itemsCount = -1;
if (window.self !== window.top && location.hash === '#tofawikiframe') {
if (links !== null) {
viewTranslator(false);
for (i = 0; i < links.length; i = i + 1) { // equals with <code>for (i in matched)</code>
$('#mw-page-base, #mw-head-base, #mw-navigation, #firstHeading, #siteSub, #footer, .read-more-container').remove();
title = links[i].replace(/\[\[:?([^\]\|]*)\|?.*?\]\]/g, "$1");
$('#content').css('margin-left', 0).css('padding-top', 0);
translateFromLanguageLinks(title);
importStylesheet('MediaWiki:Print.css');
}
}


$('#translator-equ').click(function (event) {
if (itemsCount === -1) {
event.preventDefault();
itemsCount = 0;
var title = mw.config.get('wgTitle');
}
$('#translator-equ-links').empty().append(
itemsCount = itemsCount + links.length;
$('<a>', { target: '_blank', href: 'https://translate.google.com/?sl=' + conf.fromLang + '&tl=' + conf.homeWiki + '&q=' + title, text: 'Translator' }),
}
' / ',
$('<a>', { target: '_blank', href: 'https://www.google.com/search?q="' + encodeURI(title) + '"&lr=lang_' + conf.homeWiki, text: 'Specific Language Search' }),
' / ',
$('<a>', { target: '_blank', href: 'https://www.bing.com/translator', text: 'Bing Translator' })
);
});


$('#translator-equ-play').click(function (e) {
if (templates !== null && translatorConfigs.enableTemplateTranslation === true) {
e.preventDefault();
for (i = 0; i < templates.length; i = i + 1) { // equals with <code>for (i in matched)</code>
new Audio('https://dls-espeakbox.wmflabs.org/speech?speed=100&text=' + encodeURI(mw.config.get('wgTitle'))).play();
title = templates[i].replace(/\{\{\s*(?:[Tt]emplate:)?(.*)\s*[\n\|\}]/g, '$1');
});
translateFromLanguageTemplateLinks(title);
// hide play button on non-English wiki
}
mw.config.get('wgContentLanguage') !== 'en' && $('#translator-equ-play, #translator-equ-frovo').hide();
$('#translator-switch').click(function (event) {
event.preventDefault();


var t = conf.homeWiki;
if (itemsCount === -1) {
itemsCount = 0;
}
itemsCount = itemsCount + templates.length;
}


conf.homeWiki = conf.fromLang;
if (itemsCount !== -1) {
$.cookie('homeWiki', conf.fromLang);
$('#translatorProgress').show().attr('max', itemsCount);
$('#translator-to').text(conf.fromLang);
}
}
};
}


conf.fromLang = t;
var translator = new Translator();
$.cookie('fromLang', t);
$(function () {
$('#translator-from').text(t);
"use strict";
});
// disable enter on them
$('#translator-from, #translator-to').keypress(function (e) {
if (e.which !== 13) return;
$(this).blur();
e.preventDefault();
}).click(function () {
document.execCommand('selectAll', false, null);
}).focusout(saveLanguageConfigs);


$('#enableTemplateTranslation').attr('checked', conf.enableTemplateTranslation).click(function () {
function initializeEditorFor(forEditable, inputForEditable, setVariableClosure) {
conf.enableTemplateTranslation = this.checked;
$(forEditable).click(function (event) {
});
event.preventDefault();
$(forEditable).hide();
$(inputForEditable).css('width', '2em').show().val($(forEditable).text());
});


$('#removeLinksAliases').attr('checked', conf.removeLinksAliases).click(function () {
$(inputForEditable).keyup(function (event) {
conf.removeLinksAliases = this.checked;
var selectedLanugage = $(this).val();
});
if (event.keyCode === 13) {
});
$(this).focusout(); // on enter
}(jQuery, mediaWiki));
} else if (event.keyCode === 27) {
$(forEditable).show(); // on escape
$(inputForEditable).hide().val(selectedLanugage);
}
}).focusout(function () {
var selectedLanugage = $(this).val();
if (/...?/.test(selectedLanugage)) {
setVariableClosure(selectedLanugage);
$(forEditable).html(selectedLanugage);
}
$(forEditable).show();
$(inputForEditable).hide();
});
}

$('#translatorBar').remove();
var html = '<li style="unicode-bidi: normal;margin-inline-end: 1em;list-style-type: none;display: inline-block; direction: rtl; margin-top: 0.5em; color: grey; letter-spacing: 0.5px;" id="translatorBar">' + translatorConfigs.translatorBarFormat;
if (mw.config.get('wgAction') === "edit" || mw.config.get('wgAction') === "submit") {
html = html + ' <input type="checkbox" name="enableTemplateTranslation" id="enableTemplateTranslation"><label for="enableTemplateTranslation">' + translatorConfigs.templateTranslatorText + '</label>';
html = html + ' <input type="checkbox" name="removeLinksAliases" id="removeLinksAliases"><label for="removeLinksAliases">' + translatorConfigs.removeLinksAliasesText + '</label>';
}

html = html + '<span id="translatorStatus"></span><progress id="translatorProgress" style="display: none;font-size:5px;margin-inline-start:1em">يجري...</progress></li>';

html = html.replace('$1', '(<a title="البحث أو الترجمة في غوغل" id="translator-equ" href="#"">…</a><span id="translator-equ-links"></span>) <a id="translator-button" href="#"> ');
html = html.replace('$2', '</a><span> (<a id="translator-plus" title="المقالات الناقصة في العربية" href="#">-</a>)</span>');
html = html.replace('$3', '<a id="translator-from" href="#">' + translatorConfigs.fromLang + '</a><input style="display: none" id="translator-from-input">');
html = html.replace('$4', '<a id="translator-to" href="#">' + translatorConfigs.homeWiki + '</a><input style="display: none" id="translator-to-input">');
if (mw.config.get('skin') == 'minerva') {
$('#bodyContent').prepend(html);

} else {
$('#p-tb > div > ul').append(html);

}


$('#translator-button').click(function (event) {
event.preventDefault();
translatorConfigs.enableNeedingShow = false;
translator.run();
});
$('#translator-equ').click(function (event) {
event.preventDefault();
$('#translator-equ-links').html('<a target="_blank" href="/enwiki//translate.google.com/translate_t?sl=' + translatorConfigs.fromLang + '&tl=' + translatorConfigs.homeWiki + '&q=' + mw.config.get('wgTitle') + '">جوجل: ترجمة</a> | <a target="_blank" href=\'//www.google.com/search?q="' + mw.config.get('wgTitle') + '"&lr=lang_' + translatorConfigs.homeWiki + '\'>بحث باللغة الهدف</a>');
});

$('#translator-plus').click(function (event) {
event.preventDefault();
translatorConfigs.enableNeedingShow = true;
translator.run();
});

initializeEditorFor('#translator-to', '#translator-to-input', function (value) {
translatorConfigs.homeWiki = value;
$.cookie("homeWiki", value);
});

initializeEditorFor('#translator-from', '#translator-from-input', function (value) {
translatorConfigs.fromLang = value;
$.cookie("fromLang", value);
});

$('#enableTemplateTranslation').attr('checked', translatorConfigs.enableTemplateTranslation).click(function () {
translatorConfigs.enableTemplateTranslation = this.checked;
});

$('#removeLinksAliases').attr('checked', translatorConfigs.removeLinksAliases).click(function () {
translatorConfigs.removeLinksAliases = this.checked;
});
});

mw.util.addCSS("#translator-equ, #translator-plus {font-family: monospace;} .translatorAddedcontent {font-size: small; padding-left: 5px; unicode-bidi: plaintext;font-family: serif; color: red;} #translatorStatus {margin-right:1em}");

Revision as of 05:19, 8 September 2024

// <nowiki> DO NOT COPY IT FOR TRANSLATION, READ THE DOCUMENTATION [[:en:User talk:Ebraminio/ArticleTranslator.js]]
/*global jQuery, mediaWiki*/
(function ($, mw) {
	'use strict';

	// prevent double execution of the tool
	if (window.isArticletranslatorInitialized && location.hash === '#tofawikiframe') { return; }
	window.isArticletranslatorInitialized = true;

	var action = mw.config.get('wgAction');
	if (action === 'history') {
		return;
	}

	var conf = {
		homeWiki: 'arz',
		fromLang: mw.config.get('wgPageContentLanguage'),
		translatorBarFormat: '$1translate$2 links from $3 to $4 $5',
		templateTranslatorText: 'Template translation',
		removeLinksAliasesText: 'Remove Links Aliases',
		enableTemplateTranslation: true,
		removeLinksAliases: true,
		name: 'Name',
		interwikiCount: 'Language links count',
		linkedTo: 'Linked to',
		listOfUnavailablePagesOn: 'List of not present pages on',
		definedTemplates: ['Flag icon', 'flagicon', 'Flag', 'Portal', 'About', 'ADB', 'Alsoknown', 'Alternateuses', 'Cat main',
			'Cat main article', 'Category disambiguation', 'Category main', 'Catmain', 'Consider disambiguation', 'Contrast',
			'Dabprefixes', 'Detail', 'Details', 'Disambiguation needed', 'Distinguish', 'Distinguish2', 'For', 'For other uses',
			'For2', 'In title', 'Introductory article', 'Look from', 'Main', 'Main cat', 'Main category', 'Maincat', 'More', 'Moredetails',
			'Navbox hatnote *Templates', 'Other', 'Other hurricanes', 'Other meanings', 'Other people', 'Other people2', 'Other people3',
			'Other people5', 'Other places', 'Other places3', 'Other ships', 'Other use', 'Other uses', 'Other uses of', 'Other uses1',
			'Other uses2', 'Other uses-section', 'Othermeanings', 'Otheruse', 'OtherUses', 'Otheruses1', 'Otheruses3', 'OtherusesSubtopic',
			'Othervalues', 'Outline', 'Previously', 'Redirect', 'Redirect10', 'Redirect2', 'Redirect3', 'Redirect4', 'Redirect6', 'Redirect-distinguish2',
			'Redirect-synonym', 'See introduction', 'See Wiktionary', 'Seesubarticle', 'Selfref', 'Srlink', 'Surname links', 'Technical reasons',
			'Template ambiguous', 'Template shortcut', 'This user talk', 'Three other uses', 'Two other uses', 'WikiProject Disambiguation'],
		blacklistedTemplatePattern: /Template:(cite|citation|infobox) [a-z]+/i,
	};

	$.extend(conf, window.articleTranslatorConf);

	// getting the last translator preference from the cookie
	if ($.cookie && $.cookie('homeWiki') !== null) { conf.homeWiki = $.cookie('homeWiki'); }
	if ($.cookie && $.cookie('fromLang') !== null) { conf.fromLang = $.cookie('fromLang'); }
	
	function translate(links, showMissings) {
		// unique titles
		links = Object.keys(links.reduce(function (object, item) {
			object[item] = true;
			return object;
		}, {}));
		
		var request = {
			from: conf.fromLang,
			to: conf.homeWiki,
			missings: !!showMissings,
			p: links.join('|')
		};
		
		// https://github.com/ebraminio/linkstranslator
		return $.post('https://tools.wmflabs.org/linkstranslator/', request).then(null, function () {
			return $.post('https://fa-tts.wmflabs.org/linkstranslator/', request);
		});
	}

	function hasNotPersianCharacter(x) {
		return !/[كﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴً-ِْٰء-ٕپچژگکكڪﻙﻚیﻱﻲٔ۱۲۳۴۵۶۷۸۹۰]/.test(x);
	}

	function editboxTranslator() {
		var translationTextArea;

		if (conf.fromLang === mw.config.get('wgPageContentLanguage')) {
			$('#wpTextbox2').remove();
			translationTextArea = $('#wpTextbox1').clone().attr({
				'id': 'wpTextbox2'
			}).css({
				'background-color': '#CCCEFF'
			}).val($('#wpTextbox1').val());
			$('#wpTextbox1').before(translationTextArea);
		} else {
			translationTextArea = $('#wpTextbox1');
		}
		
		var raw = translationTextArea.val();
		if (raw.match(/\{\{(Navbox|Sidebar|Campaignbox)/)) {
			raw = raw.replace(/(\|\s*name\s*=\s*)([^\n\|\}]*)/, '$1' + mw.config.get('wgTitle'));
		}
		$.Deferred().resolve().then(function () {
			var links = (raw.match(/\[\[.*?[|\]]/g) || []).map(function (x) { return x.split(/\[\[:?/)[1].split(/[|\]]/)[0]; });

			if (links.length === 0) {
				return;
			}

			if (conf.homeWiki === 'arz') {
				links = links.filter(hasNotPersianCharacter);
			}

			return translate(links).then(function (result) {
				Object.keys(result).forEach(function (from) {
					raw = raw.replace(
						new RegExp('(\\[\\[:?)' + mw.RegExp.escape(from) + '((?:\\|[^\\]]*)?)(\\]\\])', 'g'),
						'$1' + result[from] + (conf.removeLinksAliases ? '' : '$2') + '$3'
					);
				});
			});

		}).then(function () {
			var templateLinksRegexp = new RegExp('(\\{\\{\\s*(?:Template:)?(?:' + conf.definedTemplates.join('|') + ')\\|)([^\n|]+?)((?:\\|[^\n\}]*?)?\\}\\})', 'ig');
			var links = (raw.match(templateLinksRegexp) || []).map(function (x) { return x.split('|')[1].split('}')[0]; });

			if (links.length === 0) {
				return;
			}

			return translate(links).then(function (result) {
				raw = raw.replace(templateLinksRegexp, function ($0, $1, $2, $3) {
					return $1 + (result[$2] || $2) + $3;
				});
			});

		}).then(function () {
			if (!conf.enableTemplateTranslation) { return; }
			
			var templatesRegexp = /((?:[^{]|^)\{\{\s*(?:Template:|))([^\n|{]+?)([|}\n])/ig;
			var links = (raw.match(templatesRegexp) || [])
				.map(function (x) { return 'Template:' + x.split(/\{\{/)[1].split(/[|}\n]/)[0]; })
				.filter(function (x) { return !conf.blacklistedTemplatePattern.test(x); });

			if (links.length === 0) {
				return;
			}

			if (conf.homeWiki === 'arz') {
				links = links.filter(hasNotPersianCharacter);
			}

			return translate(links).then(function (result) {
				raw = raw.replace(templatesRegexp, function ($0, $1, $2, $3) {
					return result['Template:' + $2] ? ($1 + result['Template:' + $2].replace(/[^:]*:/, '') + $3) : $0;
				});
			});

		}).then(function () {
			// Persian specific cleanings, disabled: https://fa.wikipedia.org/؟diff=18668571
			//if (conf.homeWiki === 'fa')
			//	raw = raw.replace(/\]\]s/g, ']]').replace(/, /g, '، ');
			
			translationTextArea.val(raw);
		});
	}

	function linkFromWikiLang(page, lang) {
		if (lang === 'imdb')
			return 'http://www.imdb.com/title/' + page + '/';
		if (lang === 'wikidata')
			return 'https://wikidata.org' + mw.util.getUrl(page);
		return 'https://' + lang + '.wikipedia.org' + mw.util.getUrl(page);
	}
	
	var wgUserLanguage = mw.config.get('wgUserLanguage');
	
	function showTables(result) {
		var missings = result['#missings'];
		// Red nodes inserted after the missing pages
		Object.keys(missings).map(function (page) {
			if (!missings[page].langlinks) return;
			$('#bodyContent a[href$="' + mw.util.getUrl(page) + '"]').after(
				$('<span>', {
					'class': 'linkstranslator-added-content'
				}).append('(', $('<bdi>', {
					style: 'color: red',
					'class': 'translatorNeededLink'
				}).text(missings[page].langlinks), ')')
			);
		});

		// Missings table
		var links = Object.keys(missings).map(function (page) {
			return [page, missings[page].langlinks, missings[page].links];
		}).filter(function (x) { return x[1]; });

		links = links.sort(function (x, y) { return y[1] - x[1]; });
		var start = document.dir === 'ltr' ? 'left' : 'right';
		$('#translatorBar').after($('<div>', {
			style: 'line-height: 1.25; font-size: 50%;',
			id: 'linkstranslator-missings-wrapper'
		}).append(
			conf.listOfUnavailablePagesOn + ' ' + conf.homeWiki + '.wiki: ',
			$('<div>', {
				style: 'height: 10em; overflow-y: scroll; overflow-x: hidden; width: 100em;'
			}).append(
				$('<div>', { style: 'float: ' + start }).append(
					$('<table>', { 'class': 'wikitable sortable' }).append(
						$('<tr>').append(
							$('<th>').text(conf.name),
							$('<th>').text(conf.interwikiCount),
							$('<th>').text(conf.linkedTo)
						)
					).append(links.map(function (x) {
						return $('<tr>').append(
							$('<td>').append($('<a>', {
								href: linkFromWikiLang(x[0], conf.fromLang),
								text: x[0]
							})),
							$('<td>').text(x[1].toLocaleString(wgUserLanguage)),
							$('<td>').text(x[2].toLocaleString(wgUserLanguage))
						);
					}))
				),
				$('<div>', { style: 'width: 2em; float: ' + start }).append('<br>'),
				$('<div>', { style: 'float: ' + start }).append(
					$('<table>', { 'class': 'wikitable sortable' }).append(
						$('<tr>').append(
							$('<th>').text(conf.fromLang),
							$('<th>').text(conf.homeWiki)
						)
					).append(Object.keys(result).map(function (x) {
						if (x.indexOf('#') === 0) return '';
						return $('<tr>').append(
							$('<td>', { dir: 'auto' }).append($('<a>', {
								href: linkFromWikiLang(x, conf.fromLang),
								text: x
							})),
							$('<td>', { dir: 'auto' }).append($('<a>', {
								href: linkFromWikiLang(result[x], conf.homeWiki),
								text: result[x]
							}))
						);
					}))
				)
			)
		));
	}

	function viewTranslator(showMissings) {
		$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove();
		$('#translator-button, #translator-plus').css('color', 'lightgray');
		var titles = {};
		$('#bodyContent a').get().forEach(function (x) {
			var href = x.getAttribute('href');
			if (!href || href.indexOf('/wiki/') === -1) return;

			var title = decodeURI(href.replace(/.*?\/wiki\//, ''))
				.replace(/_/g, ' ').replace(/#.*$/g, '');

			if (title) {
				titles[title] = true;
			}
		});
		titles = Object.keys(titles);
		translate(titles, showMissings).then(function (result) {
			$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove();

			$('#translator-button, #translator-plus').css('color', '#808b96');

			Object.keys(result).forEach(function (from) {
				if (from.indexOf('#') === 0) return;
				var to = result[from];
				$('#bodyContent a[href$="' + mw.util.getUrl(from) + '"]').after(
					$('<span>', {
						'class': 'linkstranslator-added-content'
					}).append('(', $('<a>', {
						href: '#',
						'class': 'linkstranslator-link-copytext',
						style: 'font-size: 140%; font-weight: normal; line-height: 0;',
						title: 'Copy to clipboard',
						text: '⎘'
					}), ' ', $('<bdi>').append(
						$('<a>', {
							lang: conf.homeWiki,
							href: linkFromWikiLang(to, conf.homeWiki),
							text: to
						})
					), ')')
				);
			});
			
			$('#bodyContent').after($('<textarea id="linkstranslator-link-textarea"></textarea>').css({
				// http://stackoverflow.com/a/30810322
				position: 'fixed', top: 0, right: '-2em', width: '2em', height: '2em',
				padding: 0, border: 'none', outline: 'none', boxShadow: 'none',
				background: 'transparent'
			}));
			
			$('.linkstranslator-link-copytext').click(function (event) {
				event.preventDefault();
				var el = event.target;
				var text = el.nextElementSibling.firstChild.innerText;

				if (location.hash === '#tofawikiframe')
					text = '[[' + text + ']]';

				$('#linkstranslator-link-textarea').val(text)[0].select();
				
				var success = false;
				try { success = document.execCommand('copy'); } catch (e) { }

				if (!success) return;

				$(el).animate({ fontSize: '200%' }, 20)
					.animate({ fontSize: '140%' }, 200);
			});

			if (showMissings) showTables(result);
			
			if (result['#debug']) console.log('Server debug:', result['#debug']);
		});
	}
	
	function saveLanguageConfigs() {
		if ($('#translator-from').text().trim() === '') {
			$('#translator-from').text(conf.fromLang || 'arz');
		}
		conf.fromLang = $('#translator-from').text();
		$.cookie('fromLang', conf.fromLang);
		if ($('#translator-to').text().trim() === '') {
			$('#translator-to').text(conf.homeWiki || 'en');
		}
		conf.homeWiki = $('#translator-to').text();
		$.cookie('homeWiki', conf.homeWiki);
	}

	$(function () {
		$('#translatorBar').remove();

		var h1 = $('h1.firstHeading:first');
		
		if (h1.width() === 0 && mw.config.get('wgContentLanguage') === 'en') {
			h1 = $('<span>').prependTo($('#mw-content-text'));
		}

		h1.append($('<span>', {
			style: 'font-size: 40%; margin: 0 2em; display: inline-block',
			id: 'translatorBar',
			'class': 'noprint'
		}).append(
			$('<span contenteditable>'),
			conf.translatorBarFormat
				.replace('$1', '<sub>' + (action === 'view' ? '<a id="translator-equ" href="#">=</a> <a id="translator-equ-play" href="#">▶️</a> <a id="translator-equ-frovo" target="_blank" href="https://forvo.com/search/' + encodeURI(mw.config.get('wgTitle')) + '">f</a> ' : '') + '<span id="translator-equ-links"></span></sub><a id="translator-button" href="#">')
				.replace('$2', '</a>' + (action === 'view' ? '<sup><a id="translator-plus" href="#">+</a></sup>' : ''))
				.replace('$3', '<span id="translator-from" spellcheck="false" style="display: inline-block" contenteditable>' + conf.fromLang + '</span>')
				.replace('$4', '<span id="translator-to" spellcheck="false" style="display: inline-block" contenteditable>' + conf.homeWiki + '</span>')
				.replace('$5', '<a id="translator-switch" href="#">⇄</a>')
		));
		
		if (action === 'edit' || action === 'submit') {
			$('#translatorBar').append(
				' ',
				$('<input>', { type: 'checkbox', name: 'enableTemplateTranslation', id: 'enableTemplateTranslation' }),
				$('<label>', { 'for': 'enableTemplateTranslation', text: conf.templateTranslatorText }),
				' ',
				$('<input>', { type: 'checkbox', name: 'removeLinksAliases', id: 'removeLinksAliases' }),
				$('<label>', { 'for': 'removeLinksAliases', text: conf.removeLinksAliasesText })
			);
		}

		$('#translator-button, #translator-plus').click(function (event) {
			event.preventDefault();
			saveLanguageConfigs();
			if (action === 'edit' || action === 'submit') {
				editboxTranslator();
			} else {
				viewTranslator(this.id === 'translator-plus');
			}
		});

		// run translator if is in tofawiki context
		if (window.self !== window.top && location.hash === '#tofawikiframe') {
			viewTranslator(false);
			$('#mw-page-base, #mw-head-base, #mw-navigation, #firstHeading, #siteSub, #footer, .read-more-container').remove();
			$('#content').css('margin-left', 0).css('padding-top', 0);
			importStylesheet('MediaWiki:Print.css');
		}

		$('#translator-equ').click(function (event) {
			event.preventDefault();
			var title = mw.config.get('wgTitle');
			$('#translator-equ-links').empty().append(
				$('<a>', { target: '_blank', href: 'https://translate.google.com/?sl=' + conf.fromLang + '&tl=' + conf.homeWiki + '&q=' + title, text: 'Translator' }),
				' / ',
				$('<a>', { target: '_blank', href: 'https://www.google.com/search?q="' + encodeURI(title) + '"&lr=lang_' + conf.homeWiki, text: 'Specific Language Search' }),
				' / ',
				$('<a>', { target: '_blank', href: 'https://www.bing.com/translator', text: 'Bing Translator' })
			);
		});

		$('#translator-equ-play').click(function (e) {
			e.preventDefault();
			new Audio('https://dls-espeakbox.wmflabs.org/speech?speed=100&text=' + encodeURI(mw.config.get('wgTitle'))).play();
		});
		// hide play button on non-English wiki
		mw.config.get('wgContentLanguage') !== 'en' && $('#translator-equ-play, #translator-equ-frovo').hide();
		
		$('#translator-switch').click(function (event) {
			event.preventDefault();

			var t = conf.homeWiki;

			conf.homeWiki = conf.fromLang;
			$.cookie('homeWiki', conf.fromLang);
			$('#translator-to').text(conf.fromLang);

			conf.fromLang = t;
			$.cookie('fromLang', t);
			$('#translator-from').text(t);
		});
		
		// disable enter on them
		$('#translator-from, #translator-to').keypress(function (e) {
			if (e.which !== 13) return;
			
			$(this).blur();
			e.preventDefault();
		}).click(function () {
			document.execCommand('selectAll', false, null);
		}).focusout(saveLanguageConfigs);
		

		$('#enableTemplateTranslation').attr('checked', conf.enableTemplateTranslation).click(function () {
			conf.enableTemplateTranslation = this.checked;
		});

		$('#removeLinksAliases').attr('checked', conf.removeLinksAliases).click(function () {
			conf.removeLinksAliases = this.checked;
		});
	});
}(jQuery, mediaWiki));