Gebruiker:JNB45/translation-editor.js: verschil tussen versies

Verwijderde inhoud Toegevoegde inhoud
JNB45 (overleg | bijdragen)
Nieuwe pagina aangemaakt met '/** * This script enables adding translations without handling wikitext. * * Copied and adapted from sv:MediaWiki:Gadget-translation editor.js (oldid=231982...'
(geen verschil)

Versie van 19 dec 2016 22:12

/**
 * This script enables adding translations without handling wikitext.
 * 
 * Copied and adapted from [[sv:MediaWiki:Gadget-translation editor.js]] (oldid=2319826)
 *
 * which is itself an adaptation of the English version
 * [[en:User:Conrad.Irwin/editor.js]]
 *
 * Author : [[sv:User:Skalman]]
 * Adaptation : [[bg:User:DenisWasRight]] w/ [[fr:user:Automatik]]
 *
 * 2016-12-19 -- last modified by DenisWasRight
 */

'use strict';

/* global $, mw, editor, silentFailStorage */

if (editor.enabled) {
	$('table.translations')
		.each(function (i) {
			add_translation_form(this, i);
			add_heading_updater(this);
		});
}

function get_translation_table_index(table) {
	return $.inArray(table, $('table.translations'));
}

function get_error_html(message) {
	return '<img src="//upload.wikimedia.org/wikipedia/commons/4/4e/MW-Icon-AlertMark.png"> ' + message;
}

var heading_id_counter = 0;
function add_heading_updater(table) {
	var id = heading_id_counter++;

	var self = $(table).parent('.NavContent').prev('.NavHead');

	var edit_head = $('<a>', {
		href: '#',
		text: '±',
		'class': 'ed-edit-head',
		title: 'Edit table heading'
	}).prependTo(self);

	function remove_gloss_nodes() {
		var nodes = [];
		$.each(self[0].childNodes, function (i, node) {
			if (node.className !== 'ed-edit-head' && node.className !== 'NavToggle') {
				nodes.push(node);
			}
		});
		$(nodes).detach();
		return nodes;
	}

	var gloss_nodes;
	edit_head.click(function (e) {
		e.preventDefault();
		if (self.find('form').length) {
			self.find('form').remove();
			self.append(gloss_nodes);
			return;
		}

		edit_head.text('Loading...');

		editor.wikitext()
		.then(function (wikitext) {
			edit_head.text('±');
			gloss_nodes = remove_gloss_nodes();
			var prev_gloss_nodes = gloss_nodes;

			var gloss = translation.get_gloss(wikitext, get_translation_table_index(table));

			var form = $('<form>', { html:
				'<label>Gloss: <input name="gloss"></label>' +
				'<button type="submit">Preview</button> ' +
				'<span class="ed-loading">Loading...</span>' +
				'<span class="ed-errors"></span>'
			});
			function error() {
				form.find('.ed-errors')
					.html(get_error_html('en: Please avoid special characters ([]{}#|) in description (or use {{trans-top|your description}}).'));
			}

			self.append(form);

			form.find('input')
				.val(gloss.standard ? gloss.text : gloss.trans_top)
				.focus();
			form.click(function (e) {
				e.stopPropagation();
			}).submit(function (e) {
				e.preventDefault();
				var gloss_wikitext = this.gloss.value;
				if (!translation.is_trans_top(gloss_wikitext) && translation.contains_wikitext(gloss_wikitext)) {
					error();
					return;
				}
				form.find('.ed-loading').show();

				$.when(
					parse_wikitext(translation.make_trans_top(gloss_wikitext)),

					// get wikitext again in case it has changed since last time
					editor.wikitext()
				).done(function (gloss_html, wikitext) {
					gloss_html = $(gloss_html);
					var prev_class = self.parent('.NavFrame').attr('class');
					var new_class = gloss_html.filter('.NavFrame').attr('class');

					gloss_html = gloss_html.find('.NavHead').contents();
					if (!gloss_html.length) {
						error();
						form.find('.ed-loading').hide();
						return;
					}

					form.remove();
					wikitext = translation.set_gloss(
						wikitext,
						get_translation_table_index(table),
						gloss_wikitext
					);
					editor.edit({
						wikitext: wikitext,
						summary: 'table header: "' + gloss_wikitext + '"',
						summary_type: 'gloss' + id,
						redo: function () {
							remove_gloss_nodes();
							$('<span>', {
								'class': 'ed-added',
								html: gloss_html
							}).appendTo(self);
							if (prev_class !== new_class) {
								self.parent('.NavFrame').attr('class', new_class);
							}
						},
						undo: function () {
							remove_gloss_nodes();
							self.append(prev_gloss_nodes);
							if (prev_class !== new_class) {
								self.parent('.NavFrame').attr('class', prev_class);
							}
						}
					});
				});
			});
		});
	});
}

