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