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