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