Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[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 no-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 // eslint-disable-next-line no-jquery/no-class-state
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(
301 $( '<input>' )
302 .prop( {
303 type: 'hidden',
304 value: 1
305 } )
306 .attr( 'name', 'fulltext' )
307 );
308 }
309 return true; // allow the form to be submitted
310 }
311 },
312 $region: $searchRegion
313 } );
314
315 $searchInput.closest( 'form' )
316 // track the form submit event
317 .on( 'submit', function () {
318 var context = $searchInput.data( 'suggestionsContext' );
319 mw.track( 'mediawiki.searchSuggest', {
320 action: 'submit-form',
321 numberOfResults: context.config.suggestions.length,
322 $form: context.config.$region.closest( 'form' ),
323 inputLocation: getInputLocation( context ),
324 index: context.config.suggestions.indexOf(
325 context.data.$textbox.val()
326 )
327 } );
328 } )
329 // If the form includes any fallback fulltext search buttons, remove them
330 .find( '.mw-fallbackSearchButton' ).remove();
331 } );
332
333 }() );