Merge "objectcache: add object segmentation support to BagOStuff"
[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 !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 isRTL = $( document.documentElement ).css( 'direction' ) === 'rtl',
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 = isRTL ? 'right' : 'left';
400
401 } else if ( expandFrom === 'end' ) {
402 expandFrom = isRTL ? '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 = document.documentElement.clientWidth -
417 ( regionPosition.left + context.config.$region.outerWidth() );
418 }
419
420 context.data.$container.css( newCSS );
421 $results = context.data.$container.children( '.suggestions-results' );
422 $results.empty();
423 expWidth = -1;
424 for ( i = 0; i < context.config.suggestions.length; i++ ) {
425 text = context.config.suggestions[ i ];
426 $result = $( '<div>' )
427 .addClass( 'suggestions-result' )
428 .attr( 'rel', i )
429 .data( 'text', context.config.suggestions[ i ] )
430 .on( 'mousemove', function () {
431 context.data.selectedWithMouse = true;
432 highlight(
433 context,
434 $( this ).closest( '.suggestions-results .suggestions-result' ),
435 false
436 );
437 } )
438 .appendTo( $results );
439 // Allow custom rendering
440 if ( typeof context.config.result.render === 'function' ) {
441 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
442 } else {
443 $result.text( text );
444 }
445
446 if ( context.config.highlightInput ) {
447 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
448 }
449
450 // Widen results box if needed (new width is only calculated here, applied later).
451
452 // The monstrosity below accomplishes two things:
453 // * Wraps the text contents in a DOM element, so that we can know its width. There is
454 // no way to directly access the width of a text node, and we can't use the parent
455 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
456 // it, which trims it to a smaller width.
457 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
458 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
459 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
460 // still report the "trimmed" width. This should not be done in regular CSS
461 // stylesheets as we don't want this rule to apply to other <span> elements, like
462 // the ones generated by jquery.highlightText.
463 $spanForWidth = $result.wrapInner( '<span>' ).children();
464 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
465 $spanForWidth.contents().unwrap();
466
467 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
468 // factor in any padding, margin, or border space on the parent
469 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
470 }
471 }
472
473 // Apply new width for results box, if any
474 if ( expWidth > context.data.$container.width() ) {
475 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
476 context.data.$container.width( Math.min( expWidth, maxWidth ) );
477 }
478 }
479 }
480 break;
481 case 'maxRows':
482 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
483 break;
484 case 'delay':
485 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
486 break;
487 case 'cacheMaxAge':
488 context.config[ property ] = Math.max( 1, value );
489 break;
490 case 'maxExpandFactor':
491 context.config[ property ] = Math.max( 1, value );
492 break;
493 case 'cache':
494 case 'submitOnClick':
495 case 'positionFromLeft':
496 case 'highlightInput':
497 context.config[ property ] = !!value;
498 break;
499 }
500 }
501
502 /**
503 * Respond to keypress event
504 *
505 * @param {jQuery.Event} e
506 * @param {Object} context
507 * @param {number} key Code of key pressed
508 */
509 function keypress( e, context, key ) {
510 var selected,
511 wasVisible = context.data.$container.is( ':visible' ),
512 preventDefault = false;
513
514 switch ( key ) {
515 // Arrow down
516 case 40:
517 if ( wasVisible ) {
518 highlight( context, 'next', true );
519 context.data.selectedWithMouse = false;
520 } else {
521 update( context, false );
522 }
523 preventDefault = true;
524 break;
525 // Arrow up
526 case 38:
527 if ( wasVisible ) {
528 highlight( context, 'prev', true );
529 context.data.selectedWithMouse = false;
530 }
531 preventDefault = wasVisible;
532 break;
533 // Escape
534 case 27:
535 hide( context );
536 restore( context );
537 cancel( context );
538 context.data.$textbox.trigger( 'change' );
539 preventDefault = wasVisible;
540 break;
541 // Enter
542 case 13:
543 preventDefault = wasVisible;
544 selected = context.data.$container.find( '.suggestions-result-current' );
545 hide( context );
546 if ( selected.length === 0 || context.data.selectedWithMouse ) {
547 // If nothing is selected or if something was selected with the mouse
548 // cancel any current requests and allow the form to be submitted
549 // (simply don't prevent default behavior).
550 cancel( context );
551 preventDefault = false;
552 } else if ( selected.is( '.suggestions-special' ) ) {
553 if ( typeof context.config.special.select === 'function' ) {
554 // Allow the callback to decide whether to prevent default or not
555 if ( context.config.special.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
556 preventDefault = false;
557 }
558 }
559 } else {
560 if ( typeof context.config.result.select === 'function' ) {
561 // Allow the callback to decide whether to prevent default or not
562 if ( context.config.result.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
563 preventDefault = false;
564 }
565 }
566 }
567 break;
568 default:
569 update( context, true );
570 break;
571 }
572 if ( preventDefault ) {
573 e.preventDefault();
574 e.stopPropagation();
575 }
576 }
577
578 // See file header for method documentation
579 $.fn.suggestions = function () {
580 // Multi-context fields
581 var args = arguments;
582
583 $( this ).each( function () {
584 var context, key;
585
586 /* Construction and Loading */
587
588 context = $( this ).data( 'suggestions-context' );
589 if ( context === undefined || context === null ) {
590 context = {
591 config: {
592 fetch: function () {},
593 cancel: function () {},
594 special: {},
595 result: {},
596 update: {},
597 $region: $( this ),
598 suggestions: [],
599 maxRows: 10,
600 delay: 120,
601 cache: false,
602 cacheMaxAge: 60000,
603 submitOnClick: false,
604 maxExpandFactor: 3,
605 expandFrom: 'auto',
606 highlightInput: false
607 }
608 };
609 }
610
611 /* API */
612
613 // Handle various calling styles
614 if ( args.length > 0 ) {
615 if ( typeof args[ 0 ] === 'object' ) {
616 // Apply set of properties
617 for ( key in args[ 0 ] ) {
618 configure( context, key, args[ 0 ][ key ] );
619 }
620 } else if ( typeof args[ 0 ] === 'string' ) {
621 if ( args.length > 1 ) {
622 // Set property values
623 configure( context, args[ 0 ], args[ 1 ] );
624 }
625 }
626 }
627
628 /* Initialization */
629
630 if ( context.data === undefined ) {
631 context.data = {
632 // ID of running timer
633 timerID: null,
634
635 // Text in textbox when suggestions were last fetched
636 prevText: null,
637
638 // Cache of fetched suggestions
639 cache: Object.create( null ),
640
641 // Number of results visible without scrolling
642 visibleResults: 0,
643
644 // Suggestion the last mousedown event occurred on
645 mouseDownOn: $( [] ),
646 $textbox: $( this ),
647 selectedWithMouse: false
648 };
649
650 context.data.$container = $( '<div>' )
651 .css( 'display', 'none' )
652 .addClass( 'suggestions' )
653 .append(
654 $( '<div>' ).addClass( 'suggestions-results' )
655 // Can't use click() because the container div is hidden when the
656 // textbox loses focus. Instead, listen for a mousedown followed
657 // by a mouseup on the same div.
658 .on( 'mousedown', function ( e ) {
659 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
660 } )
661 .on( 'mouseup', function ( e ) {
662 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
663 $other = context.data.mouseDownOn;
664
665 context.data.mouseDownOn = $( [] );
666 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
667 return;
668 }
669 highlight( context, $result, true );
670 if ( typeof context.config.result.select === 'function' ) {
671 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
672 }
673 // Don't interfere with special clicks (e.g. to open in new tab)
674 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
675 // This will hide the link we're just clicking on, which causes problems
676 // when done synchronously in at least Firefox 3.6 (T64858).
677 setTimeout( function () {
678 hide( context );
679 } );
680 }
681 // Always bring focus to the textbox, as that's probably where the user expects it
682 // if they were just typing.
683 context.data.$textbox.trigger( 'focus' );
684 } )
685 )
686 .append(
687 $( '<div>' ).addClass( 'suggestions-special' )
688 // Can't use click() because the container div is hidden when the
689 // textbox loses focus. Instead, listen for a mousedown followed
690 // by a mouseup on the same div.
691 .on( 'mousedown', function ( e ) {
692 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
693 } )
694 .on( 'mouseup', function ( e ) {
695 var $special = $( e.target ).closest( '.suggestions-special' ),
696 $other = context.data.mouseDownOn;
697
698 context.data.mouseDownOn = $( [] );
699 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
700 return;
701 }
702 if ( typeof context.config.special.select === 'function' ) {
703 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
704 }
705 // Don't interfere with special clicks (e.g. to open in new tab)
706 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
707 // This will hide the link we're just clicking on, which causes problems
708 // when done synchronously in at least Firefox 3.6 (T64858).
709 setTimeout( function () {
710 hide( context );
711 } );
712 }
713 // Always bring focus to the textbox, as that's probably where the user expects it
714 // if they were just typing.
715 context.data.$textbox.trigger( 'focus' );
716 } )
717 .on( 'mousemove', function ( e ) {
718 context.data.selectedWithMouse = true;
719 highlight(
720 context, $( e.target ).closest( '.suggestions-special' ), false
721 );
722 } )
723 )
724 .appendTo( document.body );
725
726 $( this )
727 // Stop browser autocomplete from interfering
728 .attr( 'autocomplete', 'off' )
729 .on( 'keydown', function ( e ) {
730 // Store key pressed to handle later
731 context.data.keypressed = e.which;
732 context.data.keypressedCount = 0;
733 } )
734 .on( 'keypress', function ( e ) {
735 context.data.keypressedCount++;
736 keypress( e, context, context.data.keypressed );
737 } )
738 .on( 'keyup', function ( e ) {
739 // The keypress event is fired when a key is pressed down and that key normally
740 // produces a character value. We also want to handle some keys that don't
741 // produce a character value so we also attach to the keydown/keyup events.
742 // List of codes sourced from
743 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
744 var allowed = [
745 40, // up arrow
746 38, // down arrow
747 27, // escape
748 13, // enter
749 46, // delete
750 8 // backspace
751 ];
752 if ( context.data.keypressedCount === 0 &&
753 e.which === context.data.keypressed &&
754 allowed.indexOf( e.which ) !== -1
755 ) {
756 keypress( e, context, context.data.keypressed );
757 }
758 } )
759 .on( 'blur', function () {
760 // When losing focus because of a mousedown
761 // on a suggestion, don't hide the suggestions
762 if ( context.data.mouseDownOn.length > 0 ) {
763 return;
764 }
765 hide( context );
766 cancel( context );
767 } );
768 // Load suggestions if the value is changed because there are already
769 // typed characters before the JavaScript is loaded.
770 if ( $( this ).is( ':focus' ) && this.value !== this.defaultValue ) {
771 update( context, false );
772 }
773 }
774
775 // Store the context for next time
776 $( this ).data( 'suggestions-context', context );
777 } );
778 return this;
779 };
780
781 /**
782 * @class jQuery
783 * @mixins jQuery.plugin.suggestions
784 */
785
786 }() );