jquery.suggestions: Use document.documentElement.clientWidth
[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 var hasOwn = Object.hasOwnProperty;
94
95 /**
96 * Cancel any delayed maybeFetch() call and callback the context so
97 * they can cancel any async fetching if they use AJAX or something.
98 *
99 * @param {Object} context
100 */
101 function cancel( context ) {
102 if ( context.data.timerID !== null ) {
103 clearTimeout( context.data.timerID );
104 }
105 if ( typeof context.config.cancel === 'function' ) {
106 context.config.cancel.call( context.data.$textbox );
107 }
108 }
109
110 /**
111 * Hide the element with suggestions and clean up some state.
112 *
113 * @param {Object} context
114 */
115 function hide( context ) {
116 // Remove any highlights, including on "special" items
117 context.data.$container.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
118 // Hide the container
119 context.data.$container.hide();
120 }
121
122 /**
123 * Restore the text the user originally typed in the textbox, before it
124 * was overwritten by highlight(). This restores the value the currently
125 * displayed suggestions are based on, rather than the value just before
126 * highlight() overwrote it; the former is arguably slightly more sensible.
127 *
128 * @param {Object} context
129 */
130 function restore( context ) {
131 context.data.$textbox.val( context.data.prevText );
132 }
133
134 /**
135 * @param {Object} context
136 */
137 function special( context ) {
138 // Allow custom rendering - but otherwise don't do any rendering
139 if ( typeof context.config.special.render === 'function' ) {
140 // Wait for the browser to update the value
141 setTimeout( function () {
142 // Render special
143 var $special = context.data.$container.find( '.suggestions-special' );
144 context.config.special.render.call( $special, context.data.$textbox.val(), context );
145 }, 1 );
146 }
147 }
148
149 /**
150 * Ask the user-specified callback for new suggestions. Any previous delayed
151 * call to this function still pending will be canceled. If the value in the
152 * textbox is empty or hasn't changed since the last time suggestions were fetched,
153 * this function does nothing.
154 *
155 * @param {Object} context
156 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
157 */
158 function update( context, delayed ) {
159 function maybeFetch() {
160 var val = context.data.$textbox.val(),
161 cache = context.data.cache,
162 cacheHit;
163
164 if ( typeof context.config.update.before === 'function' ) {
165 context.config.update.before.call( context.data.$textbox );
166 }
167
168 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
169 // if the textbox is empty then clear the result div, but leave other settings intouched
170 if ( val.length === 0 ) {
171 hide( context );
172 context.data.prevText = '';
173 } else if (
174 val !== context.data.prevText ||
175 !context.data.$container.is( ':visible' )
176 ) {
177 context.data.prevText = val;
178 // Try cache first
179 if ( context.config.cache && hasOwn.call( cache, val ) ) {
180 if ( mw.now() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
181 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
182 if ( typeof context.config.update.after === 'function' ) {
183 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
184 }
185 cacheHit = true;
186 } else {
187 // Cache expired
188 delete cache[ val ];
189 }
190 }
191 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
192 context.config.fetch.call(
193 context.data.$textbox,
194 val,
195 function ( suggestions, metadata ) {
196 suggestions = suggestions.slice( 0, context.config.maxRows );
197 context.data.$textbox.suggestions( 'suggestions', suggestions );
198 if ( typeof context.config.update.after === 'function' ) {
199 context.config.update.after.call( context.data.$textbox, metadata );
200 }
201 if ( context.config.cache ) {
202 cache[ val ] = {
203 suggestions: suggestions,
204 metadata: metadata,
205 timestamp: mw.now()
206 };
207 }
208 },
209 context.config.maxRows
210 );
211 }
212 }
213
214 // Always update special rendering
215 special( context );
216 }
217
218 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
219 cancel( context );
220
221 if ( delayed ) {
222 // To avoid many started/aborted requests while typing, we're gonna take a short
223 // break before trying to fetch data.
224 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
225 } else {
226 maybeFetch();
227 }
228 }
229
230 /**
231 * Highlight a result in the results table
232 *
233 * @param {Object} context
234 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
235 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
236 */
237 function highlight( context, result, updateTextbox ) {
238 var selected = context.data.$container.find( '.suggestions-result-current' );
239 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
240 if ( result === 'prev' ) {
241 if ( selected.hasClass( 'suggestions-special' ) ) {
242 result = context.data.$container.find( '.suggestions-result:last' );
243 } else {
244 result = selected.prev();
245 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
246 // there is something in the DOM between selected element and the wrapper, bypass it
247 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
248 }
249
250 if ( selected.length === 0 ) {
251 // we are at the beginning, so lets jump to the last item
252 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
253 result = context.data.$container.find( '.suggestions-special' );
254 } else {
255 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
256 }
257 }
258 }
259 } else if ( result === 'next' ) {
260 if ( selected.length === 0 ) {
261 // No item selected, go to the first one
262 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
263 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
264 // No suggestion exists, go to the special one directly
265 result = context.data.$container.find( '.suggestions-special' );
266 }
267 } else {
268 result = selected.next();
269 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
270 // there is something in the DOM between selected element and the wrapper, bypass it
271 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
272 }
273
274 if ( selected.hasClass( 'suggestions-special' ) ) {
275 result = $( [] );
276 } else if (
277 result.length === 0 &&
278 context.data.$container.find( '.suggestions-special' ).html() !== ''
279 ) {
280 // We were at the last item, jump to the specials!
281 result = context.data.$container.find( '.suggestions-special' );
282 }
283 }
284 }
285 selected.removeClass( 'suggestions-result-current' );
286 result.addClass( 'suggestions-result-current' );
287 }
288 if ( updateTextbox ) {
289 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
290 restore( context );
291 } else {
292 context.data.$textbox.val( result.data( 'text' ) );
293 // .val() doesn't call any event handlers, so
294 // let the world know what happened
295 context.data.$textbox.trigger( 'change' );
296 }
297 context.data.$textbox.trigger( 'change' );
298 }
299 }
300
301 /**
302 * Sets the value of a property, and updates the widget accordingly
303 *
304 * @param {Object} context
305 * @param {string} property Name of property
306 * @param {Mixed} value Value to set property with
307 */
308 function configure( context, property, value ) {
309 var newCSS,
310 $result, $results, $spanForWidth, childrenWidth,
311 regionIsFixed, regionPosition,
312 i, expWidth, maxWidth, text;
313
314 // Validate creation using fallback values
315 switch ( property ) {
316 case 'fetch':
317 case 'cancel':
318 case 'special':
319 case 'result':
320 case 'update':
321 case '$region':
322 case 'expandFrom':
323 context.config[ property ] = value;
324 break;
325 case 'suggestions':
326 context.config[ property ] = value;
327 // Update suggestions
328 if ( context.data !== undefined ) {
329 if ( context.data.$textbox.val().length === 0 ) {
330 // Hide the div when no suggestion exist
331 hide( context );
332 } else {
333 // Rebuild the suggestions list
334 context.data.$container.show();
335 // Update the size and position of the list
336 regionIsFixed = ( function () {
337 var $el = context.config.$region;
338 do {
339 if ( $el.css( 'position' ) === 'fixed' ) {
340 return true;
341 }
342 $el = $( $el[ 0 ].offsetParent );
343 } while ( $el.length );
344 return false;
345 }() );
346 regionPosition = regionIsFixed ?
347 context.config.$region[ 0 ].getBoundingClientRect() :
348 context.config.$region.offset();
349 newCSS = {
350 position: regionIsFixed ? 'fixed' : 'absolute',
351 top: regionPosition.top + context.config.$region.outerHeight(),
352 bottom: 'auto',
353 width: context.config.$region.outerWidth(),
354 height: 'auto'
355 };
356
357 // Process expandFrom, after this it is set to left or right.
358 context.config.expandFrom = ( function ( expandFrom ) {
359 var regionWidth, docWidth, regionCenter, docCenter,
360 docDir = $( document.documentElement ).css( 'direction' ),
361 $region = context.config.$region;
362
363 // Backwards compatible
364 if ( context.config.positionFromLeft ) {
365 expandFrom = 'left';
366
367 // Catch invalid values, default to 'auto'
368 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
369 expandFrom = 'auto';
370 }
371
372 if ( expandFrom === 'auto' ) {
373 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
374 // If the markup explicitly contains a direction, use it.
375 expandFrom = $region.data( 'searchsuggest-expand-dir' );
376 } else {
377 regionWidth = $region.outerWidth();
378 docWidth = $( document ).width();
379 if ( regionWidth > ( 0.85 * docWidth ) ) {
380 // If the input size takes up more than 85% of the document horizontally
381 // expand the suggestions to the writing direction's native end.
382 expandFrom = 'start';
383 } else {
384 // Calculate the center points of the input and document
385 regionCenter = regionPosition.left + regionWidth / 2;
386 docCenter = docWidth / 2;
387 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
388 // If the input's center is within 10% of the document center
389 // use the writing direction's native end.
390 expandFrom = 'start';
391 } else {
392 // Otherwise expand the input from the closest side of the page,
393 // towards the side of the page with the most free open space
394 expandFrom = regionCenter > docCenter ? 'right' : 'left';
395 }
396 }
397 }
398 }
399
400 if ( expandFrom === 'start' ) {
401 expandFrom = docDir === 'rtl' ? 'right' : 'left';
402
403 } else if ( expandFrom === 'end' ) {
404 expandFrom = docDir === 'rtl' ? 'left' : 'right';
405 }
406
407 return expandFrom;
408
409 }( context.config.expandFrom ) );
410
411 if ( context.config.expandFrom === 'left' ) {
412 // Expand from left
413 newCSS.left = regionPosition.left;
414 newCSS.right = 'auto';
415 } else {
416 // Expand from right
417 newCSS.left = 'auto';
418 newCSS.right = document.documentElement.clientWidth -
419 ( regionPosition.left + context.config.$region.outerWidth() );
420 }
421
422 context.data.$container.css( newCSS );
423 $results = context.data.$container.children( '.suggestions-results' );
424 $results.empty();
425 expWidth = -1;
426 for ( i = 0; i < context.config.suggestions.length; i++ ) {
427 text = context.config.suggestions[ i ];
428 $result = $( '<div>' )
429 .addClass( 'suggestions-result' )
430 .attr( 'rel', i )
431 .data( 'text', context.config.suggestions[ i ] )
432 .on( 'mousemove', function () {
433 context.data.selectedWithMouse = true;
434 highlight(
435 context,
436 $( this ).closest( '.suggestions-results .suggestions-result' ),
437 false
438 );
439 } )
440 .appendTo( $results );
441 // Allow custom rendering
442 if ( typeof context.config.result.render === 'function' ) {
443 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
444 } else {
445 $result.text( text );
446 }
447
448 if ( context.config.highlightInput ) {
449 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
450 }
451
452 // Widen results box if needed (new width is only calculated here, applied later).
453
454 // The monstrosity below accomplishes two things:
455 // * Wraps the text contents in a DOM element, so that we can know its width. There is
456 // no way to directly access the width of a text node, and we can't use the parent
457 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
458 // it, which trims it to a smaller width.
459 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
460 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
461 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
462 // still report the "trimmed" width. This should not be done in regular CSS
463 // stylesheets as we don't want this rule to apply to other <span> elements, like
464 // the ones generated by jquery.highlightText.
465 $spanForWidth = $result.wrapInner( '<span>' ).children();
466 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
467 $spanForWidth.contents().unwrap();
468
469 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
470 // factor in any padding, margin, or border space on the parent
471 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
472 }
473 }
474
475 // Apply new width for results box, if any
476 if ( expWidth > context.data.$container.width() ) {
477 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
478 context.data.$container.width( Math.min( expWidth, maxWidth ) );
479 }
480 }
481 }
482 break;
483 case 'maxRows':
484 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
485 break;
486 case 'delay':
487 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
488 break;
489 case 'cacheMaxAge':
490 context.config[ property ] = Math.max( 1, value );
491 break;
492 case 'maxExpandFactor':
493 context.config[ property ] = Math.max( 1, value );
494 break;
495 case 'cache':
496 case 'submitOnClick':
497 case 'positionFromLeft':
498 case 'highlightInput':
499 context.config[ property ] = !!value;
500 break;
501 }
502 }
503
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 function keypress( e, context, key ) {
512 var selected,
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: {},
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.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 }() );