ab56499655111429619df63a1dc6687646d22a3e
[m6w6/libmemcached] / _static / searchtools.js
1 /*
2 * searchtools.js
3 * ~~~~~~~~~~~~~~~~
4 *
5 * Sphinx JavaScript utilities for the full-text search.
6 *
7 * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
8 * :license: BSD, see LICENSE for details.
9 *
10 */
11
12 if (!Scorer) {
13 /**
14 * Simple result scoring code.
15 */
16 var Scorer = {
17 // Implement the following function to further tweak the score for each result
18 // The function takes a result array [filename, title, anchor, descr, score]
19 // and returns the new score.
20 /*
21 score: function(result) {
22 return result[4];
23 },
24 */
25
26 // query matches the full name of an object
27 objNameMatch: 11,
28 // or matches in the last dotted part of the object name
29 objPartialMatch: 6,
30 // Additive scores depending on the priority of the object
31 objPrio: {0: 15, // used to be importantResults
32 1: 5, // used to be objectResults
33 2: -5}, // used to be unimportantResults
34 // Used when the priority is not in the mapping.
35 objPrioDefault: 0,
36
37 // query found in title
38 title: 15,
39 partialTitle: 7,
40 // query found in terms
41 term: 5,
42 partialTerm: 2
43 };
44 }
45
46 if (!splitQuery) {
47 function splitQuery(query) {
48 return query.split(/\s+/);
49 }
50 }
51
52 /**
53 * Search Module
54 */
55 var Search = {
56
57 _index : null,
58 _queued_query : null,
59 _pulse_status : -1,
60
61 htmlToText : function(htmlString) {
62 var htmlElement = document.createElement('span');
63 htmlElement.innerHTML = htmlString;
64 $(htmlElement).find('.headerlink').remove();
65 docContent = $(htmlElement).find('[role=main]')[0];
66 if(docContent === undefined) {
67 console.warn("Content block not found. Sphinx search tries to obtain it " +
68 "via '[role=main]'. Could you check your theme or template.");
69 return "";
70 }
71 return docContent.textContent || docContent.innerText;
72 },
73
74 init : function() {
75 var params = $.getQueryParameters();
76 if (params.q) {
77 var query = params.q[0];
78 $('input[name="q"]')[0].value = query;
79 this.performSearch(query);
80 }
81 },
82
83 loadIndex : function(url) {
84 $.ajax({type: "GET", url: url, data: null,
85 dataType: "script", cache: true,
86 complete: function(jqxhr, textstatus) {
87 if (textstatus != "success") {
88 document.getElementById("searchindexloader").src = url;
89 }
90 }});
91 },
92
93 setIndex : function(index) {
94 var q;
95 this._index = index;
96 if ((q = this._queued_query) !== null) {
97 this._queued_query = null;
98 Search.query(q);
99 }
100 },
101
102 hasIndex : function() {
103 return this._index !== null;
104 },
105
106 deferQuery : function(query) {
107 this._queued_query = query;
108 },
109
110 stopPulse : function() {
111 this._pulse_status = 0;
112 },
113
114 startPulse : function() {
115 if (this._pulse_status >= 0)
116 return;
117 function pulse() {
118 var i;
119 Search._pulse_status = (Search._pulse_status + 1) % 4;
120 var dotString = '';
121 for (i = 0; i < Search._pulse_status; i++)
122 dotString += '.';
123 Search.dots.text(dotString);
124 if (Search._pulse_status > -1)
125 window.setTimeout(pulse, 500);
126 }
127 pulse();
128 },
129
130 /**
131 * perform a search for something (or wait until index is loaded)
132 */
133 performSearch : function(query) {
134 // create the required interface elements
135 this.out = $('#search-results');
136 this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
137 this.dots = $('<span></span>').appendTo(this.title);
138 this.status = $('<p class="search-summary">&nbsp;</p>').appendTo(this.out);
139 this.output = $('<ul class="search"/>').appendTo(this.out);
140
141 $('#search-progress').text(_('Preparing search...'));
142 this.startPulse();
143
144 // index already loaded, the browser was quick!
145 if (this.hasIndex())
146 this.query(query);
147 else
148 this.deferQuery(query);
149 },
150
151 /**
152 * execute search (requires search index to be loaded)
153 */
154 query : function(query) {
155 var i;
156
157 // stem the searchterms and add them to the correct list
158 var stemmer = new Stemmer();
159 var searchterms = [];
160 var excluded = [];
161 var hlterms = [];
162 var tmp = splitQuery(query);
163 var objectterms = [];
164 for (i = 0; i < tmp.length; i++) {
165 if (tmp[i] !== "") {
166 objectterms.push(tmp[i].toLowerCase());
167 }
168
169 if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
170 tmp[i] === "") {
171 // skip this "word"
172 continue;
173 }
174 // stem the word
175 var word = stemmer.stemWord(tmp[i].toLowerCase());
176 // prevent stemmer from cutting word smaller than two chars
177 if(word.length < 3 && tmp[i].length >= 3) {
178 word = tmp[i];
179 }
180 var toAppend;
181 // select the correct list
182 if (word[0] == '-') {
183 toAppend = excluded;
184 word = word.substr(1);
185 }
186 else {
187 toAppend = searchterms;
188 hlterms.push(tmp[i].toLowerCase());
189 }
190 // only add if not already in the list
191 if (!$u.contains(toAppend, word))
192 toAppend.push(word);
193 }
194 var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
195
196 // console.debug('SEARCH: searching for:');
197 // console.info('required: ', searchterms);
198 // console.info('excluded: ', excluded);
199
200 // prepare search
201 var terms = this._index.terms;
202 var titleterms = this._index.titleterms;
203
204 // array of [filename, title, anchor, descr, score]
205 var results = [];
206 $('#search-progress').empty();
207
208 // lookup as object
209 for (i = 0; i < objectterms.length; i++) {
210 var others = [].concat(objectterms.slice(0, i),
211 objectterms.slice(i+1, objectterms.length));
212 results = results.concat(this.performObjectSearch(objectterms[i], others));
213 }
214
215 // lookup as search terms in fulltext
216 results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
217
218 // let the scorer override scores with a custom scoring function
219 if (Scorer.score) {
220 for (i = 0; i < results.length; i++)
221 results[i][4] = Scorer.score(results[i]);
222 }
223
224 // now sort the results by score (in opposite order of appearance, since the
225 // display function below uses pop() to retrieve items) and then
226 // alphabetically
227 results.sort(function(a, b) {
228 var left = a[4];
229 var right = b[4];
230 if (left > right) {
231 return 1;
232 } else if (left < right) {
233 return -1;
234 } else {
235 // same score: sort alphabetically
236 left = a[1].toLowerCase();
237 right = b[1].toLowerCase();
238 return (left > right) ? -1 : ((left < right) ? 1 : 0);
239 }
240 });
241
242 // for debugging
243 //Search.lastresults = results.slice(); // a copy
244 //console.info('search results:', Search.lastresults);
245
246 // print the results
247 var resultCount = results.length;
248 function displayNextItem() {
249 // results left, load the summary and display it
250 if (results.length) {
251 var item = results.pop();
252 var listItem = $('<li style="display:none"></li>');
253 var requestUrl = "";
254 var linkUrl = "";
255 if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {
256 // dirhtml builder
257 var dirname = item[0] + '/';
258 if (dirname.match(/\/index\/$/)) {
259 dirname = dirname.substring(0, dirname.length-6);
260 } else if (dirname == 'index/') {
261 dirname = '';
262 }
263 requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;
264 linkUrl = requestUrl;
265
266 } else {
267 // normal html builders
268 requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;
269 linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX;
270 }
271 listItem.append($('<a/>').attr('href',
272 linkUrl +
273 highlightstring + item[2]).html(item[1]));
274 if (item[3]) {
275 listItem.append($('<span> (' + item[3] + ')</span>'));
276 Search.output.append(listItem);
277 listItem.slideDown(5, function() {
278 displayNextItem();
279 });
280 } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
281 $.ajax({url: requestUrl,
282 dataType: "text",
283 complete: function(jqxhr, textstatus) {
284 var data = jqxhr.responseText;
285 if (data !== '' && data !== undefined) {
286 listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
287 }
288 Search.output.append(listItem);
289 listItem.slideDown(5, function() {
290 displayNextItem();
291 });
292 }});
293 } else {
294 // no source available, just display title
295 Search.output.append(listItem);
296 listItem.slideDown(5, function() {
297 displayNextItem();
298 });
299 }
300 }
301 // search finished, update title and status message
302 else {
303 Search.stopPulse();
304 Search.title.text(_('Search Results'));
305 if (!resultCount)
306 Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
307 else
308 Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
309 Search.status.fadeIn(500);
310 }
311 }
312 displayNextItem();
313 },
314
315 /**
316 * search for object names
317 */
318 performObjectSearch : function(object, otherterms) {
319 var filenames = this._index.filenames;
320 var docnames = this._index.docnames;
321 var objects = this._index.objects;
322 var objnames = this._index.objnames;
323 var titles = this._index.titles;
324
325 var i;
326 var results = [];
327
328 for (var prefix in objects) {
329 for (var name in objects[prefix]) {
330 var fullname = (prefix ? prefix + '.' : '') + name;
331 var fullnameLower = fullname.toLowerCase()
332 if (fullnameLower.indexOf(object) > -1) {
333 var score = 0;
334 var parts = fullnameLower.split('.');
335 // check for different match types: exact matches of full name or
336 // "last name" (i.e. last dotted part)
337 if (fullnameLower == object || parts[parts.length - 1] == object) {
338 score += Scorer.objNameMatch;
339 // matches in last name
340 } else if (parts[parts.length - 1].indexOf(object) > -1) {
341 score += Scorer.objPartialMatch;
342 }
343 var match = objects[prefix][name];
344 var objname = objnames[match[1]][2];
345 var title = titles[match[0]];
346 // If more than one term searched for, we require other words to be
347 // found in the name/title/description
348 if (otherterms.length > 0) {
349 var haystack = (prefix + ' ' + name + ' ' +
350 objname + ' ' + title).toLowerCase();
351 var allfound = true;
352 for (i = 0; i < otherterms.length; i++) {
353 if (haystack.indexOf(otherterms[i]) == -1) {
354 allfound = false;
355 break;
356 }
357 }
358 if (!allfound) {
359 continue;
360 }
361 }
362 var descr = objname + _(', in ') + title;
363
364 var anchor = match[3];
365 if (anchor === '')
366 anchor = fullname;
367 else if (anchor == '-')
368 anchor = objnames[match[1]][1] + '-' + fullname;
369 // add custom score for some objects according to scorer
370 if (Scorer.objPrio.hasOwnProperty(match[2])) {
371 score += Scorer.objPrio[match[2]];
372 } else {
373 score += Scorer.objPrioDefault;
374 }
375 results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
376 }
377 }
378 }
379
380 return results;
381 },
382
383 /**
384 * search for full-text terms in the index
385 */
386 performTermsSearch : function(searchterms, excluded, terms, titleterms) {
387 var docnames = this._index.docnames;
388 var filenames = this._index.filenames;
389 var titles = this._index.titles;
390
391 var i, j, file;
392 var fileMap = {};
393 var scoreMap = {};
394 var results = [];
395
396 // perform the search on the required terms
397 for (i = 0; i < searchterms.length; i++) {
398 var word = searchterms[i];
399 var files = [];
400 var _o = [
401 {files: terms[word], score: Scorer.term},
402 {files: titleterms[word], score: Scorer.title}
403 ];
404 // add support for partial matches
405 if (word.length > 2) {
406 for (var w in terms) {
407 if (w.match(word) && !terms[word]) {
408 _o.push({files: terms[w], score: Scorer.partialTerm})
409 }
410 }
411 for (var w in titleterms) {
412 if (w.match(word) && !titleterms[word]) {
413 _o.push({files: titleterms[w], score: Scorer.partialTitle})
414 }
415 }
416 }
417
418 // no match but word was a required one
419 if ($u.every(_o, function(o){return o.files === undefined;})) {
420 break;
421 }
422 // found search word in contents
423 $u.each(_o, function(o) {
424 var _files = o.files;
425 if (_files === undefined)
426 return
427
428 if (_files.length === undefined)
429 _files = [_files];
430 files = files.concat(_files);
431
432 // set score for the word in each file to Scorer.term
433 for (j = 0; j < _files.length; j++) {
434 file = _files[j];
435 if (!(file in scoreMap))
436 scoreMap[file] = {};
437 scoreMap[file][word] = o.score;
438 }
439 });
440
441 // create the mapping
442 for (j = 0; j < files.length; j++) {
443 file = files[j];
444 if (file in fileMap && fileMap[file].indexOf(word) === -1)
445 fileMap[file].push(word);
446 else
447 fileMap[file] = [word];
448 }
449 }
450
451 // now check if the files don't contain excluded terms
452 for (file in fileMap) {
453 var valid = true;
454
455 // check if all requirements are matched
456 var filteredTermCount = // as search terms with length < 3 are discarded: ignore
457 searchterms.filter(function(term){return term.length > 2}).length
458 if (
459 fileMap[file].length != searchterms.length &&
460 fileMap[file].length != filteredTermCount
461 ) continue;
462
463 // ensure that none of the excluded terms is in the search result
464 for (i = 0; i < excluded.length; i++) {
465 if (terms[excluded[i]] == file ||
466 titleterms[excluded[i]] == file ||
467 $u.contains(terms[excluded[i]] || [], file) ||
468 $u.contains(titleterms[excluded[i]] || [], file)) {
469 valid = false;
470 break;
471 }
472 }
473
474 // if we have still a valid result we can add it to the result list
475 if (valid) {
476 // select one (max) score for the file.
477 // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
478 var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
479 results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
480 }
481 }
482 return results;
483 },
484
485 /**
486 * helper function to return a node containing the
487 * search summary for a given text. keywords is a list
488 * of stemmed words, hlwords is the list of normal, unstemmed
489 * words. the first one is used to find the occurrence, the
490 * latter for highlighting it.
491 */
492 makeSearchSummary : function(htmlText, keywords, hlwords) {
493 var text = Search.htmlToText(htmlText);
494 var textLower = text.toLowerCase();
495 var start = 0;
496 $.each(keywords, function() {
497 var i = textLower.indexOf(this.toLowerCase());
498 if (i > -1)
499 start = i;
500 });
501 start = Math.max(start - 120, 0);
502 var excerpt = ((start > 0) ? '...' : '') +
503 $.trim(text.substr(start, 240)) +
504 ((start + 240 - text.length) ? '...' : '');
505 var rv = $('<div class="context"></div>').text(excerpt);
506 $.each(hlwords, function() {
507 rv = rv.highlightText(this, 'highlighted');
508 });
509 return rv;
510 }
511 };
512
513 $(document).ready(function() {
514 Search.init();
515 });