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