function add_balancer(self, i) {
	var row = self.find('tr:first-child');
	if (row.children().length === 1) {
		row.append('<td>', row.children().first().clone().text(''));
	}
	var cell = row.children().eq(1);
	if (cell.find('button').length) {
		return;
	}
	cell.css('vertical-align', 'middle')
	.append(
		$('<button>', { text: '←', click: balance, value: -1 }),
		$('<br>'),
		$('<button>', { text: '→', click: balance, value: 1 })
	);
	var first_list = row.children().first().children('ul');
	var last_list = row.children().last().children('ul');
	if (!first_list.length) {
		first_list = $('<ul>').appendTo(row.children().first());
	}
	if (!last_list.length) {
		last_list = $('<ul>').appendTo(row.children().last());
	}
	function move(direction) {
		if (direction === 1) {
			first_list.children().last().prependTo(last_list);
		} else {
			last_list.children().first().appendTo(first_list);
		}
	}
	function balance() {
		var direction = +this.value;
		editor.wikitext()
		.done(function (wikitext) {
			var balanced_wikitext = translation.balance(wikitext, i, direction);
			if (balanced_wikitext === wikitext) {
				throw new Error('No translations to move');
			}
			editor.edit({
				wikitext: balanced_wikitext,
				summary: 'balansera',
				summary_type: 'balance',
				redo: function () {
					move(direction);
				},
				undo: function () {
					move(-direction);
				}
			});
		});
	}
}

