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
93 var hasOwn
= Object
.hasOwnProperty
;
96 * Cancel any delayed maybeFetch() call and callback the context so
97 * they can cancel any async fetching if they use AJAX or something.
99 * @param {Object} context
101 function cancel( context
) {
102 if ( context
.data
.timerID
!== null ) {
103 clearTimeout( context
.data
.timerID
);
105 if ( typeof context
.config
.cancel
=== 'function' ) {
106 context
.config
.cancel
.call( context
.data
.$textbox
);
111 * Hide the element with suggestions and clean up some state.
113 * @param {Object} context
115 function hide( context
) {
116 // Remove any highlights, including on "special" items
117 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
118 // Hide the container
119 context
.data
.$container
.hide();
123 * Restore the text the user originally typed in the textbox, before it
124 * was overwritten by highlight(). This restores the value the currently
125 * displayed suggestions are based on, rather than the value just before
126 * highlight() overwrote it; the former is arguably slightly more sensible.
128 * @param {Object} context
130 function restore( context
) {
131 context
.data
.$textbox
.val( context
.data
.prevText
);
135 * @param {Object} context
137 function special( context
) {
138 // Allow custom rendering - but otherwise don't do any rendering
139 if ( typeof context
.config
.special
.render
=== 'function' ) {
140 // Wait for the browser to update the value
141 setTimeout( function () {
143 var $special
= context
.data
.$container
.find( '.suggestions-special' );
144 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
150 * Ask the user-specified callback for new suggestions. Any previous delayed
151 * call to this function still pending will be canceled. If the value in the
152 * textbox is empty or hasn't changed since the last time suggestions were fetched,
153 * this function does nothing.
155 * @param {Object} context
156 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
158 function update( context
, delayed
) {
159 function maybeFetch() {
160 var val
= context
.data
.$textbox
.val(),
161 cache
= context
.data
.cache
,
164 if ( typeof context
.config
.update
.before
=== 'function' ) {
165 context
.config
.update
.before
.call( context
.data
.$textbox
);
168 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
169 // if the textbox is empty then clear the result div, but leave other settings intouched
170 if ( val
.length
=== 0 ) {
172 context
.data
.prevText
= '';
174 val
!== context
.data
.prevText
||
175 !context
.data
.$container
.is( ':visible' )
177 context
.data
.prevText
= val
;
179 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
180 if ( mw
.now() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
181 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
182 if ( typeof context
.config
.update
.after
=== 'function' ) {
183 context
.config
.update
.after
.call( context
.data
.$textbox
, cache
[ val
].metadata
);
191 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
192 context
.config
.fetch
.call(
193 context
.data
.$textbox
,
195 function ( suggestions
, metadata
) {
196 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
197 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
198 if ( typeof context
.config
.update
.after
=== 'function' ) {
199 context
.config
.update
.after
.call( context
.data
.$textbox
, metadata
);
201 if ( context
.config
.cache
) {
203 suggestions
: suggestions
,
209 context
.config
.maxRows
214 // Always update special rendering
218 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
222 // To avoid many started/aborted requests while typing, we're gonna take a short
223 // break before trying to fetch data.
224 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
231 * Highlight a result in the results table
233 * @param {Object} context
234 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
235 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
237 function highlight( context
, result
, updateTextbox
) {
238 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
239 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
240 if ( result
=== 'prev' ) {
241 if ( selected
.hasClass( 'suggestions-special' ) ) {
242 result
= context
.data
.$container
.find( '.suggestions-result:last' );
244 result
= selected
.prev();
245 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
246 // there is something in the DOM between selected element and the wrapper, bypass it
247 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
250 if ( selected
.length
=== 0 ) {
251 // we are at the beginning, so lets jump to the last item
252 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
253 result
= context
.data
.$container
.find( '.suggestions-special' );
255 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
259 } else if ( result
=== 'next' ) {
260 if ( selected
.length
=== 0 ) {
261 // No item selected, go to the first one
262 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
263 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
264 // No suggestion exists, go to the special one directly
265 result
= context
.data
.$container
.find( '.suggestions-special' );
268 result
= selected
.next();
269 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
270 // there is something in the DOM between selected element and the wrapper, bypass it
271 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
274 if ( selected
.hasClass( 'suggestions-special' ) ) {
277 result
.length
=== 0 &&
278 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
280 // We were at the last item, jump to the specials!
281 result
= context
.data
.$container
.find( '.suggestions-special' );
285 selected
.removeClass( 'suggestions-result-current' );
286 result
.addClass( 'suggestions-result-current' );
288 if ( updateTextbox
) {
289 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
292 context
.data
.$textbox
.val( result
.data( 'text' ) );
293 // .val() doesn't call any event handlers, so
294 // let the world know what happened
295 context
.data
.$textbox
.trigger( 'change' );
297 context
.data
.$textbox
.trigger( 'change' );
302 * Sets the value of a property, and updates the widget accordingly
304 * @param {Object} context
305 * @param {string} property Name of property
306 * @param {Mixed} value Value to set property with
308 function configure( context
, property
, value
) {
310 $result
, $results
, $spanForWidth
, childrenWidth
,
311 regionIsFixed
, regionPosition
,
312 i
, expWidth
, maxWidth
, text
;
314 // Validate creation using fallback values
315 switch ( property
) {
323 context
.config
[ property
] = value
;
326 context
.config
[ property
] = value
;
327 // Update suggestions
328 if ( context
.data
!== undefined ) {
329 if ( context
.data
.$textbox
.val().length
=== 0 ) {
330 // Hide the div when no suggestion exist
333 // Rebuild the suggestions list
334 context
.data
.$container
.show();
335 // Update the size and position of the list
336 regionIsFixed
= ( function () {
337 var $el
= context
.config
.$region
;
339 if ( $el
.css( 'position' ) === 'fixed' ) {
342 $el
= $( $el
[ 0 ].offsetParent
);
343 } while ( $el
.length
);
346 regionPosition
= regionIsFixed
?
347 context
.config
.$region
[ 0 ].getBoundingClientRect() :
348 context
.config
.$region
.offset();
350 position
: regionIsFixed
? 'fixed' : 'absolute',
351 top
: regionPosition
.top
+ context
.config
.$region
.outerHeight(),
353 width
: context
.config
.$region
.outerWidth(),
357 // Process expandFrom, after this it is set to left or right.
358 context
.config
.expandFrom
= ( function ( expandFrom
) {
359 var regionWidth
, docWidth
, regionCenter
, docCenter
,
360 docDir
= $( document
.documentElement
).css( 'direction' ),
361 $region
= context
.config
.$region
;
363 // Backwards compatible
364 if ( context
.config
.positionFromLeft
) {
367 // Catch invalid values, default to 'auto'
368 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom
) === -1 ) {
372 if ( expandFrom
=== 'auto' ) {
373 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
374 // If the markup explicitly contains a direction, use it.
375 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
377 regionWidth
= $region
.outerWidth();
378 docWidth
= $( document
).width();
379 if ( regionWidth
> ( 0.85 * docWidth
) ) {
380 // If the input size takes up more than 85% of the document horizontally
381 // expand the suggestions to the writing direction's native end.
382 expandFrom
= 'start';
384 // Calculate the center points of the input and document
385 regionCenter
= regionPosition
.left
+ regionWidth
/ 2;
386 docCenter
= docWidth
/ 2;
387 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
388 // If the input's center is within 10% of the document center
389 // use the writing direction's native end.
390 expandFrom
= 'start';
392 // Otherwise expand the input from the closest side of the page,
393 // towards the side of the page with the most free open space
394 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
400 if ( expandFrom
=== 'start' ) {
401 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
403 } else if ( expandFrom
=== 'end' ) {
404 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
409 }( context
.config
.expandFrom
) );
411 if ( context
.config
.expandFrom
=== 'left' ) {
413 newCSS
.left
= regionPosition
.left
;
414 newCSS
.right
= 'auto';
417 newCSS
.left
= 'auto';
418 newCSS
.right
= $( 'body' ).width() - ( 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 wasVisible
= context
.data
.$container
.is( ':visible' ),
513 preventDefault
= false;
519 highlight( context
, 'next', true );
520 context
.data
.selectedWithMouse
= false;
522 update( context
, false );
524 preventDefault
= true;
529 highlight( context
, 'prev', true );
530 context
.data
.selectedWithMouse
= false;
532 preventDefault
= wasVisible
;
539 context
.data
.$textbox
.trigger( 'change' );
540 preventDefault
= wasVisible
;
544 preventDefault
= wasVisible
;
545 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
547 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
548 // If nothing is selected or if something was selected with the mouse
549 // cancel any current requests and allow the form to be submitted
550 // (simply don't prevent default behavior).
552 preventDefault
= false;
553 } else if ( selected
.is( '.suggestions-special' ) ) {
554 if ( typeof context
.config
.special
.select
=== 'function' ) {
555 // Allow the callback to decide whether to prevent default or not
556 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
557 preventDefault
= false;
561 if ( typeof context
.config
.result
.select
=== 'function' ) {
562 // Allow the callback to decide whether to prevent default or not
563 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
564 preventDefault
= false;
570 update( context
, true );
573 if ( preventDefault
) {
579 // See file header for method documentation
580 $.fn
.suggestions = function () {
581 // Multi-context fields
582 var args
= arguments
;
584 $( this ).each( function () {
587 /* Construction and Loading */
589 context
= $( this ).data( 'suggestions-context' );
590 if ( context
=== undefined || context
=== null ) {
593 fetch: function () {},
594 cancel: function () {},
604 submitOnClick
: false,
607 highlightInput
: false
614 // Handle various calling styles
615 if ( args
.length
> 0 ) {
616 if ( typeof args
[ 0 ] === 'object' ) {
617 // Apply set of properties
618 for ( key
in args
[ 0 ] ) {
619 configure( context
, key
, args
[ 0 ][ key
] );
621 } else if ( typeof args
[ 0 ] === 'string' ) {
622 if ( args
.length
> 1 ) {
623 // Set property values
624 configure( context
, args
[ 0 ], args
[ 1 ] );
631 if ( context
.data
=== undefined ) {
633 // ID of running timer
636 // Text in textbox when suggestions were last fetched
639 // Cache of fetched suggestions
642 // Number of results visible without scrolling
645 // Suggestion the last mousedown event occurred on
646 mouseDownOn
: $( [] ),
648 selectedWithMouse
: false
651 context
.data
.$container
= $( '<div>' )
652 .css( 'display', 'none' )
653 .addClass( 'suggestions' )
655 $( '<div>' ).addClass( 'suggestions-results' )
656 // Can't use click() because the container div is hidden when the
657 // textbox loses focus. Instead, listen for a mousedown followed
658 // by a mouseup on the same div.
659 .on( 'mousedown', function ( e
) {
660 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
662 .on( 'mouseup', function ( e
) {
663 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
664 $other
= context
.data
.mouseDownOn
;
666 context
.data
.mouseDownOn
= $( [] );
667 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
670 highlight( context
, $result
, true );
671 if ( typeof context
.config
.result
.select
=== 'function' ) {
672 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
, 'mouse' );
674 // Don't interfere with special clicks (e.g. to open in new tab)
675 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
676 // This will hide the link we're just clicking on, which causes problems
677 // when done synchronously in at least Firefox 3.6 (T64858).
678 setTimeout( function () {
682 // Always bring focus to the textbox, as that's probably where the user expects it
683 // if they were just typing.
684 context
.data
.$textbox
.trigger( 'focus' );
688 $( '<div>' ).addClass( 'suggestions-special' )
689 // Can't use click() because the container div is hidden when the
690 // textbox loses focus. Instead, listen for a mousedown followed
691 // by a mouseup on the same div.
692 .on( 'mousedown', function ( e
) {
693 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
695 .on( 'mouseup', function ( e
) {
696 var $special
= $( e
.target
).closest( '.suggestions-special' ),
697 $other
= context
.data
.mouseDownOn
;
699 context
.data
.mouseDownOn
= $( [] );
700 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
703 if ( typeof context
.config
.special
.select
=== 'function' ) {
704 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
, 'mouse' );
706 // Don't interfere with special clicks (e.g. to open in new tab)
707 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
708 // This will hide the link we're just clicking on, which causes problems
709 // when done synchronously in at least Firefox 3.6 (T64858).
710 setTimeout( function () {
714 // Always bring focus to the textbox, as that's probably where the user expects it
715 // if they were just typing.
716 context
.data
.$textbox
.trigger( 'focus' );
718 .on( 'mousemove', function ( e
) {
719 context
.data
.selectedWithMouse
= true;
721 context
, $( e
.target
).closest( '.suggestions-special' ), false
725 .appendTo( $( 'body' ) );
728 // Stop browser autocomplete from interfering
729 .attr( 'autocomplete', 'off' )
730 .on( 'keydown', function ( e
) {
731 // Store key pressed to handle later
732 context
.data
.keypressed
= e
.which
;
733 context
.data
.keypressedCount
= 0;
735 .on( 'keypress', function ( e
) {
736 context
.data
.keypressedCount
++;
737 keypress( e
, context
, context
.data
.keypressed
);
739 .on( 'keyup', function ( e
) {
740 // The keypress event is fired when a key is pressed down and that key normally
741 // produces a character value. We also want to handle some keys that don't
742 // produce a character value so we also attach to the keydown/keyup events.
743 // List of codes sourced from
744 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
753 if ( context
.data
.keypressedCount
=== 0 &&
754 e
.which
=== context
.data
.keypressed
&&
755 allowed
.indexOf( e
.which
) !== -1
757 keypress( e
, context
, context
.data
.keypressed
);
760 .on( 'blur', function () {
761 // When losing focus because of a mousedown
762 // on a suggestion, don't hide the suggestions
763 if ( context
.data
.mouseDownOn
.length
> 0 ) {
769 // Load suggestions if the value is changed because there are already
770 // typed characters before the JavaScript is loaded.
771 if ( this.value
!== this.defaultValue
) {
772 update( context
, false );
776 // Store the context for next time
777 $( this ).data( 'suggestions-context', context
);
784 * @mixins jQuery.plugin.suggestions