MediaWiki:Gadget-Global-PagesToTranslate.js

From wikiNonStop
Revision as of 18:00, 25 December 2024 by Majestix (talk | contribs) (1 revision imported: Initial setup)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.
/**
 * This gadget produces a list of pages to translate out of a given seed page
 */
const PagesToTranslate = {

	init: function () {
		$( '.PagesToTranslate' ).each( PagesToTranslate.getPages );
	},

	getPages: function () {
		const $div = $( this );
		const source = $div.data( 'source' ) || mw.config.get( 'wgUserLanguage' );
		const target = $div.data( 'target' ) || mw.config.get( 'wgContentLanguage' );
		if ( source === target ) {
			$div.addClass( 'error' ).text( 'The source and target languages must differ' );
		}
		const seed = $div.data( 'seed' ) || mw.config.get( 'wgPageName' );
		const limit = $div.data( 'limit' ) || 10;
		const params = {
				source: source,
				target: target,
				count: limit,
				seed: seed,
			};
		const pages = [];
		$.get( '//api.wikimedia.org/service/lw/recommendation/api/v1/translation', params ).done( response => PagesToTranslate.getPagesContinue( response, params, pages, $div ) );
	},

	getPagesContinue: function ( response, params, pages, $div ) {
		for ( const page of response ) {
			pages.push( page.title );
		}
		if ( response.continue ) {
			params.gplcontinue = response.continue.gplcontinue;
			new mw.Api().get( params ).done( response => PagesToTranslate.getPagesContinue( response, params, pages, $div ) );
		} else {
			PagesToTranslate.makeList( params, pages, $div );
		}
	},

	makeList: function ( params, pages, $div ) {
		const $list = $( '<ul></ul>' );
		for ( const page of pages ) {
			const url = 'https://' + params.source + '.wikipedia.org' + mw.util.getUrl( page );
			const $link = $( '<a target="_blank" href="' + url + '">' + page + '</a>' );
			const $item = $( '<li></li>' ).append( $link );
			const translateUrl = mw.util.getUrl( 'Special:ContentTranslation', { page: page, from: params.source, to: params.target } );
			const $translateIcon = $( '<img width="14" height="14" src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Pencil_edit_icon.svg" />' ).css( 'vertical-align', 'initial' );
			const $translateLink = $( '<a target="_blank" href="' + translateUrl + '"></a>' ).css( 'margin-left', '.5em' ).append( $translateIcon );
			$item.append( $translateLink );
			$list.append( $item );
		}
		$div.html( $list );
	}
};

$( PagesToTranslate.init );