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 `$( document.documentElement ).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 // eslint-disable-next-line no-jquery/no-sizzle
174 !context
.data
.$container
.is( ':visible' )
176 context
.data
.prevText
= val
;
178 if ( context
.config
.cache
&& val
in cache
) {
179 if ( mw
.now() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
180 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
181 if ( typeof context
.config
.update
.after
=== 'function' ) {
182 context
.config
.update
.after
.call( context
.data
.$textbox
, cache
[ val
].metadata
);
190 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
191 context
.config
.fetch
.call(
192 context
.data
.$textbox
,
194 function ( suggestions
, metadata
) {
195 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
196 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
197 if ( typeof context
.config
.update
.after
=== 'function' ) {
198 context
.config
.update
.after
.call( context
.data
.$textbox
, metadata
);
200 if ( context
.config
.cache
) {
202 suggestions
: suggestions
,
208 context
.config
.maxRows
213 // Always update special rendering
217 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
221 // To avoid many started/aborted requests while typing, we're gonna take a short
222 // break before trying to fetch data.
223 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
230 * Highlight a result in the results table
232 * @param {Object} context
233 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
234 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
236 function highlight( context
, result
, updateTextbox
) {
237 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
238 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
239 if ( result
=== 'prev' ) {
240 if ( selected
.hasClass( 'suggestions-special' ) ) {
241 result
= context
.data
.$container
.find( '.suggestions-result' ).last();
243 result
= selected
.prev();
244 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
245 // there is something in the DOM between selected element and the wrapper, bypass it
246 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
249 if ( selected
.length
=== 0 ) {
250 // we are at the beginning, so lets jump to the last item
251 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
252 result
= context
.data
.$container
.find( '.suggestions-special' );
254 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result' ).last();
258 } else if ( result
=== 'next' ) {
259 if ( selected
.length
=== 0 ) {
260 // No item selected, go to the first one
261 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result' ).first();
262 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
263 // No suggestion exists, go to the special one directly
264 result
= context
.data
.$container
.find( '.suggestions-special' );
267 result
= selected
.next();
268 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
269 // there is something in the DOM between selected element and the wrapper, bypass it
270 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
273 if ( selected
.hasClass( 'suggestions-special' ) ) {
276 result
.length
=== 0 &&
277 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
279 // We were at the last item, jump to the specials!
280 result
= context
.data
.$container
.find( '.suggestions-special' );
284 selected
.removeClass( 'suggestions-result-current' );
285 result
.addClass( 'suggestions-result-current' );
287 if ( updateTextbox
) {
288 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
291 context
.data
.$textbox
.val( result
.data( 'text' ) );
292 // .val() doesn't call any event handlers, so
293 // let the world know what happened
294 context
.data
.$textbox
.trigger( 'change' );
296 context
.data
.$textbox
.trigger( 'change' );
301 * Sets the value of a property, and updates the widget accordingly
303 * @param {Object} context
304 * @param {string} property Name of property
305 * @param {Mixed} value Value to set property with
307 function configure( context
, property
, value
) {
309 $result
, $results
, $spanForWidth
, childrenWidth
,
310 regionIsFixed
, regionPosition
,
311 i
, expWidth
, maxWidth
, text
;
313 // Validate creation using fallback values
314 switch ( property
) {
322 context
.config
[ property
] = value
;
325 context
.config
[ property
] = value
;
326 // Update suggestions
327 if ( context
.data
!== undefined ) {
328 if ( context
.data
.$textbox
.val().length
=== 0 ) {
329 // Hide the div when no suggestion exist
332 // Rebuild the suggestions list
333 context
.data
.$container
.show();
334 // Update the size and position of the list
335 regionIsFixed
= ( function () {
336 var $el
= context
.config
.$region
;
338 if ( $el
.css( 'position' ) === 'fixed' ) {
341 $el
= $( $el
[ 0 ].offsetParent
);
342 } while ( $el
.length
);
345 regionPosition
= regionIsFixed
?
346 context
.config
.$region
[ 0 ].getBoundingClientRect() :
347 context
.config
.$region
.offset();
349 position
: regionIsFixed
? 'fixed' : 'absolute',
350 top
: regionPosition
.top
+ context
.config
.$region
.outerHeight(),
352 width
: context
.config
.$region
.outerWidth(),
356 // Process expandFrom, after this it is set to left or right.
357 context
.config
.expandFrom
= ( function ( expandFrom
) {
358 var regionWidth
, docWidth
, regionCenter
, docCenter
,
359 isRTL
= $( document
.documentElement
).css( 'direction' ) === 'rtl',
360 $region
= context
.config
.$region
;
362 // Backwards compatible
363 if ( context
.config
.positionFromLeft
) {
366 // Catch invalid values, default to 'auto'
367 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom
) === -1 ) {
371 if ( expandFrom
=== 'auto' ) {
372 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
373 // If the markup explicitly contains a direction, use it.
374 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
376 regionWidth
= $region
.outerWidth();
377 docWidth
= $( document
).width();
378 if ( regionWidth
> ( 0.85 * docWidth
) ) {
379 // If the input size takes up more than 85% of the document horizontally
380 // expand the suggestions to the writing direction's native end.
381 expandFrom
= 'start';
383 // Calculate the center points of the input and document
384 regionCenter
= regionPosition
.left
+ regionWidth
/ 2;
385 docCenter
= docWidth
/ 2;
386 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
387 // If the input's center is within 10% of the document center
388 // use the writing direction's native end.
389 expandFrom
= 'start';
391 // Otherwise expand the input from the closest side of the page,
392 // towards the side of the page with the most free open space
393 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
399 if ( expandFrom
=== 'start' ) {
400 expandFrom
= isRTL
? 'right' : 'left';
402 } else if ( expandFrom
=== 'end' ) {
403 expandFrom
= isRTL
? 'left' : 'right';
408 }( context
.config
.expandFrom
) );
410 if ( context
.config
.expandFrom
=== 'left' ) {
412 newCSS
.left
= regionPosition
.left
;
413 newCSS
.right
= 'auto';
416 newCSS
.left
= 'auto';
417 newCSS
.right
= document
.documentElement
.clientWidth
-
418 ( regionPosition
.left
+ context
.config
.$region
.outerWidth() );
421 context
.data
.$container
.css( newCSS
);
422 $results
= context
.data
.$container
.children( '.suggestions-results' );
425 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
426 text
= context
.config
.suggestions
[ i
];
427 $result
= $( '<div>' )
428 .addClass( 'suggestions-result' )
430 .data( 'text', context
.config
.suggestions
[ i
] )
431 .on( 'mousemove', function () {
432 context
.data
.selectedWithMouse
= true;
435 $( this ).closest( '.suggestions-results .suggestions-result' ),
439 .appendTo( $results
);
440 // Allow custom rendering
441 if ( typeof context
.config
.result
.render
=== 'function' ) {
442 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
444 $result
.text( text
);
447 if ( context
.config
.highlightInput
) {
448 $result
.highlightText( context
.data
.prevText
, { method
: 'prefixHighlight' } );
451 // Widen results box if needed (new width is only calculated here, applied later).
453 // The monstrosity below accomplishes two things:
454 // * Wraps the text contents in a DOM element, so that we can know its width. There is
455 // no way to directly access the width of a text node, and we can't use the parent
456 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
457 // it, which trims it to a smaller width.
458 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
459 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
460 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
461 // still report the "trimmed" width. This should not be done in regular CSS
462 // stylesheets as we don't want this rule to apply to other <span> elements, like
463 // the ones generated by jquery.highlightText.
464 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
465 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
466 $spanForWidth
.contents().unwrap();
468 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
469 // factor in any padding, margin, or border space on the parent
470 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
474 // Apply new width for results box, if any
475 if ( expWidth
> context
.data
.$container
.width() ) {
476 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
477 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
483 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
486 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
489 context
.config
[ property
] = Math
.max( 1, value
);
491 case 'maxExpandFactor':
492 context
.config
[ property
] = Math
.max( 1, value
);
495 case 'submitOnClick':
496 case 'positionFromLeft':
497 case 'highlightInput':
498 context
.config
[ property
] = !!value
;
504 * Respond to keypress event
506 * @param {jQuery.Event} e
507 * @param {Object} context
508 * @param {number} key Code of key pressed
510 function keypress( e
, context
, key
) {
512 // eslint-disable-next-line no-jquery/no-sizzle
513 wasVisible
= context
.data
.$container
.is( ':visible' ),
514 preventDefault
= false;
520 highlight( context
, 'next', true );
521 context
.data
.selectedWithMouse
= false;
523 update( context
, false );
525 preventDefault
= true;
530 highlight( context
, 'prev', true );
531 context
.data
.selectedWithMouse
= false;
533 preventDefault
= wasVisible
;
540 context
.data
.$textbox
.trigger( 'change' );
541 preventDefault
= wasVisible
;
545 preventDefault
= wasVisible
;
546 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
548 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
549 // If nothing is selected or if something was selected with the mouse
550 // cancel any current requests and allow the form to be submitted
551 // (simply don't prevent default behavior).
553 preventDefault
= false;
554 } else if ( selected
.is( '.suggestions-special' ) ) {
555 if ( typeof context
.config
.special
.select
=== 'function' ) {
556 // Allow the callback to decide whether to prevent default or not
557 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
558 preventDefault
= false;
562 if ( typeof context
.config
.result
.select
=== 'function' ) {
563 // Allow the callback to decide whether to prevent default or not
564 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
565 preventDefault
= false;
571 update( context
, true );
574 if ( preventDefault
) {
580 // See file header for method documentation
581 $.fn
.suggestions = function () {
582 // Multi-context fields
583 var args
= arguments
;
585 $( this ).each( function () {
588 /* Construction and Loading */
590 context
= $( this ).data( 'suggestions-context' );
591 if ( context
=== undefined || context
=== null ) {
594 fetch: function () {},
595 cancel: function () {},
605 submitOnClick
: false,
608 highlightInput
: false
615 // Handle various calling styles
616 if ( args
.length
> 0 ) {
617 if ( typeof args
[ 0 ] === 'object' ) {
618 // Apply set of properties
619 for ( key
in args
[ 0 ] ) {
620 configure( context
, key
, args
[ 0 ][ key
] );
622 } else if ( typeof args
[ 0 ] === 'string' ) {
623 if ( args
.length
> 1 ) {
624 // Set property values
625 configure( context
, args
[ 0 ], args
[ 1 ] );
632 if ( context
.data
=== undefined ) {
634 // ID of running timer
637 // Text in textbox when suggestions were last fetched
640 // Cache of fetched suggestions
641 cache
: Object
.create( null ),
643 // Number of results visible without scrolling
646 // Suggestion the last mousedown event occurred on
647 mouseDownOn
: $( [] ),
649 selectedWithMouse
: false
652 context
.data
.$container
= $( '<div>' )
653 .css( 'display', 'none' )
654 .addClass( 'suggestions' )
656 $( '<div>' ).addClass( 'suggestions-results' )
657 // Can't use click() because the container div is hidden when the
658 // textbox loses focus. Instead, listen for a mousedown followed
659 // by a mouseup on the same div.
660 .on( 'mousedown', function ( e
) {
661 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
663 .on( 'mouseup', function ( e
) {
664 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
665 $other
= context
.data
.mouseDownOn
;
667 context
.data
.mouseDownOn
= $( [] );
668 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
671 highlight( context
, $result
, true );
672 if ( typeof context
.config
.result
.select
=== 'function' ) {
673 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
, 'mouse' );
675 // Don't interfere with special clicks (e.g. to open in new tab)
676 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
677 // This will hide the link we're just clicking on, which causes problems
678 // when done synchronously in at least Firefox 3.6 (T64858).
679 setTimeout( function () {
683 // Always bring focus to the textbox, as that's probably where the user expects it
684 // if they were just typing.
685 context
.data
.$textbox
.trigger( 'focus' );
689 $( '<div>' ).addClass( 'suggestions-special' )
690 // Can't use click() because the container div is hidden when the
691 // textbox loses focus. Instead, listen for a mousedown followed
692 // by a mouseup on the same div.
693 .on( 'mousedown', function ( e
) {
694 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
696 .on( 'mouseup', function ( e
) {
697 var $special
= $( e
.target
).closest( '.suggestions-special' ),
698 $other
= context
.data
.mouseDownOn
;
700 context
.data
.mouseDownOn
= $( [] );
701 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
704 if ( typeof context
.config
.special
.select
=== 'function' ) {
705 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
, 'mouse' );
707 // Don't interfere with special clicks (e.g. to open in new tab)
708 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
709 // This will hide the link we're just clicking on, which causes problems
710 // when done synchronously in at least Firefox 3.6 (T64858).
711 setTimeout( function () {
715 // Always bring focus to the textbox, as that's probably where the user expects it
716 // if they were just typing.
717 context
.data
.$textbox
.trigger( 'focus' );
719 .on( 'mousemove', function ( e
) {
720 context
.data
.selectedWithMouse
= true;
722 context
, $( e
.target
).closest( '.suggestions-special' ), false
726 .appendTo( document
.body
);
729 // Stop browser autocomplete from interfering
730 .attr( 'autocomplete', 'off' )
731 .on( 'keydown', function ( e
) {
732 // Store key pressed to handle later
733 context
.data
.keypressed
= e
.which
;
734 context
.data
.keypressedCount
= 0;
736 .on( 'keypress', function ( e
) {
737 context
.data
.keypressedCount
++;
738 keypress( e
, context
, context
.data
.keypressed
);
740 .on( 'keyup', function ( e
) {
741 // The keypress event is fired when a key is pressed down and that key normally
742 // produces a character value. We also want to handle some keys that don't
743 // produce a character value so we also attach to the keydown/keyup events.
744 // List of codes sourced from
745 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
754 if ( context
.data
.keypressedCount
=== 0 &&
755 e
.which
=== context
.data
.keypressed
&&
756 allowed
.indexOf( e
.which
) !== -1
758 keypress( e
, context
, context
.data
.keypressed
);
761 .on( 'blur', function () {
762 // When losing focus because of a mousedown
763 // on a suggestion, don't hide the suggestions
764 if ( context
.data
.mouseDownOn
.length
> 0 ) {
770 // Load suggestions if the value is changed because there are already
771 // typed characters before the JavaScript is loaded.
772 if ( $( this ).is( ':focus' ) && this.value
!== this.defaultValue
) {
773 update( context
, false );
777 // Store the context for next time
778 $( this ).data( 'suggestions-context', context
);
785 * @mixins jQuery.plugin.suggestions