Add disabled <datalist> support to mwsuggest
[lhc/web/wiklou.git] / skins / common / mwsuggest.js
1 /*
2 * OpenSearch ajax suggestion engine for MediaWiki
3 *
4 * uses core MediaWiki open search support to fetch suggestions
5 * and show them below search boxes and other inputs
6 *
7 * by Robert Stojnic (April 2008)
8 */
9
10 // search_box_id -> Results object
11 var os_map = {};
12 // cached data, url -> json_text
13 var os_cache = {};
14 // global variables for suggest_keypress
15 var os_cur_keypressed = 0;
16 var os_keypressed_count = 0;
17 // type: Timer
18 var os_timer = null;
19 // tie mousedown/up events
20 var os_mouse_pressed = false;
21 var os_mouse_num = -1;
22 // if true, the last change was made by mouse (and not keyboard)
23 var os_mouse_moved = false;
24 // delay between keypress and suggestion (in ms)
25 var os_search_timeout = 250;
26 // these pairs of inputs/forms will be autoloaded at startup
27 var os_autoload_inputs = new Array('searchInput', 'searchInput2', 'powerSearchText', 'searchText');
28 var os_autoload_forms = new Array('searchform', 'searchform2', 'powersearch', 'search' );
29 // if we stopped the service
30 var os_is_stopped = false;
31 // max lines to show in suggest table
32 var os_max_lines_per_suggest = 7;
33 // number of steps to animate expansion/contraction of container width
34 var os_animation_steps = 6;
35 // num of pixels of smallest step
36 var os_animation_min_step = 2;
37 // delay between steps (in ms)
38 var os_animation_delay = 30;
39 // max width of container in percent of normal size (1 == 100%)
40 var os_container_max_width = 2;
41 // currently active animation timer
42 var os_animation_timer = null;
43 /**
44 * <datalist> is a new HTML5 element that allows you to manually supply
45 * suggestion lists and have them rendered according to the right platform
46 * conventions. However, the only shipping browser as of early 2010 is Opera,
47 * and that has a fatal problem: the suggestion lags behind what the user types
48 * by one keypress. (Reported as DSK-276870 to Opera's secret bug tracker.)
49 * The code here otherwise seems to work, though, so this can be flipped on
50 * (maybe with a UA check) when some browser has a better implementation.
51 */
52 // var os_use_datalist = 'list' in document.createElement( 'input' );
53 var os_use_datalist = false;
54
55 /** Timeout timer class that will fetch the results */
56 function os_Timer( id, r, query ) {
57 this.id = id;
58 this.r = r;
59 this.query = query;
60 }
61
62 /** Property class for single search box */
63 function os_Results( name, formname ) {
64 this.searchform = formname; // id of the searchform
65 this.searchbox = name; // id of the searchbox
66 this.container = name + 'Suggest'; // div that holds results
67 this.resultTable = name + 'Result'; // id base for the result table (+num = table row)
68 this.resultText = name + 'ResultText'; // id base for the spans within result tables (+num)
69 this.toggle = name + 'Toggle'; // div that has the toggle (enable/disable) link
70 this.query = null; // last processed query
71 this.results = null; // parsed titles
72 this.resultCount = 0; // number of results
73 this.original = null; // query that user entered
74 this.selected = -1; // which result is selected
75 this.containerCount = 0; // number of results visible in container
76 this.containerRow = 0; // height of result field in the container
77 this.containerTotal = 0; // total height of the container will all results
78 this.visible = false; // if container is visible
79 this.stayHidden = false; // don't try to show if lost focus
80 }
81
82 /** Timer user to animate expansion/contraction of container width */
83 function os_AnimationTimer( r, target ) {
84 this.r = r;
85 var current = document.getElementById(r.container).offsetWidth;
86 this.inc = Math.round( ( target - current ) / os_animation_steps );
87 if( this.inc < os_animation_min_step && this.inc >=0 ) {
88 this.inc = os_animation_min_step; // minimal animation step
89 }
90 if( this.inc > -os_animation_min_step && this.inc < 0 ) {
91 this.inc = -os_animation_min_step;
92 }
93 this.target = target;
94 }
95
96 /******************
97 * Initialization
98 ******************/
99
100 /** Initialization, call upon page onload */
101 function os_MWSuggestInit() {
102 for( i = 0; i < os_autoload_inputs.length; i++ ) {
103 var id = os_autoload_inputs[i];
104 var form = os_autoload_forms[i];
105 element = document.getElementById( id );
106 if( element != null ) {
107 os_initHandlers( id, form, element );
108 }
109 }
110 }
111
112 /** Init Result objects and event handlers */
113 function os_initHandlers( name, formname, element ) {
114 var r = new os_Results( name, formname );
115 // event handler
116 os_hookEvent( element, 'keyup', function( event ) { os_eventKeyup( event ); } );
117 os_hookEvent( element, 'keydown', function( event ) { os_eventKeydown( event ); } );
118 os_hookEvent( element, 'keypress', function( event ) { os_eventKeypress( event ); } );
119 if ( !os_use_datalist ) {
120 // These are needed for the div hack to hide it if the user blurs.
121 os_hookEvent( element, 'blur', function( event ) { os_eventBlur( event ); } );
122 os_hookEvent( element, 'focus', function( event ) { os_eventFocus( event ); } );
123 // We don't want browser auto-suggestions interfering with our div, but
124 // autocomplete must be on for datalist to work (at least in Opera
125 // 10.10).
126 element.setAttribute( 'autocomplete', 'off' );
127 }
128 // stopping handler
129 os_hookEvent( document.getElementById( formname ), 'submit', function( event ) { return os_eventOnsubmit( event ); } );
130 os_map[name] = r;
131 // toggle link
132 if( document.getElementById( r.toggle ) == null ) {
133 // TODO: disable this while we figure out a way for this to work in all browsers
134 /* if( name == 'searchInput' ) {
135 // special case: place above the main search box
136 var t = os_createToggle( r, 'os-suggest-toggle' );
137 var searchBody = document.getElementById( 'searchBody' );
138 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
139 } else {
140 // default: place below search box to the right
141 var t = os_createToggle( r, 'os-suggest-toggle-def' );
142 var top = element.offsetTop + element.offsetHeight;
143 var left = element.offsetLeft + element.offsetWidth;
144 t.style.position = 'absolute';
145 t.style.top = top + 'px';
146 t.style.left = left + 'px';
147 element.parentNode.appendChild( t );
148 // only now width gets calculated, shift right
149 left -= t.offsetWidth;
150 t.style.left = left + 'px';
151 t.style.visibility = 'visible';
152 } */
153 }
154
155 }
156
157 function os_hookEvent( element, hookName, hookFunct ) {
158 if ( element.addEventListener ) {
159 element.addEventListener( hookName, hookFunct, false );
160 } else if ( window.attachEvent ) {
161 element.attachEvent( 'on' + hookName, hookFunct );
162 }
163 }
164
165 /********************
166 * Keyboard events
167 ********************/
168
169 /** Event handler that will fetch results on keyup */
170 function os_eventKeyup( e ) {
171 var targ = os_getTarget( e );
172 var r = os_map[targ.id];
173 if( r == null ) {
174 return; // not our event
175 }
176
177 // some browsers won't generate keypressed for arrow keys, catch it
178 if( os_keypressed_count == 0 ) {
179 os_processKey( r, os_cur_keypressed, targ );
180 }
181 var query = targ.value;
182 os_fetchResults( r, query, os_search_timeout );
183 }
184
185 /** catch arrows up/down and escape to hide the suggestions */
186 function os_processKey( r, keypressed, targ ) {
187 if ( keypressed == 40 && !r.visible && os_timer == null ) {
188 // If the user hits the down arrow, fetch results immediately if none
189 // are already displayed.
190 r.query = '';
191 os_fetchResults( r, targ.value, 0 );
192 }
193 // Otherwise, if we're not using datalist, we need to handle scrolling and
194 // so on.
195 if ( os_use_datalist ) {
196 return;
197 }
198 if ( keypressed == 40 ) { // Arrow Down
199 if ( r.visible ) {
200 os_changeHighlight( r, r.selected, r.selected + 1, true );
201 }
202 } else if ( keypressed == 38 ) { // Arrow Up
203 if ( r.visible ) {
204 os_changeHighlight( r, r.selected, r.selected - 1, true );
205 }
206 } else if( keypressed == 27 ) { // Escape
207 document.getElementById( r.searchbox ).value = r.original;
208 r.query = r.original;
209 os_hideResults( r );
210 } else if( r.query != document.getElementById( r.searchbox ).value ) {
211 // os_hideResults( r ); // don't show old suggestions
212 }
213 }
214
215 /** When keys is held down use a timer to output regular events */
216 function os_eventKeypress( e ) {
217 var targ = os_getTarget( e );
218 var r = os_map[targ.id];
219 if( r == null ) {
220 return; // not our event
221 }
222
223 var keypressed = os_cur_keypressed;
224
225 os_keypressed_count++;
226 os_processKey( r, keypressed, targ );
227 }
228
229 /** Catch the key code (Firefox bug) */
230 function os_eventKeydown( e ) {
231 if ( !e ) {
232 e = window.event;
233 }
234 var targ = os_getTarget( e );
235 var r = os_map[targ.id];
236 if( r == null ) {
237 return; // not our event
238 }
239
240 os_mouse_moved = false;
241
242 os_cur_keypressed = ( e.keyCode == undefined ) ? e.which : e.keyCode;
243 os_keypressed_count = 0;
244 }
245
246
247 /** When the form is submitted hide everything, cancel updates... */
248 function os_eventOnsubmit( e ) {
249 var targ = os_getTarget( e );
250
251 os_is_stopped = true;
252 // kill timed requests
253 if( os_timer != null && os_timer.id != null ) {
254 clearTimeout( os_timer.id );
255 os_timer = null;
256 }
257 // Hide all suggestions
258 for( i = 0; i < os_autoload_inputs.length; i++ ) {
259 var r = os_map[os_autoload_inputs[i]];
260 if( r != null ) {
261 var b = document.getElementById( r.searchform );
262 if( b != null && b == targ ) {
263 // set query value so the handler won't try to fetch additional results
264 r.query = document.getElementById( r.searchbox ).value;
265 }
266 os_hideResults( r );
267 }
268 }
269 return true;
270 }
271
272
273
274 /** Hide results from the user, either making the div visibility=hidden or
275 * detaching the datalist from the input. */
276 function os_hideResults( r ) {
277 if ( os_use_datalist ) {
278 document.getElementById( r.searchbox ).setAttribute( 'list', '' );
279 } else {
280 var c = document.getElementById( r.container );
281 if ( c != null ) {
282 c.style.visibility = 'hidden';
283 }
284 }
285 r.visible = false;
286 r.selected = -1;
287 }
288
289 function os_decodeValue( value ) {
290 if ( decodeURIComponent ) {
291 return decodeURIComponent( value );
292 }
293 if( unescape ) {
294 return unescape( value );
295 }
296 return null;
297 }
298
299 function os_encodeQuery( value ) {
300 if ( encodeURIComponent ) {
301 return encodeURIComponent( value );
302 }
303 if( escape ) {
304 return escape( value );
305 }
306 return null;
307 }
308
309 /** Handles data from XMLHttpRequest, and updates the suggest results */
310 function os_updateResults( r, query, text, cacheKey ) {
311 os_cache[cacheKey] = text;
312 r.query = query;
313 r.original = query;
314 if( text == '' ) {
315 r.results = null;
316 r.resultCount = 0;
317 os_hideResults( r );
318 } else {
319 try {
320 var p = eval( '(' + text + ')' ); // simple json parse, could do a safer one
321 if( p.length < 2 || p[1].length == 0 ) {
322 r.results = null;
323 r.resultCount = 0;
324 os_hideResults( r );
325 return;
326 }
327 if ( os_use_datalist ) {
328 os_setupDatalist( r, p[1] );
329 } else {
330 os_setupDiv( r, p[1] );
331 }
332 } catch( e ) {
333 // bad response from server or such
334 os_hideResults( r );
335 os_cache[cacheKey] = null;
336 }
337 }
338 }
339
340 /**
341 * Create and populate a <datalist>.
342 *
343 * @param r os_Result object
344 * @param results Array of the new results to replace existing ones
345 */
346 function os_setupDatalist( r, results ) {
347 var s = document.getElementById( r.searchbox );
348 var c = document.getElementById( r.container );
349 if ( c == null ) {
350 c = document.createElement( 'datalist' );
351 c.setAttribute( 'id', r.container );
352 document.body.appendChild( c );
353 } else {
354 c.innerHTML = '';
355 }
356 s.setAttribute( 'list', r.container );
357
358 r.results = new Array();
359 r.resultCount = results.length;
360 r.visible = true;
361 for ( i = 0; i < results.length; i++ ) {
362 var title = os_decodeValue( results[i] );
363 var opt = document.createElement( 'option' );
364 opt.value = title;
365 r.results[i] = title;
366 c.appendChild( opt );
367 }
368 }
369
370 /** Fetch namespaces from checkboxes or hidden fields in the search form,
371 if none defined use wgSearchNamespaces global */
372 function os_getNamespaces( r ) {
373 var namespaces = '';
374 var elements = document.forms[r.searchform].elements;
375 for( i = 0; i < elements.length; i++ ) {
376 var name = elements[i].name;
377 if( typeof name != 'undefined' && name.length > 2 && name[0] == 'n' &&
378 name[1] == 's' && (
379 ( elements[i].type == 'checkbox' && elements[i].checked ) ||
380 ( elements[i].type == 'hidden' && elements[i].value == '1' )
381 )
382 ) {
383 if( namespaces != '' ) {
384 namespaces += '|';
385 }
386 namespaces += name.substring( 2 );
387 }
388 }
389 if( namespaces == '' ) {
390 namespaces = wgSearchNamespaces.join('|');
391 }
392 return namespaces;
393 }
394
395 /** Update results if user hasn't already typed something else */
396 function os_updateIfRelevant( r, query, text, cacheKey ) {
397 var t = document.getElementById( r.searchbox );
398 if( t != null && t.value == query ) { // check if response is still relevant
399 os_updateResults( r, query, text, cacheKey );
400 }
401 r.query = query;
402 }
403
404 /** Fetch results after some timeout */
405 function os_delayedFetch() {
406 if( os_timer == null ) {
407 return;
408 }
409 var r = os_timer.r;
410 var query = os_timer.query;
411 os_timer = null;
412 var path = wgMWSuggestTemplate.replace( "{namespaces}", os_getNamespaces( r ) )
413 .replace( "{dbname}", wgDBname )
414 .replace( "{searchTerms}", os_encodeQuery( query ) );
415
416 // try to get from cache, if not fetch using ajax
417 var cached = os_cache[path];
418 if( cached != null && cached != undefined ) {
419 os_updateIfRelevant( r, query, cached, path );
420 } else {
421 var xmlhttp = sajax_init_object();
422 if( xmlhttp ) {
423 try {
424 xmlhttp.open( 'GET', path, true );
425 xmlhttp.onreadystatechange = function() {
426 if ( xmlhttp.readyState == 4 && typeof os_updateIfRelevant == 'function' ) {
427 os_updateIfRelevant( r, query, xmlhttp.responseText, path );
428 }
429 };
430 xmlhttp.send( null );
431 } catch ( e ) {
432 if ( window.location.hostname == 'localhost' ) {
433 alert( "Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing." );
434 }
435 throw e;
436 }
437 }
438 }
439 }
440
441 /** Init timed update via os_delayedUpdate() */
442 function os_fetchResults( r, query, timeout ) {
443 if( query == '' ) {
444 r.query = '';
445 os_hideResults( r );
446 return;
447 } else if( query == r.query ) {
448 return; // no change
449 }
450
451 os_is_stopped = false; // make sure we're running
452
453 // cancel any pending fetches
454 if( os_timer != null && os_timer.id != null ) {
455 clearTimeout( os_timer.id );
456 }
457 // schedule delayed fetching of results
458 if( timeout != 0 ) {
459 os_timer = new os_Timer( setTimeout( "os_delayedFetch()", timeout ), r, query );
460 } else {
461 os_timer = new os_Timer( null, r, query );
462 os_delayedFetch(); // do it now!
463 }
464 }
465
466 /** Find event target */
467 function os_getTarget( e ) {
468 if ( !e ) {
469 e = window.event;
470 }
471 if ( e.target ) {
472 return e.target;
473 } else if ( e.srcElement ) {
474 return e.srcElement;
475 } else {
476 return null;
477 }
478 }
479
480 /** Check if x is a valid integer */
481 function os_isNumber( x ) {
482 if( x == '' || isNaN( x ) ) {
483 return false;
484 }
485 for( var i = 0; i < x.length; i++ ) {
486 var c = x.charAt( i );
487 if( !( c >= '0' && c <= '9' ) ) {
488 return false;
489 }
490 }
491 return true;
492 }
493
494 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
495 function os_enableSuggestionsOn( inputId, formName ) {
496 os_initHandlers( inputId, formName, document.getElementById( inputId ) );
497 }
498
499 /** Call this to disable suggestios on input box (id=inputId) */
500 function os_disableSuggestionsOn( inputId ) {
501 r = os_map[inputId];
502 if( r != null ) {
503 // cancel/hide results
504 os_timer = null;
505 os_hideResults( r );
506 // turn autocomplete on !
507 document.getElementById( inputId ).setAttribute( 'autocomplete', 'on' );
508 // remove descriptor
509 os_map[inputId] = null;
510 }
511
512 // Remove the element from the os_autoload_* arrays
513 var index = os_autoload_inputs.indexOf( inputId );
514 if ( index >= 0 ) {
515 os_autoload_inputs[index] = os_autoload_forms[index] = '';
516 }
517 }
518
519 /************************************************
520 * Div-only functions (irrelevant for datalist)
521 ************************************************/
522
523 /** Event: loss of focus of input box */
524 function os_eventBlur( e ) {
525 var targ = os_getTarget( e );
526 var r = os_map[targ.id];
527 if( r == null ) {
528 return; // not our event
529 }
530 if( !os_mouse_pressed ) {
531 os_hideResults( r );
532 // force canvas to stay hidden
533 r.stayHidden = true;
534 // cancel any pending fetches
535 if( os_timer != null && os_timer.id != null ) {
536 clearTimeout( os_timer.id );
537 }
538 os_timer = null;
539 }
540 }
541
542 /** Event: focus (catch only when stopped) */
543 function os_eventFocus( e ) {
544 var targ = os_getTarget( e );
545 var r = os_map[targ.id];
546 if( r == null ) {
547 return; // not our event
548 }
549 r.stayHidden = false;
550 }
551
552 /**
553 * Create and populate a <div>, for non-<datalist>-supporting browsers.
554 *
555 * @param r os_Result object
556 * @param results Array of the new results to replace existing ones
557 */
558 function os_setupDiv( r, results ) {
559 var c = document.getElementById( r.container );
560 if ( c == null ) {
561 c = os_createContainer( r );
562 }
563 c.innerHTML = os_createResultTable( r, results );
564 // init container table sizes
565 var t = document.getElementById( r.resultTable );
566 r.containerTotal = t.offsetHeight;
567 r.containerRow = t.offsetHeight / r.resultCount;
568 os_fitContainer( r );
569 os_trimResultText( r );
570 os_showResults( r );
571 }
572
573 /** Create the result table to be placed in the container div */
574 function os_createResultTable( r, results ) {
575 var c = document.getElementById( r.container );
576 var width = c.offsetWidth - os_operaWidthFix( c.offsetWidth );
577 var html = '<table class="os-suggest-results" id="' + r.resultTable + '" style="width: ' + width + 'px;">';
578 r.results = new Array();
579 r.resultCount = results.length;
580 for( i = 0; i < results.length; i++ ) {
581 var title = os_decodeValue( results[i] );
582 r.results[i] = title;
583 html += '<tr><td class="os-suggest-result" id="' + r.resultTable + i + '"><span id="' + r.resultText + i + '">' + title + '</span></td></tr>';
584 }
585 html += '</table>';
586 return html;
587 }
588
589 /** Show results div */
590 function os_showResults( r ) {
591 if( os_is_stopped ) {
592 return;
593 }
594 if( r.stayHidden ) {
595 return;
596 }
597 os_fitContainer( r );
598 var c = document.getElementById( r.container );
599 r.selected = -1;
600 if( c != null ) {
601 c.scrollTop = 0;
602 c.style.visibility = 'visible';
603 r.visible = true;
604 }
605 }
606
607 function os_operaWidthFix( x ) {
608 // For browsers that don't understand overflow-x, estimate scrollbar width
609 if( typeof document.body.style.overflowX != 'string' ) {
610 return 30;
611 }
612 return 0;
613 }
614
615 /** Brower-dependent functions to find window inner size, and scroll status */
616 function f_clientWidth() {
617 return f_filterResults(
618 window.innerWidth ? window.innerWidth : 0,
619 document.documentElement ? document.documentElement.clientWidth : 0,
620 document.body ? document.body.clientWidth : 0
621 );
622 }
623
624 function f_clientHeight() {
625 return f_filterResults(
626 window.innerHeight ? window.innerHeight : 0,
627 document.documentElement ? document.documentElement.clientHeight : 0,
628 document.body ? document.body.clientHeight : 0
629 );
630 }
631
632 function f_scrollLeft() {
633 return f_filterResults(
634 window.pageXOffset ? window.pageXOffset : 0,
635 document.documentElement ? document.documentElement.scrollLeft : 0,
636 document.body ? document.body.scrollLeft : 0
637 );
638 }
639
640 function f_scrollTop() {
641 return f_filterResults(
642 window.pageYOffset ? window.pageYOffset : 0,
643 document.documentElement ? document.documentElement.scrollTop : 0,
644 document.body ? document.body.scrollTop : 0
645 );
646 }
647
648 function f_filterResults( n_win, n_docel, n_body ) {
649 var n_result = n_win ? n_win : 0;
650 if ( n_docel && ( !n_result || ( n_result > n_docel ) ) ) {
651 n_result = n_docel;
652 }
653 return n_body && ( !n_result || ( n_result > n_body ) ) ? n_body : n_result;
654 }
655
656 /** Get the height available for the results container */
657 function os_availableHeight( r ) {
658 var absTop = document.getElementById( r.container ).style.top;
659 var px = absTop.lastIndexOf( 'px' );
660 if( px > 0 ) {
661 absTop = absTop.substring( 0, px );
662 }
663 return f_clientHeight() - ( absTop - f_scrollTop() );
664 }
665
666 /** Get element absolute position {left,top} */
667 function os_getElementPosition( elemID ) {
668 var offsetTrail = document.getElementById( elemID );
669 var offsetLeft = 0;
670 var offsetTop = 0;
671 while ( offsetTrail ) {
672 offsetLeft += offsetTrail.offsetLeft;
673 offsetTop += offsetTrail.offsetTop;
674 offsetTrail = offsetTrail.offsetParent;
675 }
676 if ( navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined' ) {
677 offsetLeft += document.body.leftMargin;
678 offsetTop += document.body.topMargin;
679 }
680 return { left:offsetLeft, top:offsetTop };
681 }
682
683 /** Create the container div that will hold the suggested titles */
684 function os_createContainer( r ) {
685 var c = document.createElement( 'div' );
686 var s = document.getElementById( r.searchbox );
687 var pos = os_getElementPosition( r.searchbox );
688 var left = pos.left;
689 var top = pos.top + s.offsetHeight;
690 c.className = 'os-suggest';
691 c.setAttribute( 'id', r.container );
692 document.body.appendChild( c );
693
694 // dynamically generated style params
695 // IE workaround, cannot explicitely set "style" attribute
696 c = document.getElementById( r.container );
697 c.style.top = top + 'px';
698 c.style.left = left + 'px';
699 c.style.width = s.offsetWidth + 'px';
700
701 // mouse event handlers
702 c.onmouseover = function( event ) { os_eventMouseover( r.searchbox, event ); };
703 c.onmousemove = function( event ) { os_eventMousemove( r.searchbox, event ); };
704 c.onmousedown = function( event ) { return os_eventMousedown( r.searchbox, event ); };
705 c.onmouseup = function( event ) { os_eventMouseup( r.searchbox, event ); };
706 return c;
707 }
708
709 /** change container height to fit to screen */
710 function os_fitContainer( r ) {
711 var c = document.getElementById( r.container );
712 var h = os_availableHeight( r ) - 20;
713 var inc = r.containerRow;
714 h = parseInt( h / inc ) * inc;
715 if( h < ( 2 * inc ) && r.resultCount > 1 ) { // min: two results
716 h = 2 * inc;
717 }
718 if( ( h / inc ) > os_max_lines_per_suggest ) {
719 h = inc * os_max_lines_per_suggest;
720 }
721 if( h < r.containerTotal ) {
722 c.style.height = h + 'px';
723 r.containerCount = parseInt( Math.round( h / inc ) );
724 } else {
725 c.style.height = r.containerTotal + 'px';
726 r.containerCount = r.resultCount;
727 }
728 }
729
730 /** If some entries are longer than the box, replace text with "..." */
731 function os_trimResultText( r ) {
732 // find max width, first see if we could expand the container to fit it
733 var maxW = 0;
734 for( var i = 0; i < r.resultCount; i++ ) {
735 var e = document.getElementById( r.resultText + i );
736 if( e.offsetWidth > maxW ) {
737 maxW = e.offsetWidth;
738 }
739 }
740 var w = document.getElementById( r.container ).offsetWidth;
741 var fix = 0;
742 if( r.containerCount < r.resultCount ) {
743 fix = 20; // give 20px for scrollbar
744 } else {
745 fix = os_operaWidthFix( w );
746 }
747 if( fix < 4 ) {
748 fix = 4; // basic padding
749 }
750 maxW += fix;
751
752 // resize container to fit more data if permitted
753 var normW = document.getElementById( r.searchbox ).offsetWidth;
754 var prop = maxW / normW;
755 if( prop > os_container_max_width ) {
756 prop = os_container_max_width;
757 } else if( prop < 1 ) {
758 prop = 1;
759 }
760 var newW = Math.round( normW * prop );
761 if( w != newW ) {
762 w = newW;
763 if( os_animation_timer != null ) {
764 clearInterval( os_animation_timer.id );
765 }
766 os_animation_timer = new os_AnimationTimer( r, w );
767 os_animation_timer.id = setInterval( "os_animateChangeWidth()", os_animation_delay );
768 w -= fix; // this much is reserved
769 }
770
771 // trim results
772 if( w < 10 ) {
773 return;
774 }
775 for( var i = 0; i < r.resultCount; i++ ) {
776 var e = document.getElementById( r.resultText + i );
777 var replace = 1;
778 var lastW = e.offsetWidth + 1;
779 var iteration = 0;
780 var changedText = false;
781 while( e.offsetWidth > w && ( e.offsetWidth < lastW || iteration < 2 ) ) {
782 changedText = true;
783 lastW = e.offsetWidth;
784 var l = e.innerHTML;
785 e.innerHTML = l.substring( 0, l.length - replace ) + '...';
786 iteration++;
787 replace = 4; // how many chars to replace
788 }
789 if( changedText ) {
790 // show hint for trimmed titles
791 document.getElementById( r.resultTable + i ).setAttribute( 'title', r.results[i] );
792 }
793 }
794 }
795
796 /** Invoked on timer to animate change in container width */
797 function os_animateChangeWidth() {
798 var r = os_animation_timer.r;
799 var c = document.getElementById( r.container );
800 var w = c.offsetWidth;
801 var normW = document.getElementById( r.searchbox ).offsetWidth;
802 var normL = os_getElementPosition( r.searchbox ).left;
803 var inc = os_animation_timer.inc;
804 var target = os_animation_timer.target;
805 var nw = w + inc;
806 if( ( inc > 0 && nw >= target ) || ( inc <= 0 && nw <= target ) ) {
807 // finished !
808 c.style.width = target + 'px';
809 clearInterval( os_animation_timer.id );
810 os_animation_timer = null;
811 } else {
812 // in-progress
813 c.style.width = nw + 'px';
814 if( document.documentElement.dir == 'rtl' ) {
815 c.style.left = ( normL + normW + ( target - nw ) - os_animation_timer.target - 1 ) + 'px';
816 }
817 }
818 }
819
820 /** Change the highlighted row (i.e. suggestion), from position cur to next */
821 function os_changeHighlight( r, cur, next, updateSearchBox ) {
822 if ( next >= r.resultCount ) {
823 next = r.resultCount - 1;
824 }
825 if ( next < -1 ) {
826 next = -1;
827 }
828 r.selected = next;
829 if ( cur == next ) {
830 return; // nothing to do.
831 }
832
833 if( cur >= 0 ) {
834 var curRow = document.getElementById( r.resultTable + cur );
835 if( curRow != null ) {
836 curRow.className = 'os-suggest-result';
837 }
838 }
839 var newText;
840 if( next >= 0 ) {
841 var nextRow = document.getElementById( r.resultTable + next );
842 if( nextRow != null ) {
843 nextRow.className = os_HighlightClass();
844 }
845 newText = r.results[next];
846 } else {
847 newText = r.original;
848 }
849
850 // adjust the scrollbar if any
851 if( r.containerCount < r.resultCount ) {
852 var c = document.getElementById( r.container );
853 var vStart = c.scrollTop / r.containerRow;
854 var vEnd = vStart + r.containerCount;
855 if( next < vStart ) {
856 c.scrollTop = next * r.containerRow;
857 } else if( next >= vEnd ) {
858 c.scrollTop = ( next - r.containerCount + 1 ) * r.containerRow;
859 }
860 }
861
862 // update the contents of the search box
863 if( updateSearchBox ) {
864 os_updateSearchQuery( r, newText );
865 }
866 }
867
868 function os_HighlightClass() {
869 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
870 if ( match ) {
871 var webKitVersion = parseInt( match[1] );
872 if ( webKitVersion < 523 ) {
873 // CSS system highlight colors broken on old Safari
874 // https://bugs.webkit.org/show_bug.cgi?id=6129
875 // Safari 3.0.4, 3.1 known ok
876 return 'os-suggest-result-hl-webkit';
877 }
878 }
879 return 'os-suggest-result-hl';
880 }
881
882 function os_updateSearchQuery( r, newText ) {
883 document.getElementById( r.searchbox ).value = newText;
884 r.query = newText;
885 }
886
887
888 /********************
889 * Mouse events
890 ********************/
891
892 /** Mouse over the container */
893 function os_eventMouseover( srcId, e ) {
894 var targ = os_getTarget( e );
895 var r = os_map[srcId];
896 if( r == null || !os_mouse_moved ) {
897 return; // not our event
898 }
899 var num = os_getNumberSuffix( targ.id );
900 if( num >= 0 ) {
901 os_changeHighlight( r, r.selected, num, false );
902 }
903 }
904
905 /* Get row where the event occured (from its id) */
906 function os_getNumberSuffix( id ) {
907 var num = id.substring( id.length - 2 );
908 if( !( num.charAt( 0 ) >= '0' && num.charAt( 0 ) <= '9' ) ) {
909 num = num.substring( 1 );
910 }
911 if( os_isNumber( num ) ) {
912 return parseInt( num );
913 } else {
914 return -1;
915 }
916 }
917
918 /** Save mouse move as last action */
919 function os_eventMousemove( srcId, e ) {
920 os_mouse_moved = true;
921 }
922
923 /** Mouse button held down, register possible click */
924 function os_eventMousedown( srcId, e ) {
925 var targ = os_getTarget( e );
926 var r = os_map[srcId];
927 if( r == null ) {
928 return; // not our event
929 }
930 var num = os_getNumberSuffix( targ.id );
931
932 os_mouse_pressed = true;
933 if( num >= 0 ) {
934 os_mouse_num = num;
935 // os_updateSearchQuery( r, r.results[num] );
936 }
937 // keep the focus on the search field
938 document.getElementById( r.searchbox ).focus();
939
940 return false; // prevents selection
941 }
942
943 /** Mouse button released, check for click on some row */
944 function os_eventMouseup( srcId, e ) {
945 var targ = os_getTarget( e );
946 var r = os_map[srcId];
947 if( r == null ) {
948 return; // not our event
949 }
950 var num = os_getNumberSuffix( targ.id );
951
952 if( num >= 0 && os_mouse_num == num ) {
953 os_updateSearchQuery( r, r.results[num] );
954 os_hideResults( r );
955 document.getElementById( r.searchform ).submit();
956 }
957 os_mouse_pressed = false;
958 // keep the focus on the search field
959 document.getElementById( r.searchbox ).focus();
960 }
961
962 /** Toggle stuff seems to be dead code? */
963
964 /** Return the span element that contains the toggle link */
965 function os_createToggle( r, className ) {
966 var t = document.createElement( 'span' );
967 t.className = className;
968 t.setAttribute( 'id', r.toggle );
969 var link = document.createElement( 'a' );
970 link.setAttribute( 'href', 'javascript:void(0);' );
971 link.onclick = function() { os_toggle( r.searchbox, r.searchform ); };
972 var msg = document.createTextNode( wgMWSuggestMessages[0] );
973 link.appendChild( msg );
974 t.appendChild( link );
975 return t;
976 }
977
978 /** Call when user clicks on some of the toggle links */
979 function os_toggle( inputId, formName ) {
980 r = os_map[inputId];
981 var msg = '';
982 if( r == null ) {
983 os_enableSuggestionsOn( inputId, formName );
984 r = os_map[inputId];
985 msg = wgMWSuggestMessages[0];
986 } else{
987 os_disableSuggestionsOn( inputId, formName );
988 msg = wgMWSuggestMessages[1];
989 }
990 // change message
991 var link = document.getElementById( r.toggle ).firstChild;
992 link.replaceChild( document.createTextNode( msg ), link.firstChild );
993 }
994
995 hookEvent( 'load', os_MWSuggestInit );