jquery.suggestions: Debounce calls to $.suggestions.special
[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, 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 = $( document ).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
270 // New width is only calculated here, applied later
271 childrenWidth = $result.children().outerWidth();
272 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
273 // factor in any padding, margin, or border space on the parent
274 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
275 }
276 }
277
278 // Apply new width for results box, if any
279 if ( expWidth > context.data.$container.width() ) {
280 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
281 context.data.$container.width( Math.min( expWidth, maxWidth ) );
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 $.suggestions.hide( context );
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 preventDefault = wasVisible;
411 selected = context.data.$container.find( '.suggestions-result-current' );
412 $.suggestions.hide( context );
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 allow the form to be submitted
416 // (simply don't prevent default behavior).
417 $.suggestions.cancel( context );
418 preventDefault = false;
419 } else if ( selected.is( '.suggestions-special' ) ) {
420 if ( typeof context.config.special.select === 'function' ) {
421 // Allow the callback to decide whether to prevent default or not
422 if ( context.config.special.select.call( selected, context.data.$textbox ) === true ) {
423 preventDefault = false;
424 }
425 }
426 } else {
427 $.suggestions.highlight( context, selected, true );
428
429 if ( typeof context.config.result.select === 'function' ) {
430 // Allow the callback to decide whether to prevent default or not
431 if ( context.config.result.select.call( selected, context.data.$textbox ) === true ) {
432 preventDefault = false;
433 }
434 }
435 }
436 break;
437 default:
438 $.suggestions.update( context, true );
439 break;
440 }
441 if ( preventDefault ) {
442 e.preventDefault();
443 e.stopPropagation();
444 }
445 }
446 };
447 $.fn.suggestions = function () {
448
449 // Multi-context fields
450 var returnValue,
451 args = arguments;
452
453 $(this).each( function () {
454 var context, key;
455
456 /* Construction / Loading */
457
458 context = $(this).data( 'suggestions-context' );
459 if ( context === undefined || context === null ) {
460 context = {
461 config: {
462 fetch: function () {},
463 cancel: function () {},
464 special: {},
465 result: {},
466 $region: $(this),
467 suggestions: [],
468 maxRows: 7,
469 delay: 120,
470 submitOnClick: false,
471 maxExpandFactor: 3,
472 expandFrom: 'auto',
473 highlightInput: false
474 }
475 };
476 }
477
478 /* API */
479
480 // Handle various calling styles
481 if ( args.length > 0 ) {
482 if ( typeof args[0] === 'object' ) {
483 // Apply set of properties
484 for ( key in args[0] ) {
485 $.suggestions.configure( context, key, args[0][key] );
486 }
487 } else if ( typeof args[0] === 'string' ) {
488 if ( args.length > 1 ) {
489 // Set property values
490 $.suggestions.configure( context, args[0], args[1] );
491 } else if ( returnValue === null || returnValue === undefined ) {
492 // Get property values, but don't give access to internal data - returns only the first
493 returnValue = ( args[0] in context.config ? undefined : context.config[args[0]] );
494 }
495 }
496 }
497
498 /* Initialization */
499
500 if ( context.data === undefined ) {
501 context.data = {
502 // ID of running timer
503 timerID: null,
504
505 // Text in textbox when suggestions were last fetched
506 prevText: null,
507
508 // Number of results visible without scrolling
509 visibleResults: 0,
510
511 // Suggestion the last mousedown event occurred on
512 mouseDownOn: $( [] ),
513 $textbox: $(this),
514 selectedWithMouse: false
515 };
516
517 context.data.$container = $( '<div>' )
518 .css( 'display', 'none' )
519 .addClass( 'suggestions' )
520 .append(
521 $( '<div>' ).addClass( 'suggestions-results' )
522 // Can't use click() because the container div is hidden when the
523 // textbox loses focus. Instead, listen for a mousedown followed
524 // by a mouseup on the same div.
525 .mousedown( function ( e ) {
526 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
527 } )
528 .mouseup( function ( e ) {
529 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
530 $other = context.data.mouseDownOn;
531
532 context.data.mouseDownOn = $( [] );
533 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
534 return;
535 }
536 // do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click)
537 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
538 $.suggestions.highlight( context, $result, true );
539 $.suggestions.hide( context );
540 if ( typeof context.config.result.select === 'function' ) {
541 context.config.result.select.call( $result, context.data.$textbox );
542 }
543 }
544 // but still restore focus to the textbox, so that the suggestions will be hidden properly
545 context.data.$textbox.focus();
546 } )
547 )
548 .append(
549 $( '<div>' ).addClass( 'suggestions-special' )
550 // Can't use click() because the container div is hidden when the
551 // textbox loses focus. Instead, listen for a mousedown followed
552 // by a mouseup on the same div.
553 .mousedown( function ( e ) {
554 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
555 } )
556 .mouseup( function ( e ) {
557 var $special = $( e.target ).closest( '.suggestions-special' ),
558 $other = context.data.mouseDownOn;
559
560 context.data.mouseDownOn = $( [] );
561 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
562 return;
563 }
564 // do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click)
565 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
566 $.suggestions.hide( context );
567 if ( typeof context.config.special.select === 'function' ) {
568 context.config.special.select.call( $special, context.data.$textbox );
569 }
570 }
571 // but still restore focus to the textbox, so that the suggestions will be hidden properly
572 context.data.$textbox.focus();
573 } )
574 .mousemove( function ( e ) {
575 context.data.selectedWithMouse = true;
576 $.suggestions.highlight(
577 context, $( e.target ).closest( '.suggestions-special' ), false
578 );
579 } )
580 )
581 .appendTo( $( 'body' ) );
582
583 $(this)
584 // Stop browser autocomplete from interfering
585 .attr( 'autocomplete', 'off')
586 .keydown( function ( e ) {
587 // Store key pressed to handle later
588 context.data.keypressed = e.which;
589 context.data.keypressedCount = 0;
590 } )
591 .keypress( function ( e ) {
592 context.data.keypressedCount++;
593 $.suggestions.keypress( e, context, context.data.keypressed );
594 } )
595 .keyup( function ( e ) {
596 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
597 // keypress in between, solve it
598 if ( context.data.keypressedCount === 0 ) {
599 $.suggestions.keypress( e, context, context.data.keypressed );
600 }
601 } )
602 .blur( function () {
603 // When losing focus because of a mousedown
604 // on a suggestion, don't hide the suggestions
605 if ( context.data.mouseDownOn.length > 0 ) {
606 return;
607 }
608 $.suggestions.hide( context );
609 $.suggestions.cancel( context );
610 } );
611 }
612
613 // Store the context for next time
614 $(this).data( 'suggestions-context', context );
615 } );
616 return returnValue !== undefined ? returnValue : $(this);
617 };
618
619 }( jQuery ) );