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 !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 isRTL
= $( document
.documentElement
).css( 'direction' ) === 'rtl',
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
= isRTL
? 'right' : 'left';
401 } else if ( expandFrom
=== 'end' ) {
402 expandFrom
= isRTL
? '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
= document
.documentElement
.clientWidth
-
417 ( regionPosition
.left
+ context
.config
.$region
.outerWidth() );
420 context
.data
.$container
.css( newCSS
);
421 $results
= context
.data
.$container
.children( '.suggestions-results' );
424 for ( i
= 0; i
< context
.config
.suggestions
.length
; i
++ ) {
425 text
= context
.config
.suggestions
[ i
];
426 $result
= $( '<div>' )
427 .addClass( 'suggestions-result' )
429 .data( 'text', context
.config
.suggestions
[ i
] )
430 .on( 'mousemove', function () {
431 context
.data
.selectedWithMouse
= true;
434 $( this ).closest( '.suggestions-results .suggestions-result' ),
438 .appendTo( $results
);
439 // Allow custom rendering
440 if ( typeof context
.config
.result
.render
=== 'function' ) {
441 context
.config
.result
.render
.call( $result
, context
.config
.suggestions
[ i
], context
);
443 $result
.text( text
);
446 if ( context
.config
.highlightInput
) {
447 $result
.highlightText( context
.data
.prevText
, { method
: 'prefixHighlight' } );
450 // Widen results box if needed (new width is only calculated here, applied later).
452 // The monstrosity below accomplishes two things:
453 // * Wraps the text contents in a DOM element, so that we can know its width. There is
454 // no way to directly access the width of a text node, and we can't use the parent
455 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
456 // it, which trims it to a smaller width.
457 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
458 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
459 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
460 // still report the "trimmed" width. This should not be done in regular CSS
461 // stylesheets as we don't want this rule to apply to other <span> elements, like
462 // the ones generated by jquery.highlightText.
463 $spanForWidth
= $result
.wrapInner( '<span>' ).children();
464 childrenWidth
= $spanForWidth
.css( 'position', 'absolute' ).outerWidth();
465 $spanForWidth
.contents().unwrap();
467 if ( childrenWidth
> $result
.width() && childrenWidth
> expWidth
) {
468 // factor in any padding, margin, or border space on the parent
469 expWidth
= childrenWidth
+ ( context
.data
.$container
.width() - $result
.width() );
473 // Apply new width for results box, if any
474 if ( expWidth
> context
.data
.$container
.width() ) {
475 maxWidth
= context
.config
.maxExpandFactor
* context
.data
.$textbox
.width();
476 context
.data
.$container
.width( Math
.min( expWidth
, maxWidth
) );
482 context
.config
[ property
] = Math
.max( 1, Math
.min( 100, value
) );
485 context
.config
[ property
] = Math
.max( 0, Math
.min( 1200, value
) );
488 context
.config
[ property
] = Math
.max( 1, value
);
490 case 'maxExpandFactor':
491 context
.config
[ property
] = Math
.max( 1, value
);
494 case 'submitOnClick':
495 case 'positionFromLeft':
496 case 'highlightInput':
497 context
.config
[ property
] = !!value
;
503 * Respond to keypress event
505 * @param {jQuery.Event} e
506 * @param {Object} context
507 * @param {number} key Code of key pressed
509 function keypress( e
, context
, key
) {
511 wasVisible
= context
.data
.$container
.is( ':visible' ),
512 preventDefault
= false;
518 highlight( context
, 'next', true );
519 context
.data
.selectedWithMouse
= false;
521 update( context
, false );
523 preventDefault
= true;
528 highlight( context
, 'prev', true );
529 context
.data
.selectedWithMouse
= false;
531 preventDefault
= wasVisible
;
538 context
.data
.$textbox
.trigger( 'change' );
539 preventDefault
= wasVisible
;
543 preventDefault
= wasVisible
;
544 selected
= context
.data
.$container
.find( '.suggestions-result-current' );
546 if ( selected
.length
=== 0 || context
.data
.selectedWithMouse
) {
547 // If nothing is selected or if something was selected with the mouse
548 // cancel any current requests and allow the form to be submitted
549 // (simply don't prevent default behavior).
551 preventDefault
= false;
552 } else if ( selected
.is( '.suggestions-special' ) ) {
553 if ( typeof context
.config
.special
.select
=== 'function' ) {
554 // Allow the callback to decide whether to prevent default or not
555 if ( context
.config
.special
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
556 preventDefault
= false;
560 if ( typeof context
.config
.result
.select
=== 'function' ) {
561 // Allow the callback to decide whether to prevent default or not
562 if ( context
.config
.result
.select
.call( selected
, context
.data
.$textbox
, 'keyboard' ) === true ) {
563 preventDefault
= false;
569 update( context
, true );
572 if ( preventDefault
) {
578 // See file header for method documentation
579 $.fn
.suggestions = function () {
580 // Multi-context fields
581 var args
= arguments
;
583 $( this ).each( function () {
586 /* Construction and Loading */
588 context
= $( this ).data( 'suggestions-context' );
589 if ( context
=== undefined || context
=== null ) {
592 fetch: function () {},
593 cancel: function () {},
603 submitOnClick
: false,
606 highlightInput
: false
613 // Handle various calling styles
614 if ( args
.length
> 0 ) {
615 if ( typeof args
[ 0 ] === 'object' ) {
616 // Apply set of properties
617 for ( key
in args
[ 0 ] ) {
618 configure( context
, key
, args
[ 0 ][ key
] );
620 } else if ( typeof args
[ 0 ] === 'string' ) {
621 if ( args
.length
> 1 ) {
622 // Set property values
623 configure( context
, args
[ 0 ], args
[ 1 ] );
630 if ( context
.data
=== undefined ) {
632 // ID of running timer
635 // Text in textbox when suggestions were last fetched
638 // Cache of fetched suggestions
639 cache
: Object
.create( null ),
641 // Number of results visible without scrolling
644 // Suggestion the last mousedown event occurred on
645 mouseDownOn
: $( [] ),
647 selectedWithMouse
: false
650 context
.data
.$container
= $( '<div>' )
651 .css( 'display', 'none' )
652 .addClass( 'suggestions' )
654 $( '<div>' ).addClass( 'suggestions-results' )
655 // Can't use click() because the container div is hidden when the
656 // textbox loses focus. Instead, listen for a mousedown followed
657 // by a mouseup on the same div.
658 .on( 'mousedown', function ( e
) {
659 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-results .suggestions-result' );
661 .on( 'mouseup', function ( e
) {
662 var $result
= $( e
.target
).closest( '.suggestions-results .suggestions-result' ),
663 $other
= context
.data
.mouseDownOn
;
665 context
.data
.mouseDownOn
= $( [] );
666 if ( $result
.get( 0 ) !== $other
.get( 0 ) ) {
669 highlight( context
, $result
, true );
670 if ( typeof context
.config
.result
.select
=== 'function' ) {
671 context
.config
.result
.select
.call( $result
, context
.data
.$textbox
, 'mouse' );
673 // Don't interfere with special clicks (e.g. to open in new tab)
674 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
675 // This will hide the link we're just clicking on, which causes problems
676 // when done synchronously in at least Firefox 3.6 (T64858).
677 setTimeout( function () {
681 // Always bring focus to the textbox, as that's probably where the user expects it
682 // if they were just typing.
683 context
.data
.$textbox
.trigger( 'focus' );
687 $( '<div>' ).addClass( 'suggestions-special' )
688 // Can't use click() because the container div is hidden when the
689 // textbox loses focus. Instead, listen for a mousedown followed
690 // by a mouseup on the same div.
691 .on( 'mousedown', function ( e
) {
692 context
.data
.mouseDownOn
= $( e
.target
).closest( '.suggestions-special' );
694 .on( 'mouseup', function ( e
) {
695 var $special
= $( e
.target
).closest( '.suggestions-special' ),
696 $other
= context
.data
.mouseDownOn
;
698 context
.data
.mouseDownOn
= $( [] );
699 if ( $special
.get( 0 ) !== $other
.get( 0 ) ) {
702 if ( typeof context
.config
.special
.select
=== 'function' ) {
703 context
.config
.special
.select
.call( $special
, context
.data
.$textbox
, 'mouse' );
705 // Don't interfere with special clicks (e.g. to open in new tab)
706 if ( !( e
.which
!== 1 || e
.altKey
|| e
.ctrlKey
|| e
.shiftKey
|| e
.metaKey
) ) {
707 // This will hide the link we're just clicking on, which causes problems
708 // when done synchronously in at least Firefox 3.6 (T64858).
709 setTimeout( function () {
713 // Always bring focus to the textbox, as that's probably where the user expects it
714 // if they were just typing.
715 context
.data
.$textbox
.trigger( 'focus' );
717 .on( 'mousemove', function ( e
) {
718 context
.data
.selectedWithMouse
= true;
720 context
, $( e
.target
).closest( '.suggestions-special' ), false
724 .appendTo( document
.body
);
727 // Stop browser autocomplete from interfering
728 .attr( 'autocomplete', 'off' )
729 .on( 'keydown', function ( e
) {
730 // Store key pressed to handle later
731 context
.data
.keypressed
= e
.which
;
732 context
.data
.keypressedCount
= 0;
734 .on( 'keypress', function ( e
) {
735 context
.data
.keypressedCount
++;
736 keypress( e
, context
, context
.data
.keypressed
);
738 .on( 'keyup', function ( e
) {
739 // The keypress event is fired when a key is pressed down and that key normally
740 // produces a character value. We also want to handle some keys that don't
741 // produce a character value so we also attach to the keydown/keyup events.
742 // List of codes sourced from
743 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
752 if ( context
.data
.keypressedCount
=== 0 &&
753 e
.which
=== context
.data
.keypressed
&&
754 allowed
.indexOf( e
.which
) !== -1
756 keypress( e
, context
, context
.data
.keypressed
);
759 .on( 'blur', function () {
760 // When losing focus because of a mousedown
761 // on a suggestion, don't hide the suggestions
762 if ( context
.data
.mouseDownOn
.length
> 0 ) {
768 // Load suggestions if the value is changed because there are already
769 // typed characters before the JavaScript is loaded.
770 if ( this.value
!== this.defaultValue
) {
771 update( context
, false );
775 // Store the context for next time
776 $( this ).data( 'suggestions-context', context
);
783 * @mixins jQuery.plugin.suggestions