2 * This plugin provides a generic way to add suggestions to a text box.
6 * $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
7 * $( '#textbox' ).suggestions( option, value );
11 * $( '#textbox' ).suggestions();
13 * @class jQuery.plugin.suggestions
21 * @param {Object} options
23 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
24 * property. Called in context of the text box.
25 * @param {string} options.fetch.query
26 * @param {Function} options.fetch.response Callback to receive the suggestions with
27 * @param {Array} options.fetch.response.suggestions
28 * @param {number} options.fetch.maxRows
30 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
31 * suggestions fetches. Called in context of the text box.
33 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
35 * @param {Function} options.special.render Called in context of the suggestions-special element.
36 * @param {string} options.special.render.query
37 * @param {Object} options.special.render.context
39 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
40 * @param {jQuery} options.special.select.$textbox
42 * @param {Object} [options.result] Set of callbacks for rendering and selecting
44 * @param {Function} options.result.render Called in context of the suggestions-result element.
45 * @param {string} options.result.render.suggestion
46 * @param {Object} options.result.render.context
48 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
49 * @param {jQuery} options.result.select.$textbox
51 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
53 * @param {Function} options.update.before Called right after the user changes the textbox text.
54 * @param {Function} options.update.after Called after results are updated either from the cache or
55 * the API as a result of the user input.
57 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
59 * @param {string[]} [options.suggestions] Array of suggestions to display.
61 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
62 * Must be between 1 and 100.
64 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
65 * Must be between 0 and 1200.
67 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
69 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
70 * Must be higher than 1. Defaults to 1 minute.
72 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
73 * when a suggestion is clicked.
75 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
76 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
77 * the textbox. Must be higher than 1.
79 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
80 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
81 * of the current document, according to `$( 'html' ).css( 'direction' )`.
82 * Valid values: "left", "right", "start", "end", and "auto".
84 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
87 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
94 * Cancel any delayed maybeFetch() call and callback the context so
95 * they can cancel any async fetching if they use AJAX or something.
97 * @param {Object} context
99 function cancel( context
) {
100 if ( context
.data
.timerID
!== null ) {
101 clearTimeout( context
.data
.timerID
);
103 if ( typeof context
.config
.cancel
=== 'function' ) {
104 context
.config
.cancel
.call( context
.data
.$textbox
);
109 * Hide the element with suggestions and clean up some state.
111 * @param {Object} context
113 function hide( context
) {
114 // Remove any highlights, including on "special" items
115 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
116 // Hide the container
117 context
.data
.$container
.hide();
121 * Restore the text the user originally typed in the textbox, before it
122 * was overwritten by highlight(). This restores the value the currently
123 * displayed suggestions are based on, rather than the value just before
124 * highlight() overwrote it; the former is arguably slightly more sensible.
126 * @param {Object} context
128 function restore( context
) {
129 context
.data
.$textbox
.val( context
.data
.prevText
);
133 * @param {Object} context
135 function special( context
) {
136 // Allow custom rendering - but otherwise don't do any rendering
137 if ( typeof context
.config
.special
.render
=== 'function' ) {
138 // Wait for the browser to update the value
139 setTimeout( function () {
141 var $special
= context
.data
.$container
.find( '.suggestions-special' );
142 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
148 * Ask the user-specified callback for new suggestions. Any previous delayed
149 * call to this function still pending will be canceled. If the value in the
150 * textbox is empty or hasn't changed since the last time suggestions were fetched,
151 * this function does nothing.
153 * @param {Object} context
154 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
156 function update( context
, delayed
) {
157 function maybeFetch() {
158 var val
= context
.data
.$textbox
.val(),
159 cache
= context
.data
.cache
,
162 if ( typeof context
.config
.update
.before
=== 'function' ) {
163 context
.config
.update
.before
.call( context
.data
.$textbox
);
166 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
167 // if the textbox is empty then clear the result div, but leave other settings intouched
168 if ( val
.length
=== 0 ) {
170 context
.data
.prevText
= '';
172 val
!== context
.data
.prevText
||
173 !context
.data
.$container
.is( ':visible' )
175 context
.data
.prevText
= val
;
177 if ( context
.config
.cache
&& val
in cache
) {
178 if ( mw
.now() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
179 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
180 if ( typeof context
.config
.update
.after
=== 'function' ) {
181 context
.config
.update
.after
.call( context
.data
.$textbox
, cache
[ val
].metadata
);
189 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
190 context
.config
.fetch
.call(
191 context
.data
.$textbox
,
193 function ( suggestions
, metadata
) {
194 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
195 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
196 if ( typeof context
.config
.update
.after
=== 'function' ) {
197 context
.config
.update
.after
.call( context
.data
.$textbox
, metadata
);
199 if ( context
.config
.cache
) {
201 suggestions
: suggestions
,
207 context
.config
.maxRows
212 // Always update special rendering
216 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
220 // To avoid many started/aborted requests while typing, we're gonna take a short
221 // break before trying to fetch data.
222 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
229 * Highlight a result in the results table
231 * @param {Object} context
232 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
233 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
235 function highlight( context
, result
, updateTextbox
) {
236 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
237 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
238 if ( result
=== 'prev' ) {
239 if ( selected
.hasClass( 'suggestions-special' ) ) {
240 result
= context
.data
.$container
.find( '.suggestions-result:last' );
242 result
= selected
.prev();
243 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
244 // there is something in the DOM between selected element and the wrapper, bypass it
245 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
248 if ( selected
.length
=== 0 ) {
249 // we are at the beginning, so lets jump to the last item
250 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
251 result
= context
.data
.$container
.find( '.suggestions-special' );
253 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
257 } else if ( result
=== 'next' ) {
258 if ( selected
.length
=== 0 ) {
259 // No item selected, go to the first one
260 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
261 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
262 // No suggestion exists, go to the special one directly
263 result
= context
.data
.$container
.find( '.suggestions-special' );
266 result
= selected
.next();
267 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
268 // there is something in the DOM between selected element and the wrapper, bypass it
269 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
272 if ( selected
.hasClass( 'suggestions-special' ) ) {
275 result
.length
=== 0 &&
276 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
278 // We were at the last item, jump to the specials!
279 result
= context
.data
.$container
.find( '.suggestions-special' );
283 selected
.removeClass( 'suggestions-result-current' );
284 result
.addClass( 'suggestions-result-current' );
286 if ( updateTextbox
) {
287 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
290 context
.data
.$textbox
.val( result
.data( 'text' ) );
291 // .val() doesn't call any event handlers, so
292 // let the world know what happened
293 context
.data
.$textbox
.trigger( 'change' );
295 context
.data
.$textbox
.trigger( 'change' );
300 * Sets the value of a property, and updates the widget accordingly
302 * @param {Object} context
303 * @param {string} property Name of property
304 * @param {Mixed} value Value to set property with
306 function configure( context
, property
, value
) {
308 $result
, $results
, $spanForWidth
, childrenWidth
,
309 regionIsFixed
, regionPosition
,
310 i
, expWidth
, maxWidth
, text
;
312 // Validate creation using fallback values
313 switch ( property
) {
321 context
.config
[ property
] = value
;
324 context
.config
[ property
] = value
;
325 // Update suggestions
326 if ( context
.data
!== undefined ) {
327 if ( context
.data
.$textbox
.val().length
=== 0 ) {
328 // Hide the div when no suggestion exist
331 // Rebuild the suggestions list
332 context
.data
.$container
.show();
333 // Update the size and position of the list
334 regionIsFixed
= ( function () {
335 var $el
= context
.config
.$region
;
337 if ( $el
.css( 'position' ) === 'fixed' ) {
340 $el
= $( $el
[ 0 ].offsetParent
);
341 } while ( $el
.length
);
344 regionPosition
= regionIsFixed
?
345 context
.config
.$region
[ 0 ].getBoundingClientRect() :
346 context
.config
.$region
.offset();
348 position
: regionIsFixed
? 'fixed' : 'absolute',
349 top
: regionPosition
.top
+ context
.config
.$region
.outerHeight(),
351 width
: context
.config
.$region
.outerWidth(),
355 // Process expandFrom, after this it is set to left or right.
356 context
.config
.expandFrom
= ( function ( expandFrom
) {
357 var regionWidth
, docWidth
, regionCenter
, docCenter
,
358 docDir
= $( document
.documentElement
).css( 'direction' ),
359 $region
= context
.config
.$region
;
361 // Backwards compatible
362 if ( context
.config
.positionFromLeft
) {
365 // Catch invalid values, default to 'auto'
366 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom
) === -1 ) {
370 if ( expandFrom
=== 'auto' ) {
371 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
372 // If the markup explicitly contains a direction, use it.
373 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
375 regionWidth
= $region
.outerWidth();
376 docWidth
= $( document
).width();
377 if ( regionWidth
> ( 0.85 * docWidth
) ) {
378 // If the input size takes up more than 85% of the document horizontally
379 // expand the suggestions to the writing direction's native end.
380 expandFrom
= 'start';
382 // Calculate the center points of the input and document
383 regionCenter
= regionPosition
.left
+ regionWidth
/ 2;
384 docCenter
= docWidth
/ 2;
385 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
386 // If the input's center is within 10% of the document center
387 // use the writing direction's native end.
388 expandFrom
= 'start';
390 // Otherwise expand the input from the closest side of the page,
391 // towards the side of the page with the most free open space
392 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
398 if ( expandFrom
=== 'start' ) {
399 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
401 } else if ( expandFrom
=== 'end' ) {
402 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
407 }( context
.config
.expandFrom
) );
409 if ( context
.config
.expandFrom
=== 'left' ) {
411 newCSS
.left
= regionPosition
.left
;
412 newCSS
.right
= 'auto';
415 newCSS
.left
= 'auto';
416 newCSS
.right
= $( 'body' ).width() - ( regionPosition
.left
+ context
.config
.$region
.outerWidth() );
419 context
.data
.$container
.css( newCSS
);
420 $results
= context
.data
.$container
.children( '.suggestions-results' );
423 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
424 text
= context
.config
.suggestions
[ i
];
425 $result
= $( '<div>' )
426 .addClass( 'suggestions-result' )
428 .data( 'text', context
.config
.suggestions
[ i
] )
429 .on( 'mousemove', function () {
430 context
.data
.selectedWithMouse
= true;
433 $( this ).closest( '.suggestions-results .suggestions-result' ),
437 .appendTo( $results
);
438 // Allow custom rendering
439 if ( typeof context
.config
.result
.render
=== 'function' ) {
440 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
442 $result
.text( text
);
445 if ( context
.config
.highlightInput
) {
446 $result
.highlightText( context
.data
.prevText
, { method
: 'prefixHighlight' } );
449 // Widen results box if needed (new width is only calculated here, applied later).
451 // The monstrosity below accomplishes two things:
452 // * Wraps the text contents in a DOM element, so that we can know its width. There is
453 // no way to directly access the width of a text node, and we can't use the parent
454 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
455 // it, which trims it to a smaller width.
456 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
457 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
458 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
459 // still report the "trimmed" width. This should not be done in regular CSS
460 // stylesheets as we don't want this rule to apply to other <span> elements, like
461 // the ones generated by jquery.highlightText.
462 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
463 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
464 $spanForWidth
.contents().unwrap();
466 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
467 // factor in any padding, margin, or border space on the parent
468 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
472 // Apply new width for results box, if any
473 if ( expWidth
> context
.data
.$container
.width() ) {
474 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
475 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
481 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
484 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
487 context
.config
[ property
] = Math
.max( 1, value
);
489 case 'maxExpandFactor':
490 context
.config
[ property
] = Math
.max( 1, value
);
493 case 'submitOnClick':
494 case 'positionFromLeft':
495 case 'highlightInput':
496 context
.config
[ property
] = !!value
;
502 * Respond to keypress event
504 * @param {jQuery.Event} e
505 * @param {Object} context
506 * @param {number} key Code of key pressed
508 function keypress( e
, context
, key
) {
510 wasVisible
= context
.data
.$container
.is( ':visible' ),
511 preventDefault
= false;
517 highlight( context
, 'next', true );
518 context
.data
.selectedWithMouse
= false;
520 update( context
, false );
522 preventDefault
= true;
527 highlight( context
, 'prev', true );
528 context
.data
.selectedWithMouse
= false;
530 preventDefault
= wasVisible
;
537 context
.data
.$textbox
.trigger( 'change' );
538 preventDefault
= wasVisible
;
542 preventDefault
= wasVisible
;
543 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
545 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
546 // If nothing is selected or if something was selected with the mouse
547 // cancel any current requests and allow the form to be submitted
548 // (simply don't prevent default behavior).
550 preventDefault
= false;
551 } else if ( selected
.is( '.suggestions-special' ) ) {
552 if ( typeof context
.config
.special
.select
=== 'function' ) {
553 // Allow the callback to decide whether to prevent default or not
554 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
555 preventDefault
= false;
559 if ( typeof context
.config
.result
.select
=== 'function' ) {
560 // Allow the callback to decide whether to prevent default or not
561 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
562 preventDefault
= false;
568 update( context
, true );
571 if ( preventDefault
) {
577 // See file header for method documentation
578 $.fn
.suggestions = function () {
579 // Multi-context fields
580 var args
= arguments
;
582 $( this ).each( function () {
585 /* Construction and Loading */
587 context
= $( this ).data( 'suggestions-context' );
588 if ( context
=== undefined || context
=== null ) {
591 fetch: function () {},
592 cancel: function () {},
602 submitOnClick
: false,
605 highlightInput
: false
612 // Handle various calling styles
613 if ( args
.length
> 0 ) {
614 if ( typeof args
[ 0 ] === 'object' ) {
615 // Apply set of properties
616 for ( key
in args
[ 0 ] ) {
617 configure( context
, key
, args
[ 0 ][ key
] );
619 } else if ( typeof args
[ 0 ] === 'string' ) {
620 if ( args
.length
> 1 ) {
621 // Set property values
622 configure( context
, args
[ 0 ], args
[ 1 ] );
629 if ( context
.data
=== undefined ) {
631 // ID of running timer
634 // Text in textbox when suggestions were last fetched
637 // Cache of fetched suggestions
638 cache
: Object
.create( null ),
640 // Number of results visible without scrolling
643 // Suggestion the last mousedown event occurred on
644 mouseDownOn
: $( [] ),
646 selectedWithMouse
: false
649 context
.data
.$container
= $( '<div>' )
650 .css( 'display', 'none' )
651 .addClass( 'suggestions' )
653 $( '<div>' ).addClass( 'suggestions-results' )
654 // Can't use click() because the container div is hidden when the
655 // textbox loses focus. Instead, listen for a mousedown followed
656 // by a mouseup on the same div.
657 .on( 'mousedown', function ( e
) {
658 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
660 .on( 'mouseup', function ( e
) {
661 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
662 $other
= context
.data
.mouseDownOn
;
664 context
.data
.mouseDownOn
= $( [] );
665 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
668 highlight( context
, $result
, true );
669 if ( typeof context
.config
.result
.select
=== 'function' ) {
670 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
, 'mouse' );
672 // Don't interfere with special clicks (e.g. to open in new tab)
673 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
674 // This will hide the link we're just clicking on, which causes problems
675 // when done synchronously in at least Firefox 3.6 (T64858).
676 setTimeout( function () {
680 // Always bring focus to the textbox, as that's probably where the user expects it
681 // if they were just typing.
682 context
.data
.$textbox
.trigger( 'focus' );
686 $( '<div>' ).addClass( 'suggestions-special' )
687 // Can't use click() because the container div is hidden when the
688 // textbox loses focus. Instead, listen for a mousedown followed
689 // by a mouseup on the same div.
690 .on( 'mousedown', function ( e
) {
691 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
693 .on( 'mouseup', function ( e
) {
694 var $special
= $( e
.target
).closest( '.suggestions-special' ),
695 $other
= context
.data
.mouseDownOn
;
697 context
.data
.mouseDownOn
= $( [] );
698 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
701 if ( typeof context
.config
.special
.select
=== 'function' ) {
702 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
, 'mouse' );
704 // Don't interfere with special clicks (e.g. to open in new tab)
705 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
706 // This will hide the link we're just clicking on, which causes problems
707 // when done synchronously in at least Firefox 3.6 (T64858).
708 setTimeout( function () {
712 // Always bring focus to the textbox, as that's probably where the user expects it
713 // if they were just typing.
714 context
.data
.$textbox
.trigger( 'focus' );
716 .on( 'mousemove', function ( e
) {
717 context
.data
.selectedWithMouse
= true;
719 context
, $( e
.target
).closest( '.suggestions-special' ), false
723 .appendTo( $( 'body' ) );
726 // Stop browser autocomplete from interfering
727 .attr( 'autocomplete', 'off' )
728 .on( 'keydown', function ( e
) {
729 // Store key pressed to handle later
730 context
.data
.keypressed
= e
.which
;
731 context
.data
.keypressedCount
= 0;
733 .on( 'keypress', function ( e
) {
734 context
.data
.keypressedCount
++;
735 keypress( e
, context
, context
.data
.keypressed
);
737 .on( 'keyup', function ( e
) {
738 // The keypress event is fired when a key is pressed down and that key normally
739 // produces a character value. We also want to handle some keys that don't
740 // produce a character value so we also attach to the keydown/keyup events.
741 // List of codes sourced from
742 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
751 if ( context
.data
.keypressedCount
=== 0 &&
752 e
.which
=== context
.data
.keypressed
&&
753 allowed
.indexOf( e
.which
) !== -1
755 keypress( e
, context
, context
.data
.keypressed
);
758 .on( 'blur', function () {
759 // When losing focus because of a mousedown
760 // on a suggestion, don't hide the suggestions
761 if ( context
.data
.mouseDownOn
.length
> 0 ) {
767 // Load suggestions if the value is changed because there are already
768 // typed characters before the JavaScript is loaded.
769 if ( this.value
!== this.defaultValue
) {
770 update( context
, false );
774 // Store the context for next time
775 $( this ).data( 'suggestions-context', context
);
782 * @mixins jQuery.plugin.suggestions