This commit is contained in:
Andrew Pimenov 2026-08-26 17:01:14 +03:00 • committed by GitHub
commit 7a5817ac7b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -33,6 +33,10 @@ export interface SearchController {
const $ = <T extends HTMLElement>(sel: string): T => const $ = <T extends HTMLElement>(sel: string): T =>
document.querySelector(sel) as T; document.querySelector(sel) as T;
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
export function parseResultQuery( export function parseResultQuery(
engine: SumEngine, engine: SumEngine,
q: string, q: string,
@ -95,20 +99,40 @@ export function searchAllSheets(deps: SearchDeps, query: string): SearchHit[] {
} }
return hits; return hits;
} }
const ql = q.toLowerCase();
const hits: SearchHit[] = []; const hits: SearchHit[] = [];
const regex = new RegExp(escapeRegExp(q), "gi");
for (const doc of docs) { for (const doc of docs) {
const lines = doc.text.split("\n"); const text = doc.text;
for (let i = 0; i < lines.length; i++) { regex.lastIndex = 0;
if (lines[i].toLowerCase().includes(ql)) {
hits.push({ let lastNlIndex = -1;
docId: doc.id, let currentLineNum = 1;
docTitle: doc.title,
line: i + 1, let match;
text: lines[i], while ((match = regex.exec(text)) !== null) {
}); while (true) {
if (hits.length >= 200) return hits; const nextNl = text.indexOf("\n", lastNlIndex + 1);
if (nextNl === -1 || nextNl >= match.index) {
break;
}
currentLineNum++;
lastNlIndex = nextNl;
} }
const lineStart = lastNlIndex + 1;
let lineEnd = text.indexOf("\n", match.index);
if (lineEnd === -1) lineEnd = text.length;
hits.push({
docId: doc.id,
docTitle: doc.title,
line: currentLineNum,
text: text.substring(lineStart, lineEnd),
});
if (hits.length >= 200) return hits;
regex.lastIndex = lineEnd;
} }
} }
return hits; return hits;