bookshelf-doc/static/search.js

67 lines
2.1 KiB
JavaScript
Raw Normal View History

2022-02-20 17:12:49 +00:00
import { SITE_ROOT } from "./site-root.js";
2022-02-13 13:25:37 +00:00
function isSep(c) {
return c === '.' || c === '_';
}
function matchCaseSensitive(declName, lowerDeclName, pat) {
let i = 0, j = 0, err = 0, lastMatch = 0
while (i < declName.length && j < pat.length) {
if (pat[j] === declName[i] || pat[j] === lowerDeclName[i]) {
err += (isSep(pat[j]) ? 0.125 : 1) * (i - lastMatch);
if (pat[j] !== declName[i]) err += 0.5;
lastMatch = i + 1;
j++;
} else if (isSep(declName[i])) {
err += 0.125 * (i + 1 - lastMatch);
lastMatch = i + 1;
}
i++;
}
err += 0.125 * (declName.length - lastMatch);
if (j === pat.length) {
return err;
}
}
2022-02-20 16:06:15 +00:00
export function loadDecls(searchableDataCnt) {
2022-02-20 17:38:12 +00:00
return searchableDataCnt.map(({name, description, link, source}) => [name, name.toLowerCase(), description.toLowerCase(), link, source]);
2022-02-13 13:25:37 +00:00
}
2022-02-20 16:06:15 +00:00
export function getMatches(decls, pat, maxResults = 30) {
2022-02-13 13:25:37 +00:00
const lowerPats = pat.toLowerCase().split(/\s/g);
const patNoSpaces = pat.replace(/\s/g, '');
const results = [];
2022-02-20 17:38:12 +00:00
for (const [decl, lowerDecl, lowerDoc, link, source] of decls) {
2022-02-13 13:25:37 +00:00
let err = matchCaseSensitive(decl, lowerDecl, patNoSpaces);
// match all words as substrings of docstring
if (!(err < 3) && pat.length > 3 && lowerPats.every(l => lowerDoc.indexOf(l) != -1)) {
err = 3;
}
if (err !== undefined) {
2022-02-20 17:38:12 +00:00
results.push({decl, err, link, source});
2022-02-13 13:25:37 +00:00
}
}
return results.sort(({err: a}, {err: b}) => a - b).slice(0, maxResults);
2022-02-20 17:12:49 +00:00
}
const declURL = new URL(`${SITE_ROOT}searchable_data.bmp`, window.location);
export const getDecls = (() => {
let decls;
return () => {
if (!decls) decls = new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.responseType = 'json';
req.addEventListener('load', () => resolve(loadDecls(req.response)));
req.addEventListener('error', () => reject());
req.open('GET', declURL);
req.send();
})
return decls;
}
})()
export const declSearch = async (q) => getMatches(await getDecls(), q);