Debian Codegraph @

resources/src/jquery/jquery.suggestions.js

raw symbols SCIP
1 /**
2 * Provides a {@link jQuery} plugin that add suggestions to a text box.
3 *
4 * @module jquery.suggestions
5 */
6
7 ( function () {
8
9 /**
10 * Cancel any delayed maybeFetch() call and callback the context so
11 * they can cancel any async fetching if they use AJAX or something.
12 *
13 * @param {Object} context
14 */
15 function cancel( context ) {
16 if ( context.data.timerID !== null ) {
17 clearTimeout( context.data.timerID );
18 }
19 if ( typeof context.config.cancel === 'function' ) {
20 context.config.cancel.call( context.data.$textbox );
21 }
22 }
23
24 /**
25 * Hide the element with suggestions and clean up some state.
26 *
27 * @param {Object} context
28 */
29 function hide( context ) {
30 // Remove any highlights, including on "special" items
31 context.data.$container.find( '.suggestions-result-current' ).removeClass( 'suggestions-result-current' );
32 // Hide the container
33 context.data.$container.hide();
34 }
35
36 /**
37 * Restore the text the user originally typed in the textbox, before it
38 * was overwritten by highlight(). This restores the value the currently
39 * displayed suggestions are based on, rather than the value just before
40 * highlight() overwrote it; the former is arguably slightly more sensible.
41 *
42 * @param {Object} context
43 */
44 function restore( context ) {
45 context.data.$textbox.val( context.data.prevText );
46 }
47
48 /**
49 * @param {Object} context
50 */
51 function special( context ) {
52 // Allow custom rendering - but otherwise don't do any rendering
53 if ( typeof context.config.special.render === 'function' ) {
54 // Wait for the browser to update the value
55 setTimeout( () => {
56 // Render special
57 const $special = context.data.$container.find( '.suggestions-special' );
58 context.config.special.render.call( $special, context.data.$textbox.val(), context );
59 }, 1 );
60 }
61 }
62
63 /**
64 * Ask the user-specified callback for new suggestions. Any previous delayed
65 * call to this function still pending will be canceled. If the value in the
66 * textbox is empty or hasn't changed since the last time suggestions were fetched,
67 * this function does nothing.
68 *
69 * @param {Object} context
70 * @param {boolean} delayed Whether or not to delay this by the currently configured amount of time
71 */
72 function update( context, delayed ) {
73 function maybeFetch() {
74 if ( typeof context.config.update.before === 'function' ) {
75 context.config.update.before.call( context.data.$textbox );
76 }
77
78 const val = context.data.$textbox.val(),
79 cache = context.data.cache;
80
81 let cacheHit = false;
82 // Only fetch if the value in the textbox changed and is not empty, or if the results were hidden
83 // if the textbox is empty then clear the result div, but leave other settings intouched
84 if ( val.length === 0 ) {
85 hide( context );
86 context.data.prevText = '';
87 } else if (
88 val !== context.data.prevText ||
89 // eslint-disable-next-line no-jquery/no-sizzle
90 !context.data.$container.is( ':visible' )
91 ) {
92 context.data.prevText = val;
93 // Try cache first
94 if ( context.config.cache && val in cache ) {
95 if ( mw.now() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
96 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
97 if ( typeof context.config.update.after === 'function' ) {
98 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
99 }
100 cacheHit = true;
101 } else {
102 // Cache expired
103 delete cache[ val ];
104 }
105 }
106 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
107 context.config.fetch.call(
108 context.data.$textbox,
109 val,
110 ( suggestions, metadata ) => {
111 suggestions = suggestions.slice( 0, context.config.maxRows );
112 context.data.$textbox.suggestions( 'suggestions', suggestions );
113 if ( typeof context.config.update.after === 'function' ) {
114 context.config.update.after.call( context.data.$textbox, metadata );
115 }
116 if ( context.config.cache ) {
117 cache[ val ] = {
118 suggestions: suggestions,
119 metadata: metadata,
120 timestamp: mw.now()
121 };
122 }
123 },
124 context.config.maxRows
125 );
126 }
127 }
128
129 // Always update special rendering
130 special( context );
131 }
132
133 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
134 cancel( context );
135
136 if ( delayed ) {
137 // To avoid many started/aborted requests while typing, we're gonna take a short
138 // break before trying to fetch data.
139 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
140 } else {
141 maybeFetch();
142 }
143 }
144
145 /**
146 * Highlight a result in the results table
147 *
148 * @param {Object} context
149 * @param {jQuery|string} $result `<tr>` to highlight, or 'prev' or 'next'
150 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
151 */
152 function highlight( context, $result, updateTextbox ) {
153 const $selected = context.data.$container.find( '.suggestions-result-current' );
154 if ( !$result.get || $selected.get( 0 ) !== $result.get( 0 ) ) {
155 if ( $result === 'prev' ) {
156 // eslint-disable-next-line no-jquery/no-class-state
157 if ( $selected.hasClass( 'suggestions-special' ) ) {
158 $result = context.data.$container.find( '.suggestions-result' ).last();
159 } else {
160 $result = $selected.prev();
161 // eslint-disable-next-line no-jquery/no-class-state
162 if ( !( $result.length && $result.hasClass( 'suggestions-result' ) ) ) {
163 // there is something in the DOM between selected element and the wrapper, bypass it
164 $result = $selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
165 }
166
167 if ( $selected.length === 0 ) {
168 // we are at the beginning, so lets jump to the last item
169 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
170 $result = context.data.$container.find( '.suggestions-special' );
171 } else {
172 $result = context.data.$container.find( '.suggestions-results .suggestions-result' ).last();
173 }
174 }
175 }
176 } else if ( $result === 'next' ) {
177 if ( $selected.length === 0 ) {
178 // No item selected, go to the first one
179 $result = context.data.$container.find( '.suggestions-results .suggestions-result' ).first();
180 if ( $result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
181 // No suggestion exists, go to the special one directly
182 $result = context.data.$container.find( '.suggestions-special' );
183 }
184 } else {
185 $result = $selected.next();
186 // eslint-disable-next-line no-jquery/no-class-state
187 if ( !( $result.length && $result.hasClass( 'suggestions-result' ) ) ) {
188 // there is something in the DOM between selected element and the wrapper, bypass it
189 $result = $selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
190 }
191
192 // eslint-disable-next-line no-jquery/no-class-state
193 if ( $selected.hasClass( 'suggestions-special' ) ) {
194 $result = $( [] );
195 } else if (
196 $result.length === 0 &&
197 context.data.$container.find( '.suggestions-special' ).html() !== ''
198 ) {
199 // We were at the last item, jump to the specials!
200 $result = context.data.$container.find( '.suggestions-special' );
201 }
202 }
203 }
204 $selected.removeClass( 'suggestions-result-current' );
205 $result.addClass( 'suggestions-result-current' );
206 }
207 if ( updateTextbox ) {
208 if ( $result.length === 0 || $result.is( '.suggestions-special' ) ) {
209 restore( context );
210 } else {
211 context.data.$textbox.val( $result.data( 'text' ) );
212 // .val() doesn't call any event handlers, so
213 // let the world know what happened
214 context.data.$textbox.trigger( 'change' );
215 }
216 context.data.$textbox.trigger( 'change' );
217 }
218 }
219
220 /**
221 * Sets the value of a property, and updates the widget accordingly
222 *
223 * @param {Object} context
224 * @param {string} property Name of property
225 * @param {any} value Value to set property with
226 */
227 function configure( context, property, value ) {
228
229 // Validate creation using fallback values
230 switch ( property ) {
231 case 'fetch':
232 case 'cancel':
233 case 'special':
234 case 'result':
235 case 'update':
236 case '$region':
237 case 'expandFrom':
238 context.config[ property ] = value;
239 break;
240 case 'suggestions':
241 context.config[ property ] = value;
242 // Update suggestions
243 if ( context.data !== undefined ) {
244 if ( context.data.$textbox.val().length === 0 ) {
245 // Hide the div when no suggestion exist
246 hide( context );
247 } else {
248 // Rebuild the suggestions list
249 context.data.$container.show();
250 // Update the size and position of the list
251 const regionIsFixed = ( function () {
252 let $el = context.config.$region;
253 do {
254 if ( $el.css( 'position' ) === 'fixed' ) {
255 return true;
256 }
257 $el = $( $el[ 0 ].offsetParent );
258 } while ( $el.length );
259 return false;
260 }() );
261 const regionPosition = regionIsFixed ?
262 context.config.$region[ 0 ].getBoundingClientRect() :
263 context.config.$region.offset();
264 const newCSS = {
265 position: regionIsFixed ? 'fixed' : 'absolute',
266 top: regionPosition.top + context.config.$region.outerHeight(),
267 bottom: 'auto',
268 width: context.config.$region.outerWidth(),
269 height: 'auto'
270 };
271
272 // Process expandFrom, after this it is set to left or right.
273 context.config.expandFrom = ( function ( expandFrom ) {
274 const isRTL = $( document.documentElement ).css( 'direction' ) === 'rtl',
275 $region = context.config.$region;
276
277 // Backwards compatible
278 if ( context.config.positionFromLeft ) {
279 expandFrom = 'left';
280
281 // Catch invalid values, default to 'auto'
282 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
283 expandFrom = 'auto';
284 }
285
286 if ( expandFrom === 'auto' ) {
287 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
288 // If the markup explicitly contains a direction, use it.
289 expandFrom = $region.data( 'searchsuggest-expand-dir' );
290 } else {
291 const regionWidth = $region.outerWidth();
292 const docWidth = $( document ).width();
293 if ( regionWidth > ( 0.85 * docWidth ) ) {
294 // If the input size takes up more than 85% of the document horizontally
295 // expand the suggestions to the writing direction's native end.
296 expandFrom = 'start';
297 } else {
298 // Calculate the center points of the input and document
299 const regionCenter = regionPosition.left + regionWidth / 2;
300 const docCenter = docWidth / 2;
301 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
302 // If the input's center is within 10% of the document center
303 // use the writing direction's native end.
304 expandFrom = 'start';
305 } else {
306 // Otherwise expand the input from the closest side of the page,
307 // towards the side of the page with the most free open space
308 expandFrom = regionCenter > docCenter ? 'right' : 'left';
309 }
310 }
311 }
312 }
313
314 if ( expandFrom === 'start' ) {
315 expandFrom = isRTL ? 'right' : 'left';
316
317 } else if ( expandFrom === 'end' ) {
318 expandFrom = isRTL ? 'left' : 'right';
319 }
320
321 return expandFrom;
322
323 }( context.config.expandFrom ) );
324
325 if ( context.config.expandFrom === 'left' ) {
326 // Expand from left
327 newCSS.left = regionPosition.left;
328 newCSS.right = 'auto';
329 } else {
330 // Expand from right
331 newCSS.left = 'auto';
332 newCSS.right = document.documentElement.clientWidth -
333 ( regionPosition.left + context.config.$region.outerWidth() );
334 }
335
336 context.data.$container.css( newCSS );
337 const $results = context.data.$container.children( '.suggestions-results' );
338 $results.empty();
339 let expWidth = -1;
340 for ( let i = 0; i < context.config.suggestions.length; i++ ) {
341 const text = context.config.suggestions[ i ];
342 const $result = $( '<div>' )
343 .addClass( 'suggestions-result' )
344 .attr( 'rel', i )
345 .data( 'text', context.config.suggestions[ i ] )
346 .on( 'mousemove', function () {
347 context.data.selectedWithMouse = true;
348 highlight(
349 context,
350 $( this ).closest( '.suggestions-results .suggestions-result' ),
351 false
352 );
353 } )
354 .appendTo( $results );
355 // Allow custom rendering
356 if ( typeof context.config.result.render === 'function' ) {
357 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
358 } else {
359 $result.text( text );
360 }
361
362 if ( context.config.highlightInput ) {
363 $result.highlightText( context.data.prevText, { method: 'prefixPlusComboHighlight' } );
364 }
365
366 // Widen results box if needed (new width is only calculated here, applied later).
367
368 // The monstrosity below accomplishes two things:
369 // * Wraps the text contents in a DOM element, so that we can know its width. There is
370 // no way to directly access the width of a text node, and we can't use the parent
371 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
372 // it, which trims it to a smaller width.
373 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
374 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
375 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
376 // still report the "trimmed" width. This should not be done in regular CSS
377 // stylesheets as we don't want this rule to apply to other <span> elements, like
378 // the ones generated by jquery.highlightText.
379 const $spanForWidth = $result.wrapInner( '<span>' ).children();
380 const childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
381 $spanForWidth.contents().unwrap();
382
383 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
384 // factor in any padding, margin, or border space on the parent
385 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
386 }
387 }
388
389 // Apply new width for results box, if any
390 if ( expWidth > context.data.$container.width() ) {
391 const maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
392 context.data.$container.width( Math.min( expWidth, maxWidth ) );
393 }
394 }
395 }
396 break;
397 case 'maxRows':
398 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
399 break;
400 case 'delay':
401 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
402 break;
403 case 'cacheMaxAge':
404 context.config[ property ] = Math.max( 1, value );
405 break;
406 case 'maxExpandFactor':
407 context.config[ property ] = Math.max( 1, value );
408 break;
409 case 'cache':
410 case 'submitOnClick':
411 case 'positionFromLeft':
412 case 'highlightInput':
413 context.config[ property ] = !!value;
414 break;
415 }
416 }
417
418 /**
419 * Respond to keypress event
420 *
421 * @param {jQuery.Event} e
422 * @param {Object} context
423 * @param {number} key Code of key pressed
424 */
425 function keypress( e, context, key ) {
426 // eslint-disable-next-line no-jquery/no-sizzle
427 const wasVisible = context.data.$container.is( ':visible' );
428 let preventDefault = false;
429
430 switch ( key ) {
431 // Arrow down
432 case 40:
433 if ( wasVisible ) {
434 highlight( context, 'next', true );
435 context.data.selectedWithMouse = false;
436 } else {
437 update( context, false );
438 }
439 preventDefault = true;
440 break;
441 // Arrow up
442 case 38:
443 if ( wasVisible ) {
444 highlight( context, 'prev', true );
445 context.data.selectedWithMouse = false;
446 }
447 preventDefault = wasVisible;
448 break;
449 // Escape
450 case 27:
451 hide( context );
452 restore( context );
453 cancel( context );
454 context.data.$textbox.trigger( 'change' );
455 preventDefault = wasVisible;
456 break;
457 // Enter
458 case 13: {
459 preventDefault = wasVisible;
460 const $selected = context.data.$container.find( '.suggestions-result-current' );
461 hide( context );
462 if ( $selected.length === 0 || context.data.selectedWithMouse ) {
463 // If nothing is selected or if something was selected with the mouse
464 // cancel any current requests and allow the form to be submitted
465 // (simply don't prevent default behavior).
466 cancel( context );
467 preventDefault = false;
468 } else if ( $selected.is( '.suggestions-special' ) ) {
469 if ( typeof context.config.special.select === 'function' ) {
470 // Allow the callback to decide whether to prevent default or not
471 if ( context.config.special.select.call( $selected, context.data.$textbox, 'keyboard' ) === true ) {
472 preventDefault = false;
473 }
474 }
475 } else {
476 if ( typeof context.config.result.select === 'function' ) {
477 // Allow the callback to decide whether to prevent default or not
478 if ( context.config.result.select.call( $selected, context.data.$textbox, 'keyboard' ) === true ) {
479 preventDefault = false;
480 }
481 }
482 }
483 break;
484 }
485 default:
486 update( context, true );
487 break;
488 }
489 if ( preventDefault ) {
490 e.preventDefault();
491 e.stopPropagation();
492 }
493 }
494
495 /**
496 * Add suggestions to a text box.
497 *
498 * Set options:
499 *
500 * ```
501 * $( '#textbox' ).suggestions( { option1: value1, option2: value2 } );
502 * $( '#textbox' ).suggestions( option, value );
503 * ```
504 *
505 * To use this {@link jQuery} plugin, load the `jquery.suggestions` module with {@link mw.loader}.
506 *
507 * @example
508 * // Initialize:
509 * mw.loader.using( 'jquery.suggestions' ).then(()=> {
510 * $( '#textbox' ).suggestions();
511 * });
512 * @memberof module:jquery.suggestions
513 * @return {jQuery}
514 *
515 * @param {Object} options
516 *
517 * @param {Function} [options.fetch] Callback that should fetch suggestions and set the suggestions
518 * property. Called in context of the text box.
519 * @param {string} options.fetch.query
520 * @param {Function} options.fetch.response Callback to receive the suggestions with
521 * @param {Array} options.fetch.response.suggestions
522 * @param {number} options.fetch.maxRows
523 *
524 * @param {Function} [options.cancel] Callback function to call when any pending asynchronous
525 * suggestions fetches. Called in context of the text box.
526 *
527 * @param {Object} [options.special] Set of callbacks for rendering and selecting.
528 *
529 * @param {Function} options.special.render Called in context of the suggestions-special element.
530 * @param {string} options.special.render.query
531 * @param {Object} options.special.render.context
532 *
533 * @param {Function} options.special.select Called in context of the suggestions-result-current element.
534 * @param {jQuery} options.special.select.$textbox
535 *
536 * @param {Object} [options.result] Set of callbacks for rendering and selecting
537 *
538 * @param {Function} options.result.render Called in context of the suggestions-result element.
539 * @param {string} options.result.render.suggestion
540 * @param {Object} options.result.render.context
541 *
542 * @param {Function} options.result.select Called in context of the suggestions-result-current element.
543 * @param {jQuery} options.result.select.$textbox
544 *
545 * @param {Object} [options.update] Set of callbacks for listening to a change in the text input.
546 *
547 * @param {Function} options.update.before Called right after the user changes the textbox text.
548 * @param {Function} options.update.after Called after results are updated either from the cache or
549 * the API as a result of the user input.
550 *
551 * @param {jQuery} [options.$region=this] The element to place the suggestions below and match width of.
552 *
553 * @param {string[]} [options.suggestions] Array of suggestions to display.
554 *
555 * @param {number} [options.maxRows=10] Maximum number of suggestions to display at one time.
556 * Must be between 1 and 100.
557 *
558 * @param {number} [options.delay=120] Number of milliseconds to wait for the user to stop typing.
559 * Must be between 0 and 1200.
560 *
561 * @param {boolean} [options.cache=false] Whether to cache results from a fetch.
562 *
563 * @param {number} [options.cacheMaxAge=60000] Number of milliseconds to cache results from a fetch.
564 * Must be higher than 1. Defaults to 1 minute.
565 *
566 * @param {boolean} [options.submitOnClick=false] Whether to submit the form containing the textbox
567 * when a suggestion is clicked.
568 *
569 * @param {number} [options.maxExpandFactor=3] Maximum suggestions box width relative to the textbox
570 * width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of
571 * the textbox. Must be higher than 1.
572 *
573 * @param {string} [options.expandFrom=auto] Which direction to offset the suggestion box from.
574 * Values 'start' and 'end' translate to left and right respectively depending on the directionality
575 * of the current document, according to `$( document.documentElement ).css( 'direction' )`.
576 * Valid values: "left", "right", "start", "end", and "auto".
577 *
578 * @param {boolean} [options.positionFromLeft] Sets `expandFrom=left`, for backwards
579 * compatibility.
580 *
581 * @param {boolean} [options.highlightInput=false] Whether to highlight matched portions of the
582 * input or not.
583 */
584 $.fn.suggestions = function () {
585 // Multi-context fields
586 const args = arguments;
587
588 $( this ).each( function () {
589 /* Construction and Loading */
590
591 let context = $( this ).data( 'suggestions-context' );
592 if ( context === undefined || context === null ) {
593 context = {
594 config: {
595 fetch: function () {},
596 cancel: function () {},
597 special: {},
598 result: {},
599 update: {},
600 $region: $( this ),
601 suggestions: [],
602 maxRows: 10,
603 delay: 120,
604 cache: false,
605 cacheMaxAge: 60000,
606 submitOnClick: false,
607 maxExpandFactor: 3,
608 expandFrom: 'auto',
609 highlightInput: false
610 }
611 };
612 }
613
614 /* API */
615
616 // Handle various calling styles
617 if ( args.length > 0 ) {
618 if ( typeof args[ 0 ] === 'object' ) {
619 // Apply set of properties
620 for ( const key in args[ 0 ] ) {
621 configure( context, key, args[ 0 ][ key ] );
622 }
623 } else if ( typeof args[ 0 ] === 'string' ) {
624 if ( args.length > 1 ) {
625 // Set property values
626 configure( context, args[ 0 ], args[ 1 ] );
627 }
628 }
629 }
630
631 /* Initialization */
632
633 if ( context.data === undefined ) {
634 context.data = {
635 // ID of running timer
636 timerID: null,
637
638 // Text in textbox when suggestions were last fetched
639 prevText: null,
640
641 // Cache of fetched suggestions
642 cache: Object.create( null ),
643
644 // Number of results visible without scrolling
645 visibleResults: 0,
646
647 // Suggestion the last mousedown event occurred on
648 $mouseDownOn: $( [] ),
649 $textbox: $( this ),
650 selectedWithMouse: false
651 };
652
653 context.data.$container = $( '<div>' )
654 .css( 'display', 'none' )
655 .addClass( 'suggestions' )
656 .append(
657 $( '<div>' ).addClass( 'suggestions-results' )
658 // Can't use click() because the container div is hidden when the
659 // textbox loses focus. Instead, listen for a mousedown followed
660 // by a mouseup on the same div.
661 .on( 'mousedown', ( e ) => {
662 context.data.$mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
663 } )
664 .on( 'mouseup', ( e ) => {
665 const $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
666 $other = context.data.$mouseDownOn;
667
668 context.data.$mouseDownOn = $( [] );
669 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
670 return;
671 }
672 highlight( context, $result, true );
673 if ( typeof context.config.result.select === 'function' ) {
674 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
675 }
676 // Don't interfere with special clicks (e.g. to open in new tab)
677 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
678 // This will hide the link we're just clicking on, which causes problems
679 // when done synchronously in at least Firefox 3.6 (T64858).
680 setTimeout( () => {
681 hide( context );
682 } );
683 }
684 // Always bring focus to the textbox, as that's probably where the user expects it
685 // if they were just typing.
686 context.data.$textbox.trigger( 'focus' );
687 } )
688 )
689 .append(
690 $( '<div>' ).addClass( 'suggestions-special' )
691 // Can't use click() because the container div is hidden when the
692 // textbox loses focus. Instead, listen for a mousedown followed
693 // by a mouseup on the same div.
694 .on( 'mousedown', ( e ) => {
695 context.data.$mouseDownOn = $( e.target ).closest( '.suggestions-special' );
696 } )
697 .on( 'mouseup', ( e ) => {
698 const $special = $( e.target ).closest( '.suggestions-special' ),
699 $other = context.data.$mouseDownOn;
700
701 context.data.$mouseDownOn = $( [] );
702 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
703 return;
704 }
705 if ( typeof context.config.special.select === 'function' ) {
706 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
707 }
708 // Don't interfere with special clicks (e.g. to open in new tab)
709 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
710 // This will hide the link we're just clicking on, which causes problems
711 // when done synchronously in at least Firefox 3.6 (T64858).
712 setTimeout( () => {
713 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', ( e ) => {
721 context.data.selectedWithMouse = true;
722 highlight(
723 context, $( e.target ).closest( '.suggestions-special' ), false
724 );
725 } )
726 )
727 .appendTo( document.body );
728
729 $( this )
730 // Stop browser autocomplete from interfering
731 .attr( 'autocomplete', 'off' )
732 .on( 'keydown', ( e ) => {
733 // Store key pressed to handle later
734 context.data.keypressed = e.which;
735 context.data.keypressedCount = 0;
736 } )
737 .on( 'keypress', ( e ) => {
738 context.data.keypressedCount++;
739 keypress( e, context, context.data.keypressed );
740 } )
741 .on( 'keyup', ( e ) => {
742 // The keypress event is fired when a key is pressed down and that key normally
743 // produces a character value. We also want to handle some keys that don't
744 // produce a character value so we also attach to the keydown/keyup events.
745 // List of codes sourced from
746 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
747 const allowed = [
748 40, // up arrow
749 38, // down arrow
750 27, // escape
751 13, // enter
752 46, // delete
753 8 // backspace
754 ];
755 if ( context.data.keypressedCount === 0 &&
756 e.which === context.data.keypressed &&
757 allowed.indexOf( e.which ) !== -1
758 ) {
759 keypress( e, context, context.data.keypressed );
760 }
761 } )
762 .on( 'blur', () => {
763 // When losing focus because of a mousedown
764 // on a suggestion, don't hide the suggestions
765 if ( context.data.$mouseDownOn.length > 0 ) {
766 return;
767 }
768 hide( context );
769 cancel( context );
770 } );
771 // Load suggestions if the value is changed because there are already
772 // typed characters before the JavaScript is loaded.
773 if ( $( this ).is( ':focus' ) && this.value !== this.defaultValue ) {
774 update( context, false );
775 }
776 }
777
778 // Store the context for next time
779 $( this ).data( 'suggestions-context', context );
780 } );
781 return this;
782 };
783
784 /**
785 * @class jQuery
786 * @mixes jQuery.plugin.suggestions
787 */
788
789 }() );