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