Merge "Fix documentation for RevisionRecord::$mPageId"
[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 * Uses jQuery.suggestions singleton internally.
14 *
15 * @class jQuery.plugin.suggestions
16 */
17
18 /**
19 * @method suggestions
20 * @chainable
21 * @return {jQuery}
22 *
23 * @param {Object} options
24 *
25 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
26 * property. Called in context of the text box.
27 * @param {string} options.fetch.query
28 * @param {Function} options.fetch.response Callback to receive the suggestions with
29 * @param {Array} options.fetch.response.suggestions
30 * @param {number} options.fetch.maxRows
31 *
32 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
33 * suggestions fetches. Called in context of the text box.
34 *
35 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
36 *
37 * @param {Function} options.special.render Called in context of the suggestions-special element.
38 * @param {string} options.special.render.query
39 * @param {Object} options.special.render.context
40 *
41 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
42 * @param {jQuery} options.special.select.$textbox
43 *
44 * @param {Object} [options.result] Set of callbacks for rendering and selecting
45 *
46 * @param {Function} options.result.render Called in context of the suggestions-result element.
47 * @param {string} options.result.render.suggestion
48 * @param {Object} options.result.render.context
49 *
50 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
51 * @param {jQuery} options.result.select.$textbox
52 *
53 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
54 *
55 * @param {Function} options.update.before Called right after the user changes the textbox text.
56 * @param {Function} options.update.after Called after results are updated either from the cache or
57 * the API as a result of the user input.
58 *
59 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
60 *
61 * @param {string[]} [options.suggestions] Array of suggestions to display.
62 *
63 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
64 * Must be between 1 and 100.
65 *
66 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
67 * Must be between 0 and 1200.
68 *
69 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
70 *
71 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
72 * Must be higher than 1. Defaults to 1 minute.
73 *
74 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
75 * when a suggestion is clicked.
76 *
77 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
78 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
79 * the textbox. Must be higher than 1.
80 *
81 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
82 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
83 * of the current document, according to `$( 'html' ).css( 'direction' )`.
84 * Valid values: "left", "right", "start", "end", and "auto".
85 *
86 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
87 * compatibility.
88 *
89 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
90 * input or not.
91 */
92
93 ( function () {
94
95 var hasOwn = Object.hasOwnProperty;
96
97 /**
98 * Used by jQuery.plugin.suggestions.
99 *
100 * @class jQuery.suggestions
101 * @singleton
102 * @private
103 */
104 $.suggestions = {
105 /**
106 * Cancel any delayed maybeFetch() call and callback the context so
107 * they can cancel any async fetching if they use AJAX or something.
108 *
109 * @param {Object} context
110 */
111 cancel: function ( context ) {
112 if ( context.data.timerID !== null ) {
113 clearTimeout( context.data.timerID );
114 }
115 if ( typeof context.config.cancel === 'function' ) {
116 context.config.cancel.call( context.data.$textbox );
117 }
118 },
119
120 /**
121 * Hide the element with suggestions and clean up some state.
122 *
123 * @param {Object} context
124 */
125 hide: function ( context ) {
126 // Remove any highlights, including on "special" items
127 context.data.$container.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
128 // Hide the container
129 context.data.$container.hide();
130 },
131
132 /**
133 * Restore the text the user originally typed in the textbox, before it
134 * was overwritten by highlight(). This restores the value the currently
135 * displayed suggestions are based on, rather than the value just before
136 * highlight() overwrote it; the former is arguably slightly more sensible.
137 *
138 * @param {Object} context
139 */
140 restore: function ( context ) {
141 context.data.$textbox.val( context.data.prevText );
142 },
143
144 /**
145 * Ask the user-specified callback for new suggestions. Any previous delayed
146 * call to this function still pending will be canceled. If the value in the
147 * textbox is empty or hasn't changed since the last time suggestions were fetched,
148 * this function does nothing.
149 *
150 * @param {Object} context
151 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
152 */
153 update: function ( context, delayed ) {
154 function maybeFetch() {
155 var val = context.data.$textbox.val(),
156 cache = context.data.cache,
157 cacheHit;
158
159 if ( typeof context.config.update.before === 'function' ) {
160 context.config.update.before.call( context.data.$textbox );
161 }
162
163 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
164 // if the textbox is empty then clear the result div, but leave other settings intouched
165 if ( val.length === 0 ) {
166 // eslint-disable-next-line jquery/no-animate-toggle
167 $.suggestions.hide( context );
168 context.data.prevText = '';
169 } else if (
170 val !== context.data.prevText ||
171 !context.data.$container.is( ':visible' )
172 ) {
173 context.data.prevText = val;
174 // Try cache first
175 if ( context.config.cache && hasOwn.call( cache, val ) ) {
176 if ( mw.now() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
177 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
178 if ( typeof context.config.update.after === 'function' ) {
179 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
180 }
181 cacheHit = true;
182 } else {
183 // Cache expired
184 delete cache[ val ];
185 }
186 }
187 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
188 context.config.fetch.call(
189 context.data.$textbox,
190 val,
191 function ( suggestions, metadata ) {
192 suggestions = suggestions.slice( 0, context.config.maxRows );
193 context.data.$textbox.suggestions( 'suggestions', suggestions );
194 if ( typeof context.config.update.after === 'function' ) {
195 context.config.update.after.call( context.data.$textbox, metadata );
196 }
197 if ( context.config.cache ) {
198 cache[ val ] = {
199 suggestions: suggestions,
200 metadata: metadata,
201 timestamp: mw.now()
202 };
203 }
204 },
205 context.config.maxRows
206 );
207 }
208 }
209
210 // Always update special rendering
211 $.suggestions.special( context );
212 }
213
214 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
215 $.suggestions.cancel( context );
216
217 if ( delayed ) {
218 // To avoid many started/aborted requests while typing, we're gonna take a short
219 // break before trying to fetch data.
220 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
221 } else {
222 maybeFetch();
223 }
224 },
225
226 /**
227 * @param {Object} context
228 */
229 special: function ( context ) {
230 // Allow custom rendering - but otherwise don't do any rendering
231 if ( typeof context.config.special.render === 'function' ) {
232 // Wait for the browser to update the value
233 setTimeout( function () {
234 // Render special
235 var $special = context.data.$container.find( '.suggestions-special' );
236 context.config.special.render.call( $special, context.data.$textbox.val(), context );
237 }, 1 );
238 }
239 },
240
241 /**
242 * Sets the value of a property, and updates the widget accordingly
243 *
244 * @param {Object} context
245 * @param {string} property Name of property
246 * @param {Mixed} value Value to set property with
247 */
248 configure: function ( context, property, value ) {
249 var newCSS,
250 $result, $results, $spanForWidth, childrenWidth,
251 i, expWidth, maxWidth, text;
252
253 // Validate creation using fallback values
254 switch ( property ) {
255 case 'fetch':
256 case 'cancel':
257 case 'special':
258 case 'result':
259 case 'update':
260 case '$region':
261 case 'expandFrom':
262 context.config[ property ] = value;
263 break;
264 case 'suggestions':
265 context.config[ property ] = value;
266 // Update suggestions
267 if ( context.data !== undefined ) {
268 if ( context.data.$textbox.val().length === 0 ) {
269 // Hide the div when no suggestion exist
270 // eslint-disable-next-line jquery/no-animate-toggle
271 $.suggestions.hide( context );
272 } else {
273 // Rebuild the suggestions list
274 context.data.$container.show();
275 // Update the size and position of the list
276 newCSS = {
277 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
278 bottom: 'auto',
279 width: context.config.$region.outerWidth(),
280 height: 'auto'
281 };
282
283 // Process expandFrom, after this it is set to left or right.
284 context.config.expandFrom = ( function ( expandFrom ) {
285 var regionWidth, docWidth, regionCenter, docCenter,
286 docDir = $( document.documentElement ).css( 'direction' ),
287 $region = context.config.$region;
288
289 // Backwards compatible
290 if ( context.config.positionFromLeft ) {
291 expandFrom = 'left';
292
293 // Catch invalid values, default to 'auto'
294 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
295 expandFrom = 'auto';
296 }
297
298 if ( expandFrom === 'auto' ) {
299 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
300 // If the markup explicitly contains a direction, use it.
301 expandFrom = $region.data( 'searchsuggest-expand-dir' );
302 } else {
303 regionWidth = $region.outerWidth();
304 docWidth = $( document ).width();
305 if ( regionWidth > ( 0.85 * docWidth ) ) {
306 // If the input size takes up more than 85% of the document horizontally
307 // expand the suggestions to the writing direction's native end.
308 expandFrom = 'start';
309 } else {
310 // Calculate the center points of the input and document
311 regionCenter = $region.offset().left + regionWidth / 2;
312 docCenter = docWidth / 2;
313 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
314 // If the input's center is within 10% of the document center
315 // use the writing direction's native end.
316 expandFrom = 'start';
317 } else {
318 // Otherwise expand the input from the closest side of the page,
319 // towards the side of the page with the most free open space
320 expandFrom = regionCenter > docCenter ? 'right' : 'left';
321 }
322 }
323 }
324 }
325
326 if ( expandFrom === 'start' ) {
327 expandFrom = docDir === 'rtl' ? 'right' : 'left';
328
329 } else if ( expandFrom === 'end' ) {
330 expandFrom = docDir === 'rtl' ? 'left' : 'right';
331 }
332
333 return expandFrom;
334
335 }( context.config.expandFrom ) );
336
337 if ( context.config.expandFrom === 'left' ) {
338 // Expand from left
339 newCSS.left = context.config.$region.offset().left;
340 newCSS.right = 'auto';
341 } else {
342 // Expand from right
343 newCSS.left = 'auto';
344 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
345 }
346
347 context.data.$container.css( newCSS );
348 $results = context.data.$container.children( '.suggestions-results' );
349 $results.empty();
350 expWidth = -1;
351 for ( i = 0; i < context.config.suggestions.length; i++ ) {
352 text = context.config.suggestions[ i ];
353 $result = $( '<div>' )
354 .addClass( 'suggestions-result' )
355 .attr( 'rel', i )
356 .data( 'text', context.config.suggestions[ i ] )
357 .on( 'mousemove', function () {
358 context.data.selectedWithMouse = true;
359 $.suggestions.highlight(
360 context,
361 $( this ).closest( '.suggestions-results .suggestions-result' ),
362 false
363 );
364 } )
365 .appendTo( $results );
366 // Allow custom rendering
367 if ( typeof context.config.result.render === 'function' ) {
368 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
369 } else {
370 $result.text( text );
371 }
372
373 if ( context.config.highlightInput ) {
374 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
375 }
376
377 // Widen results box if needed (new width is only calculated here, applied later).
378
379 // The monstrosity below accomplishes two things:
380 // * Wraps the text contents in a DOM element, so that we can know its width. There is
381 // no way to directly access the width of a text node, and we can't use the parent
382 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
383 // it, which trims it to a smaller width.
384 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
385 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
386 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
387 // still report the "trimmed" width. This should not be done in regular CSS
388 // stylesheets as we don't want this rule to apply to other <span> elements, like
389 // the ones generated by jquery.highlightText.
390 $spanForWidth = $result.wrapInner( '<span>' ).children();
391 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
392 $spanForWidth.contents().unwrap();
393
394 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
395 // factor in any padding, margin, or border space on the parent
396 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
397 }
398 }
399
400 // Apply new width for results box, if any
401 if ( expWidth > context.data.$container.width() ) {
402 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
403 context.data.$container.width( Math.min( expWidth, maxWidth ) );
404 }
405 }
406 }
407 break;
408 case 'maxRows':
409 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
410 break;
411 case 'delay':
412 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
413 break;
414 case 'cacheMaxAge':
415 context.config[ property ] = Math.max( 1, value );
416 break;
417 case 'maxExpandFactor':
418 context.config[ property ] = Math.max( 1, value );
419 break;
420 case 'cache':
421 case 'submitOnClick':
422 case 'positionFromLeft':
423 case 'highlightInput':
424 context.config[ property ] = !!value;
425 break;
426 }
427 },
428
429 /**
430 * Highlight a result in the results table
431 *
432 * @param {Object} context
433 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
434 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
435 */
436 highlight: function ( context, result, updateTextbox ) {
437 var selected = context.data.$container.find( '.suggestions-result-current' );
438 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
439 if ( result === 'prev' ) {
440 if ( selected.hasClass( 'suggestions-special' ) ) {
441 result = context.data.$container.find( '.suggestions-result:last' );
442 } else {
443 result = selected.prev();
444 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
445 // there is something in the DOM between selected element and the wrapper, bypass it
446 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
447 }
448
449 if ( selected.length === 0 ) {
450 // we are at the beginning, so lets jump to the last item
451 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
452 result = context.data.$container.find( '.suggestions-special' );
453 } else {
454 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
455 }
456 }
457 }
458 } else if ( result === 'next' ) {
459 if ( selected.length === 0 ) {
460 // No item selected, go to the first one
461 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
462 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
463 // No suggestion exists, go to the special one directly
464 result = context.data.$container.find( '.suggestions-special' );
465 }
466 } else {
467 result = selected.next();
468 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
469 // there is something in the DOM between selected element and the wrapper, bypass it
470 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
471 }
472
473 if ( selected.hasClass( 'suggestions-special' ) ) {
474 result = $( [] );
475 } else if (
476 result.length === 0 &&
477 context.data.$container.find( '.suggestions-special' ).html() !== ''
478 ) {
479 // We were at the last item, jump to the specials!
480 result = context.data.$container.find( '.suggestions-special' );
481 }
482 }
483 }
484 selected.removeClass( 'suggestions-result-current' );
485 result.addClass( 'suggestions-result-current' );
486 }
487 if ( updateTextbox ) {
488 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
489 $.suggestions.restore( context );
490 } else {
491 context.data.$textbox.val( result.data( 'text' ) );
492 // .val() doesn't call any event handlers, so
493 // let the world know what happened
494 context.data.$textbox.trigger( 'change' );
495 }
496 context.data.$textbox.trigger( 'change' );
497 }
498 },
499
500 /**
501 * Respond to keypress event
502 *
503 * @param {jQuery.Event} e
504 * @param {Object} context
505 * @param {number} key Code of key pressed
506 */
507 keypress: function ( e, context, key ) {
508 var selected,
509 wasVisible = context.data.$container.is( ':visible' ),
510 preventDefault = false;
511
512 switch ( key ) {
513 // Arrow down
514 case 40:
515 if ( wasVisible ) {
516 $.suggestions.highlight( context, 'next', true );
517 context.data.selectedWithMouse = false;
518 } else {
519 $.suggestions.update( context, false );
520 }
521 preventDefault = true;
522 break;
523 // Arrow up
524 case 38:
525 if ( wasVisible ) {
526 $.suggestions.highlight( context, 'prev', true );
527 context.data.selectedWithMouse = false;
528 }
529 preventDefault = wasVisible;
530 break;
531 // Escape
532 case 27:
533 // eslint-disable-next-line jquery/no-animate-toggle
534 $.suggestions.hide( context );
535 $.suggestions.restore( context );
536 $.suggestions.cancel( context );
537 context.data.$textbox.trigger( 'change' );
538 preventDefault = wasVisible;
539 break;
540 // Enter
541 case 13:
542 preventDefault = wasVisible;
543 selected = context.data.$container.find( '.suggestions-result-current' );
544 // eslint-disable-next-line jquery/no-animate-toggle
545 $.suggestions.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 $.suggestions.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 $.suggestions.update( context, true );
570 break;
571 }
572 if ( preventDefault ) {
573 e.preventDefault();
574 e.stopPropagation();
575 }
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 $.suggestions.configure( context, key, args[ 0 ][ key ] );
620 }
621 } else if ( typeof args[ 0 ] === 'string' ) {
622 if ( args.length > 1 ) {
623 // Set property values
624 $.suggestions.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 $.suggestions.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 // eslint-disable-next-line jquery/no-animate-toggle
680 $.suggestions.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 // eslint-disable-next-line jquery/no-animate-toggle
713 $.suggestions.hide( context );
714 } );
715 }
716 // Always bring focus to the textbox, as that's probably where the user expects it
717 // if they were just typing.
718 context.data.$textbox.trigger( 'focus' );
719 } )
720 .on( 'mousemove', function ( e ) {
721 context.data.selectedWithMouse = true;
722 $.suggestions.highlight(
723 context, $( e.target ).closest( '.suggestions-special' ), false
724 );
725 } )
726 )
727 .appendTo( $( 'body' ) );
728
729 $( this )
730 // Stop browser autocomplete from interfering
731 .attr( 'autocomplete', 'off' )
732 .on( 'keydown', function ( e ) {
733 // Store key pressed to handle later
734 context.data.keypressed = e.which;
735 context.data.keypressedCount = 0;
736 } )
737 .on( 'keypress', function ( e ) {
738 context.data.keypressedCount++;
739 // eslint-disable-next-line jquery/no-event-shorthand
740 $.suggestions.keypress( e, context, context.data.keypressed );
741 } )
742 .on( 'keyup', function ( e ) {
743 // The keypress event is fired when a key is pressed down and that key normally
744 // produces a character value. We also want to handle some keys that don't
745 // produce a character value so we also attach to the keydown/keyup events.
746 // List of codes sourced from
747 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
748 var allowed = [
749 40, // up arrow
750 38, // down arrow
751 27, // escape
752 13, // enter
753 46, // delete
754 8 // backspace
755 ];
756 if ( context.data.keypressedCount === 0 &&
757 e.which === context.data.keypressed &&
758 allowed.indexOf( e.which ) !== -1
759 ) {
760 // eslint-disable-next-line jquery/no-event-shorthand
761 $.suggestions.keypress( e, context, context.data.keypressed );
762 }
763 } )
764 .on( 'blur', function () {
765 // When losing focus because of a mousedown
766 // on a suggestion, don't hide the suggestions
767 if ( context.data.mouseDownOn.length > 0 ) {
768 return;
769 }
770 // eslint-disable-next-line jquery/no-animate-toggle
771 $.suggestions.hide( context );
772 $.suggestions.cancel( context );
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 }() );