User:Redaking/ArticleTranslator.js: Difference between revisions
Appearance
Content deleted Content added
No edit summary Tag: Reverted |
No edit summary Tags: Reverted Disambiguation links added |
||
Line 1: | Line 1: | ||
// |
//[[:en:User:Ebraminio/ArticleTranslator.js]]; [[ويكيبيديا:الميدان/تقنية/05/2012#مترجم]] |
||
// <nowiki> |
|||
/*global jQuery, mediaWiki*/ |
|||
/*jslint regexp: true */ |
|||
(function ($, mw) { |
|||
/*browser: true*/ |
|||
'use strict'; |
|||
/*global $: false, wgNamespaceNumber: false, wgAction: false, mw: false, |
|||
wgScriptPath: false, wgPageContentLanguage: false, window: false */ |
|||
if (window.globalTranslatorConfigs === undefined) { |
|||
// prevent double execution of the tool |
|||
var globalTranslatorConfigs = { |
|||
if (window.isArticletranslatorInitialized && location.hash === '#tofawikiframe') { return; } |
|||
'homeWiki': window.homeWiki, |
|||
window.isArticletranslatorInitialized = true; |
|||
'fromLang': window.fromLang, |
|||
'translatorBarFormat': window.translatorBarFormat, |
|||
'templateTranslatorText': window.templateTranslatorText, |
|||
'removeLinksAliasesText': window.removeLinksAliasesText, |
|||
'doneText': window.doneText |
|||
}; |
|||
} |
|||
var translatorConfigs = { |
|||
var action = mw.config.get('wgAction'); |
|||
'homeWiki': 'arz', |
|||
if (action === 'history') { |
|||
'fromLang': 'en', |
|||
return; |
|||
'translatorBarFormat': '$1ترجم$2 الوصلات $4 ⇒ $3', |
|||
} |
|||
'templateTranslatorText': 'ترجم القوالب', |
|||
'removeLinksAliasesText': 'أخف عناوين الوصلات', |
|||
'doneText': 'تم', |
|||
'enableTemplateTranslation': true, |
|||
'removeLinksAliases': true, |
|||
'enableNeedingShow': false, |
|||
'name': 'اسم الصفحة', |
|||
'interwikiCount': 'عدد وصلات اللغات فيها', |
|||
'linkedTo': 'عدد الوصلات فيها', |
|||
'listOfUnavailablePagesOn': 'الصفحات غير الموجودة في ' |
|||
}; |
|||
$.extend(translatorConfigs, globalTranslatorConfigs); |
|||
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, |
|||
}; |
|||
// getting the last translator preference from the cookie |
|||
$.extend(conf, window.articleTranslatorConf); |
|||
if ($.cookie('homeWiki') !== null) { |
|||
translatorConfigs.homeWiki = $.cookie('homeWiki'); |
|||
} |
|||
if ($.cookie('fromLang') !== null) { |
|||
// getting the last translator preference from the cookie |
|||
translatorConfigs.fromLang = $.cookie('fromLang'); |
|||
} |
|||
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); |
|||
}); |
|||
} |
|||
// Regexp.escape() from: http://80.68.89.23/2006/Jan/20/escape/ |
|||
function hasNotPersianCharacter(x) { |
|||
RegExp.escape = function (text) { |
|||
return !/[كﮑﮐﮏﮎﻜﻛﻚﻙىﻯيہەھﻰ-ﻴً-ِْٰء-ٕپچژگکكڪﻙﻚیﻱﻲٔ۱۲۳۴۵۶۷۸۹۰]/.test(x); |
|||
'use strict'; |
|||
} |
|||
return text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); |
|||
}; |
|||
function Translator() { |
|||
'use strict'; |
|||
var translationTextArea; |
|||
var translationTextArea, |
|||
if (conf.fromLang === mw.config.get('wgPageContentLanguage')) { |
|||
progressCount, |
|||
$('#wpTextbox2').remove(); |
|||
itemsCount, |
|||
translationTextArea = $('#wpTextbox1').clone().attr({ |
|||
ajaxUrl; |
|||
'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]; }); |
|||
function getOrigin() { |
|||
if (links.length === 0) { |
|||
var result = window.location.protocol + '//' + window.location.host; |
|||
return; |
|||
if (window.location.port !== '') { |
|||
} |
|||
result = result + ':' + window.location.port; |
|||
} |
|||
return result; |
|||
} |
|||
function getOriginOfWikiLang(lang) { |
|||
if (conf.homeWiki === 'arz') { |
|||
return getOrigin().replace(mw.config.get('wgPageContentLanguage'), lang); |
|||
links = links.filter(hasNotPersianCharacter); |
|||
} |
|||
} |
|||
function setAjaxUrl() { |
|||
var tailOfApiUrl = '/api.php?action=query&prop=langlinks&redirects=&format=json&lllimit=500&titles='; |
|||
Object.keys(result).forEach(function (from) { |
|||
if (translatorConfigs.enableNeedingShow === true) { |
|||
raw = raw.replace( |
|||
tailOfApiUrl = '/api.php?action=query&prop=langlinks|links&redirects=&format=json&pllimit=500&lllimit=500&titles='; |
|||
new RegExp('(\\[\\[:?)' + mw.RegExp.escape(from) + '((?:\\|[^\\]]*)?)(\\]\\])', 'g'), |
|||
} |
|||
'$1' + result[from] + (conf.removeLinksAliases ? '' : '$2') + '$3' |
|||
ajaxUrl = getOriginOfWikiLang(translatorConfigs.fromLang) + mw.config.get('wgScriptPath') + tailOfApiUrl; |
|||
); |
|||
} |
|||
}); |
|||
}); |
|||
function getSelectedTextLinks() { |
|||
// borrowed from: http://stackoverflow.com/questions/4220478 :) |
|||
var templateLinksRegexp = new RegExp('(\\{\\{\\s*(?:Template:)?(?:' + conf.definedTemplates.join('|') + ')\\|)([^\n|]+?)((?:\\|[^\n\}]*?)?\\}\\})', 'ig'); |
|||
var selection, |
|||
var links = (raw.match(templateLinksRegexp) || []).map(function (x) { return x.split('|')[1].split('}')[0]; }); |
|||
selectionAncestor, |
|||
range, |
|||
allWithinRangeParent, |
|||
allSelected, |
|||
i, |
|||
el; |
|||
// if `window.getSelection` is not defined (on IE) return nothing. |
|||
if (links.length === 0) { |
|||
if (window.getSelection === undefined) { |
|||
return; |
|||
return []; |
|||
} |
|||
} |
|||
selection = window.getSelection(); |
|||
// if nothing is selected, return empty array |
|||
return translate(links).then(function (result) { |
|||
if (selection.isCollapsed) { |
|||
raw = raw.replace(templateLinksRegexp, function ($0, $1, $2, $3) { |
|||
return []; |
|||
return $1 + (result[$2] || $2) + $3; |
|||
} |
|||
}); |
|||
}); |
|||
range = selection.getRangeAt(0); |
|||
}).then(function () { |
|||
selectionAncestor = range.commonAncestorContainer; |
|||
if (!conf.enableTemplateTranslation) { return; } |
|||
if (selectionAncestor.getElementsByTagName === undefined) { // if it is not a formal HTML selection |
|||
return []; |
|||
var templatesRegexp = /((?:[^{]|^)\{\{\s*(?:Template:|))([^\n|{]+?)([|}\n])/ig; |
|||
} |
|||
var links = (raw.match(templatesRegexp) || []) |
|||
allWithinRangeParent = selectionAncestor.getElementsByTagName('a'); |
|||
.map(function (x) { return 'Template:' + x.split(/\{\{/)[1].split(/[|}\n]/)[0]; }) |
|||
.filter(function (x) { return !conf.blacklistedTemplatePattern.test(x); }); |
|||
allSelected = []; |
|||
if (links.length === 0) { |
|||
for (i = 0; (el = allWithinRangeParent[i]) !== undefined; i += 1) { |
|||
return; |
|||
// 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); |
|||
} |
|||
/*jslint unparam: true*/ // I don't want use key parameter in closures! |
|||
return translate(links).then(function (result) { |
|||
function increaseProgressCount() { |
|||
raw = raw.replace(templatesRegexp, function ($0, $1, $2, $3) { |
|||
progressCount = progressCount + 1; |
|||
return result['Template:' + $2] ? ($1 + result['Template:' + $2].replace(/[^:]*:/, '') + $3) : $0; |
|||
$('#translatorProgress').attr('value', progressCount); |
|||
}); |
|||
}); |
|||
if (progressCount === itemsCount) { |
|||
}).then(function () { |
|||
$('#translatorProgress').hide('slow'); |
|||
// Persian specific cleanings, disabled: https://fa.wikipedia.org/؟diff=18668571 |
|||
$('#translatorStatus').css('font-weight', 'bold').text(translatorConfigs.doneText).show('slow'); |
|||
//if (conf.homeWiki === 'fa') |
|||
$( ".translatorAddedcontent" ).prev().css( "color", "lightblue" ); |
|||
// raw = raw.replace(/\]\]s/g, ']]').replace(/, /g, '، '); |
|||
if (translatorConfigs.enableNeedingShow) { |
|||
var links = [], |
|||
translationTextArea.val(raw); |
|||
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) { |
|||
var languageLinks, |
|||
if (lang === 'imdb') |
|||
linksToCount = 0, |
|||
return 'http://www.imdb.com/title/' + page + '/'; |
|||
translation; |
|||
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), ')') |
|||
); |
|||
}); |
|||
if (data.query === undefined || data.query.pages === undefined) { |
|||
// Missings table |
|||
return null; |
|||
var links = Object.keys(missings).map(function (page) { |
|||
} |
|||
return [page, missings[page].langlinks, missings[page].links]; |
|||
$.each(data.query.pages, function (key, value) { // for retrieving first object index |
|||
}).filter(function (x) { return x[1]; }); |
|||
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*/ |
|||
function commonAjaxRunner(title, translatorFunction) { |
|||
links = links.sort(function (x, y) { return y[1] - x[1]; }); |
|||
$.ajax({ |
|||
var start = document.dir === 'ltr' ? 'left' : 'right'; |
|||
url: ajaxUrl + encodeURIComponent(title), |
|||
$('#translatorBar').after($('<div>', { |
|||
complete: function () { |
|||
style: 'line-height: 1.25; font-size: 50%;', |
|||
increaseProgressCount(); |
|||
id: 'linkstranslator-missings-wrapper' |
|||
}, |
|||
}).append( |
|||
success: function (data) { |
|||
conf.listOfUnavailablePagesOn + ' ' + conf.homeWiki + '.wiki: ', |
|||
var translation = queryTranslationFromData(data); |
|||
$('<div>', { |
|||
if (translation !== null) { |
|||
style: 'height: 10em; overflow-y: scroll; overflow-x: hidden; width: 100em;' |
|||
translatorFunction(translation); |
|||
}).append( |
|||
} |
|||
$('<div>', { style: 'float: ' + start }).append( |
|||
}, |
|||
$('<table>', { 'class': 'wikitable sortable' }).append( |
|||
dataType: 'jsonp' |
|||
$('<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 addTranslationToNode(node, translation) { |
|||
if (translation.translation !== undefined) { |
|||
$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove(); |
|||
node.after('<span class="translatorAddedcontent">' + '(<a href="' + getOriginOfWikiLang(translatorConfigs.homeWiki) + mw.util.getUrl(translation.translation) + '">' + translation.translation + '</a>)</span>'); |
|||
$('#translator-button, #translator-plus').css('color', 'lightgray'); |
|||
} else if (translatorConfigs.enableNeedingShow === true) { |
|||
var titles = {}; |
|||
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>'); |
|||
$('#bodyContent a').get().forEach(function (x) { |
|||
} |
|||
var href = x.getAttribute('href'); |
|||
} |
|||
if (!href || href.indexOf('/wiki/') === -1) return; |
|||
function translateFromLanguageLinkNode(title, node) { |
|||
var title = decodeURI(href.replace(/.*?\/wiki\//, '')) |
|||
commonAjaxRunner(title, function (translation) { |
|||
.replace(/_/g, ' ').replace(/#.*$/g, ''); |
|||
addTranslationToNode(node, translation); |
|||
}); |
|||
} |
|||
// for [[Link]]s in textareas |
|||
if (title) { |
|||
function addTranslationToTextareaLink(title, translation) { |
|||
titles[title] = true; |
|||
translationTextArea.val(translationTextArea.val().replace( |
|||
} |
|||
new RegExp('(\\[\\[:?)' + RegExp.escape(title) + '((?:\\|[^\\]]*)?)(\\]\\])'), |
|||
}); |
|||
'$1' + translation + (translatorConfigs.removeLinksAliases ? '' : '$2') + '$3' |
|||
titles = Object.keys(titles); |
|||
)); |
|||
translate(titles, showMissings).then(function (result) { |
|||
} |
|||
$('.linkstranslator-added-content, #linkstranslator-missings-wrapper').remove(); |
|||
function translateFromLanguageLinks(title) { |
|||
$('#translator-button, #translator-plus').css('color', '#808b96'); |
|||
commonAjaxRunner(title, function (translation) { |
|||
if (translation.translation !== undefined) { |
|||
addTranslationToTextareaLink(title, translation.translation); |
|||
} |
|||
}); |
|||
} |
|||
// for {{TemplateLink}}s in textareas |
|||
Object.keys(result).forEach(function (from) { |
|||
function addTranslationToTextareaTemplateLink(title, translation) { |
|||
if (from.indexOf('#') === 0) return; |
|||
translationTextArea.val(translationTextArea.val().replace( |
|||
var to = result[from]; |
|||
new RegExp('(\\{\\{\\s*(?:[Tt]emplate:)?)' + RegExp.escape(title) + '([\\n\\|\\}])'), |
|||
$('#bodyContent a[href$="' + mw.util.getUrl(from) + '"]').after( |
|||
'$1' + translation + '$2' |
|||
$('<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; |
|||
function translateFromLanguageTemplateLinks(title) { |
|||
if (location.hash === '#tofawikiframe') |
|||
commonAjaxRunner('Template:' + title, function (translation) { |
|||
text = '[[' + text + ']]'; |
|||
if (translation.translation !== undefined) { |
|||
addTranslationToTextareaTemplateLink(title, translation.translation.replace(/^.*?:/, '')); |
|||
} |
|||
}); |
|||
} |
|||
function parseUrl(url) { |
|||
$('#linkstranslator-link-textarea').val(text)[0].select(); |
|||
if (url === undefined) { |
|||
return undefined; |
|||
var success = false; |
|||
} |
|||
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 (match !== null) { |
|||
if (!success) return; |
|||
return decodeURI(match[1]); // returns () matched text |
|||
} |
|||
return undefined; |
|||
} |
|||
function getLinkTitle(link) { // previously it was link.attr("title") |
|||
$(el).animate({ fontSize: '200%' }, 20) |
|||
return parseUrl(link.attr('href')); |
|||
.animate({ fontSize: '140%' }, 200); |
|||
} |
|||
}); |
|||
this.run = function () { |
|||
if (showMissings) showTables(result); |
|||
setAjaxUrl(); |
|||
progressCount = 0; |
|||
if (result['#debug']) console.log('Server debug:', result['#debug']); |
|||
itemsCount = 0; |
|||
}); |
|||
$('#translatorStatus').hide(0); |
|||
} |
|||
$('#translatorProgress').removeAttr('max').removeAttr('value'); |
|||
$('.translatorAddedcontent').remove(); |
|||
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); |
|||
} |
|||
var links, |
|||
$(function () { |
|||
templates, |
|||
$('#translatorBar').remove(); |
|||
i, |
|||
title; |
|||
if (mw.config.get('wgAction') === 'view' || mw.config.get('wgAction') === 'purge' || mw.config.get('wgAction') === 'historysubmit') { |
|||
var h1 = $('h1.firstHeading:first'); |
|||
links = getSelectedTextLinks(); |
|||
if (links.length === 0) { |
|||
if (h1.width() === 0 && mw.config.get('wgContentLanguage') === 'en') { |
|||
links = $('#bodyContent a'); |
|||
h1 = $('<span>').prependTo($('#mw-content-text')); |
|||
} |
|||
} |
|||
$(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 |
|||
if (translatorConfigs.fromLang === mw.config.get('wgPageContentLanguage')) { |
|||
h1.append($('<span>', { |
|||
translationTextArea = $('#wpTextbox1').clone().attr({ |
|||
style: 'font-size: 40%; margin: 0 2em; display: inline-block', |
|||
'id': 'wpTextbox2' |
|||
id: 'translatorBar', |
|||
}).css({ // new color for translation textarea |
|||
'class': 'noprint' |
|||
'background-color': 'whitesmoke' |
|||
}).append( |
|||
}).val($('#wpTextbox1').val()); // this something that clone must do |
|||
$('<span contenteditable>'), |
|||
$('#wpTextbox1').before(translationTextArea); // put translation textarea before old |
|||
conf.translatorBarFormat |
|||
} else { |
|||
.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="#">') |
|||
translationTextArea = $('#wpTextbox1'); |
|||
.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 }) |
|||
); |
|||
} |
|||
// for links |
|||
$('#translator-button, #translator-plus').click(function (event) { |
|||
links = translationTextArea.val().match(/\[\[.*?\]\]/g); |
|||
event.preventDefault(); |
|||
templates = translationTextArea.val().match(/\{\{.*?[\n\|\}]/g); |
|||
saveLanguageConfigs(); |
|||
if (action === 'edit' || action === 'submit') { |
|||
editboxTranslator(); |
|||
} else { |
|||
viewTranslator(this.id === 'translator-plus'); |
|||
} |
|||
}); |
|||
itemsCount = -1; |
|||
// run translator if is in tofawiki context |
|||
if (links !== null) { |
|||
if (window.self !== window.top && location.hash === '#tofawikiframe') { |
|||
for (i = 0; i < links.length; i = i + 1) { // equals with <code>for (i in matched)</code> |
|||
viewTranslator(false); |
|||
title = links[i].replace(/\[\[:?([^\]\|]*)\|?.*?\]\]/g, "$1"); |
|||
$('#mw-page-base, #mw-head-base, #mw-navigation, #firstHeading, #siteSub, #footer, .read-more-container').remove(); |
|||
translateFromLanguageLinks(title); |
|||
$('#content').css('margin-left', 0).css('padding-top', 0); |
|||
} |
|||
importStylesheet('MediaWiki:Print.css'); |
|||
} |
|||
if (itemsCount === -1) { |
|||
$('#translator-equ').click(function (event) { |
|||
itemsCount = 0; |
|||
event.preventDefault(); |
|||
} |
|||
var title = mw.config.get('wgTitle'); |
|||
itemsCount = itemsCount + links.length; |
|||
$('#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' }) |
|||
); |
|||
}); |
|||
if (templates !== null && translatorConfigs.enableTemplateTranslation === true) { |
|||
$('#translator-equ-play').click(function (e) { |
|||
for (i = 0; i < templates.length; i = i + 1) { // equals with <code>for (i in matched)</code> |
|||
e.preventDefault(); |
|||
title = templates[i].replace(/\{\{\s*(?:[Tt]emplate:)?(.*)\s*[\n\|\}]/g, '$1'); |
|||
new Audio('https://dls-espeakbox.wmflabs.org/speech?speed=100&text=' + encodeURI(mw.config.get('wgTitle'))).play(); |
|||
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(); |
|||
if (itemsCount === -1) { |
|||
var t = conf.homeWiki; |
|||
itemsCount = 0; |
|||
} |
|||
itemsCount = itemsCount + templates.length; |
|||
} |
|||
if (itemsCount !== -1) { |
|||
conf.homeWiki = conf.fromLang; |
|||
$('#translatorProgress').show().attr('max', itemsCount); |
|||
$.cookie('homeWiki', conf.fromLang); |
|||
} |
|||
$('#translator-to').text(conf.fromLang); |
|||
} |
|||
}; |
|||
} |
|||
var translator = new Translator(); |
|||
conf.fromLang = t; |
|||
$(function () { |
|||
$.cookie('fromLang', t); |
|||
"use strict"; |
|||
$('#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); |
|||
function initializeEditorFor(forEditable, inputForEditable, setVariableClosure) { |
|||
$('#enableTemplateTranslation').attr('checked', conf.enableTemplateTranslation).click(function () { |
|||
$(forEditable).click(function (event) { |
|||
conf.enableTemplateTranslation = this.checked; |
|||
event.preventDefault(); |
|||
}); |
|||
$(forEditable).hide(); |
|||
$(inputForEditable).css('width', '2em').show().val($(forEditable).text()); |
|||
}); |
|||
$(inputForEditable).keyup(function (event) { |
|||
$('#removeLinksAliases').attr('checked', conf.removeLinksAliases).click(function () { |
|||
var selectedLanugage = $(this).val(); |
|||
conf.removeLinksAliases = this.checked; |
|||
if (event.keyCode === 13) { |
|||
}); |
|||
$(this).focusout(); // on enter |
|||
}); |
|||
} else if (event.keyCode === 27) { |
|||
}(jQuery, mediaWiki)); |
|||
$(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:16, 8 September 2024
//[[:en:User:Ebraminio/ArticleTranslator.js]]; [[ويكيبيديا:الميدان/تقنية/05/2012#مترجم]]
// <nowiki>
/*jslint regexp: true */
/*browser: true*/
/*global $: false, wgNamespaceNumber: false, wgAction: false, mw: false,
wgScriptPath: false, wgPageContentLanguage: false, window: false */
if (window.globalTranslatorConfigs === undefined) {
var globalTranslatorConfigs = {
'homeWiki': window.homeWiki,
'fromLang': window.fromLang,
'translatorBarFormat': window.translatorBarFormat,
'templateTranslatorText': window.templateTranslatorText,
'removeLinksAliasesText': window.removeLinksAliasesText,
'doneText': window.doneText
};
}
var translatorConfigs = {
'homeWiki': 'arz',
'fromLang': 'en',
'translatorBarFormat': '$1ترجم$2 الوصلات $4 ⇒ $3',
'templateTranslatorText': 'ترجم القوالب',
'removeLinksAliasesText': 'أخف عناوين الوصلات',
'doneText': 'تم',
'enableTemplateTranslation': true,
'removeLinksAliases': true,
'enableNeedingShow': false,
'name': 'اسم الصفحة',
'interwikiCount': 'عدد وصلات اللغات فيها',
'linkedTo': 'عدد الوصلات فيها',
'listOfUnavailablePagesOn': 'الصفحات غير الموجودة في '
};
$.extend(translatorConfigs, globalTranslatorConfigs);
// getting the last translator preference from the cookie
if ($.cookie('homeWiki') !== null) {
translatorConfigs.homeWiki = $.cookie('homeWiki');
}
if ($.cookie('fromLang') !== null) {
translatorConfigs.fromLang = $.cookie('fromLang');
}
//
// Regexp.escape() from: http://80.68.89.23/2006/Jan/20/escape/
RegExp.escape = function (text) {
'use strict';
return text.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
};
function Translator() {
'use strict';
var translationTextArea,
progressCount,
itemsCount,
ajaxUrl;
function getOrigin() {
var result = window.location.protocol + '//' + window.location.host;
if (window.location.port !== '') {
result = result + ':' + window.location.port;
}
return result;
}
function getOriginOfWikiLang(lang) {
return getOrigin().replace(mw.config.get('wgPageContentLanguage'), lang);
}
function setAjaxUrl() {
var tailOfApiUrl = '/api.php?action=query&prop=langlinks&redirects=&format=json&lllimit=500&titles=';
if (translatorConfigs.enableNeedingShow === true) {
tailOfApiUrl = '/api.php?action=query&prop=langlinks|links&redirects=&format=json&pllimit=500&lllimit=500&titles=';
}
ajaxUrl = getOriginOfWikiLang(translatorConfigs.fromLang) + mw.config.get('wgScriptPath') + tailOfApiUrl;
}
function getSelectedTextLinks() {
// borrowed from: http://stackoverflow.com/questions/4220478 :)
var selection,
selectionAncestor,
range,
allWithinRangeParent,
allSelected,
i,
el;
// if `window.getSelection` is not defined (on IE) return nothing.
if (window.getSelection === undefined) {
return [];
}
selection = window.getSelection();
// if nothing is selected, return empty array
if (selection.isCollapsed) {
return [];
}
range = selection.getRangeAt(0);
selectionAncestor = range.commonAncestorContainer;
if (selectionAncestor.getElementsByTagName === undefined) { // if it is not a formal HTML selection
return [];
}
allWithinRangeParent = selectionAncestor.getElementsByTagName('a');
allSelected = [];
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;
}
/*jslint unparam: true*/ // I don't want use key parameter in closures!
function increaseProgressCount() {
progressCount = progressCount + 1;
$('#translatorProgress').attr('value', progressCount);
if (progressCount === itemsCount) {
$('#translatorProgress').hide('slow');
$('#translatorStatus').css('font-weight', 'bold').text(translatorConfigs.doneText).show('slow');
$( ".translatorAddedcontent" ).prev().css( "color", "lightblue" );
if (translatorConfigs.enableNeedingShow) {
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) {
var languageLinks,
linksToCount = 0,
translation;
if (data.query === undefined || data.query.pages === undefined) {
return null;
}
$.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*/
function commonAjaxRunner(title, translatorFunction) {
$.ajax({
url: ajaxUrl + encodeURIComponent(title),
complete: function () {
increaseProgressCount();
},
success: function (data) {
var translation = queryTranslationFromData(data);
if (translation !== null) {
translatorFunction(translation);
}
},
dataType: 'jsonp'
});
}
function addTranslationToNode(node, translation) {
if (translation.translation !== undefined) {
node.after('<span class="translatorAddedcontent">' + '(<a href="' + getOriginOfWikiLang(translatorConfigs.homeWiki) + mw.util.getUrl(translation.translation) + '">' + translation.translation + '</a>)</span>');
} else if (translatorConfigs.enableNeedingShow === true) {
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>');
}
}
function translateFromLanguageLinkNode(title, node) {
commonAjaxRunner(title, function (translation) {
addTranslationToNode(node, translation);
});
}
// for [[Link]]s in textareas
function addTranslationToTextareaLink(title, translation) {
translationTextArea.val(translationTextArea.val().replace(
new RegExp('(\\[\\[:?)' + RegExp.escape(title) + '((?:\\|[^\\]]*)?)(\\]\\])'),
'$1' + translation + (translatorConfigs.removeLinksAliases ? '' : '$2') + '$3'
));
}
function translateFromLanguageLinks(title) {
commonAjaxRunner(title, function (translation) {
if (translation.translation !== undefined) {
addTranslationToTextareaLink(title, translation.translation);
}
});
}
// for {{TemplateLink}}s in textareas
function addTranslationToTextareaTemplateLink(title, translation) {
translationTextArea.val(translationTextArea.val().replace(
new RegExp('(\\{\\{\\s*(?:[Tt]emplate:)?)' + RegExp.escape(title) + '([\\n\\|\\}])'),
'$1' + translation + '$2'
));
}
function translateFromLanguageTemplateLinks(title) {
commonAjaxRunner('Template:' + title, function (translation) {
if (translation.translation !== undefined) {
addTranslationToTextareaTemplateLink(title, translation.translation.replace(/^.*?:/, ''));
}
});
}
function parseUrl(url) {
if (url === undefined) {
return undefined;
}
var match = url.match(/\/wiki\/([^#]*)/);
if (match === null) {
match = url.match(/\/w\/index\.php\?title=([^&#]*).*redlink=1/);
}
if (match !== null) {
return decodeURI(match[1]); // returns () matched text
}
return undefined;
}
function getLinkTitle(link) { // previously it was link.attr("title")
return parseUrl(link.attr('href'));
}
this.run = function () {
setAjaxUrl();
progressCount = 0;
itemsCount = 0;
$('#translatorStatus').hide(0);
$('#translatorProgress').removeAttr('max').removeAttr('value');
$('.translatorAddedcontent').remove();
var links,
templates,
i,
title;
if (mw.config.get('wgAction') === 'view' || mw.config.get('wgAction') === 'purge' || mw.config.get('wgAction') === 'historysubmit') {
links = getSelectedTextLinks();
if (links.length === 0) {
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
if (translatorConfigs.fromLang === mw.config.get('wgPageContentLanguage')) {
translationTextArea = $('#wpTextbox1').clone().attr({
'id': 'wpTextbox2'
}).css({ // new color for translation textarea
'background-color': 'whitesmoke'
}).val($('#wpTextbox1').val()); // this something that clone must do
$('#wpTextbox1').before(translationTextArea); // put translation textarea before old
} else {
translationTextArea = $('#wpTextbox1');
}
// for links
links = translationTextArea.val().match(/\[\[.*?\]\]/g);
templates = translationTextArea.val().match(/\{\{.*?[\n\|\}]/g);
itemsCount = -1;
if (links !== null) {
for (i = 0; i < links.length; i = i + 1) { // equals with <code>for (i in matched)</code>
title = links[i].replace(/\[\[:?([^\]\|]*)\|?.*?\]\]/g, "$1");
translateFromLanguageLinks(title);
}
if (itemsCount === -1) {
itemsCount = 0;
}
itemsCount = itemsCount + links.length;
}
if (templates !== null && translatorConfigs.enableTemplateTranslation === true) {
for (i = 0; i < templates.length; i = i + 1) { // equals with <code>for (i in matched)</code>
title = templates[i].replace(/\{\{\s*(?:[Tt]emplate:)?(.*)\s*[\n\|\}]/g, '$1');
translateFromLanguageTemplateLinks(title);
}
if (itemsCount === -1) {
itemsCount = 0;
}
itemsCount = itemsCount + templates.length;
}
if (itemsCount !== -1) {
$('#translatorProgress').show().attr('max', itemsCount);
}
}
};
}
var translator = new Translator();
$(function () {
"use strict";
function initializeEditorFor(forEditable, inputForEditable, setVariableClosure) {
$(forEditable).click(function (event) {
event.preventDefault();
$(forEditable).hide();
$(inputForEditable).css('width', '2em').show().val($(forEditable).text());
});
$(inputForEditable).keyup(function (event) {
var selectedLanugage = $(this).val();
if (event.keyCode === 13) {
$(this).focusout(); // on enter
} 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="//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}");