function add_translation_form(table) {
	var self = $(table);
	var lang_meta = {
		// en, eo, fi, hu
		'': 'p',
		
		ar: 'm f c p trans',
		bg: 'm f n p trans',
		da: 'n c p',
		ca: 'm f p',
		cu: 'm f n c p',
		de: 'm f n p',
		el: 'm f n p trans',
		es: 'm f p',
		fo: 'm f n',
		fr: 'm f mf p',
		is: 'm f n p',
		it: 'm f mf p',
		ja: 'trans',
		la: 'm f n p',
		lv: 'm f p',
		nn: 'm f n p',
		no: 'm f mf n p',
		pl: 'm f n p',
		pt: 'm f p',
		ro: 'm f n p',
		ru: 'm f n trans',
		sh: 'm f n trans',		
		sk: 'm f n',
		sl: 'm f n',
		sr: 'm f n p trans',
		uk: 'm f n p trans',
		zh: 'trans'
	};
	var options = $.map({
		gender: {
			m: 'v',
			f: 'm',
			mf: 'маш. и жен.',
			n: 'n',
			c: 'з'
		},
		number: {
			s: 's',
			//d: 'p',
			p: 'p'
		}
	}, function (items, name) {
		items = $.map(items, function (text, value) {
			return '<label class="ed-' + value + '">' +
				'<input type="radio" name="' + name + '" value="' + value + '">' +
				text +
				'</label>';
		});
		return '<p class="ed-options ed-' + name + '">' + items.join(' ') + '</p>';
	}).join('') +
	'<p class="ed-options"><label class="ed-trans">Transliteration: <input name="trans"></label></p>' +
	'<p class="ed-options"><label class="ed-note">Note: <input name="note"></label></p>';

	var form = $($.parseHTML('<form><ul><li>' +
		'<p><label>Add translation ' +
		'<input class="ed-lang-code" name="lang_code" size="12" title="language code"></label>: ' +
		'<input class="ed-word" name="word" size="20" title="translation"> ' +
		'<button type="submit">Preview translation</button> ' +
		'<a href="#" class="ed-more">More</a></p>' +
		options +
		'<div class="ed-errors"></div>' +
		'</li></ul></form>'));

	// Make radio buttons deselectable
	form.find(':radio').click(function last_click(e) {
		if (last_click[this.name] === this) {
			last_click[this.name] = null;
			this.checked = false;
		} else {
			last_click[this.name] = this;
		}
	});
	var show_all_opts = false;
	form.find('.ed-lang-code')
		.blur(update_options_visibility)

		// If the item exists, the value will be used as the value,
		// otherwise it's 'null', which empties (the already empty)
		// text field.
		.val(silentFailStorage.getItem('trans-lang'));
	form.find('.ed-more').click(function (e) {
		e.preventDefault();
		show_all_opts = !show_all_opts;
		$(this).text(show_all_opts ? 'Less' : 'More');
		update_options_visibility();
	});
	update_options_visibility();
	function update_options_visibility() {
		var elems = form.find('.ed-options label');
		if (show_all_opts) {
			elems.show();
		} else {
			var opts = lang_meta[form[0].lang_code.value] || lang_meta[''];
			elems
				.hide()
				.filter('.ed-' + opts.replace(/ /g, ', .ed-')).show();
		}
	}

	$('<tr>')
		.append('<td>', '<td>', $('<td>').append(form) )
		.appendTo(self);

	self.find('input').focus(function () {
		editor.init();
	});
	var hasSeenCommaWarning = false;
	form.submit(function (e) {
		e.preventDefault();
		var lang_code = $.trim(this.lang_code.value);
		var word = $.trim(this.word.value);
		var gender = form.find('.ed-gender input:checked').prop('checked', false).val();
		var number = form.find('.ed-number input:checked').prop('checked', false).val();
		var trans = this.trans.value;
		var note = this.note.value;

		if (!lang_code) {
			show_error(new BadInputError('lang-code', 'no-lang-code'));
			return;
		} else if (!word) {
			show_error(new BadInputError('word', 'no-word'));
			return;
		} else if (!hasSeenCommaWarning && mw.config.get('wgPageName').indexOf(',') === -1 && word.indexOf(',') !== -1) {
			show_error(new BadInputError('word', 'comma-in-word'));
			hasSeenCommaWarning = true;
			return;
		}

		var word_options = {
			lang_code: lang_code,
			word: word,
			lang_name: null,
			gender: gender,
			number: number,
			trans: trans,
			note: note
		};

		function show_error(e) {
			form.find('.ed-error').removeClass('ed-error');
			if (!e) {
				form.find('.ed-errors').empty();
				return;
			}
			if (e instanceof NoLangTplError) {
				form.find('.ed-lang-code').addClass('ed-error').focus();
				e = 'The language code "' + e.lang_code + '" does not exist or is not used';
			} else if (e instanceof BadInputError) {
				form.find('.ed-' + e.input).addClass('ed-error').focus();
				if (e.type === 'no-lang-code') {
					e = 'Enter a language code (en, fr,...)';
				} else if (e.type === 'no-word') {
					e = 'Enter translation';
				} else if (e.type === 'comma-in-word') {
					e = 'Enter one translation at a time. If you are absolutely sure that the comma is included in the translation, you can press the "Preview" button again.';
				}
			} else if (e instanceof HttpError) {
				e = 'Can not load the translation. Check your internet connection?';
			}
			form.find('.ed-errors').html(get_error_html(e));
		}


		$.when(
			// word_html -- MODIFICATION FROM SWEDISH VERSION
			page_exists(lang_code, word)
			.then(function (page_exists) {
				word_options.exists = page_exists;
				return parse_wikitext(translation.get_formatted_word(word_options))
				.then(function (html) {
					return html;
				});
			}),
			// wikitext
			editor.wikitext(),
			// lang_name
			translation.get_language(lang_code)
		).fail(function (error) {
			if (error === 'http') {
				// jQuery HTTP error
				show_error(new HttpError());
			} else {
				show_error(error);
			}
		}).done(function (word_html, wikitext, lang_name) {
			show_error(false);
			
			silentFailStorage.setItem('trans-lang', lang_code);

			form[0].word.value = '';
			form[0].trans.value = '';
			form[0].note.value = '';

			word_options.lang_name = lang_name;
			var added_elem;
			var index = get_translation_table_index(table);

			wikitext = translation.add(wikitext, index, word_options);

			add_balancer(self, index);

			editor.edit({
				summary: '+' + lang_code + ': [[' + word + ']]',
				wikitext: wikitext,
				redo: function () {
					var translations = self.find('tr:first-child > td > ul > li,' +
						'tr:first-child > td:nth-child(2)');
					translation.add_to_list({
						items: translations,
						add_only_item: function () {
							added_elem = $('<li>', { html: lang_name + ': ' + word_html });
							self.find('tr:first-child > td:first-child > ul').append(added_elem);
						},
						equal_or_before: function (item) {
							var match = /^\s*([^:]+):/.exec($(item).text());
							if (match) {
								if (match[1] === lang_name) {
									return 'equal';
								} else if (match[1] < lang_name) {
									return 'before';
								}
							}
							return false;
						},
						add_to_item: function (item) {
							added_elem = $('<span>', { html: ', ' + word_html})
								.appendTo(item);
						},
						add_after: function (item) {
							added_elem = $('<li>', { html: lang_name + ': ' + word_html })
								.insertAfter(item);
						},
						add_before: function (item) {
							added_elem = $('<li>', { html: lang_name + ': ' + word_html });
							if ($(item).is('td')) {
								// Special case: {{trans-mid}}
								self.find('tr:first-child > td:first-child > ul').append(added_elem);
							} else {
								added_elem.insertBefore(item);
							}
						},
					});
					added_elem.addClass('ed-added');
				},
				undo: function () {
					added_elem.remove();
				}
			});
		});
	});
}

