MediaWiki:Gadget-Global-ShortLinkedPages.js

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 the shortest pages linked from a given page
 */
const ShortLinkedPages = {

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

	getPages: function () {
		const $div = $( this );
		const page = $div.data( 'page' ) || mw.config.get( 'wgPageName' );
		const namespace = $div.data( 'namespace' ) || 0;
		const params = {
			action: 'query',
			titles: page,
			prop: 'info',
			generator: 'links',
			gpllimit: 'max',
			gplnamespace: namespace,
			redirects: true,
			formatversion: 2,
		};
		const pages = [];
		new mw.Api().get( params ).done( response => ShortLinkedPages.getPagesContinue( response, params, pages, $div ) );
	},

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

	makeList: function ( pages, $div ) {

		// Sort the pages by length (ascending)
		pages.sort( ( a, b ) => a.length - b.length );

		// Trim the results
		const limit = $div.data( 'limit' ) || 10;
		const top = pages.slice( 0, limit );

		// Make the list
		const $list = $( '<ul></ul>' );
		const editlink = $div.data( 'editlink' );
		const editintro = $div.data( 'editintro' );
		for ( const page of top ) {
			const url = mw.util.getUrl( page.title );
			const $link = $( '<a target="_blank" href="' + url + '">' + page.title + '</a>' );
			const $item = $( '<li></li>' ).append( $link );
			if ( editlink ) {
				const editurl = mw.util.getUrl( page.title, { veaction: 'edit', editintro: editintro } );
				const $editicon = $( '<img width="14" height="14" src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Pencil_edit_icon.svg" />' ).css( 'vertical-align', 'initial' );
				const $editlink = $( '<a target="_blank" href="' + editurl + '"></a>' ).css( 'margin-left', '.5em' ).append( $editicon );
				$item.append( $editlink );
			}
			$list.append( $item );
		}

		// Add it to the DOM
		$div.html( $list );
	}
};

$( ShortLinkedPages.init );