summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/MixedNamespaceSearchSuggestions/resources/ext.mnss.search.js
blob: 0a3e666b1639da4b818cb8a28c7079412a5f916b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
 * @author Niklas Laxström
 * @license MIT
 */

( function ( mw, $ ) {

	// 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 ] )
			.addClass( 'mw-mnss-srcc' );

		// 'this' is the container <div>, jQueryfied
		this
			.append( page, namespace )
			.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 ) {
					$el = $( this );
					$el.data( 'request', ( new mw.Api() ).get( {
						action: 'opensearch',
						search: query,
						namespace: mw.config.get( 'wgContentNamespaces' ).join( '|' ),
						suggest: ''
					} ).done( function ( data ) {
						$el.suggestions( 'suggestions', data[1] );
					} ) );
				}
			},
			result: {
				render: customRenderFunction
			}
		} );
	} );

}( mediaWiki, jQuery ) );