Jump to content

User:PleaseStand/prevnext.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
( function ( mw, $ ) {

	if ( mw.config.get( 'wgNamespaceNumber' ) < 0 ) {
		return;
	}

	mw.messages.set( {
		'ps-prevnext-prev-text': '← $1',
		'ps-prevnext-next-text': '$1 →'
	} );

	function findOtherPage( query ) {
		var articleId = String( mw.config.get( 'wgArticleId' ) ), x, p;

		if ( !query || !query.pageids || !query.pages ) {
			return null;
		}

		for ( x = 0; x < query.pageids.length; ++x ) {
			p = query.pageids[x];
			if ( p !== articleId ) {
				return query.pages[p];
			}
		}
	}

	function addLink( $elm, page, msgKey ) {
		if ( !page ) {
			return;
		}

		$( '<a>' )
			.prop( {
				href: page.fullurl,
				title: page.title,
			} )
			.text( mw.message( msgKey, page.title ).plain() )
			.appendTo( $elm );
	}

	function ready() {
		var $prev, $next, api = new mw.Api(), baseQuery, nextQuery, prevQuery;

		$prev = $( '<div class="prevnext-prev"></div>' ).insertBefore( '#firstHeading' );
		$next = $( '<div class="prevnext-next"></div>' ).insertBefore( '#firstHeading' );

		baseQuery = {
			maxage: 600,
			action: 'query',
			prop: 'info',
			inprop: 'url',
			indexpageids: '',
			generator: 'allpages',
			gapfilterredir: 'nonredirects',
			gaplimit: 2,
			gapnamespace: mw.config.get( 'wgNamespaceNumber' ),
			gapfrom: mw.config.get( 'wgTitle' ),
			'continue': ''
		};

		nextQuery = $.extend( {}, baseQuery, { gapdir: 'ascending' } );
		prevQuery = $.extend( {}, baseQuery, { gapdir: 'descending' } );

		api.get( nextQuery ).done( function ( data ) {
			addLink( $next, findOtherPage( data.query ), 'ps-prevnext-next-text' );
		} );

		api.get( prevQuery ).done( function ( data ) {
			addLink( $prev, findOtherPage( data.query ), 'ps-prevnext-prev-text' );
		} );
	}

	mw.loader.load(
		'//en.wikipedia.org/w/index.php?title=User:PleaseStand/prevnext.css&action=raw&ctype=text/css',
		'text/css'
	);

	mw.loader.using( ['mediawiki.api'], function () {
		$( ready );
	} );

}( mediaWiki, jQuery ) );