2 * OpenSearch ajax suggestion engine for MediaWiki
4 * uses core MediaWiki open search support to fetch suggestions
5 * and show them below search boxes and other inputs
7 * by Robert Stojnic (April 2008)
10 // search_box_id -> Results object
12 // cached data, url -> json_text
14 // global variables for suggest_keypress
15 var os_cur_keypressed
= 0;
16 var os_last_keypress
= 0;
17 var os_keypressed_count
= 0;
20 // tie mousedown/up events
21 var os_mouse_pressed
= false;
22 var os_mouse_num
= -1;
23 // if true, the last change was made by mouse (and not keyboard)
24 var os_mouse_moved
= false;
25 // delay between keypress and suggestion (in ms)
26 var os_search_timeout
= 250;
27 // these pairs of inputs/forms will be autoloaded at startup
28 var os_autoload_inputs
= new Array('searchInput', 'searchInput2', 'powerSearchText', 'searchText');
29 var os_autoload_forms
= new Array('searchform', 'searchform2', 'powersearch', 'search' );
30 // if we stopped the service
31 var os_is_stopped
= false;
32 // max lines to show in suggest table
33 var os_max_lines_per_suggest
= 7;
35 /** Timeout timer class that will fetch the results */
36 function os_Timer(id
,r
,query
){
42 /** Property class for single search box */
43 function os_Results(name
, formname
){
44 this.searchform
= formname
; // id of the searchform
45 this.searchbox
= name
; // id of the searchbox
46 this.container
= name
+"Suggest"; // div that holds results
47 this.resultTable
= name
+"Result"; // id base for the result table (+num = table row)
48 this.resultText
= name
+"ResultText"; // id base for the spans within result tables (+num)
49 this.toggle
= name
+"Toggle"; // div that has the toggle (enable/disable) link
50 this.query
= null; // last processed query
51 this.results
= null; // parsed titles
52 this.resultCount
= 0; // number of results
53 this.original
= null; // query that user entered
54 this.selected
= -1; // which result is selected
55 this.containerCount
= 0; // number of results visible in container
56 this.containerRow
= 0; // height of result field in the container
57 this.containerTotal
= 0; // total height of the container will all results
58 this.visible
= false; // if container is visible
61 /** Hide results div */
62 function os_hideResults(r
){
63 var c
= document
.getElementById(r
.container
);
65 c
.style
.visibility
= "hidden";
70 /** Show results div */
71 function os_showResults(r
){
75 var c
= document
.getElementById(r
.container
);
79 c
.style
.visibility
= "visible";
84 function os_operaWidthFix(x
){
85 // TODO: better css2 incompatibility detection here
86 if(is_opera
|| is_khtml
|| navigator
.userAgent
.toLowerCase().indexOf('firefox/1')!=-1){
87 return x
- 30; // opera&konqueror & old firefox don't understand overflow-x, estimate scrollbar width
92 function os_encodeQuery(value
){
93 if (encodeURIComponent
) {
94 return encodeURIComponent(value
);
100 function os_decodeValue(value
){
101 if (decodeURIComponent
) {
102 return decodeURIComponent(value
);
105 return unescape(value
);
109 /** Brower-dependent functions to find window inner size, and scroll status */
110 function f_clientWidth() {
111 return f_filterResults (
112 window
.innerWidth
? window
.innerWidth
: 0,
113 document
.documentElement
? document
.documentElement
.clientWidth
: 0,
114 document
.body
? document
.body
.clientWidth
: 0
117 function f_clientHeight() {
118 return f_filterResults (
119 window
.innerHeight
? window
.innerHeight
: 0,
120 document
.documentElement
? document
.documentElement
.clientHeight
: 0,
121 document
.body
? document
.body
.clientHeight
: 0
124 function f_scrollLeft() {
125 return f_filterResults (
126 window
.pageXOffset
? window
.pageXOffset
: 0,
127 document
.documentElement
? document
.documentElement
.scrollLeft
: 0,
128 document
.body
? document
.body
.scrollLeft
: 0
131 function f_scrollTop() {
132 return f_filterResults (
133 window
.pageYOffset
? window
.pageYOffset
: 0,
134 document
.documentElement
? document
.documentElement
.scrollTop
: 0,
135 document
.body
? document
.body
.scrollTop
: 0
138 function f_filterResults(n_win
, n_docel
, n_body
) {
139 var n_result
= n_win
? n_win
: 0;
140 if (n_docel
&& (!n_result
|| (n_result
> n_docel
)))
142 return n_body
&& (!n_result
|| (n_result
> n_body
)) ? n_body
: n_result
;
145 /** Get the height available for the results container */
146 function os_availableHeight(r
){
147 var absTop
= document
.getElementById(r
.container
).style
.top
;
148 var px
= absTop
.lastIndexOf("px");
150 absTop
= absTop
.substring(0,px
);
151 return f_clientHeight() - (absTop
- f_scrollTop());
155 /** Get element absolute position {left,top} */
156 function os_getElementPosition(elemID
){
157 var offsetTrail
= document
.getElementById(elemID
);
161 offsetLeft
+= offsetTrail
.offsetLeft
;
162 offsetTop
+= offsetTrail
.offsetTop
;
163 offsetTrail
= offsetTrail
.offsetParent
;
165 if (navigator
.userAgent
.indexOf('Mac') != -1 && typeof document
.body
.leftMargin
!= 'undefined'){
166 offsetLeft
+= document
.body
.leftMargin
;
167 offsetTop
+= document
.body
.topMargin
;
169 return {left
:offsetLeft
,top
:offsetTop
};
172 /** Create the container div that will hold the suggested titles */
173 function os_createContainer(r
){
174 var c
= document
.createElement("div");
175 var s
= document
.getElementById(r
.searchbox
);
176 var pos
= os_getElementPosition(r
.searchbox
);
178 var top
= pos
.top
+ s
.offsetHeight
;
179 c
.className
= "os-suggest";
180 c
.setAttribute("id", r
.container
);
181 document
.body
.appendChild(c
);
183 // dynamically generated style params
184 // IE workaround, cannot explicitely set "style" attribute
185 c
= document
.getElementById(r
.container
);
186 c
.style
.top
= top
+"px";
187 c
.style
.left
= left
+"px";
188 c
.style
.width
= s
.offsetWidth
+"px";
190 // mouse event handlers
191 c
.onmouseover = function(event
) { os_eventMouseover(r
.searchbox
, event
); };
192 c
.onmousemove = function(event
) { os_eventMousemove(r
.searchbox
, event
); };
193 c
.onmousedown = function(event
) { return os_eventMousedown(r
.searchbox
, event
); };
194 c
.onmouseup = function(event
) { os_eventMouseup(r
.searchbox
, event
); };
198 /** change container height to fit to screen */
199 function os_fitContainer(r
){
200 var c
= document
.getElementById(r
.container
);
201 var h
= os_availableHeight(r
) - 20;
202 var inc
= r
.containerRow
;
203 h
= parseInt(h
/inc
) * inc
;
204 if(h
< (2 * inc
) && r
.resultCount
> 1) // min: two results
206 if((h
/inc
) > os_max_lines_per_suggest
)
207 h
= inc
* os_max_lines_per_suggest
;
208 if(h
< r
.containerTotal
){
209 c
.style
.height
= h
+"px";
210 r
.containerCount
= parseInt(Math
.round(h
/inc
));
212 c
.style
.height
= r
.containerTotal
+"px";
213 r
.containerCount
= r
.resultCount
;
216 /** If some entries are longer than the box, replace text with "..." */
217 function os_trimResultText(r
){
218 var w
= document
.getElementById(r
.container
).offsetWidth
;
219 if(r
.containerCount
< r
.resultCount
){
220 w
-= 20; // give 20px for scrollbar
222 w
= os_operaWidthFix(w
);
225 for(var i
=0;i
<r
.resultCount
;i
++){
226 var e
= document
.getElementById(r
.resultText
+i
);
228 var lastW
= e
.offsetWidth
+1;
230 var changedText
= false;
231 while(e
.offsetWidth
> w
&& (e
.offsetWidth
< lastW
|| iteration
<2)){
233 lastW
= e
.offsetWidth
;
235 e
.innerHTML
= l
.substring(0,l
.length
-replace
)+"...";
237 replace
= 4; // how many chars to replace
240 // show hint for trimmed titles
241 document
.getElementById(r
.resultTable
+i
).setAttribute("title",r
.results
[i
]);
246 /** Handles data from XMLHttpRequest, and updates the suggest results */
247 function os_updateResults(r
, query
, text
, cacheKey
){
248 os_cache
[cacheKey
] = text
;
257 var p
= eval('('+text
+')'); // simple json parse, could do a safer one
258 if(p
.length
<2 || p
[1].length
== 0){
264 var c
= document
.getElementById(r
.container
);
266 c
= os_createContainer(r
);
267 c
.innerHTML
= os_createResultTable(r
,p
[1]);
268 // init container table sizes
269 var t
= document
.getElementById(r
.resultTable
);
270 r
.containerTotal
= t
.offsetHeight
;
271 r
.containerRow
= t
.offsetHeight
/ r
.resultCount
;
272 os_trimResultText(r
);
275 // bad response from server or such
277 os_cache
[cacheKey
] = null;
282 /** Create the result table to be placed in the container div */
283 function os_createResultTable(r
, results
){
284 var c
= document
.getElementById(r
.container
);
285 var width
= os_operaWidthFix(c
.offsetWidth
);
286 var html
= "<table class=\"os-suggest-results\" id=\""+r
.resultTable
+"\" style=\"width: "+width
+"px;\">";
287 r
.results
= new Array();
288 r
.resultCount
= results
.length
;
289 for(i
=0;i
<results
.length
;i
++){
290 var title
= os_decodeValue(results
[i
]);
291 r
.results
[i
] = title
;
292 html
+= "<tr><td class=\"os-suggest-result\" id=\""+r
.resultTable
+i
+"\"><span id=\""+r
.resultText
+i
+"\">"+title
+"</span></td></tr>";
298 /** Fetch namespaces from checkboxes or hidden fields in the search form,
299 if none defined use wgSearchNamespaces global */
300 function os_getNamespaces(r
){
302 var elements
= document
.forms
[r
.searchform
].elements
;
303 for(i
=0; i
< elements
.length
; i
++){
304 var name
= elements
[i
].name
;
305 if(typeof name
!= 'undefined' && name
.length
> 2
306 && name
[0]=='n' && name
[1]=='s'
307 && ((elements
[i
].type
=='checkbox' && elements
[i
].checked
)
308 || (elements
[i
].type
=='hidden' && elements
[i
].value
=="1")) ){
311 namespaces
+=name
.substring(2);
315 namespaces
= wgSearchNamespaces
.join("|");
319 /** Update results if user hasn't already typed something else */
320 function os_updateIfRelevant(r
, query
, text
, cacheKey
){
321 var t
= document
.getElementById(r
.searchbox
);
322 if(t
!= null && t
.value
== query
){ // check if response is still relevant
323 os_updateResults(r
, query
, text
, cacheKey
);
328 /** Fetch results after some timeout */
329 function os_delayedFetch(){
333 var query
= os_timer
.query
;
335 var path
= wgMWSuggestTemplate
.replace("{namespaces}",os_getNamespaces(r
))
336 .replace("{dbname}",wgDBname
)
337 .replace("{searchTerms}",os_encodeQuery(query
));
339 // try to get from cache, if not fetch using ajax
340 var cached
= os_cache
[path
];
342 os_updateIfRelevant(r
, query
, cached
, path
);
344 var xmlhttp
= sajax_init_object();
347 xmlhttp
.open("GET", path
, true);
348 xmlhttp
.onreadystatechange=function(){
349 if (xmlhttp
.readyState
==4 && typeof os_updateIfRelevant
== 'function') {
350 os_updateIfRelevant(r
, query
, xmlhttp
.responseText
, path
);
355 if (window
.location
.hostname
== "localhost") {
356 alert("Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing.");
364 /** Init timed update via os_delayedUpdate() */
365 function os_fetchResults(r
, query
, timeout
){
369 } else if(query
== r
.query
)
372 os_is_stopped
= false; // make sure we're running
374 /* var cacheKey = wgDBname+":"+query;
375 var cached = os_cache[cacheKey];
377 os_updateResults(r,wgDBname,query,cached);
381 // cancel any pending fetches
382 if(os_timer
!= null && os_timer
.id
!= null)
383 clearTimeout(os_timer
.id
);
384 // schedule delayed fetching of results
386 os_timer
= new os_Timer(setTimeout("os_delayedFetch()",timeout
),r
,query
);
388 os_timer
= new os_Timer(null,r
,query
);
389 os_delayedFetch(); // do it now!
393 /** Change the highlighted row (i.e. suggestion), from position cur to next */
394 function os_changeHighlight(r
, cur
, next
, updateSearchBox
){
395 if (next
>= r
.resultCount
)
396 next
= r
.resultCount
-1;
401 return; // nothing to do.
404 var curRow
= document
.getElementById(r
.resultTable
+ cur
);
406 curRow
.className
= "os-suggest-result";
410 var nextRow
= document
.getElementById(r
.resultTable
+ next
);
412 nextRow
.className
= os_HighlightClass();
413 newText
= r
.results
[next
];
415 newText
= r
.original
;
417 // adjust the scrollbar if any
418 if(r
.containerCount
< r
.resultCount
){
419 var c
= document
.getElementById(r
.container
);
420 var vStart
= c
.scrollTop
/ r
.containerRow
;
421 var vEnd
= vStart
+ r
.containerCount
;
423 c
.scrollTop
= next
* r
.containerRow
;
424 else if(next
>= vEnd
)
425 c
.scrollTop
= (next
- r
.containerCount
+ 1) * r
.containerRow
;
428 // update the contents of the search box
430 os_updateSearchQuery(r
,newText
);
434 function os_HighlightClass() {
435 var match
= navigator
.userAgent
.match(/AppleWebKit\/(\d+)/);
437 var webKitVersion
= parseInt(match
[1]);
438 if (webKitVersion
< 523) {
439 // CSS system highlight colors broken on old Safari
440 // https://bugs.webkit.org/show_bug.cgi?id=6129
441 // Safari 3.0.4, 3.1 known ok
442 return "os-suggest-result-hl-webkit";
445 return "os-suggest-result-hl";
448 function os_updateSearchQuery(r
,newText
){
449 document
.getElementById(r
.searchbox
).value
= newText
;
453 /** Find event target */
454 function os_getTarget(e
){
455 if (!e
) var e
= window
.event
;
456 if (e
.target
) return e
.target
;
457 else if (e
.srcElement
) return e
.srcElement
;
463 /********************
465 ********************/
467 /** Event handler that will fetch results on keyup */
468 function os_eventKeyup(e
){
469 var targ
= os_getTarget(e
);
470 var r
= os_map
[targ
.id
];
472 return; // not our event
474 // some browsers won't generate keypressed for arrow keys, catch it
475 if(os_keypressed_count
== 0){
476 os_processKey(r
,os_cur_keypressed
,targ
);
478 var query
= targ
.value
;
479 os_fetchResults(r
,query
,os_search_timeout
);
482 /** catch arrows up/down and escape to hide the suggestions */
483 function os_processKey(r,keypressed,targ){
484 if (keypressed == 40){ // Arrow Down
486 os_changeHighlight(r, r.selected, r.selected+1, true);
487 } else if(os_timer == null){
488 // user wants to get suggestions now
490 os_fetchResults(r,targ.value,0);
492 } else if (keypressed == 38){ // Arrow Up
494 os_changeHighlight(r, r.selected, r.selected-1, true);
496 } else if(keypressed == 27){ // Escape
497 document.getElementById(r.searchbox).value = r.original;
498 r.query = r.original;
500 } else if(r.query != document.getElementById(r.searchbox).value){
501 // os_hideResults(r); // don't show old suggestions
505 /** When keys is held down use a timer to output regular events */
506 function os_eventKeypress(e
){
507 var targ
= os_getTarget(e
);
508 var r
= os_map
[targ
.id
];
510 return; // not our event
512 var keypressed
= os_cur_keypressed
;
513 if(keypressed
== 38 || keypressed
== 40){
515 var now
= d
.getTime();
516 if(now
- os_last_keypress
< 120){
517 os_last_keypress
= now
;
522 os_keypressed_count
++;
523 os_processKey(r
,keypressed
,targ
);
526 /** Catch the key code (Firefox bug) */
527 function os_eventKeydown(e
){
528 if (!e
) var e
= window
.event
;
529 var targ
= os_getTarget(e
);
530 var r
= os_map
[targ
.id
];
532 return; // not our event
534 os_mouse_moved
= false;
536 os_cur_keypressed
= (window
.Event
) ? e
.which
: e
.keyCode
;
537 os_last_keypress
= 0;
538 os_keypressed_count
= 0;
541 /** Event: loss of focus of input box */
542 function os_eventBlur(e
){
543 var targ
= os_getTarget(e
);
544 var r
= os_map
[targ
.id
];
546 return; // not our event
547 if(!os_mouse_pressed
)
551 /** Event: focus (catch only when stopped) */
552 function os_eventFocus(e
){
553 // nothing happens here?
558 /********************
560 ********************/
562 /** Mouse over the container */
563 function os_eventMouseover(srcId
, e
){
564 var targ
= os_getTarget(e
);
565 var r
= os_map
[srcId
];
566 if(r
== null || !os_mouse_moved
)
567 return; // not our event
568 var num
= os_getNumberSuffix(targ
.id
);
570 os_changeHighlight(r
,r
.selected
,num
,false);
574 /* Get row where the event occured (from its id) */
575 function os_getNumberSuffix(id
){
576 var num
= id
.substring(id
.length
-2);
577 if( ! (num
.charAt(0) >= '0' && num
.charAt(0) <= '9') )
578 num
= num
.substring(1);
580 return parseInt(num
);
585 /** Save mouse move as last action */
586 function os_eventMousemove(srcId
, e
){
587 os_mouse_moved
= true;
590 /** Mouse button held down, register possible click */
591 function os_eventMousedown(srcId
, e
){
592 var targ
= os_getTarget(e
);
593 var r
= os_map
[srcId
];
595 return; // not our event
596 var num
= os_getNumberSuffix(targ
.id
);
598 os_mouse_pressed
= true;
601 // os_updateSearchQuery(r,r.results[num]);
603 // keep the focus on the search field
604 document
.getElementById(r
.searchbox
).focus();
606 return false; // prevents selection
609 /** Mouse button released, check for click on some row */
610 function os_eventMouseup(srcId
, e
){
611 var targ
= os_getTarget(e
);
612 var r
= os_map
[srcId
];
614 return; // not our event
615 var num
= os_getNumberSuffix(targ
.id
);
617 if(num
>= 0 && os_mouse_num
== num
){
618 os_updateSearchQuery(r
,r
.results
[num
]);
620 document
.getElementById(r
.searchform
).submit();
622 os_mouse_pressed
= false;
623 // keep the focus on the search field
624 document
.getElementById(r
.searchbox
).focus();
627 /** Check if x is a valid integer */
628 function os_isNumber(x
){
629 if(x
== "" || isNaN(x
))
631 for(var i
=0;i
<x
.length
;i
++){
633 if( ! (c
>= '0' && c
<= '9') )
640 /** When the form is submitted hide everything, cancel updates... */
641 function os_eventOnsubmit(e
){
642 var targ
= os_getTarget(e
);
644 os_is_stopped
= true;
645 // kill timed requests
646 if(os_timer
!= null && os_timer
.id
!= null){
647 clearTimeout(os_timer
.id
);
650 // Hide all suggestions
651 for(i
=0;i
<os_autoload_inputs
.length
;i
++){
652 var r
= os_map
[os_autoload_inputs
[i
]];
654 var b
= document
.getElementById(r
.searchform
);
655 if(b
!= null && b
== targ
){
656 // set query value so the handler won't try to fetch additional results
657 r
.query
= document
.getElementById(r
.searchbox
).value
;
665 function os_hookEvent(element
, hookName
, hookFunct
) {
666 if (element
.addEventListener
) {
667 element
.addEventListener(hookName
, hookFunct
, false);
668 } else if (window
.attachEvent
) {
669 element
.attachEvent("on" + hookName
, hookFunct
);
673 /** Init Result objects and event handlers */
674 function os_initHandlers(name
, formname
, element
){
675 var r
= new os_Results(name
, formname
);
677 os_hookEvent(element
, "keyup", function(event
) { os_eventKeyup(event
); });
678 os_hookEvent(element
, "keydown", function(event
) { os_eventKeydown(event
); });
679 os_hookEvent(element
, "keypress", function(event
) { os_eventKeypress(event
); });
680 os_hookEvent(element
, "blur", function(event
) { os_eventBlur(event
); });
681 os_hookEvent(element
, "focus", function(event
) { os_eventFocus(event
); });
682 element
.setAttribute("autocomplete","off");
684 os_hookEvent(document
.getElementById(formname
), "submit", function(event
){ return os_eventOnsubmit(event
); });
687 if(document
.getElementById(r
.toggle
) == null){
688 // TODO: disable this while we figure out a way for this to work in all browsers
689 /* if(name=='searchInput'){
690 // special case: place above the main search box
691 var t = os_createToggle(r,"os-suggest-toggle");
692 var searchBody = document.getElementById('searchBody');
693 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
695 // default: place below search box to the right
696 var t = os_createToggle(r,"os-suggest-toggle-def");
697 var top = element.offsetTop + element.offsetHeight;
698 var left = element.offsetLeft + element.offsetWidth;
699 t.style.position = "absolute";
700 t.style.top = top + "px";
701 t.style.left = left + "px";
702 element.parentNode.appendChild(t);
703 // only now width gets calculated, shift right
704 left -= t.offsetWidth;
705 t.style.left = left + "px";
706 t.style.visibility = "visible";
712 /** Return the span element that contains the toggle link */
713 function os_createToggle(r
,className
){
714 var t
= document
.createElement("span");
715 t
.className
= className
;
716 t
.setAttribute("id", r
.toggle
);
717 var link
= document
.createElement("a");
718 link
.setAttribute("href","javascript:void(0);");
719 link
.onclick = function(){ os_toggle(r
.searchbox
,r
.searchform
) };
720 var msg
= document
.createTextNode(wgMWSuggestMessages
[0]);
721 link
.appendChild(msg
);
726 /** Call when user clicks on some of the toggle links */
727 function os_toggle(inputId
,formName
){
731 os_enableSuggestionsOn(inputId
,formName
);
733 msg
= wgMWSuggestMessages
[0];
735 os_disableSuggestionsOn(inputId
,formName
);
736 msg
= wgMWSuggestMessages
[1];
739 var link
= document
.getElementById(r
.toggle
).firstChild
;
740 link
.replaceChild(document
.createTextNode(msg
),link
.firstChild
);
743 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
744 function os_enableSuggestionsOn(inputId
, formName
){
745 os_initHandlers( inputId
, formName
, document
.getElementById(inputId
) );
748 /** Call this to disable suggestios on input box (id=inputId) */
749 function os_disableSuggestionsOn(inputId
){
752 // cancel/hide results
755 // turn autocomplete on !
756 document
.getElementById(inputId
).setAttribute("autocomplete","on");
758 os_map
[inputId
] = null;
762 /** Initialization, call upon page onload */
763 function os_MWSuggestInit() {
764 for(i
=0;i
<os_autoload_inputs
.length
;i
++){
765 var id
= os_autoload_inputs
[i
];
766 var form
= os_autoload_forms
[i
];
767 element
= document
.getElementById( id
);
769 os_initHandlers(id
,form
,element
);
773 hookEvent("load", os_MWSuggestInit
);