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