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 * value = $( '#textbox' ).suggestions( option );
15 * $( '#textbox' ).suggestions();
17 * Uses jQuery.suggestions singleton internally.
19 * @class jQuery.plugin.suggestions
22 // jscs:disable checkParamNames
28 * @param {Object} options
30 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
31 * property. Called in context of the text box.
32 * @param {string} options.fetch.query
33 * @param {Function} options.fetch.response Callback to receive the suggestions with
34 * @param {Array} options.fetch.response.suggestions
35 * @param {number} options.fetch.maxRows
37 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
38 * suggestions fetches. Called in context of the text box.
40 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
42 * @param {Function} options.special.render Called in context of the suggestions-special element.
43 * @param {string} options.special.render.query
44 * @param {Object} options.special.render.context
46 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
47 * @param {jQuery} options.special.select.$textbox
49 * @param {Object} [options.result] Set of callbacks for rendering and selecting
51 * @param {Function} options.result.render Called in context of the suggestions-result element.
52 * @param {string} options.result.render.suggestion
53 * @param {Object} options.result.render.context
55 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
56 * @param {jQuery} options.result.select.$textbox
58 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
60 * @param {Function} options.update.before Called right after the user changes the textbox text.
61 * @param {Function} options.update.after Called after results are updated either from the cache or
62 * the API as a result of the user input.
64 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
66 * @param {string[]} [options.suggestions] Array of suggestions to display.
68 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
69 * Must be between 1 and 100.
71 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
72 * Must be between 0 and 1200.
74 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
76 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
77 * Must be higher than 1. Defaults to 1 minute.
79 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
80 * when a suggestion is clicked.
82 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
83 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
84 * the textbox. Must be higher than 1.
86 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
87 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
88 * of the current document, according to `$( 'html' ).css( 'direction' )`.
89 * Valid values: "left", "right", "start", "end", and "auto".
91 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
94 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
97 // jscs:enable checkParamNames
101 var hasOwn = Object.hasOwnProperty;
104 * Used by jQuery.plugin.suggestions.
106 * @class jQuery.suggestions
112 * Cancel any delayed maybeFetch() call and callback the context so
113 * they can cancel any async fetching if they use AJAX or something.
115 * @param {Object} context
117 cancel: function ( context ) {
118 if ( context.data.timerID !== null ) {
119 clearTimeout( context.data.timerID );
121 if ( $.isFunction( context.config.cancel ) ) {
122 context.config.cancel.call( context.data.$textbox );
127 * Hide the element with suggestions and clean up some state.
129 * @param {Object} context
131 hide: function ( context ) {
132 // Remove any highlights, including on "special" items
133 context.data.$container.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
134 // Hide the container
135 context.data.$container.hide();
139 * Restore the text the user originally typed in the textbox, before it
140 * was overwritten by highlight(). This restores the value the currently
141 * displayed suggestions are based on, rather than the value just before
142 * highlight() overwrote it; the former is arguably slightly more sensible.
144 * @param {Object} context
146 restore: function ( context ) {
147 context.data.$textbox.val( context.data.prevText );
151 * Ask the user-specified callback for new suggestions. Any previous delayed
152 * call to this function still pending will be canceled. If the value in the
153 * textbox is empty or hasn't changed since the last time suggestions were fetched,
154 * this function does nothing.
156 * @param {Object} context
157 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
159 update: function ( context, delayed ) {
160 function maybeFetch() {
161 var val = context.data.$textbox.val(),
162 cache = context.data.cache,
165 if ( typeof context.config.update.before === 'function' ) {
166 context.config.update.before.call( context.data.$textbox );
169 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
170 // if the textbox is empty then clear the result div, but leave other settings intouched
171 if ( val.length === 0 ) {
172 $.suggestions.hide( context );
173 context.data.prevText = '';
175 val !== context.data.prevText ||
176 !context.data.$container.is( ':visible' )
178 context.data.prevText = val;
180 if ( context.config.cache && hasOwn.call( cache, val ) ) {
181 if ( +new Date() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
182 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
183 if ( typeof context.config.update.after === 'function' ) {
184 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
192 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
193 context.config.fetch.call(
194 context.data.$textbox,
196 function ( suggestions, metadata ) {
197 suggestions = suggestions.slice( 0, context.config.maxRows );
198 context.data.$textbox.suggestions( 'suggestions', suggestions );
199 if ( typeof context.config.update.after === 'function' ) {
200 context.config.update.after.call( context.data.$textbox, metadata );
202 if ( context.config.cache ) {
204 suggestions: suggestions,
206 timestamp: +new Date()
210 context.config.maxRows
215 // Always update special rendering
216 $.suggestions.special( context );
219 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
220 $.suggestions.cancel( context );
223 // To avoid many started/aborted requests while typing, we're gonna take a short
224 // break before trying to fetch data.
225 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
232 * @param {Object} context
234 special: function ( context ) {
235 // Allow custom rendering - but otherwise don't do any rendering
236 if ( typeof context.config.special.render === 'function' ) {
237 // Wait for the browser to update the value
238 setTimeout( function () {
240 var $special = context.data.$container.find( '.suggestions-special' );
241 context.config.special.render.call( $special, context.data.$textbox.val(), context );
247 * Sets the value of a property, and updates the widget accordingly
249 * @param {Object} context
250 * @param {string} property Name of property
251 * @param {Mixed} value Value to set property with
253 configure: function ( context, property, value ) {
255 $result, $results, $spanForWidth, childrenWidth,
256 i, expWidth, maxWidth, text;
258 // Validate creation using fallback values
259 switch ( property ) {
267 context.config[ property ] = value;
270 context.config[ property ] = value;
271 // Update suggestions
272 if ( context.data !== undefined ) {
273 if ( context.data.$textbox.val().length === 0 ) {
274 // Hide the div when no suggestion exist
275 $.suggestions.hide( context );
277 // Rebuild the suggestions list
278 context.data.$container.show();
279 // Update the size and position of the list
281 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
283 width: context.config.$region.outerWidth(),
287 // Process expandFrom, after this it is set to left or right.
288 context.config.expandFrom = ( function ( expandFrom ) {
289 var regionWidth, docWidth, regionCenter, docCenter,
290 docDir = $( document.documentElement ).css( 'direction' ),
291 $region = context.config.$region;
293 // Backwards compatible
294 if ( context.config.positionFromLeft ) {
297 // Catch invalid values, default to 'auto'
298 } else if ( $.inArray( expandFrom, [ 'left', 'right', 'start', 'end', 'auto' ] ) === -1 ) {
302 if ( expandFrom === 'auto' ) {
303 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
304 // If the markup explicitly contains a direction, use it.
305 expandFrom = $region.data( 'searchsuggest-expand-dir' );
307 regionWidth = $region.outerWidth();
308 docWidth = $( document ).width();
309 if ( regionWidth > ( 0.85 * docWidth ) ) {
310 // If the input size takes up more than 85% of the document horizontally
311 // expand the suggestions to the writing direction's native end.
312 expandFrom = 'start';
314 // Calculate the center points of the input and document
315 regionCenter = $region.offset().left + regionWidth / 2;
316 docCenter = docWidth / 2;
317 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
318 // If the input's center is within 10% of the document center
319 // use the writing direction's native end.
320 expandFrom = 'start';
322 // Otherwise expand the input from the closest side of the page,
323 // towards the side of the page with the most free open space
324 expandFrom = regionCenter > docCenter ? 'right' : 'left';
330 if ( expandFrom === 'start' ) {
331 expandFrom = docDir === 'rtl' ? 'right' : 'left';
333 } else if ( expandFrom === 'end' ) {
334 expandFrom = docDir === 'rtl' ? 'left' : 'right';
339 }( context.config.expandFrom ) );
341 if ( context.config.expandFrom === 'left' ) {
343 newCSS.left = context.config.$region.offset().left;
344 newCSS.right = 'auto';
347 newCSS.left = 'auto';
348 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
351 context.data.$container.css( newCSS );
352 $results = context.data.$container.children( '.suggestions-results' );
355 for ( i = 0; i < context.config.suggestions.length; i++ ) {
356 text = context.config.suggestions[ i ];
357 $result = $( '<div>' )
358 .addClass( 'suggestions-result' )
360 .data( 'text', context.config.suggestions[ i ] )
361 .mousemove( function () {
362 context.data.selectedWithMouse = true;
363 $.suggestions.highlight(
365 $( this ).closest( '.suggestions-results .suggestions-result' ),
369 .appendTo( $results );
370 // Allow custom rendering
371 if ( typeof context.config.result.render === 'function' ) {
372 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
374 $result.text( text );
377 if ( context.config.highlightInput ) {
378 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
381 // Widen results box if needed (new width is only calculated here, applied later).
383 // The monstrosity below accomplishes two things:
384 // * Wraps the text contents in a DOM element, so that we can know its width. There is
385 // no way to directly access the width of a text node, and we can't use the parent
386 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
387 // it, which trims it to a smaller width.
388 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
389 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
390 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
391 // still report the "trimmed" width. This should not be done in regular CSS
392 // stylesheets as we don't want this rule to apply to other <span> elements, like
393 // the ones generated by jquery.highlightText.
394 $spanForWidth = $result.wrapInner( '<span>' ).children();
395 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
396 $spanForWidth.contents().unwrap();
398 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
399 // factor in any padding, margin, or border space on the parent
400 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
404 // Apply new width for results box, if any
405 if ( expWidth > context.data.$container.width() ) {
406 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
407 context.data.$container.width( Math.min( expWidth, maxWidth ) );
413 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
416 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
419 context.config[ property ] = Math.max( 1, value );
421 case 'maxExpandFactor':
422 context.config[ property ] = Math.max( 1, value );
425 case 'submitOnClick':
426 case 'positionFromLeft':
427 case 'highlightInput':
428 context.config[ property ] = !!value;
434 * Highlight a result in the results table
436 * @param {Object} context
437 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
438 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
440 highlight: function ( context, result, updateTextbox ) {
441 var selected = context.data.$container.find( '.suggestions-result-current' );
442 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
443 if ( result === 'prev' ) {
444 if ( selected.hasClass( 'suggestions-special' ) ) {
445 result = context.data.$container.find( '.suggestions-result:last' );
447 result = selected.prev();
448 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
449 // there is something in the DOM between selected element and the wrapper, bypass it
450 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
453 if ( selected.length === 0 ) {
454 // we are at the beginning, so lets jump to the last item
455 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
456 result = context.data.$container.find( '.suggestions-special' );
458 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
462 } else if ( result === 'next' ) {
463 if ( selected.length === 0 ) {
464 // No item selected, go to the first one
465 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
466 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
467 // No suggestion exists, go to the special one directly
468 result = context.data.$container.find( '.suggestions-special' );
471 result = selected.next();
472 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
473 // there is something in the DOM between selected element and the wrapper, bypass it
474 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
477 if ( selected.hasClass( 'suggestions-special' ) ) {
480 result.length === 0 &&
481 context.data.$container.find( '.suggestions-special' ).html() !== ''
483 // We were at the last item, jump to the specials!
484 result = context.data.$container.find( '.suggestions-special' );
488 selected.removeClass( 'suggestions-result-current' );
489 result.addClass( 'suggestions-result-current' );
491 if ( updateTextbox ) {
492 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
493 $.suggestions.restore( context );
495 context.data.$textbox.val( result.data( 'text' ) );
496 // .val() doesn't call any event handlers, so
497 // let the world know what happened
498 context.data.$textbox.change();
500 context.data.$textbox.trigger( 'change' );
505 * Respond to keypress event
507 * @param {jQuery.Event} e
508 * @param {Object} context
509 * @param {number} key Code of key pressed
511 keypress: function ( e, context, key ) {
513 wasVisible = context.data.$container.is( ':visible' ),
514 preventDefault = false;
520 $.suggestions.highlight( context, 'next', true );
521 context.data.selectedWithMouse = false;
523 $.suggestions.update( context, false );
525 preventDefault = true;
530 $.suggestions.highlight( context, 'prev', true );
531 context.data.selectedWithMouse = false;
533 preventDefault = wasVisible;
537 $.suggestions.hide( context );
538 $.suggestions.restore( context );
539 $.suggestions.cancel( context );
540 context.data.$textbox.trigger( 'change' );
541 preventDefault = wasVisible;
545 preventDefault = wasVisible;
546 selected = context.data.$container.find( '.suggestions-result-current' );
547 $.suggestions.hide( context );
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).
552 $.suggestions.cancel( context );
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 $.suggestions.update( context, true );
574 if ( preventDefault ) {
581 // See file header for method documentation
582 $.fn.suggestions = function () {
584 // Multi-context fields
588 $( this ).each( function () {
591 /* Construction and Loading */
593 context = $( this ).data( 'suggestions-context' );
594 if ( context === undefined || context === null ) {
597 fetch: function () {},
598 cancel: function () {},
608 submitOnClick: false,
611 highlightInput: false
618 // Handle various calling styles
619 if ( args.length > 0 ) {
620 if ( typeof args[ 0 ] === 'object' ) {
621 // Apply set of properties
622 for ( key in args[ 0 ] ) {
623 $.suggestions.configure( context, key, args[ 0 ][ key ] );
625 } else if ( typeof args[ 0 ] === 'string' ) {
626 if ( args.length > 1 ) {
627 // Set property values
628 $.suggestions.configure( context, args[ 0 ], args[ 1 ] );
629 } else if ( returnValue === null || returnValue === undefined ) {
630 // Get property values, but don't give access to internal data - returns only the first
631 returnValue = ( args[ 0 ] in context.config ? undefined : context.config[ args[ 0 ] ] );
638 if ( context.data === undefined ) {
640 // ID of running timer
643 // Text in textbox when suggestions were last fetched
646 // Cache of fetched suggestions
649 // Number of results visible without scrolling
652 // Suggestion the last mousedown event occurred on
653 mouseDownOn: $( [] ),
655 selectedWithMouse: false
658 context.data.$container = $( '<div>' )
659 .css( 'display', 'none' )
660 .addClass( 'suggestions' )
662 $( '<div>' ).addClass( 'suggestions-results' )
663 // Can't use click() because the container div is hidden when the
664 // textbox loses focus. Instead, listen for a mousedown followed
665 // by a mouseup on the same div.
666 .mousedown( function ( e ) {
667 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
669 .mouseup( function ( e ) {
670 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
671 $other = context.data.mouseDownOn;
673 context.data.mouseDownOn = $( [] );
674 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
677 $.suggestions.highlight( context, $result, true );
678 if ( typeof context.config.result.select === 'function' ) {
679 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
681 // Don't interfere with special clicks (e.g. to open in new tab)
682 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
683 // This will hide the link we're just clicking on, which causes problems
684 // when done synchronously in at least Firefox 3.6 (T64858).
685 setTimeout( function () {
686 $.suggestions.hide( context );
689 // Always bring focus to the textbox, as that's probably where the user expects it
690 // if they were just typing.
691 context.data.$textbox.focus();
695 $( '<div>' ).addClass( 'suggestions-special' )
696 // Can't use click() because the container div is hidden when the
697 // textbox loses focus. Instead, listen for a mousedown followed
698 // by a mouseup on the same div.
699 .mousedown( function ( e ) {
700 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
702 .mouseup( function ( e ) {
703 var $special = $( e.target ).closest( '.suggestions-special' ),
704 $other = context.data.mouseDownOn;
706 context.data.mouseDownOn = $( [] );
707 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
710 if ( typeof context.config.special.select === 'function' ) {
711 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
713 // Don't interfere with special clicks (e.g. to open in new tab)
714 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
715 // This will hide the link we're just clicking on, which causes problems
716 // when done synchronously in at least Firefox 3.6 (T64858).
717 setTimeout( function () {
718 $.suggestions.hide( context );
721 // Always bring focus to the textbox, as that's probably where the user expects it
722 // if they were just typing.
723 context.data.$textbox.focus();
725 .mousemove( function ( e ) {
726 context.data.selectedWithMouse = true;
727 $.suggestions.highlight(
728 context, $( e.target ).closest( '.suggestions-special' ), false
732 .appendTo( $( 'body' ) );
735 // Stop browser autocomplete from interfering
736 .attr( 'autocomplete', 'off' )
737 .keydown( function ( e ) {
738 // Store key pressed to handle later
739 context.data.keypressed = e.which;
740 context.data.keypressedCount = 0;
742 .keypress( function ( e ) {
743 context.data.keypressedCount++;
744 $.suggestions.keypress( e, context, context.data.keypressed );
746 .keyup( function ( e ) {
747 // The keypress event is fired when a key is pressed down and that key normally
748 // produces a character value. We also want to handle some keys that don't
749 // produce a character value so we also attach to the keydown/keyup events.
750 // List of codes sourced from
751 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
760 if ( context.data.keypressedCount === 0 &&
761 e.which === context.data.keypressed &&
762 $.inArray( e.which, allowed ) !== -1
764 $.suggestions.keypress( e, context, context.data.keypressed );
768 // When losing focus because of a mousedown
769 // on a suggestion, don't hide the suggestions
770 if ( context.data.mouseDownOn.length > 0 ) {
773 $.suggestions.hide( context );
774 $.suggestions.cancel( context );
778 // Store the context for next time
779 $( this ).data( 'suggestions-context', context );
781 return returnValue !== undefined ? returnValue : $( this );
786 * @mixins jQuery.plugin.suggestions