search: index and search subheadings

This commit is contained in:
Matilde Park 2022-07-26 14:41:49 -07:00
parent 68a133bc00
commit 066c2142be
3 changed files with 45 additions and 1 deletions

View File

@ -283,6 +283,11 @@ class Search extends Component {
}`}
>
{item.content.content}
{item?.content?.foundOnPage && (
<span className="italic block">
Found in page content
</span>
)}
</p>
</div>
</li>
@ -324,6 +329,11 @@ class Search extends Component {
}`}
>
{item.content.content}
{item?.content?.foundOnPage && (
<span className="italic block">
Found in page content
</span>
)}
</p>
</div>
</li>
@ -365,6 +375,11 @@ class Search extends Component {
}`}
>
{item.content.content}
{item?.content?.foundOnPage && (
<span className="italic block">
Found in page content
</span>
)}
</p>
</div>
</li>

View File

@ -2,6 +2,7 @@ const fs = require("fs");
const path = require("path");
const matter = require("gray-matter");
const toml = require("@iarna/toml");
const markdoc = require("@markdoc/markdoc");
const options = {
engines: {
@ -37,6 +38,8 @@ function buildSearchIndex(dir) {
fs.readFileSync(path.join(dir, page.name)),
options
);
const parsed = markdoc.parse(pageContent);
const transform = markdoc.transform(parsed);
return {
title: pageData.title,
base: page.name,
@ -46,6 +49,11 @@ function buildSearchIndex(dir) {
page.name.replace(/.md$/, "")
),
content: pageData.description || "",
headings: transform.children
.filter((e) => e.name === "h2" || e.name === "h3")
.map((e) => e.children)
.flat()
.filter((e) => typeof e === "string"),
parent: metadata.data.title,
};
})

View File

@ -8,7 +8,28 @@ export default (req, res) => {
e?.slug.includes(req.query.q.toLowerCase()) ||
e?.parent.toLowerCase().includes(req.query.q.toLowerCase())
);
const sorted = levenSort(results, req.query.q, ["title", "slug", "parent"]);
results.push(
...index
.filter((e) => !results.includes(e))
.filter((e) => {
let found = false;
e.headings.forEach((heading) => {
if (heading.toLowerCase().includes(req.query.q.toLowerCase())) {
found = true;
}
});
return found;
})
.map((e) => ({ ...e, foundOnPage: true }))
);
const sorted = levenSort(results, req.q, [
"title",
"slug",
"parent",
"headings",
]);
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ results: sorted }));