Debian Codegraph @

resources/src/mediawiki.searchSuggest/searchSuggest.js

raw symbols SCIP
1 /*!
2 * Add search suggestions to the search form.
3 */
4 ( function () {
5 // eslint-disable-next-line no-jquery/no-map-util
6 const searchNS = $.map( mw.config.get( 'wgFormattedNamespaces' ), ( 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 // T251544: Collect search performance metrics to compare Vue search with
13 // mediawiki.searchSuggest performance. Marks and Measures will only be
14 // recorded on the Vector skin.
15 shouldTestSearch = !!( mw.config.get( 'skin' ) === 'vector' &&
16 window.performance &&
17 performance.mark &&
18 performance.measure &&
19
20 performance.getEntriesByName &&
21 performance.clearMarks ),
22
23 loadStartMark = 'mwVectorLegacySearchLoadStart',
24 queryMark = 'mwVectorLegacySearchQuery',
25 renderMark = 'mwVectorLegacySearchRender',
26 queryToRenderMeasure = 'mwVectorLegacySearchQueryToRender',
27 loadStartToFirstRenderMeasure = 'mwVectorLegacySearchLoadStartToFirstRender';
28
29 /**
30 * Convenience library for making searches for titles that match a string.
31 * Loaded via the `mediawiki.searchSuggest` ResourceLoader library.
32 *
33 * @example
34 * mw.loader.using('mediawiki.searchSuggest').then(() => {
35 * var api = new mw.Api();
36 * mw.searchSuggest.request(api, 'Dogs that', ( results ) => {
37 * alert( `Results that match: ${results.join( '\n' );}` );
38 * });
39 * });
40 * @namespace mw.searchSuggest
41 */
42 mw.searchSuggest = {
43 /**
44 * @typedef {Object} mw.searchSuggest~ResponseMetaData
45 * @property {string} type the contents of the X-OpenSearch-Type response header.
46 * @property {string} searchId the contents of the X-Search-ID response header.
47 * @property {string} query
48 */
49 /**
50 * @callback mw.searchSuggest~ResponseFunction
51 * @param {string[]} titles titles of pages that match search
52 * @param {ResponseMetaData} meta meta data relating to search.
53 */
54 /**
55 * Queries the wiki and calls response with the result.
56 *
57 * @param {mw.Api} api
58 * @param {string} query
59 * @param {ResponseFunction} response
60 * @param {string|number} [limit]
61 * @param {string|number|string[]|number[]} [namespace]
62 * @return {jQuery.Deferred}
63 */
64 request: function ( api, query, response, limit, namespace ) {
65 return api.get( {
66 formatversion: 2,
67 action: 'opensearch',
68 search: query,
69 namespace: namespace || searchNS,
70 limit
71 } ).done( ( data, jqXHR ) => {
72 response( data[ 1 ], {
73 type: jqXHR.getResponseHeader( 'X-OpenSearch-Type' ),
74 searchId: jqXHR.getResponseHeader( 'X-Search-ID' ),
75 query
76 } );
77 } );
78 }
79 };
80
81 $( () => {
82 let api;
83 // Region where the suggestions box will appear directly below
84 // (using the same width). Can be a container element or the input
85 // itself, depending on what suits best in the environment.
86 // For Vector the suggestion box should align with the simpleSearch
87 // container's borders, in other skins it should align with the input
88 // element (not the search form, as that would leave the buttons
89 // vertically between the input and the suggestions).
90 const $searchRegion = $( '#simpleSearch, #searchInput' ).first(),
91 $searchInput = $( '#searchInput' );
92 let previousSearchText = $searchInput.val();
93
94 function serializeObject( fields ) {
95 const obj = {};
96
97 for ( let i = 0; i < fields.length; i++ ) {
98 obj[ fields[ i ].name ] = fields[ i ].value;
99 }
100
101 return obj;
102 }
103
104 // Compute form data for search suggestions functionality.
105 function getFormData( context ) {
106 if ( !context.formData ) {
107 // Compute common parameters for links' hrefs
108 const $form = context.config.$region.closest( 'form' );
109
110 let baseHref = $form.attr( 'action' ) || '';
111 baseHref += baseHref.indexOf( '?' ) > -1 ? '&' : '?';
112
113 const linkParams = serializeObject( $form.serializeArray() );
114
115 context.formData = {
116 textParam: context.data.$textbox.attr( 'name' ),
117 linkParams: linkParams,
118 baseHref: baseHref
119 };
120 }
121
122 return context.formData;
123 }
124
125 /**
126 * Callback that's run when the user changes the search input text
127 * 'this' is the search input box (jQuery object)
128 *
129 * @ignore
130 */
131 function onBeforeUpdate() {
132 const searchText = this.val();
133
134 if ( searchText && searchText !== previousSearchText ) {
135 mw.track( 'mediawiki.searchSuggest', {
136 action: 'session-start'
137 } );
138 }
139 previousSearchText = searchText;
140
141 if ( !shouldTestSearch ) {
142 return;
143 }
144
145 // Clear past marks that are no longer relevant. This likely means that the
146 // search request failed or was cancelled. Whatever the reason, the mark
147 // is no longer needed since we are only interested in collecting the time
148 // from query to render.
149 if ( performance.getEntriesByName( queryMark ).length ) {
150 performance.clearMarks( queryMark );
151 }
152
153 performance.mark( queryMark );
154 }
155
156 /**
157 * Defines the location of autocomplete. Typically either
158 * header, which is in the top right of vector (for example)
159 * and content which identifies the main search bar on
160 * Special:Search. Defaults to header for skins that don't set
161 * explicitly.
162 *
163 * @ignore
164 * @param {Object} context
165 * @return {string}
166 */
167 function getInputLocation( context ) {
168 return context.config.$region
169 .closest( 'form' )
170 .find( '[data-search-loc]' )
171 .data( 'search-loc' ) || 'header';
172 }
173
174 /**
175 * Callback that's run when suggestions have been updated either from the cache or the API
176 * 'this' is the search input box (jQuery object)
177 *
178 * @ignore
179 * @param {Object} metadata
180 */
181 function onAfterUpdate( metadata ) {
182 const context = this.data( 'suggestionsContext' );
183
184 mw.track( 'mediawiki.searchSuggest', {
185 action: 'impression-results',
186 numberOfResults: context.config.suggestions.length,
187 resultSetType: metadata.type || 'unknown',
188 searchId: metadata.searchId || null,
189 query: metadata.query,
190 inputLocation: getInputLocation( context )
191 } );
192
193 if ( shouldTestSearch ) {
194 // Schedule the mark after the search results have rendered and are
195 // visible to the user. Two rAF's are needed for this since rAF will
196 // execute before the rendering steps happen (e.g. layout and paint). A
197 // nested rAF will execute after these rendering steps have completed
198 // and ensure the search results are visible to the user.
199 requestAnimationFrame( () => {
200 requestAnimationFrame( () => {
201 if ( !performance.getEntriesByName( queryMark ).length ) {
202 return;
203 }
204
205 performance.mark( renderMark );
206 performance.measure( queryToRenderMeasure, queryMark, renderMark );
207
208 // Measure from the start of the lazy load to the first render if we
209 // haven't already captured that info.
210 if ( performance.getEntriesByName( loadStartMark ).length &&
211 !performance.getEntriesByName( loadStartToFirstRenderMeasure ).length ) {
212 performance.measure( loadStartToFirstRenderMeasure, loadStartMark, renderMark );
213 }
214
215 // The measures are the most meaningful info so we remove the marks
216 // after we have the measure.
217 performance.clearMarks( queryMark );
218 performance.clearMarks( renderMark );
219 } );
220 } );
221 }
222 }
223
224 // The function used to render the suggestions.
225 function renderFunction( text, context ) {
226 const formData = getFormData( context ),
227 textboxConfig = context.data.$textbox.data( 'mw-searchsuggest' ) || {};
228
229 // linkParams object is modified and reused
230 formData.linkParams[ formData.textParam ] = text;
231
232 // Allow trackers to attach tracking information, such
233 // as wprov, to clicked links.
234 mw.track( 'mediawiki.searchSuggest', {
235 action: 'render-one',
236 formData: formData,
237 index: context.config.suggestions.indexOf( text )
238 } );
239
240 // this is the container <div>, jQueryfied
241 this.text( text );
242
243 // wrap only as link, if the config doesn't disallow it
244 if ( textboxConfig.wrapAsLink !== false ) {
245 this.wrap(
246 $( '<a>' )
247 .attr( 'href', formData.baseHref + $.param( formData.linkParams ) )
248 .attr( 'title', text )
249 .addClass( 'mw-searchSuggest-link' )
250 );
251 }
252 }
253
254 // The function used when the user makes a selection
255 function selectFunction( $input, source ) {
256 const context = $input.data( 'suggestionsContext' ),
257 text = $input.val(),
258 url = $( this ).parent( 'a' ).attr( 'href' );
259
260 // We want to track a click-result XOR a submit-form action.
261 // If the source was 'click' (or otherwise non-'keyboard'),
262 // track it and then let the rest of the event proceed as normal.
263 // If the source was 'keyboard', and we have a URL
264 // (from the <a> that the result was wrapped in, see renderFunction()),
265 // then also track a click, prevent the regular form submit,
266 // and instead directly navigate to the URL as if it had been clicked.
267 // If the source was 'keyboard', but we have no URL,
268 // then we have to let the regular form submit go through,
269 // so skip the click tracking in that case to avoid duplicate tracking.
270 if ( source === 'keyboard' && url || source !== 'keyboard' ) {
271 mw.track( 'mediawiki.searchSuggest', {
272 action: 'click-result',
273 numberOfResults: context.config.suggestions.length,
274 index: context.config.suggestions.indexOf( text )
275 } );
276
277 if ( source === 'keyboard' ) {
278 window.location.assign( url );
279 // prevent default and stop propagation
280 return false;
281 }
282 }
283
284 // allow the form to be submitted
285 return true;
286 }
287
288 function specialRenderFunction( query, context ) {
289 const $el = this,
290 formData = getFormData( context );
291
292 // linkParams object is modified and reused
293 formData.linkParams[ formData.textParam ] = query;
294
295 mw.track( 'mediawiki.searchSuggest', {
296 action: 'render-one',
297 formData: formData,
298 index: context.config.suggestions.indexOf( query )
299 } );
300
301 if ( mw.user.options.get( 'search-match-redirect' ) && $el.children().length === 0 ) {
302 $el
303 .append(
304 $( '<div>' )
305 .addClass( 'special-label' )
306 .text( mw.msg( 'searchsuggest-containing' ) ),
307 $( '<div>' )
308 .addClass( 'special-query' )
309 .text( query )
310 )
311 .show();
312 } else {
313 $el.find( '.special-query' )
314 .text( query );
315 }
316
317 // eslint-disable-next-line no-jquery/no-class-state
318 if ( $el.parent().hasClass( 'mw-searchSuggest-link' ) ) {
319 $el.parent().attr( 'href', formData.baseHref + $.param( formData.linkParams ) + '&fulltext=1' );
320 } else {
321 $el.wrap(
322 $( '<a>' )
323 .attr( 'href', formData.baseHref + $.param( formData.linkParams ) + '&fulltext=1' )
324 .addClass( 'mw-searchSuggest-link' )
325 );
326 }
327 }
328
329 // Generic suggestions functionality for all search boxes
330 const searchboxesSelectors = [
331 // Primary searchbox on every page in standard skins
332 '#searchInput',
333 // Generic selector for skins with multiple searchboxes (used by CologneBlue)
334 // and for MediaWiki itself (special pages with page title inputs)
335 '.mw-searchInput'
336 ];
337 $( searchboxesSelectors.join( ', ' ) )
338 .suggestions( {
339 fetch: function ( query, response, maxRows ) {
340 const node = this[ 0 ];
341
342 api = api || new mw.Api();
343
344 $.data( node, 'request', mw.searchSuggest.request( api, query, response, maxRows ) );
345 },
346 cancel: function () {
347 const node = this[ 0 ],
348 request = $.data( node, 'request' );
349
350 if ( request ) {
351 request.abort();
352 $.removeData( node, 'request' );
353 }
354 },
355 result: {
356 render: renderFunction,
357 select: function () {
358 // allow the form to be submitted
359 return true;
360 }
361 },
362 update: {
363 before: onBeforeUpdate,
364 after: onAfterUpdate
365 },
366 cache: true,
367 highlightInput: true
368 } )
369 .on( 'paste cut drop', function () {
370 // make sure paste and cut events from the mouse and drag&drop events
371 // trigger the keypress handler and cause the suggestions to update
372 $( this ).trigger( 'keypress' );
373 } )
374 // In most skins (at least Monobook and Vector), the font-size is messed up in <body>.
375 // (they use 2 elements to get a sensible font-height). So, instead of making exceptions for
376 // each skin or adding more stylesheets, just copy it from the active element so auto-fit.
377 .each( function () {
378 const $this = $( this );
379 $this
380 .data( 'suggestions-context' )
381 .data.$container.css( 'fontSize', $this.css( 'fontSize' ) );
382 } );
383
384 // Ensure that the thing is actually present!
385 if ( $searchRegion.length === 0 ) {
386 // Don't try to set anything up if simpleSearch is disabled sitewide.
387 // The loader code loads us if the option is present, even if we're
388 // not actually enabled (anymore).
389 return;
390 }
391
392 // Special suggestions functionality and tracking for skin-provided search box
393 $searchInput.suggestions( {
394 update: {
395 before: onBeforeUpdate,
396 after: onAfterUpdate
397 },
398 result: {
399 render: renderFunction,
400 select: selectFunction
401 },
402 special: {
403 render: specialRenderFunction,
404 select: function ( $input, source ) {
405 const context = $input.data( 'suggestionsContext' ),
406 text = $input.val();
407 if ( source === 'mouse' ) {
408 // mouse click won't trigger form submission, so we need to send a click event
409 mw.track( 'mediawiki.searchSuggest', {
410 action: 'click-result',
411 numberOfResults: context.config.suggestions.length,
412 index: context.config.suggestions.indexOf( text )
413 } );
414 } else {
415 $input.closest( 'form' )
416 .append(
417 $( '<input>' )
418 .prop( {
419 type: 'hidden',
420 value: 1
421 } )
422 .attr( 'name', 'fulltext' )
423 );
424 }
425 return true; // allow the form to be submitted
426 }
427 },
428 $region: $searchRegion
429 } );
430
431 const $searchForm = $searchInput.closest( 'form' );
432 $searchForm
433 // Track the form submit event.
434 // Note that the form is mainly submitted for manual user input;
435 // selecting a suggestion is tracked as a click instead (see selectFunction()).
436 .on( 'submit', () => {
437 const context = $searchInput.data( 'suggestionsContext' );
438 mw.track( 'mediawiki.searchSuggest', {
439 action: 'submit-form',
440 numberOfResults: context.config.suggestions.length,
441 $form: context.config.$region.closest( 'form' ),
442 inputLocation: getInputLocation( context ),
443 index: context.config.suggestions.indexOf(
444 context.data.$textbox.val()
445 )
446 } );
447 } );
448
449 // Check to see if the fulltext search button is placed before the go search button
450 if ( $searchForm.find( '.mw-fallbackSearchButton ~ .searchButton' ).length ) {
451 // Submitting the form with enter should always trigger "search within pages"
452 // for JavaScript capable browsers.
453 // If it is, remove the "full text search" fallback button.
454 // In skins, where the "full text search" button
455 // precedes the "search by title" button, e.g. Vector this is done for
456 // non-JavaScript support. If the "search by title" button is first,
457 // and two search buttons are shown e.g. MonoBook no change is needed.
458 $searchForm.find( '.mw-fallbackSearchButton' ).remove();
459 }
460 } );
461
462 }() );