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