MediaWiki:Gadget-Global-InlineSearch.js

From wikiNonStop
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.
/**
 * 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
 */
const InlineSearch = {

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

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

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

		// Do the query
		new mw.Api().get( params ).done( function ( data ) {
			const results = data.query.search;
			if ( results ) {
				const list = $( '<ul class="InlineSearch-results"></ul>' );
				for ( const result of results ) {
					const title = new mw.Title( result.title, result.ns );
					const text = title.getPrefixedText();
					const url = title.getUrl();
					const link = $( '<a class="InlineSearch-result-link" href="' + url + '">' + text + '</a>' );
					const 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 );