Jump to content

MediaWiki:Gadget-Global-InlineSearch.js: Difference between revisions

From wikiNonStop
Use const rather than var
 
m 1 revision imported: Initial setup
 
(No difference)

Latest revision as of 17:55, 25 December 2024

/**
 * 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 );