Merge "Type hint against LinkTarget in WatchedItemStore"
[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 `$( document.documentElement ).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 // eslint-disable-next-line no-jquery/no-sizzle
174 !context.data.$container.is( ':visible' )
175 ) {
176 context.data.prevText = val;
177 // Try cache first
178 if ( context.config.cache && val in cache ) {
179 if ( mw.now() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
180 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
181 if ( typeof context.config.update.after === 'function' ) {
182 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
183 }
184 cacheHit = true;
185 } else {
186 // Cache expired
187 delete cache[ val ];
188 }
189 }
190 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
191 context.config.fetch.call(
192 context.data.$textbox,
193 val,
194 function ( suggestions, metadata ) {
195 suggestions = suggestions.slice( 0, context.config.maxRows );
196 context.data.$textbox.suggestions( 'suggestions', suggestions );
197 if ( typeof context.config.update.after === 'function' ) {
198 context.config.update.after.call( context.data.$textbox, metadata );
199 }
200 if ( context.config.cache ) {
201 cache[ val ] = {
202 suggestions: suggestions,
203 metadata: metadata,
204 timestamp: mw.now()
205 };
206 }
207 },
208 context.config.maxRows
209 );
210 }
211 }
212
213 // Always update special rendering
214 special( context );
215 }
216
217 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
218 cancel( context );
219
220 if ( delayed ) {
221 // To avoid many started/aborted requests while typing, we're gonna take a short
222 // break before trying to fetch data.
223 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
224 } else {
225 maybeFetch();
226 }
227 }
228
229 /**
230 * Highlight a result in the results table
231 *
232 * @param {Object} context
233 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
234 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
235 */
236 function highlight( context, result, updateTextbox ) {
237 var selected = context.data.$container.find( '.suggestions-result-current' );
238 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
239 if ( result === 'prev' ) {
240 if ( selected.hasClass( 'suggestions-special' ) ) {
241 result = context.data.$container.find( '.suggestions-result' ).last();
242 } else {
243 result = selected.prev();
244 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
245 // there is something in the DOM between selected element and the wrapper, bypass it
246 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
247 }
248
249 if ( selected.length === 0 ) {
250 // we are at the beginning, so lets jump to the last item
251 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
252 result = context.data.$container.find( '.suggestions-special' );
253 } else {
254 result = context.data.$container.find( '.suggestions-results .suggestions-result' ).last();
255 }
256 }
257 }
258 } else if ( result === 'next' ) {
259 if ( selected.length === 0 ) {
260 // No item selected, go to the first one
261 result = context.data.$container.find( '.suggestions-results .suggestions-result' ).first();
262 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
263 // No suggestion exists, go to the special one directly
264 result = context.data.$container.find( '.suggestions-special' );
265 }
266 } else {
267 result = selected.next();
268 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
269 // there is something in the DOM between selected element and the wrapper, bypass it
270 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
271 }
272
273 if ( selected.hasClass( 'suggestions-special' ) ) {
274 result = $( [] );
275 } else if (
276 result.length === 0 &&
277 context.data.$container.find( '.suggestions-special' ).html() !== ''
278 ) {
279 // We were at the last item, jump to the specials!
280 result = context.data.$container.find( '.suggestions-special' );
281 }
282 }
283 }
284 selected.removeClass( 'suggestions-result-current' );
285 result.addClass( 'suggestions-result-current' );
286 }
287 if ( updateTextbox ) {
288 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
289 restore( context );
290 } else {
291 context.data.$textbox.val( result.data( 'text' ) );
292 // .val() doesn't call any event handlers, so
293 // let the world know what happened
294 context.data.$textbox.trigger( 'change' );
295 }
296 context.data.$textbox.trigger( 'change' );
297 }
298 }
299
300 /**
301 * Sets the value of a property, and updates the widget accordingly
302 *
303 * @param {Object} context
304 * @param {string} property Name of property
305 * @param {Mixed} value Value to set property with
306 */
307 function configure( context, property, value ) {
308 var newCSS,
309 $result, $results, $spanForWidth, childrenWidth,
310 regionIsFixed, regionPosition,
311 i, expWidth, maxWidth, text;
312
313 // Validate creation using fallback values
314 switch ( property ) {
315 case 'fetch':
316 case 'cancel':
317 case 'special':
318 case 'result':
319 case 'update':
320 case '$region':
321 case 'expandFrom':
322 context.config[ property ] = value;
323 break;
324 case 'suggestions':
325 context.config[ property ] = value;
326 // Update suggestions
327 if ( context.data !== undefined ) {
328 if ( context.data.$textbox.val().length === 0 ) {
329 // Hide the div when no suggestion exist
330 hide( context );
331 } else {
332 // Rebuild the suggestions list
333 context.data.$container.show();
334 // Update the size and position of the list
335 regionIsFixed = ( function () {
336 var $el = context.config.$region;
337 do {
338 if ( $el.css( 'position' ) === 'fixed' ) {
339 return true;
340 }
341 $el = $( $el[ 0 ].offsetParent );
342 } while ( $el.length );
343 return false;
344 }() );
345 regionPosition = regionIsFixed ?
346 context.config.$region[ 0 ].getBoundingClientRect() :
347 context.config.$region.offset();
348 newCSS = {
349 position: regionIsFixed ? 'fixed' : 'absolute',
350 top: regionPosition.top + context.config.$region.outerHeight(),
351 bottom: 'auto',
352 width: context.config.$region.outerWidth(),
353 height: 'auto'
354 };
355
356 // Process expandFrom, after this it is set to left or right.
357 context.config.expandFrom = ( function ( expandFrom ) {
358 var regionWidth, docWidth, regionCenter, docCenter,
359 isRTL = $( document.documentElement ).css( 'direction' ) === 'rtl',
360 $region = context.config.$region;
361
362 // Backwards compatible
363 if ( context.config.positionFromLeft ) {
364 expandFrom = 'left';
365
366 // Catch invalid values, default to 'auto'
367 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
368 expandFrom = 'auto';
369 }
370
371 if ( expandFrom === 'auto' ) {
372 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
373 // If the markup explicitly contains a direction, use it.
374 expandFrom = $region.data( 'searchsuggest-expand-dir' );
375 } else {
376 regionWidth = $region.outerWidth();
377 docWidth = $( document ).width();
378 if ( regionWidth > ( 0.85 * docWidth ) ) {
379 // If the input size takes up more than 85% of the document horizontally
380 // expand the suggestions to the writing direction's native end.
381 expandFrom = 'start';
382 } else {
383 // Calculate the center points of the input and document
384 regionCenter = regionPosition.left + regionWidth / 2;
385 docCenter = docWidth / 2;
386 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
387 // If the input's center is within 10% of the document center
388 // use the writing direction's native end.
389 expandFrom = 'start';
390 } else {
391 // Otherwise expand the input from the closest side of the page,
392 // towards the side of the page with the most free open space
393 expandFrom = regionCenter > docCenter ? 'right' : 'left';
394 }
395 }
396 }
397 }
398
399 if ( expandFrom === 'start' ) {
400 expandFrom = isRTL ? 'right' : 'left';
401
402 } else if ( expandFrom === 'end' ) {
403 expandFrom = isRTL ? 'left' : 'right';
404 }
405
406 return expandFrom;
407
408 }( context.config.expandFrom ) );
409
410 if ( context.config.expandFrom === 'left' ) {
411 // Expand from left
412 newCSS.left = regionPosition.left;
413 newCSS.right = 'auto';
414 } else {
415 // Expand from right
416 newCSS.left = 'auto';
417 newCSS.right = document.documentElement.clientWidth -
418 ( regionPosition.left + context.config.$region.outerWidth() );
419 }
420
421 context.data.$container.css( newCSS );
422 $results = context.data.$container.children( '.suggestions-results' );
423 $results.empty();
424 expWidth = -1;
425 for ( i = 0; i < context.config.suggestions.length; i++ ) {
426 text = context.config.suggestions[ i ];
427 $result = $( '<div>' )
428 .addClass( 'suggestions-result' )
429 .attr( 'rel', i )
430 .data( 'text', context.config.suggestions[ i ] )
431 .on( 'mousemove', function () {
432 context.data.selectedWithMouse = true;
433 highlight(
434 context,
435 $( this ).closest( '.suggestions-results .suggestions-result' ),
436 false
437 );
438 } )
439 .appendTo( $results );
440 // Allow custom rendering
441 if ( typeof context.config.result.render === 'function' ) {
442 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
443 } else {
444 $result.text( text );
445 }
446
447 if ( context.config.highlightInput ) {
448 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
449 }
450
451 // Widen results box if needed (new width is only calculated here, applied later).
452
453 // The monstrosity below accomplishes two things:
454 // * Wraps the text contents in a DOM element, so that we can know its width. There is
455 // no way to directly access the width of a text node, and we can't use the parent
456 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
457 // it, which trims it to a smaller width.
458 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
459 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
460 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
461 // still report the "trimmed" width. This should not be done in regular CSS
462 // stylesheets as we don't want this rule to apply to other <span> elements, like
463 // the ones generated by jquery.highlightText.
464 $spanForWidth = $result.wrapInner( '<span>' ).children();
465 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
466 $spanForWidth.contents().unwrap();
467
468 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
469 // factor in any padding, margin, or border space on the parent
470 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
471 }
472 }
473
474 // Apply new width for results box, if any
475 if ( expWidth > context.data.$container.width() ) {
476 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
477 context.data.$container.width( Math.min( expWidth, maxWidth ) );
478 }
479 }
480 }
481 break;
482 case 'maxRows':
483 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
484 break;
485 case 'delay':
486 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
487 break;
488 case 'cacheMaxAge':
489 context.config[ property ] = Math.max( 1, value );
490 break;
491 case 'maxExpandFactor':
492 context.config[ property ] = Math.max( 1, value );
493 break;
494 case 'cache':
495 case 'submitOnClick':
496 case 'positionFromLeft':
497 case 'highlightInput':
498 context.config[ property ] = !!value;
499 break;
500 }
501 }
502
503 /**
504 * Respond to keypress event
505 *
506 * @param {jQuery.Event} e
507 * @param {Object} context
508 * @param {number} key Code of key pressed
509 */
510 function keypress( e, context, key ) {
511 var selected,
512 // eslint-disable-next-line no-jquery/no-sizzle
513 wasVisible = context.data.$container.is( ':visible' ),
514 preventDefault = false;
515
516 switch ( key ) {
517 // Arrow down
518 case 40:
519 if ( wasVisible ) {
520 highlight( context, 'next', true );
521 context.data.selectedWithMouse = false;
522 } else {
523 update( context, false );
524 }
525 preventDefault = true;
526 break;
527 // Arrow up
528 case 38:
529 if ( wasVisible ) {
530 highlight( context, 'prev', true );
531 context.data.selectedWithMouse = false;
532 }
533 preventDefault = wasVisible;
534 break;
535 // Escape
536 case 27:
537 hide( context );
538 restore( context );
539 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 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 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 update( context, true );
572 break;
573 }
574 if ( preventDefault ) {
575 e.preventDefault();
576 e.stopPropagation();
577 }
578 }
579
580 // See file header for method documentation
581 $.fn.suggestions = function () {
582 // Multi-context fields
583 var args = arguments;
584
585 $( this ).each( function () {
586 var context, key;
587
588 /* Construction and Loading */
589
590 context = $( this ).data( 'suggestions-context' );
591 if ( context === undefined || context === null ) {
592 context = {
593 config: {
594 fetch: function () {},
595 cancel: function () {},
596 special: {},
597 result: {},
598 update: {},
599 $region: $( this ),
600 suggestions: [],
601 maxRows: 10,
602 delay: 120,
603 cache: false,
604 cacheMaxAge: 60000,
605 submitOnClick: false,
606 maxExpandFactor: 3,
607 expandFrom: 'auto',
608 highlightInput: false
609 }
610 };
611 }
612
613 /* API */
614
615 // Handle various calling styles
616 if ( args.length > 0 ) {
617 if ( typeof args[ 0 ] === 'object' ) {
618 // Apply set of properties
619 for ( key in args[ 0 ] ) {
620 configure( context, key, args[ 0 ][ key ] );
621 }
622 } else if ( typeof args[ 0 ] === 'string' ) {
623 if ( args.length > 1 ) {
624 // Set property values
625 configure( context, args[ 0 ], args[ 1 ] );
626 }
627 }
628 }
629
630 /* Initialization */
631
632 if ( context.data === undefined ) {
633 context.data = {
634 // ID of running timer
635 timerID: null,
636
637 // Text in textbox when suggestions were last fetched
638 prevText: null,
639
640 // Cache of fetched suggestions
641 cache: Object.create( null ),
642
643 // Number of results visible without scrolling
644 visibleResults: 0,
645
646 // Suggestion the last mousedown event occurred on
647 mouseDownOn: $( [] ),
648 $textbox: $( this ),
649 selectedWithMouse: false
650 };
651
652 context.data.$container = $( '<div>' )
653 .css( 'display', 'none' )
654 .addClass( 'suggestions' )
655 .append(
656 $( '<div>' ).addClass( 'suggestions-results' )
657 // Can't use click() because the container div is hidden when the
658 // textbox loses focus. Instead, listen for a mousedown followed
659 // by a mouseup on the same div.
660 .on( 'mousedown', function ( e ) {
661 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
662 } )
663 .on( 'mouseup', function ( e ) {
664 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
665 $other = context.data.mouseDownOn;
666
667 context.data.mouseDownOn = $( [] );
668 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
669 return;
670 }
671 highlight( context, $result, true );
672 if ( typeof context.config.result.select === 'function' ) {
673 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
674 }
675 // Don't interfere with special clicks (e.g. to open in new tab)
676 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
677 // This will hide the link we're just clicking on, which causes problems
678 // when done synchronously in at least Firefox 3.6 (T64858).
679 setTimeout( function () {
680 hide( context );
681 } );
682 }
683 // Always bring focus to the textbox, as that's probably where the user expects it
684 // if they were just typing.
685 context.data.$textbox.trigger( 'focus' );
686 } )
687 )
688 .append(
689 $( '<div>' ).addClass( 'suggestions-special' )
690 // Can't use click() because the container div is hidden when the
691 // textbox loses focus. Instead, listen for a mousedown followed
692 // by a mouseup on the same div.
693 .on( 'mousedown', function ( e ) {
694 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
695 } )
696 .on( 'mouseup', function ( e ) {
697 var $special = $( e.target ).closest( '.suggestions-special' ),
698 $other = context.data.mouseDownOn;
699
700 context.data.mouseDownOn = $( [] );
701 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
702 return;
703 }
704 if ( typeof context.config.special.select === 'function' ) {
705 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
706 }
707 // Don't interfere with special clicks (e.g. to open in new tab)
708 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
709 // This will hide the link we're just clicking on, which causes problems
710 // when done synchronously in at least Firefox 3.6 (T64858).
711 setTimeout( function () {
712 hide( context );
713 } );
714 }
715 // Always bring focus to the textbox, as that's probably where the user expects it
716 // if they were just typing.
717 context.data.$textbox.trigger( 'focus' );
718 } )
719 .on( 'mousemove', function ( e ) {
720 context.data.selectedWithMouse = true;
721 highlight(
722 context, $( e.target ).closest( '.suggestions-special' ), false
723 );
724 } )
725 )
726 .appendTo( document.body );
727
728 $( this )
729 // Stop browser autocomplete from interfering
730 .attr( 'autocomplete', 'off' )
731 .on( 'keydown', function ( e ) {
732 // Store key pressed to handle later
733 context.data.keypressed = e.which;
734 context.data.keypressedCount = 0;
735 } )
736 .on( 'keypress', function ( e ) {
737 context.data.keypressedCount++;
738 keypress( e, context, context.data.keypressed );
739 } )
740 .on( 'keyup', function ( e ) {
741 // The keypress event is fired when a key is pressed down and that key normally
742 // produces a character value. We also want to handle some keys that don't
743 // produce a character value so we also attach to the keydown/keyup events.
744 // List of codes sourced from
745 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
746 var allowed = [
747 40, // up arrow
748 38, // down arrow
749 27, // escape
750 13, // enter
751 46, // delete
752 8 // backspace
753 ];
754 if ( context.data.keypressedCount === 0 &&
755 e.which === context.data.keypressed &&
756 allowed.indexOf( e.which ) !== -1
757 ) {
758 keypress( e, context, context.data.keypressed );
759 }
760 } )
761 .on( 'blur', function () {
762 // When losing focus because of a mousedown
763 // on a suggestion, don't hide the suggestions
764 if ( context.data.mouseDownOn.length > 0 ) {
765 return;
766 }
767 hide( context );
768 cancel( context );
769 } );
770 // Load suggestions if the value is changed because there are already
771 // typed characters before the JavaScript is loaded.
772 if ( $( this ).is( ':focus' ) && this.value !== this.defaultValue ) {
773 update( context, false );
774 }
775 }
776
777 // Store the context for next time
778 $( this ).data( 'suggestions-context', context );
779 } );
780 return this;
781 };
782
783 /**
784 * @class jQuery
785 * @mixins jQuery.plugin.suggestions
786 */
787
788 }() );