jquery.suggestions: Remove public object $.suggestions
[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 = $( 'body' ).width() - ( 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 wasVisible = context.data.$container.is( ':visible' ),
513 preventDefault = false;
514
515 switch ( key ) {
516 // Arrow down
517 case 40:
518 if ( wasVisible ) {
519 highlight( context, 'next', true );
520 context.data.selectedWithMouse = false;
521 } else {
522 update( context, false );
523 }
524 preventDefault = true;
525 break;
526 // Arrow up
527 case 38:
528 if ( wasVisible ) {
529 highlight( context, 'prev', true );
530 context.data.selectedWithMouse = false;
531 }
532 preventDefault = wasVisible;
533 break;
534 // Escape
535 case 27:
536 hide( context );
537 restore( context );
538 cancel( context );
539 context.data.$textbox.trigger( 'change' );
540 preventDefault = wasVisible;
541 break;
542 // Enter
543 case 13:
544 preventDefault = wasVisible;
545 selected = context.data.$container.find( '.suggestions-result-current' );
546 hide( context );
547 if ( selected.length === 0 || context.data.selectedWithMouse ) {
548 // If nothing is selected or if something was selected with the mouse
549 // cancel any current requests and allow the form to be submitted
550 // (simply don't prevent default behavior).
551 cancel( context );
552 preventDefault = false;
553 } else if ( selected.is( '.suggestions-special' ) ) {
554 if ( typeof context.config.special.select === 'function' ) {
555 // Allow the callback to decide whether to prevent default or not
556 if ( context.config.special.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
557 preventDefault = false;
558 }
559 }
560 } else {
561 if ( typeof context.config.result.select === 'function' ) {
562 // Allow the callback to decide whether to prevent default or not
563 if ( context.config.result.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
564 preventDefault = false;
565 }
566 }
567 }
568 break;
569 default:
570 update( context, true );
571 break;
572 }
573 if ( preventDefault ) {
574 e.preventDefault();
575 e.stopPropagation();
576 }
577 }
578
579 // See file header for method documentation
580 $.fn.suggestions = function () {
581 // Multi-context fields
582 var args = arguments;
583
584 $( this ).each( function () {
585 var context, key;
586
587 /* Construction and Loading */
588
589 context = $( this ).data( 'suggestions-context' );
590 if ( context === undefined || context === null ) {
591 context = {
592 config: {
593 fetch: function () {},
594 cancel: function () {},
595 special: {},
596 result: {},
597 update: {},
598 $region: $( this ),
599 suggestions: [],
600 maxRows: 10,
601 delay: 120,
602 cache: false,
603 cacheMaxAge: 60000,
604 submitOnClick: false,
605 maxExpandFactor: 3,
606 expandFrom: 'auto',
607 highlightInput: false
608 }
609 };
610 }
611
612 /* API */
613
614 // Handle various calling styles
615 if ( args.length > 0 ) {
616 if ( typeof args[ 0 ] === 'object' ) {
617 // Apply set of properties
618 for ( key in args[ 0 ] ) {
619 configure( context, key, args[ 0 ][ key ] );
620 }
621 } else if ( typeof args[ 0 ] === 'string' ) {
622 if ( args.length > 1 ) {
623 // Set property values
624 configure( context, args[ 0 ], args[ 1 ] );
625 }
626 }
627 }
628
629 /* Initialization */
630
631 if ( context.data === undefined ) {
632 context.data = {
633 // ID of running timer
634 timerID: null,
635
636 // Text in textbox when suggestions were last fetched
637 prevText: null,
638
639 // Cache of fetched suggestions
640 cache: {},
641
642 // Number of results visible without scrolling
643 visibleResults: 0,
644
645 // Suggestion the last mousedown event occurred on
646 mouseDownOn: $( [] ),
647 $textbox: $( this ),
648 selectedWithMouse: false
649 };
650
651 context.data.$container = $( '<div>' )
652 .css( 'display', 'none' )
653 .addClass( 'suggestions' )
654 .append(
655 $( '<div>' ).addClass( 'suggestions-results' )
656 // Can't use click() because the container div is hidden when the
657 // textbox loses focus. Instead, listen for a mousedown followed
658 // by a mouseup on the same div.
659 .on( 'mousedown', function ( e ) {
660 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
661 } )
662 .on( 'mouseup', function ( e ) {
663 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
664 $other = context.data.mouseDownOn;
665
666 context.data.mouseDownOn = $( [] );
667 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
668 return;
669 }
670 highlight( context, $result, true );
671 if ( typeof context.config.result.select === 'function' ) {
672 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
673 }
674 // Don't interfere with special clicks (e.g. to open in new tab)
675 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
676 // This will hide the link we're just clicking on, which causes problems
677 // when done synchronously in at least Firefox 3.6 (T64858).
678 setTimeout( function () {
679 hide( context );
680 } );
681 }
682 // Always bring focus to the textbox, as that's probably where the user expects it
683 // if they were just typing.
684 context.data.$textbox.trigger( 'focus' );
685 } )
686 )
687 .append(
688 $( '<div>' ).addClass( 'suggestions-special' )
689 // Can't use click() because the container div is hidden when the
690 // textbox loses focus. Instead, listen for a mousedown followed
691 // by a mouseup on the same div.
692 .on( 'mousedown', function ( e ) {
693 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
694 } )
695 .on( 'mouseup', function ( e ) {
696 var $special = $( e.target ).closest( '.suggestions-special' ),
697 $other = context.data.mouseDownOn;
698
699 context.data.mouseDownOn = $( [] );
700 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
701 return;
702 }
703 if ( typeof context.config.special.select === 'function' ) {
704 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
705 }
706 // Don't interfere with special clicks (e.g. to open in new tab)
707 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
708 // This will hide the link we're just clicking on, which causes problems
709 // when done synchronously in at least Firefox 3.6 (T64858).
710 setTimeout( function () {
711 hide( context );
712 } );
713 }
714 // Always bring focus to the textbox, as that's probably where the user expects it
715 // if they were just typing.
716 context.data.$textbox.trigger( 'focus' );
717 } )
718 .on( 'mousemove', function ( e ) {
719 context.data.selectedWithMouse = true;
720 highlight(
721 context, $( e.target ).closest( '.suggestions-special' ), false
722 );
723 } )
724 )
725 .appendTo( $( 'body' ) );
726
727 $( this )
728 // Stop browser autocomplete from interfering
729 .attr( 'autocomplete', 'off' )
730 .on( 'keydown', function ( e ) {
731 // Store key pressed to handle later
732 context.data.keypressed = e.which;
733 context.data.keypressedCount = 0;
734 } )
735 .on( 'keypress', function ( e ) {
736 context.data.keypressedCount++;
737 keypress( e, context, context.data.keypressed );
738 } )
739 .on( 'keyup', function ( e ) {
740 // The keypress event is fired when a key is pressed down and that key normally
741 // produces a character value. We also want to handle some keys that don't
742 // produce a character value so we also attach to the keydown/keyup events.
743 // List of codes sourced from
744 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
745 var allowed = [
746 40, // up arrow
747 38, // down arrow
748 27, // escape
749 13, // enter
750 46, // delete
751 8 // backspace
752 ];
753 if ( context.data.keypressedCount === 0 &&
754 e.which === context.data.keypressed &&
755 allowed.indexOf( e.which ) !== -1
756 ) {
757 keypress( e, context, context.data.keypressed );
758 }
759 } )
760 .on( 'blur', function () {
761 // When losing focus because of a mousedown
762 // on a suggestion, don't hide the suggestions
763 if ( context.data.mouseDownOn.length > 0 ) {
764 return;
765 }
766 hide( context );
767 cancel( context );
768 } );
769 // Load suggestions if the value is changed because there are already
770 // typed characters before the JavaScript is loaded.
771 if ( this.value !== this.defaultValue ) {
772 update( context, false );
773 }
774 }
775
776 // Store the context for next time
777 $( this ).data( 'suggestions-context', context );
778 } );
779 return this;
780 };
781
782 /**
783 * @class jQuery
784 * @mixins jQuery.plugin.suggestions
785 */
786
787 }() );