(bug 40448) Replace legacy mwsuggest with mediawiki.searchSuggest
[lhc/web/wiklou.git] / resources / jquery / jquery.suggestions.js
1 /**
2 * This plugin provides a generic way to add suggestions to a text box.
3 *
4 * Usage:
5 *
6 * Set options:
7 * $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
8 * $( '#textbox' ).suggestions( option, value );
9 * Get option:
10 * value = $( '#textbox' ).suggestions( option );
11 * Initialize:
12 * $( '#textbox' ).suggestions();
13 *
14 * Options:
15 *
16 * fetch(query): Callback that should fetch suggestions and set the suggestions property. Executed in the context of the
17 * textbox
18 * Type: Function
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches should be canceled.
20 * Executed in the context of the textbox
21 * Type: Function
22 * special: Set of callbacks for rendering and selecting
23 * Type: Object of Functions 'render' and 'select'
24 * result: Set of callbacks for rendering and selecting
25 * Type: Object of Functions 'render' and 'select'
26 * $region: jQuery selection of element to place the suggestions below and match width of
27 * Type: jQuery Object, Default: $(this)
28 * suggestions: Suggestions to display
29 * Type: Array of strings
30 * maxRows: Maximum number of suggestions to display at one time
31 * Type: Number, Range: 1 - 100, Default: 7
32 * delay: Number of ms to wait for the user to stop typing
33 * Type: Number, Range: 0 - 1200, Default: 120
34 * submitOnClick: Whether to submit the form containing the textbox when a suggestion is clicked
35 * Type: Boolean, Default: false
36 * maxExpandFactor: Maximum suggestions box width relative to the textbox width. If set to e.g. 2, the suggestions box
37 * will never be grown beyond 2 times the width of the textbox.
38 * Type: Number, Range: 1 - infinity, Default: 3
39 * expandFrom: Which direction to offset the suggestion box from.
40 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
41 * of the current document, according to $( 'html' ).css( 'direction' ).
42 * Type: String, default: 'auto', options: 'left', 'right', 'start', 'end', 'auto'.
43 * positionFromLeft: Sets expandFrom=left, for backwards compatibility
44 * Type: Boolean, Default: true
45 * highlightInput: Whether to hightlight matched portions of the input or not
46 * Type: Boolean, Default: false
47 */
48 ( function ( $ ) {
49
50 $.suggestions = {
51 /**
52 * Cancel any delayed updateSuggestions() call and inform the user so
53 * they can cancel their result fetching if they use AJAX or something
54 */
55 cancel: function ( context ) {
56 if ( context.data.timerID !== null ) {
57 clearTimeout( context.data.timerID );
58 }
59 if ( $.isFunction( context.config.cancel ) ) {
60 context.config.cancel.call( context.data.$textbox );
61 }
62 },
63 /**
64 * Restore the text the user originally typed in the textbox, before it was overwritten by highlight(). This
65 * restores the value the currently displayed suggestions are based on, rather than the value just before
66 * highlight() overwrote it; the former is arguably slightly more sensible.
67 */
68 restore: function ( context ) {
69 context.data.$textbox.val( context.data.prevText );
70 },
71 /**
72 * Ask the user-specified callback for new suggestions. Any previous delayed call to this function still pending
73 * will be canceled. If the value in the textbox is empty or hasn't changed since the last time suggestions were fetched, this
74 * function does nothing.
75 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
76 */
77 update: function ( context, delayed ) {
78 // Only fetch if the value in the textbox changed and is not empty
79 // if the textbox is empty then clear the result div, but leave other settings intouched
80 function maybeFetch() {
81 if ( context.data.$textbox.val().length === 0 ) {
82 context.data.$container.hide();
83 context.data.prevText = '';
84 } else if ( context.data.$textbox.val() !== context.data.prevText ) {
85 if ( typeof context.config.fetch === 'function' ) {
86 context.data.prevText = context.data.$textbox.val();
87 context.config.fetch.call( context.data.$textbox, context.data.$textbox.val() );
88 }
89 }
90 }
91
92 // Cancel previous call
93 if ( context.data.timerID !== null ) {
94 clearTimeout( context.data.timerID );
95 }
96 if ( delayed ) {
97 // Start a new asynchronous call
98 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
99 } else {
100 maybeFetch();
101 }
102 $.suggestions.special( context );
103 },
104 special: function ( context ) {
105 // Allow custom rendering - but otherwise don't do any rendering
106 if ( typeof context.config.special.render === 'function' ) {
107 // Wait for the browser to update the value
108 setTimeout( function () {
109 // Render special
110 var $special = context.data.$container.find( '.suggestions-special' );
111 context.config.special.render.call( $special, context.data.$textbox.val() );
112 }, 1 );
113 }
114 },
115 /**
116 * Sets the value of a property, and updates the widget accordingly
117 * @param property String Name of property
118 * @param value Mixed Value to set property with
119 */
120 configure: function ( context, property, value ) {
121 var newCSS;
122 // Validate creation using fallback values
123 switch( property ) {
124 case 'fetch':
125 case 'cancel':
126 case 'special':
127 case 'result':
128 case '$region':
129 case 'expandFrom':
130 context.config[property] = value;
131 break;
132 case 'suggestions':
133 context.config[property] = value;
134 // Update suggestions
135 if ( context.data !== undefined ) {
136 if ( context.data.$textbox.val().length === 0 ) {
137 // Hide the div when no suggestion exist
138 context.data.$container.hide();
139 } else {
140 // Rebuild the suggestions list
141 context.data.$container.show();
142 // Update the size and position of the list
143 newCSS = {
144 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
145 bottom: 'auto',
146 width: context.config.$region.outerWidth(),
147 height: 'auto'
148 };
149
150 // Process expandFrom, after this it is set to left or right.
151 context.config.expandFrom = ( function ( expandFrom ) {
152 var regionWidth, docWidth, regionCenter, docCenter,
153 docDir = $( document.documentElement ).css( 'direction' ),
154 $region = context.config.$region;
155
156 // Backwards compatible
157 if ( context.config.positionFromLeft ) {
158 expandFrom = 'left';
159
160 // Catch invalid values, default to 'auto'
161 } else if ( $.inArray( expandFrom, ['left', 'right', 'start', 'end', 'auto'] ) === -1 ) {
162 expandFrom = 'auto';
163 }
164
165 if ( expandFrom === 'auto' ) {
166 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
167 // If the markup explicitly contains a direction, use it.
168 expandFrom = $region.data( 'searchsuggest-expand-dir' );
169 } else {
170 regionWidth = $region.outerWidth();
171 docWidth = $( document ).width();
172 if ( ( regionWidth / docWidth ) > 0.85 ) {
173 // If the input size takes up more than 85% of the document horizontally
174 // expand the suggestions to the writing direction's native end.
175 expandFrom = 'start';
176 } else {
177 // Calculate the center points of the input and document
178 regionCenter = $region.offset().left + regionWidth / 2;
179 docCenter = docWidth / 2;
180 if ( Math.abs( regionCenter - docCenter ) / docCenter < 0.10 ) {
181 // If the input's center is within 10% of the document center
182 // use the writing direction's native end.
183 expandFrom = 'start';
184 } else {
185 // Otherwise expand the input from the closest side of the page,
186 // towards the side of the page with the most free open space
187 expandFrom = regionCenter > docCenter ? 'right' : 'left';
188 }
189 }
190 }
191 }
192
193 if ( expandFrom === 'start' ) {
194 expandFrom = docDir === 'rtl' ? 'right': 'left';
195
196 } else if ( expandFrom === 'end' ) {
197 expandFrom = docDir === 'rtl' ? 'left': 'right';
198 }
199
200 return expandFrom;
201
202 }( context.config.expandFrom ) );
203
204 if ( context.config.expandFrom === 'left' ) {
205 // Expand from left
206 newCSS.left = context.config.$region.offset().left;
207 newCSS.right = 'auto';
208 } else {
209 // Expand from right
210 newCSS.left = 'auto';
211 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
212 }
213
214 context.data.$container.css( newCSS );
215 var $results = context.data.$container.children( '.suggestions-results' );
216 $results.empty();
217 var expWidth = -1;
218 var $autoEllipseMe = $( [] );
219 var matchedText = null;
220 for ( var i = 0; i < context.config.suggestions.length; i++ ) {
221 /*jshint loopfunc:true */
222 var text = context.config.suggestions[i];
223 var $result = $( '<div>' )
224 .addClass( 'suggestions-result' )
225 .attr( 'rel', i )
226 .data( 'text', context.config.suggestions[i] )
227 .mousemove( function ( e ) {
228 context.data.selectedWithMouse = true;
229 $.suggestions.highlight(
230 context, $(this).closest( '.suggestions-results div' ), false
231 );
232 } )
233 .appendTo( $results );
234 // Allow custom rendering
235 if ( typeof context.config.result.render === 'function' ) {
236 context.config.result.render.call( $result, context.config.suggestions[i] );
237 } else {
238 // Add <span> with text
239 if( context.config.highlightInput ) {
240 matchedText = context.data.prevText;
241 }
242 $result.append( $( '<span>' )
243 .css( 'whiteSpace', 'nowrap' )
244 .text( text )
245 );
246
247 // Widen results box if needed
248 // New width is only calculated here, applied later
249 var $span = $result.children( 'span' );
250 if ( $span.outerWidth() > $result.width() && $span.outerWidth() > expWidth ) {
251 // factor in any padding, margin, or border space on the parent
252 expWidth = $span.outerWidth() + ( context.data.$container.width() - $span.parent().width());
253 }
254 $autoEllipseMe = $autoEllipseMe.add( $result );
255 }
256 }
257 // Apply new width for results box, if any
258 if ( expWidth > context.data.$container.width() ) {
259 var maxWidth = context.config.maxExpandFactor*context.data.$textbox.width();
260 context.data.$container.width( Math.min( expWidth, maxWidth ) );
261 }
262 // autoEllipse the results. Has to be done after changing the width
263 $autoEllipseMe.autoEllipsis( { hasSpan: true, tooltip: true, matchText: matchedText } );
264 }
265 }
266 break;
267 case 'maxRows':
268 context.config[property] = Math.max( 1, Math.min( 100, value ) );
269 break;
270 case 'delay':
271 context.config[property] = Math.max( 0, Math.min( 1200, value ) );
272 break;
273 case 'maxExpandFactor':
274 context.config[property] = Math.max( 1, value );
275 break;
276 case 'submitOnClick':
277 case 'positionFromLeft':
278 case 'highlightInput':
279 context.config[property] = value ? true : false;
280 break;
281 }
282 },
283 /**
284 * Highlight a result in the results table
285 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
286 * @param updateTextbox If true, put the suggestion in the textbox
287 */
288 highlight: function ( context, result, updateTextbox ) {
289 var selected = context.data.$container.find( '.suggestions-result-current' );
290 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
291 if ( result === 'prev' ) {
292 if( selected.is( '.suggestions-special' ) ) {
293 result = context.data.$container.find( '.suggestions-result:last' );
294 } else {
295 result = selected.prev();
296 if ( selected.length === 0 ) {
297 // we are at the beginning, so lets jump to the last item
298 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
299 result = context.data.$container.find( '.suggestions-special' );
300 } else {
301 result = context.data.$container.find( '.suggestions-results div:last' );
302 }
303 }
304 }
305 } else if ( result === 'next' ) {
306 if ( selected.length === 0 ) {
307 // No item selected, go to the first one
308 result = context.data.$container.find( '.suggestions-results div:first' );
309 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
310 // No suggestion exists, go to the special one directly
311 result = context.data.$container.find( '.suggestions-special' );
312 }
313 } else {
314 result = selected.next();
315 if ( selected.is( '.suggestions-special' ) ) {
316 result = $( [] );
317 } else if (
318 result.length === 0 &&
319 context.data.$container.find( '.suggestions-special' ).html() !== ''
320 ) {
321 // We were at the last item, jump to the specials!
322 result = context.data.$container.find( '.suggestions-special' );
323 }
324 }
325 }
326 selected.removeClass( 'suggestions-result-current' );
327 result.addClass( 'suggestions-result-current' );
328 }
329 if ( updateTextbox ) {
330 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
331 $.suggestions.restore( context );
332 } else {
333 context.data.$textbox.val( result.data( 'text' ) );
334 // .val() doesn't call any event handlers, so
335 // let the world know what happened
336 context.data.$textbox.change();
337 }
338 context.data.$textbox.trigger( 'change' );
339 }
340 },
341 /**
342 * Respond to keypress event
343 * @param key Integer Code of key pressed
344 */
345 keypress: function ( e, context, key ) {
346 var wasVisible = context.data.$container.is( ':visible' ),
347 preventDefault = false;
348 switch ( key ) {
349 // Arrow down
350 case 40:
351 if ( wasVisible ) {
352 $.suggestions.highlight( context, 'next', true );
353 context.data.selectedWithMouse = false;
354 } else {
355 $.suggestions.update( context, false );
356 }
357 preventDefault = true;
358 break;
359 // Arrow up
360 case 38:
361 if ( wasVisible ) {
362 $.suggestions.highlight( context, 'prev', true );
363 context.data.selectedWithMouse = false;
364 }
365 preventDefault = wasVisible;
366 break;
367 // Escape
368 case 27:
369 context.data.$container.hide();
370 $.suggestions.restore( context );
371 $.suggestions.cancel( context );
372 context.data.$textbox.trigger( 'change' );
373 preventDefault = wasVisible;
374 break;
375 // Enter
376 case 13:
377 context.data.$container.hide();
378 preventDefault = wasVisible;
379 var selected = context.data.$container.find( '.suggestions-result-current' );
380 if ( selected.length === 0 || context.data.selectedWithMouse ) {
381 // if nothing is selected OR if something was selected with the mouse,
382 // cancel any current requests and submit the form
383 $.suggestions.cancel( context );
384 context.config.$region.closest( 'form' ).submit();
385 } else if ( selected.is( '.suggestions-special' ) ) {
386 if ( typeof context.config.special.select === 'function' ) {
387 context.config.special.select.call( selected, context.data.$textbox );
388 }
389 } else {
390 if ( typeof context.config.result.select === 'function' ) {
391 $.suggestions.highlight( context, selected, true );
392 context.config.result.select.call( selected, context.data.$textbox );
393 } else {
394 $.suggestions.highlight( context, selected, true );
395 }
396 }
397 break;
398 default:
399 $.suggestions.update( context, true );
400 break;
401 }
402 if ( preventDefault ) {
403 e.preventDefault();
404 e.stopImmediatePropagation();
405 }
406 }
407 };
408 $.fn.suggestions = function () {
409
410 // Multi-context fields
411 var returnValue,
412 args = arguments;
413
414 $(this).each( function () {
415 var context, key;
416
417 /* Construction / Loading */
418
419 context = $(this).data( 'suggestions-context' );
420 if ( context === undefined || context === null ) {
421 context = {
422 config: {
423 'fetch' : function () {},
424 'cancel': function () {},
425 'special': {},
426 'result': {},
427 '$region': $(this),
428 'suggestions': [],
429 'maxRows': 7,
430 'delay': 120,
431 'submitOnClick': false,
432 'maxExpandFactor': 3,
433 'expandFrom': 'auto',
434 'highlightInput': false
435 }
436 };
437 }
438
439 /* API */
440
441 // Handle various calling styles
442 if ( args.length > 0 ) {
443 if ( typeof args[0] === 'object' ) {
444 // Apply set of properties
445 for ( key in args[0] ) {
446 $.suggestions.configure( context, key, args[0][key] );
447 }
448 } else if ( typeof args[0] === 'string' ) {
449 if ( args.length > 1 ) {
450 // Set property values
451 $.suggestions.configure( context, args[0], args[1] );
452 } else if ( returnValue === null || returnValue === undefined ) {
453 // Get property values, but don't give access to internal data - returns only the first
454 returnValue = ( args[0] in context.config ? undefined : context.config[args[0]] );
455 }
456 }
457 }
458
459 /* Initialization */
460
461 if ( context.data === undefined ) {
462 context.data = {
463 // ID of running timer
464 timerID: null,
465
466 // Text in textbox when suggestions were last fetched
467 prevText: null,
468
469 // Number of results visible without scrolling
470 visibleResults: 0,
471
472 // Suggestion the last mousedown event occured on
473 mouseDownOn: $( [] ),
474 $textbox: $(this),
475 selectedWithMouse: false
476 };
477
478 context.data.$container = $( '<div>' )
479 .css( 'display', 'none' )
480 .addClass( 'suggestions' )
481 .append(
482 $( '<div>' ).addClass( 'suggestions-results' )
483 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
484 // listen for a mousedown followed by a mouseup on the same div
485 .mousedown( function ( e ) {
486 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results div' );
487 } )
488 .mouseup( function ( e ) {
489 var $result = $( e.target ).closest( '.suggestions-results div' );
490 var $other = context.data.mouseDownOn;
491 context.data.mouseDownOn = $( [] );
492 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
493 return;
494 }
495 $.suggestions.highlight( context, $result, true );
496 context.data.$container.hide();
497 if ( typeof context.config.result.select === 'function' ) {
498 context.config.result.select.call( $result, context.data.$textbox );
499 }
500 context.data.$textbox.focus();
501 } )
502 )
503 .append(
504 $( '<div>' ).addClass( 'suggestions-special' )
505 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
506 // listen for a mousedown followed by a mouseup on the same div
507 .mousedown( function ( e ) {
508 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
509 } )
510 .mouseup( function ( e ) {
511 var $special = $( e.target ).closest( '.suggestions-special' );
512 var $other = context.data.mouseDownOn;
513 context.data.mouseDownOn = $( [] );
514 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
515 return;
516 }
517 context.data.$container.hide();
518 if ( typeof context.config.special.select === 'function' ) {
519 context.config.special.select.call( $special, context.data.$textbox );
520 }
521 context.data.$textbox.focus();
522 } )
523 .mousemove( function ( e ) {
524 context.data.selectedWithMouse = true;
525 $.suggestions.highlight(
526 context, $( e.target ).closest( '.suggestions-special' ), false
527 );
528 } )
529 )
530 .appendTo( $( 'body' ) );
531
532 $(this)
533 // Stop browser autocomplete from interfering
534 .attr( 'autocomplete', 'off')
535 .keydown( function ( e ) {
536 // Store key pressed to handle later
537 context.data.keypressed = e.which;
538 context.data.keypressedCount = 0;
539
540 switch ( context.data.keypressed ) {
541 // This preventDefault logic is duplicated from
542 // $.suggestions.keypress(), which sucks
543 case 40:
544 e.preventDefault();
545 e.stopImmediatePropagation();
546 break;
547 case 38:
548 case 27:
549 case 13:
550 if ( context.data.$container.is( ':visible' ) ) {
551 e.preventDefault();
552 e.stopImmediatePropagation();
553 }
554 }
555 } )
556 .keypress( function ( e ) {
557 context.data.keypressedCount++;
558 $.suggestions.keypress( e, context, context.data.keypressed );
559 } )
560 .keyup( function ( e ) {
561 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
562 // keypress in between, solve it
563 if ( context.data.keypressedCount === 0 ) {
564 $.suggestions.keypress( e, context, context.data.keypressed );
565 }
566 } )
567 .blur( function () {
568 // When losing focus because of a mousedown
569 // on a suggestion, don't hide the suggestions
570 if ( context.data.mouseDownOn.length > 0 ) {
571 return;
572 }
573 context.data.$container.hide();
574 $.suggestions.cancel( context );
575 } );
576 }
577
578 // Store the context for next time
579 $(this).data( 'suggestions-context', context );
580 } );
581 return returnValue !== undefined ? returnValue : $(this);
582 };
583
584 }( jQuery ) );