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