function parse_wikitext(wikitext) {
	return new mw.Api().get({
		action: 'parse',
		text: '<div>' + wikitext + '</div>',
		title: mw.config.get('wgPageName')
	}).then(function (data) {
		var html = data.parse.text['*'];
		// Get only the parts between <div> and </div>
		html = html.substring(
			html.indexOf('<div>') + '<div>'.length,
			html.lastIndexOf('</div>')
		);
		return $.trim(html);
	});
}

function page_exists(lang_code, page) {
	var def = $.Deferred();
	$.ajax({
		url: '//' + lang_code + '.wiktionary.org/w/api.php?origin=' + location.protocol + '//' + location.host,
		data: {
			action: 'query',
			titles: page,
			format: 'json'
		},
		dataType: 'json'
	}).fail(function () {
		def.resolve(false);
	}).then(function (data) {
		def.resolve(!data.query.pages[-1]);
	});
	return def.promise();
}

var translation = {
	re_wikitext: /[[\]{}#|]/,

	contains_wikitext: function (str) {
		return translation.re_wikitext.test(str);
	},

	re_gloss: /\{\{trans\-top([^\}]*)\}\}/g,

	re_section: /(\{\{trans\-top[^\}]*\}\})([\s\S]*?)(\{\{trans\-bottom\}\})/g,

	is_trans_top: function (gloss) {
		return gloss.replace(translation.re_gloss, '-') === '-';
	},

	make_trans_top: function (gloss) {
		if (translation.is_trans_top(gloss)) {
			return gloss;
		} else {
			return '{{trans-top|' + gloss + '}}';
		}
	},

	get_gloss: function (wikitext, index) {
		if (wikitext.indexOf('<!--') !== -1) {
			throw new Error('Wikitext contains "<!--". Change manually.');
		}
		translation.re_gloss.lastIndex = 0;

		for (var i = 0; i <= index; i++) {
			var match = translation.re_gloss.exec(wikitext);
			if (i === index && match) {
				var standard = /^(|\|[^\|=]*)$/.test(match[1]);
				return {
					trans_top: match[0],
					text: standard ? match[1].substr(1) : void 0,
					standard: standard
				};
			}
		}
		throw new Error('Can not find {{trans-top}} temp. ' + (index+1) + ' in wikitext.');
	},
	set_gloss: function (wikitext, index, gloss) {
		index++;
		var count = 0;
		return wikitext.replace(translation.re_gloss, function (match, p1, p2) {
			count++;
			if (count !== index) {
				return match;
			}
			return translation.make_trans_top(gloss);
		});
	},
	get_formatted_word: function (opts) {
		var tpl = [
			opts.exists ? 't+' : 't',
			opts.lang_code,
			opts.word
		];
		opts.gender && tpl.push(opts.gender);
		opts.number && tpl.push(opts.number);
		opts.trans && tpl.push('trans=' + opts.trans);
		opts.note && tpl.push('note=' + opts.note);
		return '{{' + tpl.join('|') + '}}';
	},
	// Options:
	// - items: Array of items
	// - equal_or_before: Function that returns either 'equal', 'before' or false
	// - add_to_item: Adds a word to an item
	// - add_after: Adds the item after an item
	// - add_before: Adds the item before an item
	add_to_list: function (opts) {
		var items = opts.items;
		if (!items.length) {
			items[0] = opts.add_only_item();
			return items;
		}
		for (var i = items.length - 1; i >= 0; i--) {
			var eq_or_bef = opts.equal_or_before(items[i]);
			if (eq_or_bef === 'equal') {
				items[i] = opts.add_to_item(items[i]);
				return items;
			} else if (eq_or_bef === 'before') {
				items[i] = opts.add_after(items[i]);
				return items;
			}
		}
		items[0] = opts.add_before(items[0]);
		return items;
	},
	add: function (wikitext, index, opts) {
		if (wikitext.indexOf('<!--') !== -1) {
			throw new Error('Wikitext contains "<!--". Change manually.');
		}
		index++;
		var count = 0;
		return wikitext.replace(translation.re_section, function (match, p1, p2, p3) {
			count++;
			if (count !== index) {
				return match;
			}

			p2 = $.trim(p2);

			var formatted_word = translation.get_formatted_word(opts);

			var lines = translation.add_to_list({
				// split into lines
				items: p2 ? p2.split('\n') : [],
				add_only_item: function () {
					return '*' + opts.lang_name + ': ' + formatted_word;
				},
				equal_or_before: function (line) {
					var match = /^\*\s*([^:]+):/.exec(line);
					if (match) {
						if (match[1] === opts.lang_name) {
							return 'equal';
						} else if (match[1] < opts.lang_name) {
							return 'before';
						}
					}
					return false;
				},
				add_to_item: function (line) {
					return line + ', ' + formatted_word;
				},
				add_before: function (line) {
					return this.add_only_item() + '\n' + line;
				},
				add_after: function (line) {
					return line + '\n' + this.add_only_item();
				}
			});

			if (p2.indexOf('{{trans-mid}}') === -1) {
				lines.push('{{trans-mid}}');
			}

			return p1 + '\n' + lines.join('\n') + '\n' + p3;
		});
	},
	get_language: function (lang_code) {
		var known = {
			en: 'Англиски',
			fi: 'Фински',
		};
		if (lang_code in known) {
			return $.Deferred().resolve(known[lang_code]).promise();
		} else {
			return new mw.Api().get({
				action: 'expandtemplates',
				text: '{{' + lang_code + '}}'
			}).then(function (data) {
				data = data.expandtemplates['*'];
				if (data.substr(0, 3) === '[[:') {
					return $.Deferred().reject(new NoLangTplError(lang_code)).promise();
				}
				return data;
			});
		}
	},
	balance: function (wikitext, index, direction) {
		if (wikitext.indexOf('<!--') !== -1) {
			throw new Error('Wikitext contains "<!--". Change manually.');
		}
		index++;
		var count = 0;
		return wikitext.replace(translation.re_section, function (match, p1, p2, p3) {
			count++;
			if (count !== index) {
				return match;
			}
			if (/(^|\n)(\*\*|\*:|:)/.test(p2)) {
				throw new Error('Kan inte balansera pga. indragna rader');
			}

			p2 = $.trim(p2);

			var lines = p2 ? p2.split('\n') : [];
			for (var i = 0; i < lines.length; i++) {
				if (lines[i] === '{{trans-mid}}') {
					if (!lines[i - direction]) {
						// nowhere to move
						return match;
					}
					lines[i] = lines[i - direction];
					lines[i - direction] = '{{trans-mid}}';
					return p1 + '\n' + lines.join('\n') + '\n' + p3;
				}
			}
			// couldn't find {{trans-mid}}
			return match;
		});
	}
};


function extend_error(name, p1_name, p2_name) {
	function E(p1, p2) {
		this.message = p1;
		if (p1_name) this[p1_name] = p1;
		if (p2_name) this[p2_name] = p2;
	}
	E.prototype = new Error();
	E.prototype.constructor = E;
	E.prototype.name = name;
	return E;
}

var NoLangTplError = extend_error('NoLangTplError', 'lang_code');
var BadInputError = extend_error('BadInputError', 'input', 'type');
var HttpError = extend_error('HttpError');

// Export some useful components
window.translation = translation;
window.parse_wikitext = parse_wikitext;
window.add_heading_updater = add_heading_updater;
window.add_translation_form = add_translation_form;