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 * Uses jQuery.suggestions singleton internally.
15 * @class jQuery.plugin.suggestions
23 * @param {Object} options
25 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
26 * property. Called in context of the text box.
27 * @param {string} options.fetch.query
28 * @param {Function} options.fetch.response Callback to receive the suggestions with
29 * @param {Array} options.fetch.response.suggestions
30 * @param {number} options.fetch.maxRows
32 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
33 * suggestions fetches. Called in context of the text box.
35 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
37 * @param {Function} options.special.render Called in context of the suggestions-special element.
38 * @param {string} options.special.render.query
39 * @param {Object} options.special.render.context
41 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
42 * @param {jQuery} options.special.select.$textbox
44 * @param {Object} [options.result] Set of callbacks for rendering and selecting
46 * @param {Function} options.result.render Called in context of the suggestions-result element.
47 * @param {string} options.result.render.suggestion
48 * @param {Object} options.result.render.context
50 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
51 * @param {jQuery} options.result.select.$textbox
53 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
55 * @param {Function} options.update.before Called right after the user changes the textbox text.
56 * @param {Function} options.update.after Called after results are updated either from the cache or
57 * the API as a result of the user input.
59 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
61 * @param {string[]} [options.suggestions] Array of suggestions to display.
63 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
64 * Must be between 1 and 100.
66 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
67 * Must be between 0 and 1200.
69 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
71 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
72 * Must be higher than 1. Defaults to 1 minute.
74 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
75 * when a suggestion is clicked.
77 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
78 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
79 * the textbox. Must be higher than 1.
81 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
82 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
83 * of the current document, according to `$( 'html' ).css( 'direction' )`.
84 * Valid values: "left", "right", "start", "end", and "auto".
86 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
89 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
95 var hasOwn
= Object
.hasOwnProperty
;
98 * Used by jQuery.plugin.suggestions.
100 * @class jQuery.suggestions
106 * Cancel any delayed maybeFetch() call and callback the context so
107 * they can cancel any async fetching if they use AJAX or something.
109 * @param {Object} context
111 cancel: function ( context
) {
112 if ( context
.data
.timerID
!== null ) {
113 clearTimeout( context
.data
.timerID
);
115 if ( typeof context
.config
.cancel
=== 'function' ) {
116 context
.config
.cancel
.call( context
.data
.$textbox
);
121 * Hide the element with suggestions and clean up some state.
123 * @param {Object} context
125 hide: function ( context
) {
126 // Remove any highlights, including on "special" items
127 context
.data
.$container
.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
128 // Hide the container
129 context
.data
.$container
.hide();
133 * Restore the text the user originally typed in the textbox, before it
134 * was overwritten by highlight(). This restores the value the currently
135 * displayed suggestions are based on, rather than the value just before
136 * highlight() overwrote it; the former is arguably slightly more sensible.
138 * @param {Object} context
140 restore: function ( context
) {
141 context
.data
.$textbox
.val( context
.data
.prevText
);
145 * Ask the user-specified callback for new suggestions. Any previous delayed
146 * call to this function still pending will be canceled. If the value in the
147 * textbox is empty or hasn't changed since the last time suggestions were fetched,
148 * this function does nothing.
150 * @param {Object} context
151 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
153 update: function ( context
, delayed
) {
154 function maybeFetch() {
155 var val
= context
.data
.$textbox
.val(),
156 cache
= context
.data
.cache
,
159 if ( typeof context
.config
.update
.before
=== 'function' ) {
160 context
.config
.update
.before
.call( context
.data
.$textbox
);
163 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
164 // if the textbox is empty then clear the result div, but leave other settings intouched
165 if ( val
.length
=== 0 ) {
166 $.suggestions
.hide( context
);
167 context
.data
.prevText
= '';
169 val
!== context
.data
.prevText
||
170 !context
.data
.$container
.is( ':visible' )
172 context
.data
.prevText
= val
;
174 if ( context
.config
.cache
&& hasOwn
.call( cache
, val
) ) {
175 if ( mw
.now() - cache
[ val
].timestamp
< context
.config
.cacheMaxAge
) {
176 context
.data
.$textbox
.suggestions( 'suggestions', cache
[ val
].suggestions
);
177 if ( typeof context
.config
.update
.after
=== 'function' ) {
178 context
.config
.update
.after
.call( context
.data
.$textbox
, cache
[ val
].metadata
);
186 if ( !cacheHit
&& typeof context
.config
.fetch
=== 'function' ) {
187 context
.config
.fetch
.call(
188 context
.data
.$textbox
,
190 function ( suggestions
, metadata
) {
191 suggestions
= suggestions
.slice( 0, context
.config
.maxRows
);
192 context
.data
.$textbox
.suggestions( 'suggestions', suggestions
);
193 if ( typeof context
.config
.update
.after
=== 'function' ) {
194 context
.config
.update
.after
.call( context
.data
.$textbox
, metadata
);
196 if ( context
.config
.cache
) {
198 suggestions
: suggestions
,
204 context
.config
.maxRows
209 // Always update special rendering
210 $.suggestions
.special( context
);
213 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
214 $.suggestions
.cancel( context
);
217 // To avoid many started/aborted requests while typing, we're gonna take a short
218 // break before trying to fetch data.
219 context
.data
.timerID
= setTimeout( maybeFetch
, context
.config
.delay
);
226 * @param {Object} context
228 special: function ( context
) {
229 // Allow custom rendering - but otherwise don't do any rendering
230 if ( typeof context
.config
.special
.render
=== 'function' ) {
231 // Wait for the browser to update the value
232 setTimeout( function () {
234 var $special
= context
.data
.$container
.find( '.suggestions-special' );
235 context
.config
.special
.render
.call( $special
, context
.data
.$textbox
.val(), context
);
241 * Sets the value of a property, and updates the widget accordingly
243 * @param {Object} context
244 * @param {string} property Name of property
245 * @param {Mixed} value Value to set property with
247 configure: function ( context
, property
, value
) {
249 $result
, $results
, $spanForWidth
, childrenWidth
,
250 i
, expWidth
, maxWidth
, text
;
252 // Validate creation using fallback values
253 switch ( property
) {
261 context
.config
[ property
] = value
;
264 context
.config
[ property
] = value
;
265 // Update suggestions
266 if ( context
.data
!== undefined ) {
267 if ( context
.data
.$textbox
.val().length
=== 0 ) {
268 // Hide the div when no suggestion exist
269 $.suggestions
.hide( context
);
271 // Rebuild the suggestions list
272 context
.data
.$container
.show();
273 // Update the size and position of the list
275 top
: context
.config
.$region
.offset().top
+ context
.config
.$region
.outerHeight(),
277 width
: context
.config
.$region
.outerWidth(),
281 // Process expandFrom, after this it is set to left or right.
282 context
.config
.expandFrom
= ( function ( expandFrom
) {
283 var regionWidth
, docWidth
, regionCenter
, docCenter
,
284 docDir
= $( document
.documentElement
).css( 'direction' ),
285 $region
= context
.config
.$region
;
287 // Backwards compatible
288 if ( context
.config
.positionFromLeft
) {
291 // Catch invalid values, default to 'auto'
292 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom
) === -1 ) {
296 if ( expandFrom
=== 'auto' ) {
297 if ( $region
.data( 'searchsuggest-expand-dir' ) ) {
298 // If the markup explicitly contains a direction, use it.
299 expandFrom
= $region
.data( 'searchsuggest-expand-dir' );
301 regionWidth
= $region
.outerWidth();
302 docWidth
= $( document
).width();
303 if ( regionWidth
> ( 0.85 * docWidth
) ) {
304 // If the input size takes up more than 85% of the document horizontally
305 // expand the suggestions to the writing direction's native end.
306 expandFrom
= 'start';
308 // Calculate the center points of the input and document
309 regionCenter
= $region
.offset().left
+ regionWidth
/ 2;
310 docCenter
= docWidth
/ 2;
311 if ( Math
.abs( regionCenter
- docCenter
) < ( 0.10 * docCenter
) ) {
312 // If the input's center is within 10% of the document center
313 // use the writing direction's native end.
314 expandFrom
= 'start';
316 // Otherwise expand the input from the closest side of the page,
317 // towards the side of the page with the most free open space
318 expandFrom
= regionCenter
> docCenter
? 'right' : 'left';
324 if ( expandFrom
=== 'start' ) {
325 expandFrom
= docDir
=== 'rtl' ? 'right' : 'left';
327 } else if ( expandFrom
=== 'end' ) {
328 expandFrom
= docDir
=== 'rtl' ? 'left' : 'right';
333 }( context
.config
.expandFrom
) );
335 if ( context
.config
.expandFrom
=== 'left' ) {
337 newCSS
.left
= context
.config
.$region
.offset().left
;
338 newCSS
.right
= 'auto';
341 newCSS
.left
= 'auto';
342 newCSS
.right
= $( 'body' ).width() - ( context
.config
.$region
.offset().left
+ context
.config
.$region
.outerWidth() );
345 context
.data
.$container
.css( newCSS
);
346 $results
= context
.data
.$container
.children( '.suggestions-results' );
349 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
350 text
= context
.config
.suggestions
[ i
];
351 $result
= $( '<div>' )
352 .addClass( 'suggestions-result' )
354 .data( 'text', context
.config
.suggestions
[ i
] )
355 .on( 'mousemove', function () {
356 context
.data
.selectedWithMouse
= true;
357 $.suggestions
.highlight(
359 $( this ).closest( '.suggestions-results .suggestions-result' ),
363 .appendTo( $results
);
364 // Allow custom rendering
365 if ( typeof context
.config
.result
.render
=== 'function' ) {
366 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
368 $result
.text( text
);
371 if ( context
.config
.highlightInput
) {
372 $result
.highlightText( context
.data
.prevText
, { method
: 'prefixHighlight' } );
375 // Widen results box if needed (new width is only calculated here, applied later).
377 // The monstrosity below accomplishes two things:
378 // * Wraps the text contents in a DOM element, so that we can know its width. There is
379 // no way to directly access the width of a text node, and we can't use the parent
380 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
381 // it, which trims it to a smaller width.
382 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
383 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
384 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
385 // still report the "trimmed" width. This should not be done in regular CSS
386 // stylesheets as we don't want this rule to apply to other <span> elements, like
387 // the ones generated by jquery.highlightText.
388 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
389 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
390 $spanForWidth
.contents().unwrap();
392 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
393 // factor in any padding, margin, or border space on the parent
394 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
398 // Apply new width for results box, if any
399 if ( expWidth
> context
.data
.$container
.width() ) {
400 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
401 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
407 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
410 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
413 context
.config
[ property
] = Math
.max( 1, value
);
415 case 'maxExpandFactor':
416 context
.config
[ property
] = Math
.max( 1, value
);
419 case 'submitOnClick':
420 case 'positionFromLeft':
421 case 'highlightInput':
422 context
.config
[ property
] = !!value
;
428 * Highlight a result in the results table
430 * @param {Object} context
431 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
432 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
434 highlight: function ( context
, result
, updateTextbox
) {
435 var selected
= context
.data
.$container
.find( '.suggestions-result-current' );
436 if ( !result
.get || selected
.get( 0 ) !== result
.get( 0 ) ) {
437 if ( result
=== 'prev' ) {
438 if ( selected
.hasClass( 'suggestions-special' ) ) {
439 result
= context
.data
.$container
.find( '.suggestions-result:last' );
441 result
= selected
.prev();
442 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
443 // there is something in the DOM between selected element and the wrapper, bypass it
444 result
= selected
.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
447 if ( selected
.length
=== 0 ) {
448 // we are at the beginning, so lets jump to the last item
449 if ( context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
450 result
= context
.data
.$container
.find( '.suggestions-special' );
452 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:last' );
456 } else if ( result
=== 'next' ) {
457 if ( selected
.length
=== 0 ) {
458 // No item selected, go to the first one
459 result
= context
.data
.$container
.find( '.suggestions-results .suggestions-result:first' );
460 if ( result
.length
=== 0 && context
.data
.$container
.find( '.suggestions-special' ).html() !== '' ) {
461 // No suggestion exists, go to the special one directly
462 result
= context
.data
.$container
.find( '.suggestions-special' );
465 result
= selected
.next();
466 if ( !( result
.length
&& result
.hasClass( 'suggestions-result' ) ) ) {
467 // there is something in the DOM between selected element and the wrapper, bypass it
468 result
= selected
.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
471 if ( selected
.hasClass( 'suggestions-special' ) ) {
474 result
.length
=== 0 &&
475 context
.data
.$container
.find( '.suggestions-special' ).html() !== ''
477 // We were at the last item, jump to the specials!
478 result
= context
.data
.$container
.find( '.suggestions-special' );
482 selected
.removeClass( 'suggestions-result-current' );
483 result
.addClass( 'suggestions-result-current' );
485 if ( updateTextbox
) {
486 if ( result
.length
=== 0 || result
.is( '.suggestions-special' ) ) {
487 $.suggestions
.restore( context
);
489 context
.data
.$textbox
.val( result
.data( 'text' ) );
490 // .val() doesn't call any event handlers, so
491 // let the world know what happened
492 context
.data
.$textbox
.trigger( 'change' );
494 context
.data
.$textbox
.trigger( 'change' );
499 * Respond to keypress event
501 * @param {jQuery.Event} e
502 * @param {Object} context
503 * @param {number} key Code of key pressed
505 keypress: function ( e
, context
, key
) {
507 wasVisible
= context
.data
.$container
.is( ':visible' ),
508 preventDefault
= false;
514 $.suggestions
.highlight( context
, 'next', true );
515 context
.data
.selectedWithMouse
= false;
517 $.suggestions
.update( context
, false );
519 preventDefault
= true;
524 $.suggestions
.highlight( context
, 'prev', true );
525 context
.data
.selectedWithMouse
= false;
527 preventDefault
= wasVisible
;
531 $.suggestions
.hide( context
);
532 $.suggestions
.restore( context
);
533 $.suggestions
.cancel( context
);
534 context
.data
.$textbox
.trigger( 'change' );
535 preventDefault
= wasVisible
;
539 preventDefault
= wasVisible
;
540 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
541 $.suggestions
.hide( context
);
542 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
543 // If nothing is selected or if something was selected with the mouse
544 // cancel any current requests and allow the form to be submitted
545 // (simply don't prevent default behavior).
546 $.suggestions
.cancel( context
);
547 preventDefault
= false;
548 } else if ( selected
.is( '.suggestions-special' ) ) {
549 if ( typeof context
.config
.special
.select
=== 'function' ) {
550 // Allow the callback to decide whether to prevent default or not
551 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
552 preventDefault
= false;
556 if ( typeof context
.config
.result
.select
=== 'function' ) {
557 // Allow the callback to decide whether to prevent default or not
558 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
559 preventDefault
= false;
565 $.suggestions
.update( context
, true );
568 if ( preventDefault
) {
575 // See file header for method documentation
576 $.fn
.suggestions = function () {
577 // Multi-context fields
578 var args
= arguments
;
580 $( this ).each( function () {
583 /* Construction and Loading */
585 context
= $( this ).data( 'suggestions-context' );
586 if ( context
=== undefined || context
=== null ) {
589 fetch: function () {},
590 cancel: function () {},
600 submitOnClick
: false,
603 highlightInput
: false
610 // Handle various calling styles
611 if ( args
.length
> 0 ) {
612 if ( typeof args
[ 0 ] === 'object' ) {
613 // Apply set of properties
614 for ( key
in args
[ 0 ] ) {
615 $.suggestions
.configure( context
, key
, args
[ 0 ][ key
] );
617 } else if ( typeof args
[ 0 ] === 'string' ) {
618 if ( args
.length
> 1 ) {
619 // Set property values
620 $.suggestions
.configure( context
, args
[ 0 ], args
[ 1 ] );
627 if ( context
.data
=== undefined ) {
629 // ID of running timer
632 // Text in textbox when suggestions were last fetched
635 // Cache of fetched suggestions
638 // Number of results visible without scrolling
641 // Suggestion the last mousedown event occurred on
642 mouseDownOn
: $( [] ),
644 selectedWithMouse
: false
647 context
.data
.$container
= $( '<div>' )
648 .css( 'display', 'none' )
649 .addClass( 'suggestions' )
651 $( '<div>' ).addClass( 'suggestions-results' )
652 // Can't use click() because the container div is hidden when the
653 // textbox loses focus. Instead, listen for a mousedown followed
654 // by a mouseup on the same div.
655 .on( 'mousedown', function ( e
) {
656 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
658 .on( 'mouseup', function ( e
) {
659 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
660 $other
= context
.data
.mouseDownOn
;
662 context
.data
.mouseDownOn
= $( [] );
663 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
666 $.suggestions
.highlight( context
, $result
, true );
667 if ( typeof context
.config
.result
.select
=== 'function' ) {
668 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
, 'mouse' );
670 // Don't interfere with special clicks (e.g. to open in new tab)
671 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
672 // This will hide the link we're just clicking on, which causes problems
673 // when done synchronously in at least Firefox 3.6 (T64858).
674 setTimeout( function () {
675 $.suggestions
.hide( context
);
678 // Always bring focus to the textbox, as that's probably where the user expects it
679 // if they were just typing.
680 context
.data
.$textbox
.trigger( 'focus' );
684 $( '<div>' ).addClass( 'suggestions-special' )
685 // Can't use click() because the container div is hidden when the
686 // textbox loses focus. Instead, listen for a mousedown followed
687 // by a mouseup on the same div.
688 .on( 'mousedown', function ( e
) {
689 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
691 .on( 'mouseup', function ( e
) {
692 var $special
= $( e
.target
).closest( '.suggestions-special' ),
693 $other
= context
.data
.mouseDownOn
;
695 context
.data
.mouseDownOn
= $( [] );
696 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
699 if ( typeof context
.config
.special
.select
=== 'function' ) {
700 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
, 'mouse' );
702 // Don't interfere with special clicks (e.g. to open in new tab)
703 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
704 // This will hide the link we're just clicking on, which causes problems
705 // when done synchronously in at least Firefox 3.6 (T64858).
706 setTimeout( function () {
707 $.suggestions
.hide( context
);
710 // Always bring focus to the textbox, as that's probably where the user expects it
711 // if they were just typing.
712 context
.data
.$textbox
.trigger( 'focus' );
714 .on( 'mousemove', function ( e
) {
715 context
.data
.selectedWithMouse
= true;
716 $.suggestions
.highlight(
717 context
, $( e
.target
).closest( '.suggestions-special' ), false
721 .appendTo( $( 'body' ) );
724 // Stop browser autocomplete from interfering
725 .attr( 'autocomplete', 'off' )
726 .on( 'keydown', function ( e
) {
727 // Store key pressed to handle later
728 context
.data
.keypressed
= e
.which
;
729 context
.data
.keypressedCount
= 0;
731 .on( 'keypress', function ( e
) {
732 context
.data
.keypressedCount
++;
733 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
735 .on( 'keyup', function ( e
) {
736 // The keypress event is fired when a key is pressed down and that key normally
737 // produces a character value. We also want to handle some keys that don't
738 // produce a character value so we also attach to the keydown/keyup events.
739 // List of codes sourced from
740 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
749 if ( context
.data
.keypressedCount
=== 0 &&
750 e
.which
=== context
.data
.keypressed
&&
751 allowed
.indexOf( e
.which
) !== -1
753 $.suggestions
.keypress( e
, context
, context
.data
.keypressed
);
756 .on( 'blur', function () {
757 // When losing focus because of a mousedown
758 // on a suggestion, don't hide the suggestions
759 if ( context
.data
.mouseDownOn
.length
> 0 ) {
762 $.suggestions
.hide( context
);
763 $.suggestions
.cancel( context
);
767 // Store the context for next time
768 $( this ).data( 'suggestions-context', context
);
775 * @mixins jQuery.plugin.suggestions