User:0x010C/scripts/MixedNamespaceSearchSuggestions.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/**
 * Makes the search box autocomplete terms matching pages from several namespaces.
 * 
 * Set in a global variable called 'mnssNamespaces' an array of the namespace's
 * numbers you want to search through.
 * 
 * For exemple, to search in the main, file and category namespace, use:
 * var mnssNamespaces = [ 0, 6, 14 ];
 * 
 * Adapted from [[:mediawiki:Extension:MixedNamespaceSearchSuggestions]]
 * @author Niklas Laxström ([[User:Nikerabbit]]), [[User:0x010C]]
 * @license MIT
 */

$( function () {

	// Compute form data for search suggestions functionality.
	function computeResultRenderCache( context ) {
		var $form, baseHref, linkParams;

		// Compute common parameters for links' hrefs
		$form = context.config.$region.closest( 'form' );

		baseHref = $form.attr( 'action' );
		baseHref += baseHref.indexOf( '?' ) > -1 ? '&' : '?';

		linkParams = {};
		$.each( $form.serializeArray(), function ( idx, obj ) {
			linkParams[ obj.name ] = obj.value;
		} );

		return {
			textParam: context.data.$textbox.attr( 'name' ),
			linkParams: linkParams,
			baseHref: baseHref
		};
	}

	// The function used to render the suggestions.
	function customRenderFunction( text, context ) {
		var page, namespace,
			title = mw.Title.newFromText( text ),
			info = computeResultRenderCache( context );

		info.linkParams[ info.textParam ] = text;

		page = title.getMainText();
		namespace = $( '<span>' )
			.text( mw.config.get( 'wgFormattedNamespaces' )[ title.namespace ] )
			.css( 'color', 'grey' )
      .css( 'float', 'right' );

		// 'this' is the container <div>, jQueryfied
		this
			.append( namespace, page )
			.wrap(
				$( '<a>' )
					.attr( 'href', info.baseHref + $.param( info.linkParams ) )
					.addClass( 'mw-searchSuggest-link' )
			);
	}

	$( document ).ready( function () {
		var $searchInput = $( '#searchInput' );

		$searchInput.suggestions( {
			fetch: function ( query ) {
				var $el;

				if ( query.length !== 0 ) {
					var namespaces = '0';
					if ( typeof mnssNamespaces !== 'undefined' ) {
						namespaces = mnssNamespaces.join( '|' );
					}
					$el = $( this );
					$el.data( 'request', ( new mw.Api() ).get( {
						action: 'opensearch',
						search: query,
						namespace: namespaces,
						suggest: ''
					} ).done( function ( data ) {
						$el.suggestions( 'suggestions', data[1] );
					} ) );
				}
			},
			result: {
				render: customRenderFunction
			}
		} );
	} );

} );