Merge "Improve sorting on SpecialWanted*-Pages"
[mediawiki.git] / resources / src / jquery / jquery.suggestions.js
blobfdc8a266adf875d8a70b1a8d27a61e2d90bb61eb
1 /**
2  * This plugin provides a generic way to add suggestions to a text box.
3  *
4  * Set options:
5  *
6  *              $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
7  *              $( '#textbox' ).suggestions( option, value );
8  *
9  * Get option:
10  *
11  *              value = $( '#textbox' ).suggestions( option );
12  *
13  * Initialize:
14  *
15  *              $( '#textbox' ).suggestions();
16  *
17  * Uses jQuery.suggestions singleton internally.
18  *
19  * @class jQuery.plugin.suggestions
20  */
22  // jscs:disable checkParamNames
23 /**
24  * @method suggestions
25  * @chainable
26  * @return {jQuery}
27  *
28  * @param {Object} options
29  *
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
36  *
37  * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
38  *  suggestions fetches. Called in context of the text box.
39  *
40  * @param {Object} [options.special] Set of callbacks for rendering and selecting.
41  *
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
45  *
46  * @param {Function} options.special.select Called in context of the suggestions-result-current element.
47  * @param {jQuery} options.special.select.$textbox
48  *
49  * @param {Object} [options.result] Set of callbacks for rendering and selecting
50  *
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
54  *
55  * @param {Function} options.result.select Called in context of the suggestions-result-current element.
56  * @param {jQuery} options.result.select.$textbox
57  *
58  * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
59  *
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.
63  *
64  * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
65  *
66  * @param {string[]} [options.suggestions] Array of suggestions to display.
67  *
68  * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
69  *  Must be between 1 and 100.
70  *
71  * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
72  *  Must be between 0 and 1200.
73  *
74  * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
75  *
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.
78  *
79  * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
80  *  when a suggestion is clicked.
81  *
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.
85  *
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".
90  *
91  * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
92  *  compatibility.
93  *
94  * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
95  *  input or not.
96  */
97  // jscs:enable checkParamNames
99 ( function ( $ ) {
101         var hasOwn = Object.hasOwnProperty;
103         /**
104          * Used by jQuery.plugin.suggestions.
105          *
106          * @class jQuery.suggestions
107          * @singleton
108          * @private
109          */
110         $.suggestions = {
111                 /**
112                  * Cancel any delayed maybeFetch() call and callback the context so
113                  * they can cancel any async fetching if they use AJAX or something.
114                  *
115                  * @param {Object} context
116                  */
117                 cancel: function ( context ) {
118                         if ( context.data.timerID !== null ) {
119                                 clearTimeout( context.data.timerID );
120                         }
121                         if ( $.isFunction( context.config.cancel ) ) {
122                                 context.config.cancel.call( context.data.$textbox );
123                         }
124                 },
126                 /**
127                  * Hide the element with suggestions and clean up some state.
128                  *
129                  * @param {Object} context
130                  */
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();
136                 },
138                 /**
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.
143                  *
144                  * @param {Object} context
145                  */
146                 restore: function ( context ) {
147                         context.data.$textbox.val( context.data.prevText );
148                 },
150                 /**
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.
155                  *
156                  * @param {Object} context
157                  * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
158                  */
159                 update: function ( context, delayed ) {
160                         function maybeFetch() {
161                                 var val = context.data.$textbox.val(),
162                                         cache = context.data.cache,
163                                         cacheHit;
165                                 if ( typeof context.config.update.before === 'function' ) {
166                                         context.config.update.before.call( context.data.$textbox );
167                                 }
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 = '';
174                                 } else if (
175                                         val !== context.data.prevText ||
176                                         !context.data.$container.is( ':visible' )
177                                 ) {
178                                         context.data.prevText = val;
179                                         // Try cache first
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 );
185                                                         }
186                                                         cacheHit = true;
187                                                 } else {
188                                                         // Cache expired
189                                                         delete cache[ val ];
190                                                 }
191                                         }
192                                         if ( !cacheHit && typeof context.config.fetch === 'function' ) {
193                                                 context.config.fetch.call(
194                                                         context.data.$textbox,
195                                                         val,
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 );
201                                                                 }
202                                                                 if ( context.config.cache ) {
203                                                                         cache[ val ] = {
204                                                                                 suggestions: suggestions,
205                                                                                 metadata: metadata,
206                                                                                 timestamp: +new Date()
207                                                                         };
208                                                                 }
209                                                         },
210                                                         context.config.maxRows
211                                                 );
212                                         }
213                                 }
215                                 // Always update special rendering
216                                 $.suggestions.special( context );
217                         }
219                         // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
220                         $.suggestions.cancel( context );
222                         if ( delayed ) {
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 );
226                         } else {
227                                 maybeFetch();
228                         }
229                 },
231                 /**
232                  * @param {Object} context
233                 */
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 () {
239                                         // Render special
240                                         var $special = context.data.$container.find( '.suggestions-special' );
241                                         context.config.special.render.call( $special, context.data.$textbox.val(), context );
242                                 }, 1 );
243                         }
244                 },
246                 /**
247                  * Sets the value of a property, and updates the widget accordingly
248                  *
249                  * @param {Object} context
250                  * @param {string} property Name of property
251                  * @param {Mixed} value Value to set property with
252                  */
253                 configure: function ( context, property, value ) {
254                         var newCSS,
255                                 $result, $results, $spanForWidth, childrenWidth,
256                                 i, expWidth, maxWidth, text;
258                         // Validate creation using fallback values
259                         switch ( property ) {
260                                 case 'fetch':
261                                 case 'cancel':
262                                 case 'special':
263                                 case 'result':
264                                 case 'update':
265                                 case '$region':
266                                 case 'expandFrom':
267                                         context.config[ property ] = value;
268                                         break;
269                                 case 'suggestions':
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 );
276                                                 } else {
277                                                         // Rebuild the suggestions list
278                                                         context.data.$container.show();
279                                                         // Update the size and position of the list
280                                                         newCSS = {
281                                                                 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
282                                                                 bottom: 'auto',
283                                                                 width: context.config.$region.outerWidth(),
284                                                                 height: 'auto'
285                                                         };
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 ) {
295                                                                         expandFrom = 'left';
297                                                                 // Catch invalid values, default to 'auto'
298                                                                 } else if ( $.inArray( expandFrom, [ 'left', 'right', 'start', 'end', 'auto' ] ) === -1 ) {
299                                                                         expandFrom = 'auto';
300                                                                 }
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' );
306                                                                         } else {
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';
313                                                                                 } else {
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';
321                                                                                         } else {
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';
325                                                                                         }
326                                                                                 }
327                                                                         }
328                                                                 }
330                                                                 if ( expandFrom === 'start' ) {
331                                                                         expandFrom = docDir === 'rtl' ? 'right' : 'left';
333                                                                 } else if ( expandFrom === 'end' ) {
334                                                                         expandFrom = docDir === 'rtl' ? 'left' : 'right';
335                                                                 }
337                                                                 return expandFrom;
339                                                         }( context.config.expandFrom ) );
341                                                         if ( context.config.expandFrom === 'left' ) {
342                                                                 // Expand from left
343                                                                 newCSS.left = context.config.$region.offset().left;
344                                                                 newCSS.right = 'auto';
345                                                         } else {
346                                                                 // Expand from right
347                                                                 newCSS.left = 'auto';
348                                                                 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
349                                                         }
351                                                         context.data.$container.css( newCSS );
352                                                         $results = context.data.$container.children( '.suggestions-results' );
353                                                         $results.empty();
354                                                         expWidth = -1;
355                                                         for ( i = 0; i < context.config.suggestions.length; i++ ) {
356                                                                 text = context.config.suggestions[ i ];
357                                                                 $result = $( '<div>' )
358                                                                         .addClass( 'suggestions-result' )
359                                                                         .attr( 'rel', i )
360                                                                         .data( 'text', context.config.suggestions[ i ] )
361                                                                         .mousemove( function () {
362                                                                                 context.data.selectedWithMouse = true;
363                                                                                 $.suggestions.highlight(
364                                                                                         context,
365                                                                                         $( this ).closest( '.suggestions-results .suggestions-result' ),
366                                                                                         false
367                                                                                 );
368                                                                         } )
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 );
373                                                                 } else {
374                                                                         $result.text( text );
375                                                                 }
377                                                                 if ( context.config.highlightInput ) {
378                                                                         $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
379                                                                 }
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() );
401                                                                 }
402                                                         }
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 ) );
408                                                         }
409                                                 }
410                                         }
411                                         break;
412                                 case 'maxRows':
413                                         context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
414                                         break;
415                                 case 'delay':
416                                         context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
417                                         break;
418                                 case 'cacheMaxAge':
419                                         context.config[ property ] = Math.max( 1, value );
420                                         break;
421                                 case 'maxExpandFactor':
422                                         context.config[ property ] = Math.max( 1, value );
423                                         break;
424                                 case 'cache':
425                                 case 'submitOnClick':
426                                 case 'positionFromLeft':
427                                 case 'highlightInput':
428                                         context.config[ property ] = !!value;
429                                         break;
430                         }
431                 },
433                 /**
434                  * Highlight a result in the results table
435                  *
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
439                  */
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' );
446                                         } else {
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 );
451                                                 }
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' );
457                                                         } else {
458                                                                 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
459                                                         }
460                                                 }
461                                         }
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' );
469                                                 }
470                                         } else {
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 );
475                                                 }
477                                                 if ( selected.hasClass( 'suggestions-special' ) ) {
478                                                         result = $( [] );
479                                                 } else if (
480                                                         result.length === 0 &&
481                                                         context.data.$container.find( '.suggestions-special' ).html() !== ''
482                                                 ) {
483                                                         // We were at the last item, jump to the specials!
484                                                         result = context.data.$container.find( '.suggestions-special' );
485                                                 }
486                                         }
487                                 }
488                                 selected.removeClass( 'suggestions-result-current' );
489                                 result.addClass( 'suggestions-result-current' );
490                         }
491                         if ( updateTextbox ) {
492                                 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
493                                         $.suggestions.restore( context );
494                                 } else {
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();
499                                 }
500                                 context.data.$textbox.trigger( 'change' );
501                         }
502                 },
504                 /**
505                  * Respond to keypress event
506                  *
507                  * @param {jQuery.Event} e
508                  * @param {Object} context
509                  * @param {number} key Code of key pressed
510                  */
511                 keypress: function ( e, context, key ) {
512                         var selected,
513                                 wasVisible = context.data.$container.is( ':visible' ),
514                                 preventDefault = false;
516                         switch ( key ) {
517                                 // Arrow down
518                                 case 40:
519                                         if ( wasVisible ) {
520                                                 $.suggestions.highlight( context, 'next', true );
521                                                 context.data.selectedWithMouse = false;
522                                         } else {
523                                                 $.suggestions.update( context, false );
524                                         }
525                                         preventDefault = true;
526                                         break;
527                                 // Arrow up
528                                 case 38:
529                                         if ( wasVisible ) {
530                                                 $.suggestions.highlight( context, 'prev', true );
531                                                 context.data.selectedWithMouse = false;
532                                         }
533                                         preventDefault = wasVisible;
534                                         break;
535                                 // Escape
536                                 case 27:
537                                         $.suggestions.hide( context );
538                                         $.suggestions.restore( context );
539                                         $.suggestions.cancel( context );
540                                         context.data.$textbox.trigger( 'change' );
541                                         preventDefault = wasVisible;
542                                         break;
543                                 // Enter
544                                 case 13:
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;
559                                                         }
560                                                 }
561                                         } else {
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;
566                                                         }
567                                                 }
568                                         }
569                                         break;
570                                 default:
571                                         $.suggestions.update( context, true );
572                                         break;
573                         }
574                         if ( preventDefault ) {
575                                 e.preventDefault();
576                                 e.stopPropagation();
577                         }
578                 }
579         };
581         // See file header for method documentation
582         $.fn.suggestions = function () {
584                 // Multi-context fields
585                 var returnValue,
586                         args = arguments;
588                 $( this ).each( function () {
589                         var context, key;
591                         /* Construction and Loading */
593                         context = $( this ).data( 'suggestions-context' );
594                         if ( context === undefined || context === null ) {
595                                 context = {
596                                         config: {
597                                                 fetch: function () {},
598                                                 cancel: function () {},
599                                                 special: {},
600                                                 result: {},
601                                                 update: {},
602                                                 $region: $( this ),
603                                                 suggestions: [],
604                                                 maxRows: 10,
605                                                 delay: 120,
606                                                 cache: false,
607                                                 cacheMaxAge: 60000,
608                                                 submitOnClick: false,
609                                                 maxExpandFactor: 3,
610                                                 expandFrom: 'auto',
611                                                 highlightInput: false
612                                         }
613                                 };
614                         }
616                         /* API */
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 ] );
624                                         }
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 ] ] );
632                                         }
633                                 }
634                         }
636                         /* Initialization */
638                         if ( context.data === undefined ) {
639                                 context.data = {
640                                         // ID of running timer
641                                         timerID: null,
643                                         // Text in textbox when suggestions were last fetched
644                                         prevText: null,
646                                         // Cache of fetched suggestions
647                                         cache: {},
649                                         // Number of results visible without scrolling
650                                         visibleResults: 0,
652                                         // Suggestion the last mousedown event occurred on
653                                         mouseDownOn: $( [] ),
654                                         $textbox: $( this ),
655                                         selectedWithMouse: false
656                                 };
658                                 context.data.$container = $( '<div>' )
659                                         .css( 'display', 'none' )
660                                         .addClass( 'suggestions' )
661                                         .append(
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' );
668                                                         } )
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 ) ) {
675                                                                         return;
676                                                                 }
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' );
680                                                                 }
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 );
687                                                                         }, 0 );
688                                                                 }
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();
692                                                         } )
693                                         )
694                                         .append(
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' );
701                                                         } )
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 ) ) {
708                                                                         return;
709                                                                 }
710                                                                 if ( typeof context.config.special.select === 'function' ) {
711                                                                         context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
712                                                                 }
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 );
719                                                                         }, 0 );
720                                                                 }
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();
724                                                         } )
725                                                         .mousemove( function ( e ) {
726                                                                 context.data.selectedWithMouse = true;
727                                                                 $.suggestions.highlight(
728                                                                         context, $( e.target ).closest( '.suggestions-special' ), false
729                                                                 );
730                                                         } )
731                                         )
732                                         .appendTo( $( 'body' ) );
734                                 $( this )
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;
741                                         } )
742                                         .keypress( function ( e ) {
743                                                 context.data.keypressedCount++;
744                                                 $.suggestions.keypress( e, context, context.data.keypressed );
745                                         } )
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
752                                                 var allowed = [
753                                                         40, // up arrow
754                                                         38, // down arrow
755                                                         27, // escape
756                                                         13, // enter
757                                                         46, // delete
758                                                         8   // backspace
759                                                 ];
760                                                 if ( context.data.keypressedCount === 0 &&
761                                                         e.which === context.data.keypressed &&
762                                                         $.inArray( e.which, allowed ) !== -1
763                                                 ) {
764                                                         $.suggestions.keypress( e, context, context.data.keypressed );
765                                                 }
766                                         } )
767                                         .blur( function () {
768                                                 // When losing focus because of a mousedown
769                                                 // on a suggestion, don't hide the suggestions
770                                                 if ( context.data.mouseDownOn.length > 0 ) {
771                                                         return;
772                                                 }
773                                                 $.suggestions.hide( context );
774                                                 $.suggestions.cancel( context );
775                                         } );
776                         }
778                         // Store the context for next time
779                         $( this ).data( 'suggestions-context', context );
780                 } );
781                 return returnValue !== undefined ? returnValue : $( this );
782         };
784         /**
785          * @class jQuery
786          * @mixins jQuery.plugin.suggestions
787          */
789 }( jQuery ) );