Merge "Add checkDependencies.php"
[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 $.suggestions.hide( context );
167 context.data.prevText = '';
168 } else if (
169 val !== context.data.prevText ||
170 !context.data.$container.is( ':visible' )
171 ) {
172 context.data.prevText = val;
173 // Try cache first
174 if ( context.config.cache && hasOwn.call( cache, val ) ) {
175 if ( mw.now() - cache[ val ].timestamp < context.config.cacheMaxAge ) {
176 context.data.$textbox.suggestions( 'suggestions', cache[ val ].suggestions );
177 if ( typeof context.config.update.after === 'function' ) {
178 context.config.update.after.call( context.data.$textbox, cache[ val ].metadata );
179 }
180 cacheHit = true;
181 } else {
182 // Cache expired
183 delete cache[ val ];
184 }
185 }
186 if ( !cacheHit && typeof context.config.fetch === 'function' ) {
187 context.config.fetch.call(
188 context.data.$textbox,
189 val,
190 function ( suggestions, metadata ) {
191 suggestions = suggestions.slice( 0, context.config.maxRows );
192 context.data.$textbox.suggestions( 'suggestions', suggestions );
193 if ( typeof context.config.update.after === 'function' ) {
194 context.config.update.after.call( context.data.$textbox, metadata );
195 }
196 if ( context.config.cache ) {
197 cache[ val ] = {
198 suggestions: suggestions,
199 metadata: metadata,
200 timestamp: mw.now()
201 };
202 }
203 },
204 context.config.maxRows
205 );
206 }
207 }
208
209 // Always update special rendering
210 $.suggestions.special( context );
211 }
212
213 // Cancels any delayed maybeFetch call, and invokes context.config.cancel.
214 $.suggestions.cancel( context );
215
216 if ( delayed ) {
217 // To avoid many started/aborted requests while typing, we're gonna take a short
218 // break before trying to fetch data.
219 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
220 } else {
221 maybeFetch();
222 }
223 },
224
225 /**
226 * @param {Object} context
227 */
228 special: function ( context ) {
229 // Allow custom rendering - but otherwise don't do any rendering
230 if ( typeof context.config.special.render === 'function' ) {
231 // Wait for the browser to update the value
232 setTimeout( function () {
233 // Render special
234 var $special = context.data.$container.find( '.suggestions-special' );
235 context.config.special.render.call( $special, context.data.$textbox.val(), context );
236 }, 1 );
237 }
238 },
239
240 /**
241 * Sets the value of a property, and updates the widget accordingly
242 *
243 * @param {Object} context
244 * @param {string} property Name of property
245 * @param {Mixed} value Value to set property with
246 */
247 configure: function ( context, property, value ) {
248 var newCSS,
249 $result, $results, $spanForWidth, childrenWidth,
250 regionIsFixed, regionPosition,
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 $.suggestions.hide( context );
271 } else {
272 // Rebuild the suggestions list
273 context.data.$container.show();
274 // Update the size and position of the list
275 regionIsFixed = ( function () {
276 var $el = context.config.$region;
277 do {
278 if ( $el.css( 'position' ) === 'fixed' ) {
279 return true;
280 }
281 $el = $( $el[ 0 ].offsetParent );
282 } while ( $el.length );
283 return false;
284 }() );
285 regionPosition = regionIsFixed ?
286 context.config.$region[ 0 ].getBoundingClientRect() :
287 context.config.$region.offset();
288 newCSS = {
289 position: regionIsFixed ? 'fixed' : 'absolute',
290 top: regionPosition.top + context.config.$region.outerHeight(),
291 bottom: 'auto',
292 width: context.config.$region.outerWidth(),
293 height: 'auto'
294 };
295
296 // Process expandFrom, after this it is set to left or right.
297 context.config.expandFrom = ( function ( expandFrom ) {
298 var regionWidth, docWidth, regionCenter, docCenter,
299 docDir = $( document.documentElement ).css( 'direction' ),
300 $region = context.config.$region;
301
302 // Backwards compatible
303 if ( context.config.positionFromLeft ) {
304 expandFrom = 'left';
305
306 // Catch invalid values, default to 'auto'
307 } else if ( [ 'left', 'right', 'start', 'end', 'auto' ].indexOf( expandFrom ) === -1 ) {
308 expandFrom = 'auto';
309 }
310
311 if ( expandFrom === 'auto' ) {
312 if ( $region.data( 'searchsuggest-expand-dir' ) ) {
313 // If the markup explicitly contains a direction, use it.
314 expandFrom = $region.data( 'searchsuggest-expand-dir' );
315 } else {
316 regionWidth = $region.outerWidth();
317 docWidth = $( document ).width();
318 if ( regionWidth > ( 0.85 * docWidth ) ) {
319 // If the input size takes up more than 85% of the document horizontally
320 // expand the suggestions to the writing direction's native end.
321 expandFrom = 'start';
322 } else {
323 // Calculate the center points of the input and document
324 regionCenter = regionPosition.left + regionWidth / 2;
325 docCenter = docWidth / 2;
326 if ( Math.abs( regionCenter - docCenter ) < ( 0.10 * docCenter ) ) {
327 // If the input's center is within 10% of the document center
328 // use the writing direction's native end.
329 expandFrom = 'start';
330 } else {
331 // Otherwise expand the input from the closest side of the page,
332 // towards the side of the page with the most free open space
333 expandFrom = regionCenter > docCenter ? 'right' : 'left';
334 }
335 }
336 }
337 }
338
339 if ( expandFrom === 'start' ) {
340 expandFrom = docDir === 'rtl' ? 'right' : 'left';
341
342 } else if ( expandFrom === 'end' ) {
343 expandFrom = docDir === 'rtl' ? 'left' : 'right';
344 }
345
346 return expandFrom;
347
348 }( context.config.expandFrom ) );
349
350 if ( context.config.expandFrom === 'left' ) {
351 // Expand from left
352 newCSS.left = regionPosition.left;
353 newCSS.right = 'auto';
354 } else {
355 // Expand from right
356 newCSS.left = 'auto';
357 newCSS.right = $( 'body' ).width() - ( regionPosition.left + context.config.$region.outerWidth() );
358 }
359
360 context.data.$container.css( newCSS );
361 $results = context.data.$container.children( '.suggestions-results' );
362 $results.empty();
363 expWidth = -1;
364 for ( i = 0; i < context.config.suggestions.length; i++ ) {
365 text = context.config.suggestions[ i ];
366 $result = $( '<div>' )
367 .addClass( 'suggestions-result' )
368 .attr( 'rel', i )
369 .data( 'text', context.config.suggestions[ i ] )
370 .on( 'mousemove', function () {
371 context.data.selectedWithMouse = true;
372 $.suggestions.highlight(
373 context,
374 $( this ).closest( '.suggestions-results .suggestions-result' ),
375 false
376 );
377 } )
378 .appendTo( $results );
379 // Allow custom rendering
380 if ( typeof context.config.result.render === 'function' ) {
381 context.config.result.render.call( $result, context.config.suggestions[ i ], context );
382 } else {
383 $result.text( text );
384 }
385
386 if ( context.config.highlightInput ) {
387 $result.highlightText( context.data.prevText, { method: 'prefixHighlight' } );
388 }
389
390 // Widen results box if needed (new width is only calculated here, applied later).
391
392 // The monstrosity below accomplishes two things:
393 // * Wraps the text contents in a DOM element, so that we can know its width. There is
394 // no way to directly access the width of a text node, and we can't use the parent
395 // node width as it has text-overflow: ellipsis; and overflow: hidden; applied to
396 // it, which trims it to a smaller width.
397 // * Temporarily applies position: absolute; to the wrapper to pull it out of normal
398 // document flow. Otherwise the CSS text-overflow: ellipsis; and overflow: hidden;
399 // rules would cause some browsers (at least all versions of IE from 6 to 11) to
400 // still report the "trimmed" width. This should not be done in regular CSS
401 // stylesheets as we don't want this rule to apply to other <span> elements, like
402 // the ones generated by jquery.highlightText.
403 $spanForWidth = $result.wrapInner( '<span>' ).children();
404 childrenWidth = $spanForWidth.css( 'position', 'absolute' ).outerWidth();
405 $spanForWidth.contents().unwrap();
406
407 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
408 // factor in any padding, margin, or border space on the parent
409 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
410 }
411 }
412
413 // Apply new width for results box, if any
414 if ( expWidth > context.data.$container.width() ) {
415 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
416 context.data.$container.width( Math.min( expWidth, maxWidth ) );
417 }
418 }
419 }
420 break;
421 case 'maxRows':
422 context.config[ property ] = Math.max( 1, Math.min( 100, value ) );
423 break;
424 case 'delay':
425 context.config[ property ] = Math.max( 0, Math.min( 1200, value ) );
426 break;
427 case 'cacheMaxAge':
428 context.config[ property ] = Math.max( 1, value );
429 break;
430 case 'maxExpandFactor':
431 context.config[ property ] = Math.max( 1, value );
432 break;
433 case 'cache':
434 case 'submitOnClick':
435 case 'positionFromLeft':
436 case 'highlightInput':
437 context.config[ property ] = !!value;
438 break;
439 }
440 },
441
442 /**
443 * Highlight a result in the results table
444 *
445 * @param {Object} context
446 * @param {jQuery|string} result `<tr>` to highlight, or 'prev' or 'next'
447 * @param {boolean} updateTextbox If true, put the suggestion in the textbox
448 */
449 highlight: function ( context, result, updateTextbox ) {
450 var selected = context.data.$container.find( '.suggestions-result-current' );
451 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
452 if ( result === 'prev' ) {
453 if ( selected.hasClass( 'suggestions-special' ) ) {
454 result = context.data.$container.find( '.suggestions-result:last' );
455 } else {
456 result = selected.prev();
457 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
458 // there is something in the DOM between selected element and the wrapper, bypass it
459 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
460 }
461
462 if ( selected.length === 0 ) {
463 // we are at the beginning, so lets jump to the last item
464 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
465 result = context.data.$container.find( '.suggestions-special' );
466 } else {
467 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
468 }
469 }
470 }
471 } else if ( result === 'next' ) {
472 if ( selected.length === 0 ) {
473 // No item selected, go to the first one
474 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
475 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
476 // No suggestion exists, go to the special one directly
477 result = context.data.$container.find( '.suggestions-special' );
478 }
479 } else {
480 result = selected.next();
481 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
482 // there is something in the DOM between selected element and the wrapper, bypass it
483 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
484 }
485
486 if ( selected.hasClass( 'suggestions-special' ) ) {
487 result = $( [] );
488 } else if (
489 result.length === 0 &&
490 context.data.$container.find( '.suggestions-special' ).html() !== ''
491 ) {
492 // We were at the last item, jump to the specials!
493 result = context.data.$container.find( '.suggestions-special' );
494 }
495 }
496 }
497 selected.removeClass( 'suggestions-result-current' );
498 result.addClass( 'suggestions-result-current' );
499 }
500 if ( updateTextbox ) {
501 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
502 $.suggestions.restore( context );
503 } else {
504 context.data.$textbox.val( result.data( 'text' ) );
505 // .val() doesn't call any event handlers, so
506 // let the world know what happened
507 context.data.$textbox.trigger( 'change' );
508 }
509 context.data.$textbox.trigger( 'change' );
510 }
511 },
512
513 /**
514 * Respond to keypress event
515 *
516 * @param {jQuery.Event} e
517 * @param {Object} context
518 * @param {number} key Code of key pressed
519 */
520 keypress: function ( e, context, key ) {
521 var selected,
522 wasVisible = context.data.$container.is( ':visible' ),
523 preventDefault = false;
524
525 switch ( key ) {
526 // Arrow down
527 case 40:
528 if ( wasVisible ) {
529 $.suggestions.highlight( context, 'next', true );
530 context.data.selectedWithMouse = false;
531 } else {
532 $.suggestions.update( context, false );
533 }
534 preventDefault = true;
535 break;
536 // Arrow up
537 case 38:
538 if ( wasVisible ) {
539 $.suggestions.highlight( context, 'prev', true );
540 context.data.selectedWithMouse = false;
541 }
542 preventDefault = wasVisible;
543 break;
544 // Escape
545 case 27:
546 $.suggestions.hide( context );
547 $.suggestions.restore( context );
548 $.suggestions.cancel( context );
549 context.data.$textbox.trigger( 'change' );
550 preventDefault = wasVisible;
551 break;
552 // Enter
553 case 13:
554 preventDefault = wasVisible;
555 selected = context.data.$container.find( '.suggestions-result-current' );
556 $.suggestions.hide( context );
557 if ( selected.length === 0 || context.data.selectedWithMouse ) {
558 // If nothing is selected or if something was selected with the mouse
559 // cancel any current requests and allow the form to be submitted
560 // (simply don't prevent default behavior).
561 $.suggestions.cancel( context );
562 preventDefault = false;
563 } else if ( selected.is( '.suggestions-special' ) ) {
564 if ( typeof context.config.special.select === 'function' ) {
565 // Allow the callback to decide whether to prevent default or not
566 if ( context.config.special.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
567 preventDefault = false;
568 }
569 }
570 } else {
571 if ( typeof context.config.result.select === 'function' ) {
572 // Allow the callback to decide whether to prevent default or not
573 if ( context.config.result.select.call( selected, context.data.$textbox, 'keyboard' ) === true ) {
574 preventDefault = false;
575 }
576 }
577 }
578 break;
579 default:
580 $.suggestions.update( context, true );
581 break;
582 }
583 if ( preventDefault ) {
584 e.preventDefault();
585 e.stopPropagation();
586 }
587 }
588 };
589
590 // See file header for method documentation
591 $.fn.suggestions = function () {
592 // Multi-context fields
593 var args = arguments;
594
595 $( this ).each( function () {
596 var context, key;
597
598 /* Construction and Loading */
599
600 context = $( this ).data( 'suggestions-context' );
601 if ( context === undefined || context === null ) {
602 context = {
603 config: {
604 fetch: function () {},
605 cancel: function () {},
606 special: {},
607 result: {},
608 update: {},
609 $region: $( this ),
610 suggestions: [],
611 maxRows: 10,
612 delay: 120,
613 cache: false,
614 cacheMaxAge: 60000,
615 submitOnClick: false,
616 maxExpandFactor: 3,
617 expandFrom: 'auto',
618 highlightInput: false
619 }
620 };
621 }
622
623 /* API */
624
625 // Handle various calling styles
626 if ( args.length > 0 ) {
627 if ( typeof args[ 0 ] === 'object' ) {
628 // Apply set of properties
629 for ( key in args[ 0 ] ) {
630 $.suggestions.configure( context, key, args[ 0 ][ key ] );
631 }
632 } else if ( typeof args[ 0 ] === 'string' ) {
633 if ( args.length > 1 ) {
634 // Set property values
635 $.suggestions.configure( context, args[ 0 ], args[ 1 ] );
636 }
637 }
638 }
639
640 /* Initialization */
641
642 if ( context.data === undefined ) {
643 context.data = {
644 // ID of running timer
645 timerID: null,
646
647 // Text in textbox when suggestions were last fetched
648 prevText: null,
649
650 // Cache of fetched suggestions
651 cache: {},
652
653 // Number of results visible without scrolling
654 visibleResults: 0,
655
656 // Suggestion the last mousedown event occurred on
657 mouseDownOn: $( [] ),
658 $textbox: $( this ),
659 selectedWithMouse: false
660 };
661
662 context.data.$container = $( '<div>' )
663 .css( 'display', 'none' )
664 .addClass( 'suggestions' )
665 .append(
666 $( '<div>' ).addClass( 'suggestions-results' )
667 // Can't use click() because the container div is hidden when the
668 // textbox loses focus. Instead, listen for a mousedown followed
669 // by a mouseup on the same div.
670 .on( 'mousedown', function ( e ) {
671 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
672 } )
673 .on( 'mouseup', function ( e ) {
674 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
675 $other = context.data.mouseDownOn;
676
677 context.data.mouseDownOn = $( [] );
678 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
679 return;
680 }
681 $.suggestions.highlight( context, $result, true );
682 if ( typeof context.config.result.select === 'function' ) {
683 context.config.result.select.call( $result, context.data.$textbox, 'mouse' );
684 }
685 // Don't interfere with special clicks (e.g. to open in new tab)
686 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
687 // This will hide the link we're just clicking on, which causes problems
688 // when done synchronously in at least Firefox 3.6 (T64858).
689 setTimeout( function () {
690 $.suggestions.hide( context );
691 } );
692 }
693 // Always bring focus to the textbox, as that's probably where the user expects it
694 // if they were just typing.
695 context.data.$textbox.trigger( 'focus' );
696 } )
697 )
698 .append(
699 $( '<div>' ).addClass( 'suggestions-special' )
700 // Can't use click() because the container div is hidden when the
701 // textbox loses focus. Instead, listen for a mousedown followed
702 // by a mouseup on the same div.
703 .on( 'mousedown', function ( e ) {
704 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
705 } )
706 .on( 'mouseup', function ( e ) {
707 var $special = $( e.target ).closest( '.suggestions-special' ),
708 $other = context.data.mouseDownOn;
709
710 context.data.mouseDownOn = $( [] );
711 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
712 return;
713 }
714 if ( typeof context.config.special.select === 'function' ) {
715 context.config.special.select.call( $special, context.data.$textbox, 'mouse' );
716 }
717 // Don't interfere with special clicks (e.g. to open in new tab)
718 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
719 // This will hide the link we're just clicking on, which causes problems
720 // when done synchronously in at least Firefox 3.6 (T64858).
721 setTimeout( function () {
722 $.suggestions.hide( context );
723 } );
724 }
725 // Always bring focus to the textbox, as that's probably where the user expects it
726 // if they were just typing.
727 context.data.$textbox.trigger( 'focus' );
728 } )
729 .on( 'mousemove', function ( e ) {
730 context.data.selectedWithMouse = true;
731 $.suggestions.highlight(
732 context, $( e.target ).closest( '.suggestions-special' ), false
733 );
734 } )
735 )
736 .appendTo( $( 'body' ) );
737
738 $( this )
739 // Stop browser autocomplete from interfering
740 .attr( 'autocomplete', 'off' )
741 .on( 'keydown', function ( e ) {
742 // Store key pressed to handle later
743 context.data.keypressed = e.which;
744 context.data.keypressedCount = 0;
745 } )
746 .on( 'keypress', function ( e ) {
747 context.data.keypressedCount++;
748 $.suggestions.keypress( e, context, context.data.keypressed );
749 } )
750 .on( 'keyup', function ( e ) {
751 // The keypress event is fired when a key is pressed down and that key normally
752 // produces a character value. We also want to handle some keys that don't
753 // produce a character value so we also attach to the keydown/keyup events.
754 // List of codes sourced from
755 // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
756 var allowed = [
757 40, // up arrow
758 38, // down arrow
759 27, // escape
760 13, // enter
761 46, // delete
762 8 // backspace
763 ];
764 if ( context.data.keypressedCount === 0 &&
765 e.which === context.data.keypressed &&
766 allowed.indexOf( e.which ) !== -1
767 ) {
768 $.suggestions.keypress( e, context, context.data.keypressed );
769 }
770 } )
771 .on( 'blur', function () {
772 // When losing focus because of a mousedown
773 // on a suggestion, don't hide the suggestions
774 if ( context.data.mouseDownOn.length > 0 ) {
775 return;
776 }
777 $.suggestions.hide( context );
778 $.suggestions.cancel( context );
779 } )
780 // Simulate a keypress on load. This loads the search suggestions when there are already
781 // typed characters before the JavaScript is loaded.
782 .trigger( 'keypress' );
783 }
784
785 // Store the context for next time
786 $( this ).data( 'suggestions-context', context );
787 } );
788 return this;
789 };
790
791 /**
792 * @class jQuery
793 * @mixins jQuery.plugin.suggestions
794 */
795
796 }() );