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