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