MediaWiki:Gadget-Global-InlineSearch.js

From Irregularpedia
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)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/**
 * InlineSearch allows to search the wiki and display the results in a wiki page
 * Documentation: https://www.mediawiki.org/wiki/InlineSearch
 * License: GNU General Public License (http://www.gnu.org/licenses/gpl.html)
 * Author: Sophivorus
 */
var InlineSearch = {

	init: function () {
		$( '.InlineSearch' ).each( InlineSearch.search );
	},

	search: function () {
		var $div = $( this );
		var search = $div.data( 'search' );
		var namespace = $div.data( 'namespace' );
		var limit = $div.data( 'limit' );
		var sort = $div.data( 'sort' );
		var params = {
			format: 'json',
			formatversion: 2,
			action: 'query',
			list: 'search',
			srsearch: search,
			srnamespace: namespace,
			srlimit: limit,
			srsort: sort,
		};

		// Remove empty parameters
		for ( var key in params ) {
			if ( params[ key ] === '' ) {
				delete params[ key ];
			}
		}

		// Do the query
		new mw.Api().get( params ).done( function ( data ) {
			var results = data.query.search;
			if ( results ) {
				var list = $( '<ul class="InlineSearch-results"></ul>' );
				for ( var result of results ) {
					var title = new mw.Title( result.title, result.ns );
					var text = title.getPrefixedText();
					var url = title.getUrl();
					var link = $( '<a class="InlineSearch-result-link" href="' + url + '">' + text + '</a>' );
					var item = $( '<li class="InlineSearch-result "></li>' );
					item.append( link );
					list.append( item );
				}
				$div.html( list );
			} else {
				$div.text( 'No results!' ); // @todo i18n
			}
		} ).fail( console.log );
	}
};

$( InlineSearch.init );