Merge "jquery.suggestions: Use Object.create( null )"
[lhc/web/wiklou.git] / resources / src / jquery / jquery.suggestions.js
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 * Initialize:
10 *
11 * $( '#textbox' ).suggestions();
12 *
13 * @class jQuery.plugin.suggestions
14 */
15
16 /**
17 * @method suggestions
18 * @chainable
19 * @return {jQuery}
20 *
21 * @param {Object} options
22 *
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
29 *
30 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
31 * suggestions fetches. Called in context of the text box.
32 *
33 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
34 *
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
38 *
39 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
40 * @param {jQuery} options.special.select.$textbox
41 *
42 * @param {Object} [options.result] Set of callbacks for rendering and selecting
43 *
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
47 *
48 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
49 * @param {jQuery} options.result.select.$textbox
50 *
51 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
52 *
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.
56 *
57 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
58 *
59 * @param {string[]} [options.suggestions] Array of suggestions to display.
60 *
61 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
62 * Must be between 1 and 100.
63 *
64 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
65 * Must be between 0 and 1200.
66 *
67 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
68 *
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.
71 *
72 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
73 * when a suggestion is clicked.
74 *
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.
78 *
79 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
80 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
81 * of the current document, according to `$( 'html' ).css( 'direction' )`.
82 * Valid values: "left", "right", "start", "end", and "auto".
83 *
84 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
85 * compatibility.
86 *
87 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
88 * input or not.
89 */
90
91 ( function () {
92
93 /**
94 * Cancel any delayed maybeFetch() call and callback the context so
95 * they can cancel any async fetching if they use AJAX or something.
96 *
97 * @param {Object} context
98 */
99 function cancel( context ) {
100 if ( context.data.timerID !== null ) {
101 clearTimeout( context.data.timerID );
102 }
103 if ( typeof context.config.cancel === 'function' ) {
104 context.config.cancel.call( context.data.$textbox );
105 }
106 }
107
108 /**
109 * Hide the element with suggestions and clean up some state.
110 *
111 * @param {Object} context
112 */
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();
118 }
119
120 /**
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.
125 *
126 * @param {Object} context
127 */
128 function restore( context ) {
129 context.data.$textbox.val( context.data.prevText );
130 }
131
132 /**
133 * @param {Object} context
134 */
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 () {
140 // Render special
141 var $special = context.data.$container.find( '.suggestions-special' );
142 context.config.special.render.call( $special, context.data.$textbox.val(), context );
143 }, 1 );
144 }
145 }
146
147 /**
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.
152 *
153 * @param {Object} context
154 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
155 */
156 function update( context, delayed ) {
157 function maybeFetch() {
158 var val = context.data.$textbox.val(),
159 cache = context.data.cache,
160 cacheHit;
161
162 if ( typeof context.config.update.before === 'function' ) {
163 context.config.update.before.call( context.data.$textbox );
164 }
165
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 ) {
169 hide( context );
170 context.data.prevText = '';
171 } else if (
172 val !== context.data.prevText ||
173 !context.data.$container.is( ':visible' )
174 ) {
175 context.data.prevText = val;
176 // Try cache first
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 );
182 }
183 cacheHit = true;
184 } else {
185 // Cache expired
186 delete cache[ val ];
187 }
188 }
189 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
190 context.config.fetch.call(
191 context.data.$textbox,
192 val,
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 );
198 }
199 if ( context.config.cache ) {
200 cache[ val ] = {
201 suggestions: suggestions,
202 metadata: metadata,
203 timestamp: mw.now()
204 };
205 }
206 },
207 context.config.maxRows
208 );
209 }
210 }
211
212 // Always update special rendering
213 special( context );
214 }
215
216 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
217 cancel( context );
218
219 if ( delayed ) {
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 );
223 } else {
224 maybeFetch();
225 }
226 }
227
228 /**
229 * Highlight a result in the results table
230 *
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
234 */
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' );
241 } else {
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 );
246 }
247
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' );
252 } else {
253 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
254 }
255 }
256 }
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' );
264 }
265 } else {
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 );
270 }
271
272 if ( selected.hasClass( 'suggestions-special' ) ) {
273 result = $( [] );
274 } else if (
275 result.length === 0 &&
276 context.data.$container.find( '.suggestions-special' ).html() !== ''
277 ) {
278 // We were at the last item, jump to the specials!
279 result = context.data.$container.find( '.suggestions-special' );
280 }
281 }
282 }
283 selected.removeClass( 'suggestions-result-current' );
284 result.addClass( 'suggestions-result-current' );
285 }
286 if ( updateTextbox ) {
287 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
288 restore( context );
289 } else {
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' );
294 }
295 context.data.$textbox.trigger( 'change' );
296 }
297 }
298
299 /**
300 * Sets the value of a property, and updates the widget accordingly
301 *
302 * @param {Object} context
303 * @param {string} property Name of property
304 * @param {Mixed} value Value to set property with
305 */
306 function configure( context, property, value ) {
307 var newCSS,
308 $result, $results, $spanForWidth, childrenWidth,
309 regionIsFixed, regionPosition,
310 i, expWidth, maxWidth, text;
311
312 // Validate creation using fallback values
313 switch ( property ) {
314 case 'fetch':
315 case 'cancel':
316 case 'special':
317 case 'result':
318 case 'update':
319 case '$region':
320 case 'expandFrom':
321 context.config[ property ] = value;
322 break;
323 case 'suggestions':
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
329 hide( context );
330 } else {
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;
336 do {
337 if ( $el.css( 'position' ) === 'fixed' ) {
338 return true;
339 }
340 $el = $( $el[ 0 ].offsetParent );
341 } while ( $el.length );
342 return false;
343 }() );
344 regionPosition = regionIsFixed ?
345 context.config.$region[ 0 ].getBoundingClientRect() :
346 context.config.$region.offset();
347 newCSS = {
348 position: regionIsFixed ? 'fixed' : 'absolute',
349 top: regionPosition.top + context.config.$region.outerHeight(),
350 bottom: 'auto',
351 width: context.config.$region.outerWidth(),
352 height: 'auto'
353 };
354
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 docDir = $( document.documentElement ).css( 'direction' ),
359 $region = context.config.$region;
360
361 // Backwards compatible
362 if ( context.config.positionFromLeft ) {
363 expandFrom = 'left';
364
365 // Catch invalid values, default to 'auto'
366 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
367 expandFrom = 'auto';
368 }
369
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' );
374 } else {
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';
381 } else {
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';
389 } else {
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';
393 }
394 }
395 }
396 }
397
398 if ( expandFrom === 'start' ) {
399 expandFrom = docDir === 'rtl' ? 'right' : 'left';
400
401 } else if ( expandFrom === 'end' ) {
402 expandFrom = docDir === 'rtl' ? 'left' : 'right';
403 }
404
405 return expandFrom;
406
407 }( context.config.expandFrom ) );
408
409 if ( context.config.expandFrom === 'left' ) {
410 // Expand from left
411 newCSS.left = regionPosition.left;
412 newCSS.right = 'auto';
413 } else {
414 // Expand from right
415 newCSS.left = 'auto';
416 newCSS.right = $( 'body' ).width() - ( regionPosition.left + context.config.$region.outerWidth() );
417 }
418
419 context.data.$container.css( newCSS );
420 $results = context.data.$container.children( '.suggestions-results' );
421 $results.empty();
422 expWidth = -1;
423 for ( i = 0; i < context.config.suggestions.length; i++ ) {
424 text = context.config.suggestions[ i ];
425 $result = $( '<div>' )
426 .addClass( 'suggestions-result' )
427 .attr( 'rel', i )
428 .data( 'text', context.config.suggestions[ i ] )
429 .on( 'mousemove', function () {
430 context.data.selectedWithMouse = true;
431 highlight(
432 context,
433 $( this ).closest( '.suggestions-results .suggestions-result' ),
434 false
435 );
436 } )
437 .appendTo( $results );
438 // Allow custom rendering
439 if ( typeof context.config.result.render === 'function' ) {
440 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
441 } else {
442 $result.text( text );
443 }
444
445 if ( context.config.highlightInput ) {
446 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
447 }
448
449 // Widen results box if needed (new width is only calculated here, applied later).
450
451 // The monstrosity below accomplishes two things:
452 // * Wraps the text contents in a DOM element, so that we can know its width. There is
453 // no way to directly access the width of a text node, and we can't use the parent
454 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
455 // it, which trims it to a smaller width.
456 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
457 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
458 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
459 // still report the "trimmed" width. This should not be done in regular CSS
460 // stylesheets as we don't want this rule to apply to other <span> elements, like
461 // the ones generated by jquery.highlightText.
462 $spanForWidth = $result.wrapInner( '<span>' ).children();
463 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
464 $spanForWidth.contents().unwrap();
465
466 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
467 // factor in any padding, margin, or border space on the parent
468 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
469 }
470 }
471
472 // Apply new width for results box, if any
473 if ( expWidth > context.data.$container.width() ) {
474 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
475 context.data.$container.width( Math.min( expWidth, maxWidth ) );
476 }
477 }
478 }
479 break;
480 case 'maxRows':
481 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
482 break;
483 case 'delay':
484 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
485 break;
486 case 'cacheMaxAge':
487 context.config[ property ] = Math.max( 1, value );
488 break;
489 case 'maxExpandFactor':
490 context.config[ property ] = Math.max( 1, value );
491 break;
492 case 'cache':
493 case 'submitOnClick':
494 case 'positionFromLeft':
495 case 'highlightInput':
496 context.config[ property ] = !!value;
497 break;
498 }
499 }
500
501 /**
502 * Respond to keypress event
503 *
504 * @param {jQuery.Event} e
505 * @param {Object} context
506 * @param {number} key Code of key pressed
507 */
508 function keypress( e, context, key ) {
509 var selected,
510 wasVisible = context.data.$container.is( ':visible' ),
511 preventDefault = false;
512
513 switch ( key ) {
514 // Arrow down
515 case 40:
516 if ( wasVisible ) {
517 highlight( context, 'next', true );
518 context.data.selectedWithMouse = false;
519 } else {
520 update( context, false );
521 }
522 preventDefault = true;
523 break;
524 // Arrow up
525 case 38:
526 if ( wasVisible ) {
527 highlight( context, 'prev', true );
528 context.data.selectedWithMouse = false;
529 }
530 preventDefault = wasVisible;
531 break;
532 // Escape
533 case 27:
534 hide( context );
535 restore( context );
536 cancel( context );
537 context.data.$textbox.trigger( 'change' );
538 preventDefault = wasVisible;
539 break;
540 // Enter
541 case 13:
542 preventDefault = wasVisible;
543 selected = context.data.$container.find( '.suggestions-result-current' );
544 hide( context );
545 if ( selected.length === 0 || context.data.selectedWithMouse ) {
546 // If nothing is selected or if something was selected with the mouse
547 // cancel any current requests and allow the form to be submitted
548 // (simply don't prevent default behavior).
549 cancel( context );
550 preventDefault = false;
551 } else if ( selected.is( '.suggestions-special' ) ) {
552 if ( typeof context.config.special.select === 'function' ) {
553 // Allow the callback to decide whether to prevent default or not
554 if ( context.config.special.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
555 preventDefault = false;
556 }
557 }
558 } else {
559 if ( typeof context.config.result.select === 'function' ) {
560 // Allow the callback to decide whether to prevent default or not
561 if ( context.config.result.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
562 preventDefault = false;
563 }
564 }
565 }
566 break;
567 default:
568 update( context, true );
569 break;
570 }
571 if ( preventDefault ) {
572 e.preventDefault();
573 e.stopPropagation();
574 }
575 }
576
577 // See file header for method documentation
578 $.fn.suggestions = function () {
579 // Multi-context fields
580 var args = arguments;
581
582 $( this ).each( function () {
583 var context, key;
584
585 /* Construction and Loading */
586
587 context = $( this ).data( 'suggestions-context' );
588 if ( context === undefined || context === null ) {
589 context = {
590 config: {
591 fetch: function () {},
592 cancel: function () {},
593 special: {},
594 result: {},
595 update: {},
596 $region: $( this ),
597 suggestions: [],
598 maxRows: 10,
599 delay: 120,
600 cache: false,
601 cacheMaxAge: 60000,
602 submitOnClick: false,
603 maxExpandFactor: 3,
604 expandFrom: 'auto',
605 highlightInput: false
606 }
607 };
608 }
609
610 /* API */
611
612 // Handle various calling styles
613 if ( args.length > 0 ) {
614 if ( typeof args[ 0 ] === 'object' ) {
615 // Apply set of properties
616 for ( key in args[ 0 ] ) {
617 configure( context, key, args[ 0 ][ key ] );
618 }
619 } else if ( typeof args[ 0 ] === 'string' ) {
620 if ( args.length > 1 ) {
621 // Set property values
622 configure( context, args[ 0 ], args[ 1 ] );
623 }
624 }
625 }
626
627 /* Initialization */
628
629 if ( context.data === undefined ) {
630 context.data = {
631 // ID of running timer
632 timerID: null,
633
634 // Text in textbox when suggestions were last fetched
635 prevText: null,
636
637 // Cache of fetched suggestions
638 cache: Object.create( null ),
639
640 // Number of results visible without scrolling
641 visibleResults: 0,
642
643 // Suggestion the last mousedown event occurred on
644 mouseDownOn: $( [] ),
645 $textbox: $( this ),
646 selectedWithMouse: false
647 };
648
649 context.data.$container = $( '<div>' )
650 .css( 'display', 'none' )
651 .addClass( 'suggestions' )
652 .append(
653 $( '<div>' ).addClass( 'suggestions-results' )
654 // Can't use click() because the container div is hidden when the
655 // textbox loses focus. Instead, listen for a mousedown followed
656 // by a mouseup on the same div.
657 .on( 'mousedown', function ( e ) {
658 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
659 } )
660 .on( 'mouseup', function ( e ) {
661 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
662 $other = context.data.mouseDownOn;
663
664 context.data.mouseDownOn = $( [] );
665 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
666 return;
667 }
668 highlight( context, $result, true );
669 if ( typeof context.config.result.select === 'function' ) {
670 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
671 }
672 // Don't interfere with special clicks (e.g. to open in new tab)
673 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
674 // This will hide the link we're just clicking on, which causes problems
675 // when done synchronously in at least Firefox 3.6 (T64858).
676 setTimeout( function () {
677 hide( context );
678 } );
679 }
680 // Always bring focus to the textbox, as that's probably where the user expects it
681 // if they were just typing.
682 context.data.$textbox.trigger( 'focus' );
683 } )
684 )
685 .append(
686 $( '<div>' ).addClass( 'suggestions-special' )
687 // Can't use click() because the container div is hidden when the
688 // textbox loses focus. Instead, listen for a mousedown followed
689 // by a mouseup on the same div.
690 .on( 'mousedown', function ( e ) {
691 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
692 } )
693 .on( 'mouseup', function ( e ) {
694 var $special = $( e.target ).closest( '.suggestions-special' ),
695 $other = context.data.mouseDownOn;
696
697 context.data.mouseDownOn = $( [] );
698 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
699 return;
700 }
701 if ( typeof context.config.special.select === 'function' ) {
702 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
703 }
704 // Don't interfere with special clicks (e.g. to open in new tab)
705 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
706 // This will hide the link we're just clicking on, which causes problems
707 // when done synchronously in at least Firefox 3.6 (T64858).
708 setTimeout( function () {
709 hide( context );
710 } );
711 }
712 // Always bring focus to the textbox, as that's probably where the user expects it
713 // if they were just typing.
714 context.data.$textbox.trigger( 'focus' );
715 } )
716 .on( 'mousemove', function ( e ) {
717 context.data.selectedWithMouse = true;
718 highlight(
719 context, $( e.target ).closest( '.suggestions-special' ), false
720 );
721 } )
722 )
723 .appendTo( $( 'body' ) );
724
725 $( this )
726 // Stop browser autocomplete from interfering
727 .attr( 'autocomplete', 'off' )
728 .on( 'keydown', function ( e ) {
729 // Store key pressed to handle later
730 context.data.keypressed = e.which;
731 context.data.keypressedCount = 0;
732 } )
733 .on( 'keypress', function ( e ) {
734 context.data.keypressedCount++;
735 keypress( e, context, context.data.keypressed );
736 } )
737 .on( 'keyup', function ( e ) {
738 // The keypress event is fired when a key is pressed down and that key normally
739 // produces a character value. We also want to handle some keys that don't
740 // produce a character value so we also attach to the keydown/keyup events.
741 // List of codes sourced from
742 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
743 var allowed = [
744 40, // up arrow
745 38, // down arrow
746 27, // escape
747 13, // enter
748 46, // delete
749 8 // backspace
750 ];
751 if ( context.data.keypressedCount === 0 &&
752 e.which === context.data.keypressed &&
753 allowed.indexOf( e.which ) !== -1
754 ) {
755 keypress( e, context, context.data.keypressed );
756 }
757 } )
758 .on( 'blur', function () {
759 // When losing focus because of a mousedown
760 // on a suggestion, don't hide the suggestions
761 if ( context.data.mouseDownOn.length > 0 ) {
762 return;
763 }
764 hide( context );
765 cancel( context );
766 } );
767 // Load suggestions if the value is changed because there are already
768 // typed characters before the JavaScript is loaded.
769 if ( this.value !== this.defaultValue ) {
770 update( context, false );
771 }
772 }
773
774 // Store the context for next time
775 $( this ).data( 'suggestions-context', context );
776 } );
777 return this;
778 };
779
780 /**
781 * @class jQuery
782 * @mixins jQuery.plugin.suggestions
783 */
784
785 }() );