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