MediaWiki:Gadget-translation editor.js

Bemærk: Efter at have gemt er du måske nødt til at tømme din browsers cache for at kunne se ændringerne.

  • Firefox / Safari: Hold Shift nede og klik på Reload, eller tryk enten Ctrl-F5 eller Ctrl-R (⌘-R på en Mac).
  • Google Chrome: Tryk Ctrl-Shift-R (⌘-Shift-R på en Mac).
  • Edge: Hold Ctrl nede og klik på Refresh, eller tryk på Ctrl-F5.
//  Kopieret, med få ændringer, fra https://sv.wiktionary.org/wiki/MediaWiki:Gadget-translation_editor.js.
'use strict';

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

if (editor.enabled) {
	$('table.översättningar')
		.each(function (i) {
			add_translation_form(this, i);
			add_heading_updater(this);
		});
}

function get_translation_table_index(table) {
	return $.inArray(table, $('table.översättningar'));
}

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

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: 'Ændr oversættelsesoverskrift'
	}).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('Loader...');

		editor.wikitext()
		.then(function (wikitext) {
			edit_head.text('±');

			var gloss;
			try {
				gloss = translation.get_gloss(wikitext, get_translation_table_index(table));
			} catch (e) {
				edit_head.remove();
				$('<span>', { class: 'ed-errors', html: get_error_html(e) }).appendTo(self);
				return;
			}

			gloss_nodes = remove_gloss_nodes();
			var prev_gloss_nodes = gloss_nodes;

			var form = $('<form>', { html:
				'<label>Definition: <input name="gloss"></label>' +
				'<button type="submit">Se forhåndsvisning</button> ' +
				'<span class="ed-loading">Loader...</span>' +
				'<span class="ed-errors"></span>'
			});
			function error() {
				form.find('.ed-errors')
					.html(get_error_html('Angiv enten hele skabelonen, {{t}}, eller udelad helt wikitekst ([]{}#|).'));
			}

			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: 'oversættelsesoverskrift: "' + 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('Ingen oversættelse at flytte.');
			}
			editor.edit({
				wikitext: balanced_wikitext,
				summary: 'balancér',
				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',

		ab: 'trans p',
		an: 'm f p',
		ar: 'trans m f p',
		ast: 'm f p',
		ba: 'trans p',
		be: 'trans m f n p pf impf',
		bg: 'trans m f n p pf impf',
		bs: 'm f n p pf impf',
		ca: 'm f mf p',
		ce: 'trans',
		chr: 'trans p',
		cs: 'm f n p pf impf',
		csb: 'pf impf',
		cu: 'trans m f n p pf impf',
		cv: 'trans',
		de: 'm f n p',
		dsb: 'pf impf',
		el: 'trans m f n p',
		es: 'm f mf p',
		fa: 'trans',
		fo: 'm f n',
		fr: 'm f mf p',
		gl: 'm f mf p',
		'gmq-bot': 'm f n p',
		got: 'm f n p trans',
		grc: 'trans m f n p d',
		he: 'trans m f p',
		hi: 'trans m f p',
		hr: 'm f n p pf impf',
		hsb: 'pf impf',
		hy: 'trans',
		is: 'm f n p',
		it: 'm f mf p',
		ja: 'trans',
		ka: 'trans p',
		kk: 'trans p',
		km: 'trans p',
		ko: 'trans',
		kpv: 'trans p',
		krc: 'trans p',
		ky: 'trans p',
		la: 'm f n p',
		lez: 'trans p',
		lo: 'trans',
		lt: 'm f p',
		lv: 'm f p',
		mk: 'trans m f n p pf impf',
		ml: 'trans',
		mn: 'trans',
		mr: 'trans m f n',
		mt: 'm f p',
		nl: 'm f n p',
		nn: 'm f n p',
		no: 'm f n p',
		orv: 'pf impf',
		ovd: 'm f n p',
		pl: 'm f n p pf impf',
		pox: 'pf impf',
		pt: 'm f mf p',
		ro: 'm f n p',
		ru: 'trans m f n p pf impf',
		rue: 'pf impf',
		sa: 'trans m f n p d',
		sah: 'trans',
		sk: 'm f n p pf impf',
		sl: 'm f n p pf impf',
		sq: 'm f n p',
		sr: 'm f n p pf impf',
		sv: 'c n p',
		szl: 'pf impf',
		tt: 'trans',
		tyv: 'trans',
		udm: 'trans',
		uk: 'trans m f n p pf impf',
		yi: 'trans m f n p',
		zh: 'trans'
	};
	var options = $.map({
		gender: {
			m: 'hankøn',
			f: 'hunkøn',
			mf: 'hankøn og hunkøn',
			n: 'intetkøn',
			c: 'fælleskøn'
		},
		number: {
			s: 'singularis',
			d: 'dualis',
			p: 'flertal'
		},
		aspect: {
			pf: 'perfekt aspekt',
			impf: 'imperfekt aspekt'
		}
	}, 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">Translitteration: <input name="trans"></label></p>' +
	'<p class="ed-options"><label class="ed-note">Not: <input name="note"></label></p>' +
	'<p class="ed-options"><label class="ed-display_text">Visad text: <input name="display_text"></label></p>';

	var form = $($.parseHTML('<form><ul><li>' +
		'<p><label>Tilføj oversættelse ' +
		'<input class="ed-lang-code" name="lang_code" size="3" placeholder="Sprogkode" title="Sprogkode (to eller tre bogstaver)"></label>: ' +
		'<input class="ed-word" name="word" size="20" placeholder="Ord på fremmedsproget" title="Ord på fremmedsproget"> ' +
		'<button type="submit">Se forhåndsvisning</button> ' +
		'<a href="#" class="ed-more">Mere</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 ? 'Mindre' : 'Mere');
		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 aspect = form.find('.ed-aspect input:checked').prop('checked', false).val();
		var trans = this.trans.value;
		var note = this.note.value;
		var display_text = this.display_text.value;

		if (!lang_code) {
			show_error(new BadInputError('lang-code', 'no-lang-code'));
			return;
		} else if (lang_code === 'da') {
			show_error(new BadInputError('lang-code', 'origin-lang'));
			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,
			exists: null,
			gender: gender,
			number: number,
			aspect: aspect,
			trans: trans,
			note: note,
			display_text: display_text
		};

		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 = 'Sprogkoden "' + e.lang_code + '" anerkendes ikke';
			} else if (e instanceof BadInputError) {
				form.find('.ed-' + e.input).addClass('ed-error').focus();
				if (e.type === 'no-lang-code') {
					e = 'Angiv sprogkode (en, fr, abq)';
				} else if (e.type === 'origin-lang') {
					e = 'Angiv sprogkode for målsproget';
				} else if (e.type === 'no-word') {
					e = 'Angiv oversættelse';
				} else if (e.type === 'comma-in-word') {
					e = 'Angiv kun én oversættelse ad gangen. Hvis der skal være et komma i oversættelsen, tryk da på "Se forhåndsvisning" igen.';
				}
			} else if (e instanceof HttpError) {
				e = 'Kan ikke loade oversættelse. Tjek venligst din internetforbindelse.';
			}
			form.find('.ed-errors').html(get_error_html(e));
		}


		$.when(
			// word_html
			get_pagename(lang_code, word)
			.then(function (pagename) {
				return page_exists(lang_code, pagename);
			})
			.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);

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

			try {
				wikitext = translation.add(wikitext, index, word_options);
			} catch (e) {
				show_error(e);
				return;
			}

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

			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');
					mw.hook('wikipage.content').fire(added_elem);
				},
				undo: function () {
					added_elem.remove();
				}
			});
		});
	});
}

function parse_wikitext(wikitext) {
	return new mw.Api().get({
		action: 'parse',
		prop: 'text',
		disablelimitreport: '',
		wrapoutputclass: '',
		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 get_pagename(lang_code, title) {
	return parse_wikitext('{' + '{sidnamn|' + lang_code + '|' + title + '}}');
}

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

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('Wikitekst indeholder "<!--". Ændr manuelt.');
		}
		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('Finder ikke {{trans-top}} nr. ' + (index+1) + ' i wikiteksten.');
	},
	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.aspect && tpl.push(opts.aspect);
		opts.display_text && tpl.push('text=' + opts.display_text);
		opts.trans && tpl.push('tr=' + opts.trans);
		opts.note && tpl.push('not=' + 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('Wikitekst indeholder "<!--". Ændr manuelt.');
		}
		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) {
			return new mw.Api().get({
				action: 'expandtemplates',
				prop: 'wikitext',
				text: '{{' + lang_code + '|first_letter=lowercase}}'
			}).then(function (data) {
				data = data.expandtemplates.wikitext;
				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('Wikitekst indeholder "<!--". Ændr manuelt.');
		}
		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 ikke balancere pga. indskudte linjer.');
			}

			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;