Merge "fix backup unit tests"
[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. Executed in the context of the
17 * textbox
18 * Type: Function
19 * cancel: Callback function to call when any pending asynchronous suggestions fetches should be canceled.
20 * 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 to e.g. 2, the suggestions box
37 * will never be grown beyond 2 times the width of the textbox.
38 * Type: Number, Range: 1 - infinity, Default: 3
39 * positionFromLeft: Whether to position the suggestion box with the left attribute or the right
40 * Type: Boolean, Default: true
41 * highlightInput: Whether to hightlight matched portions of the input or not
42 * Type: Boolean, Default: false
43 */
44 ( function( $ ) {
45
46 $.suggestions = {
47 /**
48 * Cancel any delayed updateSuggestions() call and inform the user so
49 * they can cancel their result fetching if they use AJAX or something
50 */
51 cancel: function( context ) {
52 if ( context.data.timerID != null ) {
53 clearTimeout( context.data.timerID );
54 }
55 if ( $.isFunction( context.config.cancel ) ) {
56 context.config.cancel.call( context.data.$textbox );
57 }
58 },
59 /**
60 * Restore the text the user originally typed in the textbox, before it was overwritten by highlight(). This
61 * restores the value the currently displayed suggestions are based on, rather than the value just before
62 * highlight() overwrote it; the former is arguably slightly more sensible.
63 */
64 restore: function( context ) {
65 context.data.$textbox.val( context.data.prevText );
66 },
67 /**
68 * Ask the user-specified callback for new suggestions. Any previous delayed call to this function still pending
69 * will be canceled. If the value in the textbox is empty or hasn't changed since the last time suggestions were fetched, this
70 * function does nothing.
71 * @param {Boolean} delayed Whether or not to delay this by the currently configured amount of time
72 */
73 update: function( context, delayed ) {
74 // Only fetch if the value in the textbox changed and is not empty
75 // if the textbox is empty then clear the result div, but leave other settings intouched
76 function maybeFetch() {
77 if ( context.data.$textbox.val().length === 0 ) {
78 context.data.$container.hide();
79 context.data.prevText = '';
80 } else if ( context.data.$textbox.val() !== context.data.prevText ) {
81 if ( typeof context.config.fetch === 'function' ) {
82 context.data.prevText = context.data.$textbox.val();
83 context.config.fetch.call( context.data.$textbox, context.data.$textbox.val() );
84 }
85 }
86 }
87
88 // Cancel previous call
89 if ( context.data.timerID != null ) {
90 clearTimeout( context.data.timerID );
91 }
92 if ( delayed ) {
93 // Start a new asynchronous call
94 context.data.timerID = setTimeout( maybeFetch, context.config.delay );
95 } else {
96 maybeFetch();
97 }
98 $.suggestions.special( context );
99 },
100 special: function( context ) {
101 // Allow custom rendering - but otherwise don't do any rendering
102 if ( typeof context.config.special.render === 'function' ) {
103 // Wait for the browser to update the value
104 setTimeout( function() {
105 // Render special
106 var $special = context.data.$container.find( '.suggestions-special' );
107 context.config.special.render.call( $special, context.data.$textbox.val() );
108 }, 1 );
109 }
110 },
111 /**
112 * Sets the value of a property, and updates the widget accordingly
113 * @param property String Name of property
114 * @param value Mixed Value to set property with
115 */
116 configure: function( context, property, value ) {
117 // Validate creation using fallback values
118 switch( property ) {
119 case 'fetch':
120 case 'cancel':
121 case 'special':
122 case 'result':
123 case '$region':
124 context.config[property] = value;
125 break;
126 case 'suggestions':
127 context.config[property] = value;
128 // Update suggestions
129 if ( context.data !== undefined ) {
130 if ( context.data.$textbox.val().length === 0 ) {
131 // Hide the div when no suggestion exist
132 context.data.$container.hide();
133 } else {
134 // Rebuild the suggestions list
135 context.data.$container.show();
136 // Update the size and position of the list
137 var newCSS = {
138 top: context.config.$region.offset().top + context.config.$region.outerHeight(),
139 bottom: 'auto',
140 width: context.config.$region.outerWidth(),
141 height: 'auto'
142 };
143 if ( context.config.positionFromLeft ) {
144 newCSS.left = context.config.$region.offset().left;
145 newCSS.right = 'auto';
146 } else {
147 newCSS.left = 'auto';
148 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
149 }
150 context.data.$container.css( newCSS );
151 var $results = context.data.$container.children( '.suggestions-results' );
152 $results.empty();
153 var expWidth = -1;
154 var $autoEllipseMe = $( [] );
155 var matchedText = null;
156 for ( var i = 0; i < context.config.suggestions.length; i++ ) {
157 var text = context.config.suggestions[i];
158 var $result = $( '<div>' )
159 .addClass( 'suggestions-result' )
160 .attr( 'rel', i )
161 .data( 'text', context.config.suggestions[i] )
162 .mousemove( function( e ) {
163 context.data.selectedWithMouse = true;
164 $.suggestions.highlight(
165 context, $(this).closest( '.suggestions-results div' ), false
166 );
167 } )
168 .appendTo( $results );
169 // Allow custom rendering
170 if ( typeof context.config.result.render === 'function' ) {
171 context.config.result.render.call( $result, context.config.suggestions[i] );
172 } else {
173 // Add <span> with text
174 if( context.config.highlightInput ) {
175 matchedText = context.data.prevText;
176 }
177 $result.append( $( '<span>' )
178 .css( 'whiteSpace', 'nowrap' )
179 .text( text )
180 );
181
182 // Widen results box if needed
183 // New width is only calculated here, applied later
184 var $span = $result.children( 'span' );
185 if ( $span.outerWidth() > $result.width() && $span.outerWidth() > expWidth ) {
186 // factor in any padding, margin, or border space on the parent
187 expWidth = $span.outerWidth() + ( context.data.$container.width() - $span.parent().width());
188 }
189 $autoEllipseMe = $autoEllipseMe.add( $result );
190 }
191 }
192 // Apply new width for results box, if any
193 if ( expWidth > context.data.$container.width() ) {
194 var maxWidth = context.config.maxExpandFactor*context.data.$textbox.width();
195 context.data.$container.width( Math.min( expWidth, maxWidth ) );
196 }
197 // autoEllipse the results. Has to be done after changing the width
198 $autoEllipseMe.autoEllipsis( { hasSpan: true, tooltip: true, matchText: matchedText } );
199 }
200 }
201 break;
202 case 'maxRows':
203 context.config[property] = Math.max( 1, Math.min( 100, value ) );
204 break;
205 case 'delay':
206 context.config[property] = Math.max( 0, Math.min( 1200, value ) );
207 break;
208 case 'maxExpandFactor':
209 context.config[property] = Math.max( 1, value );
210 break;
211 case 'submitOnClick':
212 case 'positionFromLeft':
213 case 'highlightInput':
214 context.config[property] = value ? true : false;
215 break;
216 }
217 },
218 /**
219 * Highlight a result in the results table
220 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
221 * @param updateTextbox If true, put the suggestion in the textbox
222 */
223 highlight: function( context, result, updateTextbox ) {
224 var selected = context.data.$container.find( '.suggestions-result-current' );
225 if ( !result.get || selected.get( 0 ) != result.get( 0 ) ) {
226 if ( result === 'prev' ) {
227 if( selected.is( '.suggestions-special' ) ) {
228 result = context.data.$container.find( '.suggestions-result:last' );
229 } else {
230 result = selected.prev();
231 if ( selected.length === 0 ) {
232 // we are at the beginning, so lets jump to the last item
233 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
234 result = context.data.$container.find( '.suggestions-special' );
235 } else {
236 result = context.data.$container.find( '.suggestions-results div:last' );
237 }
238 }
239 }
240 } else if ( result === 'next' ) {
241 if ( selected.length === 0 ) {
242 // No item selected, go to the first one
243 result = context.data.$container.find( '.suggestions-results div:first' );
244 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
245 // No suggestion exists, go to the special one directly
246 result = context.data.$container.find( '.suggestions-special' );
247 }
248 } else {
249 result = selected.next();
250 if ( selected.is( '.suggestions-special' ) ) {
251 result = $( [] );
252 } else if (
253 result.length === 0 &&
254 context.data.$container.find( '.suggestions-special' ).html() !== ''
255 ) {
256 // We were at the last item, jump to the specials!
257 result = context.data.$container.find( '.suggestions-special' );
258 }
259 }
260 }
261 selected.removeClass( 'suggestions-result-current' );
262 result.addClass( 'suggestions-result-current' );
263 }
264 if ( updateTextbox ) {
265 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
266 $.suggestions.restore( context );
267 } else {
268 context.data.$textbox.val( result.data( 'text' ) );
269 // .val() doesn't call any event handlers, so
270 // let the world know what happened
271 context.data.$textbox.change();
272 }
273 context.data.$textbox.trigger( 'change' );
274 }
275 },
276 /**
277 * Respond to keypress event
278 * @param key Integer Code of key pressed
279 */
280 keypress: function( e, context, key ) {
281 var wasVisible = context.data.$container.is( ':visible' ),
282 preventDefault = false;
283 switch ( key ) {
284 // Arrow down
285 case 40:
286 if ( wasVisible ) {
287 $.suggestions.highlight( context, 'next', true );
288 context.data.selectedWithMouse = false;
289 } else {
290 $.suggestions.update( context, false );
291 }
292 preventDefault = true;
293 break;
294 // Arrow up
295 case 38:
296 if ( wasVisible ) {
297 $.suggestions.highlight( context, 'prev', true );
298 context.data.selectedWithMouse = false;
299 }
300 preventDefault = wasVisible;
301 break;
302 // Escape
303 case 27:
304 context.data.$container.hide();
305 $.suggestions.restore( context );
306 $.suggestions.cancel( context );
307 context.data.$textbox.trigger( 'change' );
308 preventDefault = wasVisible;
309 break;
310 // Enter
311 case 13:
312 context.data.$container.hide();
313 preventDefault = wasVisible;
314 var selected = context.data.$container.find( '.suggestions-result-current' );
315 if ( selected.length === 0 || context.data.selectedWithMouse ) {
316 // if nothing is selected OR if something was selected with the mouse,
317 // cancel any current requests and submit the form
318 $.suggestions.cancel( context );
319 context.config.$region.closest( 'form' ).submit();
320 } else if ( selected.is( '.suggestions-special' ) ) {
321 if ( typeof context.config.special.select === 'function' ) {
322 context.config.special.select.call( selected, context.data.$textbox );
323 }
324 } else {
325 if ( typeof context.config.result.select === 'function' ) {
326 $.suggestions.highlight( context, selected, true );
327 context.config.result.select.call( selected, context.data.$textbox );
328 } else {
329 $.suggestions.highlight( context, selected, true );
330 }
331 }
332 break;
333 default:
334 $.suggestions.update( context, true );
335 break;
336 }
337 if ( preventDefault ) {
338 e.preventDefault();
339 e.stopImmediatePropagation();
340 }
341 }
342 };
343 $.fn.suggestions = function() {
344
345 // Multi-context fields
346 var returnValue = null;
347 var args = arguments;
348
349 $(this).each( function() {
350
351 /* Construction / Loading */
352
353 var context = $(this).data( 'suggestions-context' );
354 if ( context === undefined || context === null ) {
355 context = {
356 config: {
357 'fetch' : function() {},
358 'cancel': function() {},
359 'special': {},
360 'result': {},
361 '$region': $(this),
362 'suggestions': [],
363 'maxRows': 7,
364 'delay': 120,
365 'submitOnClick': false,
366 'maxExpandFactor': 3,
367 'positionFromLeft': true,
368 'highlightInput': false
369 }
370 };
371 }
372
373 /* API */
374
375 // Handle various calling styles
376 if ( args.length > 0 ) {
377 if ( typeof args[0] === 'object' ) {
378 // Apply set of properties
379 for ( var key in args[0] ) {
380 $.suggestions.configure( context, key, args[0][key] );
381 }
382 } else if ( typeof args[0] === 'string' ) {
383 if ( args.length > 1 ) {
384 // Set property values
385 $.suggestions.configure( context, args[0], args[1] );
386 } else if ( returnValue == null ) {
387 // Get property values, but don't give access to internal data - returns only the first
388 returnValue = ( args[0] in context.config ? undefined : context.config[args[0]] );
389 }
390 }
391 }
392
393 /* Initialization */
394
395 if ( context.data === undefined ) {
396 context.data = {
397 // ID of running timer
398 'timerID': null,
399 // Text in textbox when suggestions were last fetched
400 'prevText': null,
401 // Number of results visible without scrolling
402 'visibleResults': 0,
403 // Suggestion the last mousedown event occured on
404 'mouseDownOn': $( [] ),
405 '$textbox': $(this),
406 'selectedWithMouse': false
407 };
408 // Setup the css for positioning the results box
409 var newCSS = {
410 top: Math.round( context.data.$textbox.offset().top + context.data.$textbox.outerHeight() ),
411 width: context.data.$textbox.outerWidth(),
412 display: 'none'
413 };
414 if ( context.config.positionFromLeft ) {
415 newCSS.left = context.config.$region.offset().left;
416 newCSS.right = 'auto';
417 } else {
418 newCSS.left = 'auto';
419 newCSS.right = $( 'body' ).width() - ( context.config.$region.offset().left + context.config.$region.outerWidth() );
420 }
421
422 context.data.$container = $( '<div>' )
423 .css( newCSS )
424 .addClass( 'suggestions' )
425 .append(
426 $( '<div>' ).addClass( 'suggestions-results' )
427 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
428 // listen for a mousedown followed by a mouseup on the same div
429 .mousedown( function( e ) {
430 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results div' );
431 } )
432 .mouseup( function( e ) {
433 var $result = $( e.target ).closest( '.suggestions-results div' );
434 var $other = context.data.mouseDownOn;
435 context.data.mouseDownOn = $( [] );
436 if ( $result.get( 0 ) != $other.get( 0 ) ) {
437 return;
438 }
439 $.suggestions.highlight( context, $result, true );
440 context.data.$container.hide();
441 if ( typeof context.config.result.select === 'function' ) {
442 context.config.result.select.call( $result, context.data.$textbox );
443 }
444 context.data.$textbox.focus();
445 } )
446 )
447 .append(
448 $( '<div>' ).addClass( 'suggestions-special' )
449 // Can't use click() because the container div is hidden when the textbox loses focus. Instead,
450 // listen for a mousedown followed by a mouseup on the same div
451 .mousedown( function( e ) {
452 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
453 } )
454 .mouseup( function( e ) {
455 var $special = $( e.target ).closest( '.suggestions-special' );
456 var $other = context.data.mouseDownOn;
457 context.data.mouseDownOn = $( [] );
458 if ( $special.get( 0 ) != $other.get( 0 ) ) {
459 return;
460 }
461 context.data.$container.hide();
462 if ( typeof context.config.special.select === 'function' ) {
463 context.config.special.select.call( $special, context.data.$textbox );
464 }
465 context.data.$textbox.focus();
466 } )
467 .mousemove( function( e ) {
468 context.data.selectedWithMouse = true;
469 $.suggestions.highlight(
470 context, $( e.target ).closest( '.suggestions-special' ), false
471 );
472 } )
473 )
474 .appendTo( $( 'body' ) );
475 $(this)
476 // Stop browser autocomplete from interfering
477 .attr( 'autocomplete', 'off')
478 .keydown( function( e ) {
479 // Store key pressed to handle later
480 context.data.keypressed = ( e.keyCode === undefined ) ? e.which : e.keyCode;
481 context.data.keypressedCount = 0;
482
483 switch ( context.data.keypressed ) {
484 // This preventDefault logic is duplicated from
485 // $.suggestions.keypress(), which sucks
486 case 40:
487 e.preventDefault();
488 e.stopImmediatePropagation();
489 break;
490 case 38:
491 case 27:
492 case 13:
493 if ( context.data.$container.is( ':visible' ) ) {
494 e.preventDefault();
495 e.stopImmediatePropagation();
496 }
497 }
498 } )
499 .keypress( function( e ) {
500 context.data.keypressedCount++;
501 $.suggestions.keypress( e, context, context.data.keypressed );
502 } )
503 .keyup( function( e ) {
504 // Some browsers won't throw keypress() for arrow keys. If we got a keydown and a keyup without a
505 // keypress in between, solve it
506 if ( context.data.keypressedCount === 0 ) {
507 $.suggestions.keypress( e, context, context.data.keypressed );
508 }
509 } )
510 .blur( function() {
511 // When losing focus because of a mousedown
512 // on a suggestion, don't hide the suggestions
513 if ( context.data.mouseDownOn.length > 0 ) {
514 return;
515 }
516 context.data.$container.hide();
517 $.suggestions.cancel( context );
518 } );
519 }
520 // Store the context for next time
521 $(this).data( 'suggestions-context', context );
522 } );
523 return returnValue !== null ? returnValue : $(this);
524 };
525 } )( jQuery );