resources: Strip '$' and 'mw' from file closures
[lhc/web/wiklou.git] / resources / src / mediawiki.searchSuggest / searchSuggest.js
1 /* eslint-disable no-restricted-properties */
2 /*!
3 * Add search suggestions to the search form.
4 */
5 ( function () {
6 var searchNS = $.map( mw.config.get( 'wgFormattedNamespaces' ), function ( nsName, nsID ) {
7 if ( nsID >= 0 && mw.user.options.get( 'searchNs' + nsID ) ) {
8 // Cast string key to number
9 return Number( nsID );
10 }
11 } );
12 mw.searchSuggest = {
13 // queries the wiki and calls response with the result
14 request: function ( api, query, response, maxRows, namespace ) {
15 return api.get( {
16 formatversion: 2,
17 action: 'opensearch',
18 search: query,
19 namespace: namespace || searchNS,
20 limit: maxRows,
21 suggest: true
22 } ).done( function ( data, jqXHR ) {
23 response( data[ 1 ], {
24 type: jqXHR.getResponseHeader( 'X-OpenSearch-Type' ),
25 query: query
26 } );
27 } );
28 }
29 };
30
31 $( function () {
32 var api, searchboxesSelectors,
33 // Region where the suggestions box will appear directly below
34 // (using the same width). Can be a container element or the input
35 // itself, depending on what suits best in the environment.
36 // For Vector the suggestion box should align with the simpleSearch
37 // container's borders, in other skins it should align with the input
38 // element (not the search form, as that would leave the buttons
39 // vertically between the input and the suggestions).
40 $searchRegion = $( '#simpleSearch, #searchInput' ).first(),
41 $searchInput = $( '#searchInput' ),
42 previousSearchText = $searchInput.val();
43
44 // Compute form data for search suggestions functionality.
45 function getFormData( context ) {
46 var $form, baseHref, linkParams;
47
48 if ( !context.formData ) {
49 // Compute common parameters for links' hrefs
50 $form = context.config.$region.closest( 'form' );
51
52 baseHref = $form.attr( 'action' );
53 baseHref += baseHref.indexOf( '?' ) > -1 ? '&' : '?';
54
55 linkParams = $form.serializeObject();
56
57 context.formData = {
58 textParam: context.data.$textbox.attr( 'name' ),
59 linkParams: linkParams,
60 baseHref: baseHref
61 };
62 }
63
64 return context.formData;
65 }
66
67 /**
68 * Callback that's run when the user changes the search input text
69 * 'this' is the search input box (jQuery object)
70 *
71 * @ignore
72 */
73 function onBeforeUpdate() {
74 var searchText = this.val();
75
76 if ( searchText && searchText !== previousSearchText ) {
77 mw.track( 'mediawiki.searchSuggest', {
78 action: 'session-start'
79 } );
80 }
81 previousSearchText = searchText;
82 }
83
84 /**
85 * Defines the location of autocomplete. Typically either
86 * header, which is in the top right of vector (for example)
87 * and content which identifies the main search bar on
88 * Special:Search. Defaults to header for skins that don't set
89 * explicitly.
90 *
91 * @ignore
92 * @param {Object} context
93 * @return {string}
94 */
95 function getInputLocation( context ) {
96 return context.config.$region
97 .closest( 'form' )
98 .find( '[data-search-loc]' )
99 .data( 'search-loc' ) || 'header';
100 }
101
102 /**
103 * Callback that's run when suggestions have been updated either from the cache or the API
104 * 'this' is the search input box (jQuery object)
105 *
106 * @ignore
107 * @param {Object} metadata
108 */
109 function onAfterUpdate( metadata ) {
110 var context = this.data( 'suggestionsContext' );
111
112 mw.track( 'mediawiki.searchSuggest', {
113 action: 'impression-results',
114 numberOfResults: context.config.suggestions.length,
115 resultSetType: metadata.type || 'unknown',
116 query: metadata.query,
117 inputLocation: getInputLocation( context )
118 } );
119 }
120
121 // The function used to render the suggestions.
122 function renderFunction( text, context ) {
123 var formData = getFormData( context ),
124 textboxConfig = context.data.$textbox.data( 'mw-searchsuggest' ) || {};
125
126 // linkParams object is modified and reused
127 formData.linkParams[ formData.textParam ] = text;
128
129 // Allow trackers to attach tracking information, such
130 // as wprov, to clicked links.
131 mw.track( 'mediawiki.searchSuggest', {
132 action: 'render-one',
133 formData: formData,
134 index: context.config.suggestions.indexOf( text )
135 } );
136
137 // this is the container <div>, jQueryfied
138 this.text( text );
139
140 // wrap only as link, if the config doesn't disallow it
141 if ( textboxConfig.wrapAsLink !== false ) {
142 this.wrap(
143 $( '<a>' )
144 .attr( 'href', formData.baseHref + $.param( formData.linkParams ) )
145 .attr( 'title', text )
146 .addClass( 'mw-searchSuggest-link' )
147 );
148 }
149 }
150
151 // The function used when the user makes a selection
152 function selectFunction( $input, source ) {
153 var context = $input.data( 'suggestionsContext' ),
154 text = $input.val();
155
156 // Selecting via keyboard triggers a form submission. That will fire
157 // the submit-form event in addition to this click-result event.
158 if ( source !== 'keyboard' ) {
159 mw.track( 'mediawiki.searchSuggest', {
160 action: 'click-result',
161 numberOfResults: context.config.suggestions.length,
162 index: context.config.suggestions.indexOf( text )
163 } );
164 }
165
166 // allow the form to be submitted
167 return true;
168 }
169
170 function specialRenderFunction( query, context ) {
171 var $el = this,
172 formData = getFormData( context );
173
174 // linkParams object is modified and reused
175 formData.linkParams[ formData.textParam ] = query;
176
177 mw.track( 'mediawiki.searchSuggest', {
178 action: 'render-one',
179 formData: formData,
180 index: context.config.suggestions.indexOf( query )
181 } );
182
183 if ( $el.children().length === 0 ) {
184 $el
185 .append(
186 $( '<div>' )
187 .addClass( 'special-label' )
188 .text( mw.msg( 'searchsuggest-containing' ) ),
189 $( '<div>' )
190 .addClass( 'special-query' )
191 .text( query )
192 )
193 .show();
194 } else {
195 $el.find( '.special-query' )
196 .text( query );
197 }
198
199 if ( $el.parent().hasClass( 'mw-searchSuggest-link' ) ) {
200 $el.parent().attr( 'href', formData.baseHref + $.param( formData.linkParams ) + '&fulltext=1' );
201 } else {
202 $el.wrap(
203 $( '<a>' )
204 .attr( 'href', formData.baseHref + $.param( formData.linkParams ) + '&fulltext=1' )
205 .addClass( 'mw-searchSuggest-link' )
206 );
207 }
208 }
209
210 // Generic suggestions functionality for all search boxes
211 searchboxesSelectors = [
212 // Primary searchbox on every page in standard skins
213 '#searchInput',
214 // Generic selector for skins with multiple searchboxes (used by CologneBlue)
215 // and for MediaWiki itself (special pages with page title inputs)
216 '.mw-searchInput'
217 ];
218 $( searchboxesSelectors.join( ', ' ) )
219 .suggestions( {
220 fetch: function ( query, response, maxRows ) {
221 var node = this[ 0 ];
222
223 api = api || new mw.Api();
224
225 $.data( node, 'request', mw.searchSuggest.request( api, query, response, maxRows ) );
226 },
227 cancel: function () {
228 var node = this[ 0 ],
229 request = $.data( node, 'request' );
230
231 if ( request ) {
232 request.abort();
233 $.removeData( node, 'request' );
234 }
235 },
236 result: {
237 render: renderFunction,
238 select: function () {
239 // allow the form to be submitted
240 return true;
241 }
242 },
243 update: {
244 before: onBeforeUpdate,
245 after: onAfterUpdate
246 },
247 cache: true,
248 highlightInput: true
249 } )
250 .on( 'paste cut drop', function () {
251 // make sure paste and cut events from the mouse and drag&drop events
252 // trigger the keypress handler and cause the suggestions to update
253 $( this ).trigger( 'keypress' );
254 } )
255 // In most skins (at least Monobook and Vector), the font-size is messed up in <body>.
256 // (they use 2 elements to get a sane font-height). So, instead of making exceptions for
257 // each skin or adding more stylesheets, just copy it from the active element so auto-fit.
258 .each( function () {
259 var $this = $( this );
260 $this
261 .data( 'suggestions-context' )
262 .data.$container.css( 'fontSize', $this.css( 'fontSize' ) );
263 } );
264
265 // Ensure that the thing is actually present!
266 if ( $searchRegion.length === 0 ) {
267 // Don't try to set anything up if simpleSearch is disabled sitewide.
268 // The loader code loads us if the option is present, even if we're
269 // not actually enabled (anymore).
270 return;
271 }
272
273 // Special suggestions functionality and tracking for skin-provided search box
274 $searchInput.suggestions( {
275 update: {
276 before: onBeforeUpdate,
277 after: onAfterUpdate
278 },
279 result: {
280 render: renderFunction,
281 select: selectFunction
282 },
283 special: {
284 render: specialRenderFunction,
285 select: function ( $input, source ) {
286 var context = $input.data( 'suggestionsContext' ),
287 text = $input.val();
288 if ( source === 'mouse' ) {
289 // mouse click won't trigger form submission, so we need to send a click event
290 mw.track( 'mediawiki.searchSuggest', {
291 action: 'click-result',
292 numberOfResults: context.config.suggestions.length,
293 index: context.config.suggestions.indexOf( text )
294 } );
295 } else {
296 $input.closest( 'form' )
297 .append( $( '<input type="hidden" name="fulltext" value="1"/>' ) );
298 }
299 return true; // allow the form to be submitted
300 }
301 },
302 $region: $searchRegion
303 } );
304
305 $searchInput.closest( 'form' )
306 // track the form submit event
307 .on( 'submit', function () {
308 var context = $searchInput.data( 'suggestionsContext' );
309 mw.track( 'mediawiki.searchSuggest', {
310 action: 'submit-form',
311 numberOfResults: context.config.suggestions.length,
312 $form: context.config.$region.closest( 'form' ),
313 inputLocation: getInputLocation( context ),
314 index: context.config.suggestions.indexOf(
315 context.data.$textbox.val()
316 )
317 } );
318 } )
319 // If the form includes any fallback fulltext search buttons, remove them
320 .find( '.mw-fallbackSearchButton' ).remove();
321 } );
322
323 }() );