-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.js
53 lines (45 loc) · 1.81 KB
/
search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const { readdir, readFile } = require("fs/promises");
const { writeFileSync } = require("fs");
const { JSDOM } = require("jsdom");
const lunr = require("lunr");
const main = async () => {
const buildDir = await readdir("build");
const files = buildDir.filter((file) => file.endsWith(".html"));
const cleanupText = (t) => {
return t.trim().replaceAll("\n\n", "");
};
const promises = files.map((filename) => {
return readFile(`build/${filename}`, "utf-8").then((file) => {
const dom = new JSDOM(file);
console.log(`Indexing ${filename}`);
const pageTitle = dom.window.document.querySelector("#contenuMain").querySelectorAll("h1")[0].textContent;
const contents = dom.window.document.querySelector("#contenuMain").querySelectorAll("h2");
const sections = [...contents].map((h2, index) => {
let text = cleanupText(h2.textContent);
let next = h2.nextElementSibling;
while (next && next.tagName !== "H2") {
text += " " + cleanupText(next.textContent);
next = next.nextElementSibling;
}
return {
title: h2.textContent.trim(),
content: text,
url: `${filename}#${h2.id}|${pageTitle} > ${h2.textContent} >`,
};
});
return sections;
});
});
const results = await Promise.all(promises);
const flatResults = results.flat(2);
const idx = lunr(function () {
this.ref("url");
this.field("title");
this.field("content");
flatResults.forEach(function (post) {
this.add(post);
}, this);
});
writeFileSync("build/search.json", JSON.stringify(idx));
};
main();