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
);
101 function os_decodeValue(value
){
102 if (decodeURIComponent
) {
103 return decodeURIComponent(value
);
106 return unescape(value
);
111 /** Brower-dependent functions to find window inner size, and scroll status */
112 function f_clientWidth() {
113 return f_filterResults (
114 window
.innerWidth
? window
.innerWidth
: 0,
115 document
.documentElement
? document
.documentElement
.clientWidth
: 0,
116 document
.body
? document
.body
.clientWidth
: 0
119 function f_clientHeight() {
120 return f_filterResults (
121 window
.innerHeight
? window
.innerHeight
: 0,
122 document
.documentElement
? document
.documentElement
.clientHeight
: 0,
123 document
.body
? document
.body
.clientHeight
: 0
126 function f_scrollLeft() {
127 return f_filterResults (
128 window
.pageXOffset
? window
.pageXOffset
: 0,
129 document
.documentElement
? document
.documentElement
.scrollLeft
: 0,
130 document
.body
? document
.body
.scrollLeft
: 0
133 function f_scrollTop() {
134 return f_filterResults (
135 window
.pageYOffset
? window
.pageYOffset
: 0,
136 document
.documentElement
? document
.documentElement
.scrollTop
: 0,
137 document
.body
? document
.body
.scrollTop
: 0
140 function f_filterResults(n_win
, n_docel
, n_body
) {
141 var n_result
= n_win
? n_win
: 0;
142 if (n_docel
&& (!n_result
|| (n_result
> n_docel
)))
144 return n_body
&& (!n_result
|| (n_result
> n_body
)) ? n_body
: n_result
;
147 /** Get the height available for the results container */
148 function os_availableHeight(r
){
149 var absTop
= document
.getElementById(r
.container
).style
.top
;
150 var px
= absTop
.lastIndexOf("px");
152 absTop
= absTop
.substring(0,px
);
153 return f_clientHeight() - (absTop
- f_scrollTop());
157 /** Get element absolute position {left,top} */
158 function os_getElementPosition(elemID
){
159 var offsetTrail
= document
.getElementById(elemID
);
163 offsetLeft
+= offsetTrail
.offsetLeft
;
164 offsetTop
+= offsetTrail
.offsetTop
;
165 offsetTrail
= offsetTrail
.offsetParent
;
167 if (navigator
.userAgent
.indexOf('Mac') != -1 && typeof document
.body
.leftMargin
!= 'undefined'){
168 offsetLeft
+= document
.body
.leftMargin
;
169 offsetTop
+= document
.body
.topMargin
;
171 return {left
:offsetLeft
,top
:offsetTop
};
174 /** Create the container div that will hold the suggested titles */
175 function os_createContainer(r
){
176 var c
= document
.createElement("div");
177 var s
= document
.getElementById(r
.searchbox
);
178 var pos
= os_getElementPosition(r
.searchbox
);
180 var top
= pos
.top
+ s
.offsetHeight
;
181 c
.className
= "os-suggest";
182 c
.setAttribute("id", r
.container
);
183 document
.body
.appendChild(c
);
185 // dynamically generated style params
186 // IE workaround, cannot explicitely set "style" attribute
187 c
= document
.getElementById(r
.container
);
188 c
.style
.top
= top
+"px";
189 c
.style
.left
= left
+"px";
190 c
.style
.width
= s
.offsetWidth
+"px";
192 // mouse event handlers
193 c
.onmouseover = function(event
) { os_eventMouseover(r
.searchbox
, event
); };
194 c
.onmousemove = function(event
) { os_eventMousemove(r
.searchbox
, event
); };
195 c
.onmousedown = function(event
) { return os_eventMousedown(r
.searchbox
, event
); };
196 c
.onmouseup = function(event
) { os_eventMouseup(r
.searchbox
, event
); };
200 /** change container height to fit to screen */
201 function os_fitContainer(r
){
202 var c
= document
.getElementById(r
.container
);
203 var h
= os_availableHeight(r
) - 20;
204 var inc
= r
.containerRow
;
205 h
= parseInt(h
/inc
) * inc
;
206 if(h
< (2 * inc
) && r
.resultCount
> 1) // min: two results
208 if((h
/inc
) > os_max_lines_per_suggest
)
209 h
= inc
* os_max_lines_per_suggest
;
210 if(h
< r
.containerTotal
){
211 c
.style
.height
= h
+"px";
212 r
.containerCount
= parseInt(Math
.round(h
/inc
));
214 c
.style
.height
= r
.containerTotal
+"px";
215 r
.containerCount
= r
.resultCount
;
218 /** If some entries are longer than the box, replace text with "..." */
219 function os_trimResultText(r
){
220 var w
= document
.getElementById(r
.container
).offsetWidth
;
221 if(r
.containerCount
< r
.resultCount
){
222 w
-= 20; // give 20px for scrollbar
224 w
= os_operaWidthFix(w
);
227 for(var i
=0;i
<r
.resultCount
;i
++){
228 var e
= document
.getElementById(r
.resultText
+i
);
230 var lastW
= e
.offsetWidth
+1;
232 var changedText
= false;
233 while(e
.offsetWidth
> w
&& (e
.offsetWidth
< lastW
|| iteration
<2)){
235 lastW
= e
.offsetWidth
;
237 e
.innerHTML
= l
.substring(0,l
.length
-replace
)+"...";
239 replace
= 4; // how many chars to replace
242 // show hint for trimmed titles
243 document
.getElementById(r
.resultTable
+i
).setAttribute("title",r
.results
[i
]);
248 /** Handles data from XMLHttpRequest, and updates the suggest results */
249 function os_updateResults(r
, query
, text
, cacheKey
){
250 os_cache
[cacheKey
] = text
;
259 var p
= eval('('+text
+')'); // simple json parse, could do a safer one
260 if(p
.length
<2 || p
[1].length
== 0){
266 var c
= document
.getElementById(r
.container
);
268 c
= os_createContainer(r
);
269 c
.innerHTML
= os_createResultTable(r
,p
[1]);
270 // init container table sizes
271 var t
= document
.getElementById(r
.resultTable
);
272 r
.containerTotal
= t
.offsetHeight
;
273 r
.containerRow
= t
.offsetHeight
/ r
.resultCount
;
274 os_trimResultText(r
);
277 // bad response from server or such
279 os_cache
[cacheKey
] = null;
284 /** Create the result table to be placed in the container div */
285 function os_createResultTable(r
, results
){
286 var c
= document
.getElementById(r
.container
);
287 var width
= os_operaWidthFix(c
.offsetWidth
);
288 var html
= "<table class=\"os-suggest-results\" id=\""+r
.resultTable
+"\" style=\"width: "+width
+"px;\">";
289 r
.results
= new Array();
290 r
.resultCount
= results
.length
;
291 for(i
=0;i
<results
.length
;i
++){
292 var title
= os_decodeValue(results
[i
]);
293 r
.results
[i
] = title
;
294 html
+= "<tr><td class=\"os-suggest-result\" id=\""+r
.resultTable
+i
+"\"><span id=\""+r
.resultText
+i
+"\">"+title
+"</span></td></tr>";
300 /** Fetch namespaces from checkboxes or hidden fields in the search form,
301 if none defined use wgSearchNamespaces global */
302 function os_getNamespaces(r
){
304 var elements
= document
.forms
[r
.searchform
].elements
;
305 for(i
=0; i
< elements
.length
; i
++){
306 var name
= elements
[i
].name
;
307 if(typeof name
!= 'undefined' && name
.length
> 2
308 && name
[0]=='n' && name
[1]=='s'
309 && ((elements
[i
].type
=='checkbox' && elements
[i
].checked
)
310 || (elements
[i
].type
=='hidden' && elements
[i
].value
=="1")) ){
313 namespaces
+=name
.substring(2);
317 namespaces
= wgSearchNamespaces
.join("|");
321 /** Update results if user hasn't already typed something else */
322 function os_updateIfRelevant(r
, query
, text
, cacheKey
){
323 var t
= document
.getElementById(r
.searchbox
);
324 if(t
!= null && t
.value
== query
){ // check if response is still relevant
325 os_updateResults(r
, query
, text
, cacheKey
);
330 /** Fetch results after some timeout */
331 function os_delayedFetch(){
335 var query
= os_timer
.query
;
337 var path
= wgMWSuggestTemplate
.replace("{namespaces}",os_getNamespaces(r
))
338 .replace("{dbname}",wgDBname
)
339 .replace("{searchTerms}",os_encodeQuery(query
));
341 // try to get from cache, if not fetch using ajax
342 var cached
= os_cache
[path
];
344 os_updateIfRelevant(r
, query
, cached
, path
);
346 var xmlhttp
= sajax_init_object();
349 xmlhttp
.open("GET", path
, true);
350 xmlhttp
.onreadystatechange=function(){
351 if (xmlhttp
.readyState
==4 && typeof os_updateIfRelevant
== 'function') {
352 os_updateIfRelevant(r
, query
, xmlhttp
.responseText
, path
);
357 if (window
.location
.hostname
== "localhost") {
358 alert("Your browser blocks XMLHttpRequest to 'localhost', try using a real hostname for development/testing.");
366 /** Init timed update via os_delayedUpdate() */
367 function os_fetchResults(r
, query
, timeout
){
371 } else if(query
== r
.query
)
374 os_is_stopped
= false; // make sure we're running
376 /* var cacheKey = wgDBname+":"+query;
377 var cached = os_cache[cacheKey];
379 os_updateResults(r,wgDBname,query,cached);
383 // cancel any pending fetches
384 if(os_timer
!= null && os_timer
.id
!= null)
385 clearTimeout(os_timer
.id
);
386 // schedule delayed fetching of results
388 os_timer
= new os_Timer(setTimeout("os_delayedFetch()",timeout
),r
,query
);
390 os_timer
= new os_Timer(null,r
,query
);
391 os_delayedFetch(); // do it now!
395 /** Change the highlighted row (i.e. suggestion), from position cur to next */
396 function os_changeHighlight(r
, cur
, next
, updateSearchBox
){
397 if (next
>= r
.resultCount
)
398 next
= r
.resultCount
-1;
403 return; // nothing to do.
406 var curRow
= document
.getElementById(r
.resultTable
+ cur
);
408 curRow
.className
= "os-suggest-result";
412 var nextRow
= document
.getElementById(r
.resultTable
+ next
);
414 nextRow
.className
= os_HighlightClass();
415 newText
= r
.results
[next
];
417 newText
= r
.original
;
419 // adjust the scrollbar if any
420 if(r
.containerCount
< r
.resultCount
){
421 var c
= document
.getElementById(r
.container
);
422 var vStart
= c
.scrollTop
/ r
.containerRow
;
423 var vEnd
= vStart
+ r
.containerCount
;
425 c
.scrollTop
= next
* r
.containerRow
;
426 else if(next
>= vEnd
)
427 c
.scrollTop
= (next
- r
.containerCount
+ 1) * r
.containerRow
;
430 // update the contents of the search box
432 os_updateSearchQuery(r
,newText
);
436 function os_HighlightClass() {
437 var match
= navigator
.userAgent
.match(/AppleWebKit\/(\d+)/);
439 var webKitVersion
= parseInt(match
[1]);
440 if (webKitVersion
< 523) {
441 // CSS system highlight colors broken on old Safari
442 // https://bugs.webkit.org/show_bug.cgi?id=6129
443 // Safari 3.0.4, 3.1 known ok
444 return "os-suggest-result-hl-webkit";
447 return "os-suggest-result-hl";
450 function os_updateSearchQuery(r
,newText
){
451 document
.getElementById(r
.searchbox
).value
= newText
;
455 /** Find event target */
456 function os_getTarget(e
){
457 if (!e
) e
= window
.event
;
458 if (e
.target
) return e
.target
;
459 else if (e
.srcElement
) return e
.srcElement
;
465 /********************
467 ********************/
469 /** Event handler that will fetch results on keyup */
470 function os_eventKeyup(e
){
471 var targ
= os_getTarget(e
);
472 var r
= os_map
[targ
.id
];
474 return; // not our event
476 // some browsers won't generate keypressed for arrow keys, catch it
477 if(os_keypressed_count
== 0){
478 os_processKey(r
,os_cur_keypressed
,targ
);
480 var query
= targ
.value
;
481 os_fetchResults(r
,query
,os_search_timeout
);
484 /** catch arrows up/down and escape to hide the suggestions */
485 function os_processKey(r,keypressed,targ){
486 if (keypressed == 40){ // Arrow Down
488 os_changeHighlight(r, r.selected, r.selected+1, true);
489 } else if(os_timer == null){
490 // user wants to get suggestions now
492 os_fetchResults(r,targ.value,0);
494 } else if (keypressed == 38){ // Arrow Up
496 os_changeHighlight(r, r.selected, r.selected-1, true);
498 } else if(keypressed == 27){ // Escape
499 document.getElementById(r.searchbox).value = r.original;
500 r.query = r.original;
502 } else if(r.query != document.getElementById(r.searchbox).value){
503 // os_hideResults(r); // don't show old suggestions
507 /** When keys is held down use a timer to output regular events */
508 function os_eventKeypress(e
){
509 var targ
= os_getTarget(e
);
510 var r
= os_map
[targ
.id
];
512 return; // not our event
514 var keypressed
= os_cur_keypressed
;
515 if(keypressed
== 38 || keypressed
== 40){
517 var now
= d
.getTime();
518 if(now
- os_last_keypress
< 120){
519 os_last_keypress
= now
;
524 os_keypressed_count
++;
525 os_processKey(r
,keypressed
,targ
);
528 /** Catch the key code (Firefox bug) */
529 function os_eventKeydown(e
){
530 if (!e
) e
= window
.event
;
531 var targ
= os_getTarget(e
);
532 var r
= os_map
[targ
.id
];
534 return; // not our event
536 os_mouse_moved
= false;
538 os_cur_keypressed
= (window
.Event
) ? e
.which
: e
.keyCode
;
539 os_last_keypress
= 0;
540 os_keypressed_count
= 0;
543 /** Event: loss of focus of input box */
544 function os_eventBlur(e
){
545 var targ
= os_getTarget(e
);
546 var r
= os_map
[targ
.id
];
548 return; // not our event
549 if(!os_mouse_pressed
)
553 /** Event: focus (catch only when stopped) */
554 function os_eventFocus(e
){
555 // nothing happens here?
560 /********************
562 ********************/
564 /** Mouse over the container */
565 function os_eventMouseover(srcId
, e
){
566 var targ
= os_getTarget(e
);
567 var r
= os_map
[srcId
];
568 if(r
== null || !os_mouse_moved
)
569 return; // not our event
570 var num
= os_getNumberSuffix(targ
.id
);
572 os_changeHighlight(r
,r
.selected
,num
,false);
576 /* Get row where the event occured (from its id) */
577 function os_getNumberSuffix(id
){
578 var num
= id
.substring(id
.length
-2);
579 if( ! (num
.charAt(0) >= '0' && num
.charAt(0) <= '9') )
580 num
= num
.substring(1);
582 return parseInt(num
);
587 /** Save mouse move as last action */
588 function os_eventMousemove(srcId
, e
){
589 os_mouse_moved
= true;
592 /** Mouse button held down, register possible click */
593 function os_eventMousedown(srcId
, e
){
594 var targ
= os_getTarget(e
);
595 var r
= os_map
[srcId
];
597 return; // not our event
598 var num
= os_getNumberSuffix(targ
.id
);
600 os_mouse_pressed
= true;
603 // os_updateSearchQuery(r,r.results[num]);
605 // keep the focus on the search field
606 document
.getElementById(r
.searchbox
).focus();
608 return false; // prevents selection
611 /** Mouse button released, check for click on some row */
612 function os_eventMouseup(srcId
, e
){
613 var targ
= os_getTarget(e
);
614 var r
= os_map
[srcId
];
616 return; // not our event
617 var num
= os_getNumberSuffix(targ
.id
);
619 if(num
>= 0 && os_mouse_num
== num
){
620 os_updateSearchQuery(r
,r
.results
[num
]);
622 document
.getElementById(r
.searchform
).submit();
624 os_mouse_pressed
= false;
625 // keep the focus on the search field
626 document
.getElementById(r
.searchbox
).focus();
629 /** Check if x is a valid integer */
630 function os_isNumber(x
){
631 if(x
== "" || isNaN(x
))
633 for(var i
=0;i
<x
.length
;i
++){
635 if( ! (c
>= '0' && c
<= '9') )
642 /** When the form is submitted hide everything, cancel updates... */
643 function os_eventOnsubmit(e
){
644 var targ
= os_getTarget(e
);
646 os_is_stopped
= true;
647 // kill timed requests
648 if(os_timer
!= null && os_timer
.id
!= null){
649 clearTimeout(os_timer
.id
);
652 // Hide all suggestions
653 for(i
=0;i
<os_autoload_inputs
.length
;i
++){
654 var r
= os_map
[os_autoload_inputs
[i
]];
656 var b
= document
.getElementById(r
.searchform
);
657 if(b
!= null && b
== targ
){
658 // set query value so the handler won't try to fetch additional results
659 r
.query
= document
.getElementById(r
.searchbox
).value
;
667 function os_hookEvent(element
, hookName
, hookFunct
) {
668 if (element
.addEventListener
) {
669 element
.addEventListener(hookName
, hookFunct
, false);
670 } else if (window
.attachEvent
) {
671 element
.attachEvent("on" + hookName
, hookFunct
);
675 /** Init Result objects and event handlers */
676 function os_initHandlers(name
, formname
, element
){
677 var r
= new os_Results(name
, formname
);
679 os_hookEvent(element
, "keyup", function(event
) { os_eventKeyup(event
); });
680 os_hookEvent(element
, "keydown", function(event
) { os_eventKeydown(event
); });
681 os_hookEvent(element
, "keypress", function(event
) { os_eventKeypress(event
); });
682 os_hookEvent(element
, "blur", function(event
) { os_eventBlur(event
); });
683 os_hookEvent(element
, "focus", function(event
) { os_eventFocus(event
); });
684 element
.setAttribute("autocomplete","off");
686 os_hookEvent(document
.getElementById(formname
), "submit", function(event
){ return os_eventOnsubmit(event
); });
689 if(document
.getElementById(r
.toggle
) == null){
690 // TODO: disable this while we figure out a way for this to work in all browsers
691 /* if(name=='searchInput'){
692 // special case: place above the main search box
693 var t = os_createToggle(r,"os-suggest-toggle");
694 var searchBody = document.getElementById('searchBody');
695 var first = searchBody.parentNode.firstChild.nextSibling.appendChild(t);
697 // default: place below search box to the right
698 var t = os_createToggle(r,"os-suggest-toggle-def");
699 var top = element.offsetTop + element.offsetHeight;
700 var left = element.offsetLeft + element.offsetWidth;
701 t.style.position = "absolute";
702 t.style.top = top + "px";
703 t.style.left = left + "px";
704 element.parentNode.appendChild(t);
705 // only now width gets calculated, shift right
706 left -= t.offsetWidth;
707 t.style.left = left + "px";
708 t.style.visibility = "visible";
714 /** Return the span element that contains the toggle link */
715 function os_createToggle(r
,className
){
716 var t
= document
.createElement("span");
717 t
.className
= className
;
718 t
.setAttribute("id", r
.toggle
);
719 var link
= document
.createElement("a");
720 link
.setAttribute("href","javascript:void(0);");
721 link
.onclick = function(){ os_toggle(r
.searchbox
,r
.searchform
) };
722 var msg
= document
.createTextNode(wgMWSuggestMessages
[0]);
723 link
.appendChild(msg
);
728 /** Call when user clicks on some of the toggle links */
729 function os_toggle(inputId
,formName
){
733 os_enableSuggestionsOn(inputId
,formName
);
735 msg
= wgMWSuggestMessages
[0];
737 os_disableSuggestionsOn(inputId
,formName
);
738 msg
= wgMWSuggestMessages
[1];
741 var link
= document
.getElementById(r
.toggle
).firstChild
;
742 link
.replaceChild(document
.createTextNode(msg
),link
.firstChild
);
745 /** Call this to enable suggestions on input (id=inputId), on a form (name=formName) */
746 function os_enableSuggestionsOn(inputId
, formName
){
747 os_initHandlers( inputId
, formName
, document
.getElementById(inputId
) );
750 /** Call this to disable suggestios on input box (id=inputId) */
751 function os_disableSuggestionsOn(inputId
){
754 // cancel/hide results
757 // turn autocomplete on !
758 document
.getElementById(inputId
).setAttribute("autocomplete","on");
760 os_map
[inputId
] = null;
764 /** Initialization, call upon page onload */
765 function os_MWSuggestInit() {
766 for(i
=0;i
<os_autoload_inputs
.length
;i
++){
767 var id
= os_autoload_inputs
[i
];
768 var form
= os_autoload_forms
[i
];
769 element
= document
.getElementById( id
);
771 os_initHandlers(id
,form
,element
);
775 hookEvent("load", os_MWSuggestInit
);