Jump to content

User:NguoiDungKhongDinhDanh/QuickTranslation.js

From translatewiki.net

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/** <nowiki>
 * Add a blue button to pages.
 * 
 * For attribution: [[:metawikimedia:User:DannyS712/TranslationSource.js]]
 * See also: [[:metawikimedia:User:NguoiDungKhongDinhDanh/QuickTranslation.js]]
**/

$(document).ready(() => {
	var a = mw.config.get('wgAction'),
		b = mw.config.get('wgPageName'),
		ar = [0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15],
		nn = mw.config.get('wgNamespaceNumber');
		
	if (a !== 'view' || // View only
		!b.match(/^\w+?:.+?\/.+?$/) || // At least one slash
		nn < 0 || ar.includes(nn)) { // No special, main, user, project, file, template, help, category & corr talk nses.
		return;
	}
	
	// Load CSS file
	mw.loader.load(
		'//meta.wikimedia.org/w/index.php?title=User:NguoiDungKhongDinhDanh/QuickTranslation.css&action=raw&ctype=text/css', 'text/css'
	);
	
	var quickTranslationCore = function(docHTML, sourceTitleNoLang, sourceWikitext, translationWikitext) {
		// Hide the button
		$('#quickTranslationButton, #mw-content-text').hide();
		$('#quickTranslationButton').text('QuickTrans!');
		
		// Create form
		$('#firstHeading').after(
			'<div id="quickTranslationEditor">' +
				(docHTML.length <= 0 ? '' :
					'<span class="quickTranslationLabel" id="quickTranslation-doc-span">' +
						'<label for="quickTranslation-doc">' +
							'<a href="/wiki/' + sourceTitleNoLang.replace(/ /g, '_') + '/qqq' + '">Translation documentation</a>:' +
						'</label>'+
					'</span>' +
					'<div id="quickTranslation-doc">' +
						docHTML.replace(/mw-collapsible|mw-collapsed/g, '') +
					'</div>'
				) +
				'<span class="quickTranslationLabel" id="quickTranslation-sourcecode-span">' +
					'<label for="quickTranslation-sourcecode">' +
						'<a href="/wiki/' + sourceTitle.replace(/ /g, '_') + '">Source code</a>:' +
					'</label>'+
				'</span>' +
				'<pre class="quickTranslationCode" id="quickTranslation-sourcecode">' +
				'</pre>' +
				(translationWikitext.length <= 0 ? '' :
					'<span class="quickTranslationLabel" id="quickTranslation-curtrans-span">' +
						'<label for="quickTranslation-curtrans">Current translation:</label>'+
					'</span>' +
					'<pre class="quickTranslationCode" id="quickTranslation-curtrans">' +
					'</pre>'
				) +
				'<span class="quickTranslationLabel" id="quickTranslation-yourtrans-span">' +
					'<label for="quickTranslation-yourtrans">Your translation:</label>'+
				'</span>' +
				'<div id="quickTranslation-yourtrans">' +
					'<textarea tabindex="0" name="wpText-quickTranslation" rows="15" id="quickTranslationEditorTextarea" \
					class="oo-ui-inputWidget-input">' +
					'</textarea>' +
				'</div>' +
				'<div id="quickTranslation-others">' +
					'<input type="text" placeholder="Optional edit summary..." \
					id="quickTranslationSummary" maxlength="255" value="' +
						'(via [[:metawikimedia:User:NguoiDungKhongDinhDanh/QT|QuickTranslation]])' + // Need some promotion here
					'">' +
					'<br>' +
					'<button class="mw-ui-button mw-ui-progressive quickTranslationButtons" \
					id="translationSubmit">Submit</button>' +
					'<button class="mw-ui-button mw-ui-destructive quickTranslationButtons" \
					id="translationCancel">Cancel</button>' +
				'</div>' +
			'</div>'
		);
		
		// Workaround to prevent parsing HTML tags in wikitext.
		$('#quickTranslation-sourcecode').text(sourceWikitext);
		$('#quickTranslation-curtrans').text(translationWikitext);
		$('#quickTranslationEditorTextarea').text(translationWikitext);
			
		// Event handlers
		$('#translationSubmit').click(function() {
			var submission = $('#quickTranslationEditorTextarea').val(),
				editsummary = $('#quickTranslationSummary').val();
			new mw.Api().postWithToken('csrf', {
				action: 'edit',
				title: fulltitle,
				text: submission,
				summary: editsummary,
				format: 'json'
			}).done(function() {
				$('#quickTranslationEditor').remove();
				mw.notify(
					'You have successfully submitted your translation. Reloading...',
					{
						title: 'Translation submitted!'
					}
				);
				location.reload();
			});
		});
		
		$('#translationCancel').click(function() {
			$('#quickTranslationEditor').remove();
			$('#quickTranslationButton, #mw-content-text').show();
		});
	};
	
	// Pagenames
	var fulltitle = mw.config.get('wgPageName'),
		title = mw.config.get('wgTitle'),
		ns = mw.config.get('wgNamespaceNumber');
		ns = mw.config.get('wgFormattedNamespaces')[ns];
	
	// Trim off last 1 slash
	var sourceTitleNoLang = ns + ':' + title.substr(0, title.lastIndexOf('/')),
		sourceTitle = sourceTitleNoLang + '/en';
	
	// So that there will be no buttons on source page.
	if (ns + ':' +title.replace(/_/g, ' ') == sourceTitle.replace(/_/g, ' ')) return;
		
	// Add button after title
	$('#firstHeading').after(
		$('<button>')
		.text('QuickTrans!')
		.attr('title', sourceTitle)
		.attr('id', 'quickTranslationButton')
		.attr('class', 'mw-ui-button mw-ui-progressive')
	);
	
	// Main function
	$('#quickTranslationButton').click(function(e) {
		e.preventDefault();
		$(this).text('Initializing...');
		var tid = (mw.config.get('wgArticleId') == 0 ? undefined : mw.config.get('wgArticleId'));
		new mw.Api().get({
			action: 'query',
			prop: 'revisions',
			titles: sourceTitle + '|' + fulltitle,
			rvslots: '*',
			rvprop: 'content',
			formatversion: 2
		}).done(function(response) {
			// Get source/target wikitext
			var sourceWikitext, translationWikitext,
				p = response.query.pages[0],
				getwt = function(n) {
					if (!!response.query.pages[n].missing) {
						return '';
					} else {
						return response.query.pages[n].revisions[0].slots.main.content;
					}
				};
			
			if (tid !== p.pageid &&	typeof p.pageid !== 'undefined') { // If the translation's id differs from first page's id (not undefined),
				sourceWikitext = getwt(0); // then the first page is the source page.
				translationWikitext = getwt(1);
			} else if (tid !== p.pageid && typeof p.pageid === 'undefined') { // If first page's id is undefined,
				sourceWikitext = getwt(0); // then the first page is the source page.
				translationWikitext = getwt(1);
			} else { // Else, the second one is the source.
				sourceWikitext = getwt(1);
				translationWikitext = getwt(0);
			}
			
			if (sourceWikitext.length == 0) {
				$('#quickTranslationButton').remove();
				$('#firstHeading').after(
					'<strong class="error" style="color: #D33;" id="quickTranslationError">Source page is blank or doesn\'t exist!</span>'
				);
				setTimeout(function() {
					$('#quickTranslationError').fadeOut('slow', function() {
						$('#quickTranslationError, #quickTranslationButton').remove();
					});
				}, 1000);
				return;
			}
			
			new mw.Api().get({ // Get translation documentation. This one use a different API action.
				action: 'parse',
				page: sourceTitleNoLang + '/qqq',
				prop: 'text',
				wrapoutputclass: 'mw-parser-output',
				format: 'json',
				formatversion: 2
			}).then( // Dirty workaround...
				function(response) {
					quickTranslationCore(response.parse.text, sourceTitleNoLang, sourceWikitext, translationWikitext);
				},
				function() {
					quickTranslationCore('', sourceTitleNoLang, sourceWikitext, translationWikitext);
				}
			);
		});
	});
});

// </nowiki>