Update list item newline handling to follow Parsoid's model
[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, $spanForWidth, 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 = $( 'body' ).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 (new width is only calculated here, applied later).
270 // We need this awful hack to calculate the actual pre-ellipsis width.
271 $spanForWidth = $result.wrapInner( '<span>' ).children();
272 childrenWidth = $spanForWidth.outerWidth();
273 $spanForWidth.contents().unwrap();
274 if ( childrenWidth > $result.width() && childrenWidth > expWidth ) {
275 // factor in any padding, margin, or border space on the parent
276 expWidth = childrenWidth + ( context.data.$container.width() - $result.width() );
277 }
278 }
279
280 // Apply new width for results box, if any
281 if ( expWidth > context.data.$container.width() ) {
282 maxWidth = context.config.maxExpandFactor * context.data.$textbox.width();
283 context.data.$container.width( Math.min( expWidth, maxWidth ) );
284 }
285 }
286 }
287 break;
288 case 'maxRows':
289 context.config[property] = Math.max( 1, Math.min( 100, value ) );
290 break;
291 case 'delay':
292 context.config[property] = Math.max( 0, Math.min( 1200, value ) );
293 break;
294 case 'maxExpandFactor':
295 context.config[property] = Math.max( 1, value );
296 break;
297 case 'submitOnClick':
298 case 'positionFromLeft':
299 case 'highlightInput':
300 context.config[property] = value ? true : false;
301 break;
302 }
303 },
304
305 /**
306 * Highlight a result in the results table
307 * @param result <tr> to highlight: jQuery object, or 'prev' or 'next'
308 * @param updateTextbox If true, put the suggestion in the textbox
309 */
310 highlight: function ( context, result, updateTextbox ) {
311 var selected = context.data.$container.find( '.suggestions-result-current' );
312 if ( !result.get || selected.get( 0 ) !== result.get( 0 ) ) {
313 if ( result === 'prev' ) {
314 if ( selected.hasClass( 'suggestions-special' ) ) {
315 result = context.data.$container.find( '.suggestions-result:last' );
316 } else {
317 result = selected.prev();
318 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
319 // there is something in the DOM between selected element and the wrapper, bypass it
320 result = selected.parents( '.suggestions-results > *' ).prev().find( '.suggestions-result' ).eq( 0 );
321 }
322
323 if ( selected.length === 0 ) {
324 // we are at the beginning, so lets jump to the last item
325 if ( context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
326 result = context.data.$container.find( '.suggestions-special' );
327 } else {
328 result = context.data.$container.find( '.suggestions-results .suggestions-result:last' );
329 }
330 }
331 }
332 } else if ( result === 'next' ) {
333 if ( selected.length === 0 ) {
334 // No item selected, go to the first one
335 result = context.data.$container.find( '.suggestions-results .suggestions-result:first' );
336 if ( result.length === 0 && context.data.$container.find( '.suggestions-special' ).html() !== '' ) {
337 // No suggestion exists, go to the special one directly
338 result = context.data.$container.find( '.suggestions-special' );
339 }
340 } else {
341 result = selected.next();
342 if ( !( result.length && result.hasClass( 'suggestions-result' ) ) ) {
343 // there is something in the DOM between selected element and the wrapper, bypass it
344 result = selected.parents( '.suggestions-results > *' ).next().find( '.suggestions-result' ).eq( 0 );
345 }
346
347 if ( selected.hasClass( 'suggestions-special' ) ) {
348 result = $( [] );
349 } else if (
350 result.length === 0 &&
351 context.data.$container.find( '.suggestions-special' ).html() !== ''
352 ) {
353 // We were at the last item, jump to the specials!
354 result = context.data.$container.find( '.suggestions-special' );
355 }
356 }
357 }
358 selected.removeClass( 'suggestions-result-current' );
359 result.addClass( 'suggestions-result-current' );
360 }
361 if ( updateTextbox ) {
362 if ( result.length === 0 || result.is( '.suggestions-special' ) ) {
363 $.suggestions.restore( context );
364 } else {
365 context.data.$textbox.val( result.data( 'text' ) );
366 // .val() doesn't call any event handlers, so
367 // let the world know what happened
368 context.data.$textbox.change();
369 }
370 context.data.$textbox.trigger( 'change' );
371 }
372 },
373
374 /**
375 * Respond to keypress event
376 * @param key Integer Code of key pressed
377 */
378 keypress: function ( e, context, key ) {
379 var selected,
380 wasVisible = context.data.$container.is( ':visible' ),
381 preventDefault = false;
382
383 switch ( key ) {
384 // Arrow down
385 case 40:
386 if ( wasVisible ) {
387 $.suggestions.highlight( context, 'next', true );
388 context.data.selectedWithMouse = false;
389 } else {
390 $.suggestions.update( context, false );
391 }
392 preventDefault = true;
393 break;
394 // Arrow up
395 case 38:
396 if ( wasVisible ) {
397 $.suggestions.highlight( context, 'prev', true );
398 context.data.selectedWithMouse = false;
399 }
400 preventDefault = wasVisible;
401 break;
402 // Escape
403 case 27:
404 $.suggestions.hide( context );
405 $.suggestions.restore( context );
406 $.suggestions.cancel( context );
407 context.data.$textbox.trigger( 'change' );
408 preventDefault = wasVisible;
409 break;
410 // Enter
411 case 13:
412 preventDefault = wasVisible;
413 selected = context.data.$container.find( '.suggestions-result-current' );
414 $.suggestions.hide( context );
415 if ( selected.length === 0 || context.data.selectedWithMouse ) {
416 // If nothing is selected or if something was selected with the mouse
417 // cancel any current requests and allow the form to be submitted
418 // (simply don't prevent default behavior).
419 $.suggestions.cancel( context );
420 preventDefault = false;
421 } else if ( selected.is( '.suggestions-special' ) ) {
422 if ( typeof context.config.special.select === 'function' ) {
423 // Allow the callback to decide whether to prevent default or not
424 if ( context.config.special.select.call( selected, context.data.$textbox ) === true ) {
425 preventDefault = false;
426 }
427 }
428 } else {
429 $.suggestions.highlight( context, selected, true );
430
431 if ( typeof context.config.result.select === 'function' ) {
432 // Allow the callback to decide whether to prevent default or not
433 if ( context.config.result.select.call( selected, context.data.$textbox ) === true ) {
434 preventDefault = false;
435 }
436 }
437 }
438 break;
439 default:
440 $.suggestions.update( context, true );
441 break;
442 }
443 if ( preventDefault ) {
444 e.preventDefault();
445 e.stopPropagation();
446 }
447 }
448 };
449 $.fn.suggestions = function () {
450
451 // Multi-context fields
452 var returnValue,
453 args = arguments;
454
455 $( this ).each( function () {
456 var context, key;
457
458 /* Construction / Loading */
459
460 context = $( this ).data( 'suggestions-context' );
461 if ( context === undefined || context === null ) {
462 context = {
463 config: {
464 fetch: function () {},
465 cancel: function () {},
466 special: {},
467 result: {},
468 $region: $( this ),
469 suggestions: [],
470 maxRows: 7,
471 delay: 120,
472 submitOnClick: false,
473 maxExpandFactor: 3,
474 expandFrom: 'auto',
475 highlightInput: false
476 }
477 };
478 }
479
480 /* API */
481
482 // Handle various calling styles
483 if ( args.length > 0 ) {
484 if ( typeof args[0] === 'object' ) {
485 // Apply set of properties
486 for ( key in args[0] ) {
487 $.suggestions.configure( context, key, args[0][key] );
488 }
489 } else if ( typeof args[0] === 'string' ) {
490 if ( args.length > 1 ) {
491 // Set property values
492 $.suggestions.configure( context, args[0], args[1] );
493 } else if ( returnValue === null || returnValue === undefined ) {
494 // Get property values, but don't give access to internal data - returns only the first
495 returnValue = ( args[0] in context.config ? undefined : context.config[args[0]] );
496 }
497 }
498 }
499
500 /* Initialization */
501
502 if ( context.data === undefined ) {
503 context.data = {
504 // ID of running timer
505 timerID: null,
506
507 // Text in textbox when suggestions were last fetched
508 prevText: null,
509
510 // Number of results visible without scrolling
511 visibleResults: 0,
512
513 // Suggestion the last mousedown event occurred on
514 mouseDownOn: $( [] ),
515 $textbox: $( this ),
516 selectedWithMouse: false
517 };
518
519 context.data.$container = $( '<div>' )
520 .css( 'display', 'none' )
521 .addClass( 'suggestions' )
522 .append(
523 $( '<div>' ).addClass( 'suggestions-results' )
524 // Can't use click() because the container div is hidden when the
525 // textbox loses focus. Instead, listen for a mousedown followed
526 // by a mouseup on the same div.
527 .mousedown( function ( e ) {
528 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-results .suggestions-result' );
529 } )
530 .mouseup( function ( e ) {
531 var $result = $( e.target ).closest( '.suggestions-results .suggestions-result' ),
532 $other = context.data.mouseDownOn;
533
534 context.data.mouseDownOn = $( [] );
535 if ( $result.get( 0 ) !== $other.get( 0 ) ) {
536 return;
537 }
538 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
539 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
540 $.suggestions.highlight( context, $result, true );
541 if ( typeof context.config.result.select === 'function' ) {
542 context.config.result.select.call( $result, context.data.$textbox );
543 }
544 // This will hide the link we're just clicking on, which causes problems
545 // when done synchronously in at least Firefox 3.6 (bug 62858).
546 setTimeout( function () {
547 $.suggestions.hide( context );
548 }, 0 );
549 }
550 // Always bring focus to the textbox, as that's probably where the user expects it
551 // if they were just typing.
552 context.data.$textbox.focus();
553 } )
554 )
555 .append(
556 $( '<div>' ).addClass( 'suggestions-special' )
557 // Can't use click() because the container div is hidden when the
558 // textbox loses focus. Instead, listen for a mousedown followed
559 // by a mouseup on the same div.
560 .mousedown( function ( e ) {
561 context.data.mouseDownOn = $( e.target ).closest( '.suggestions-special' );
562 } )
563 .mouseup( function ( e ) {
564 var $special = $( e.target ).closest( '.suggestions-special' ),
565 $other = context.data.mouseDownOn;
566
567 context.data.mouseDownOn = $( [] );
568 if ( $special.get( 0 ) !== $other.get( 0 ) ) {
569 return;
570 }
571 // Do not interfere with non-left clicks or if modifier keys are pressed (e.g. ctrl-click).
572 if ( !( e.which !== 1 || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) ) {
573 if ( typeof context.config.special.select === 'function' ) {
574 context.config.special.select.call( $special, context.data.$textbox );
575 }
576 // This will hide the link we're just clicking on, which causes problems
577 // when done synchronously in at least Firefox 3.6 (bug 62858).
578 setTimeout( function () {
579 $.suggestions.hide( context );
580 }, 0 );
581 }
582 // Always bring focus to the textbox, as that's probably where the user expects it
583 // if they were just typing.
584 context.data.$textbox.focus();
585 } )
586 .mousemove( function ( e ) {
587 context.data.selectedWithMouse = true;
588 $.suggestions.highlight(
589 context, $( e.target ).closest( '.suggestions-special' ), false
590 );
591 } )
592 )
593 .appendTo( $( 'body' ) );
594
595 $( this )
596 // Stop browser autocomplete from interfering
597 .attr( 'autocomplete', 'off' )
598 .keydown( function ( e ) {
599 // Store key pressed to handle later
600 context.data.keypressed = e.which;
601 context.data.keypressedCount = 0;
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 $.suggestions.hide( context );
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 ) );