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