rizaldy.club/assets/js/full-text-search.js

62 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-08-01 00:54:23 +07:00
; (async function() {
2022-08-04 13:46:55 +07:00
const encoder = (str) => str.toLowerCase().split(/([^a-z]|[^\x00-\x7F])/)
const contentIndex = new FlexSearch.Document({
cache: true,
2022-05-30 10:40:44 +07:00
charset: "latin:extra",
optimize: true,
2022-05-02 12:06:33 +07:00
index: [
{
2022-05-30 10:40:44 +07:00
field: "content",
tokenize: "reverse",
2022-05-02 12:06:33 +07:00
encode: encoder,
},
{
2022-05-30 10:40:44 +07:00
field: "title",
tokenize: "forward",
2022-05-02 12:06:33 +07:00
encode: encoder,
},
],
})
const { content } = await fetchData
for (const [key, value] of Object.entries(content)) {
contentIndex.add({
id: key,
title: value.title,
content: removeMarkdown(value.content),
})
}
2022-05-02 12:06:33 +07:00
const formatForDisplay = (id) => ({
id,
url: id,
title: content[id].title,
2022-05-02 12:06:33 +07:00
content: content[id].content,
})
2022-08-01 00:54:23 +07:00
registerHandlers((e) => {
term = e.target.value
const searchResults = contentIndex.search(term, [
{
2022-05-30 10:40:44 +07:00
field: "content",
limit: 10,
},
{
2022-05-30 10:40:44 +07:00
field: "title",
limit: 5,
2022-05-02 12:06:33 +07:00
},
])
2022-05-02 12:06:33 +07:00
const getByField = (field) => {
2022-05-02 23:56:44 +07:00
const results = searchResults.filter((x) => x.field === field)
if (results.length === 0) {
return []
} else {
return [...results[0].result]
}
}
2022-05-30 10:40:44 +07:00
const allIds = new Set([...getByField("title"), ...getByField("content")])
const finalResults = [...allIds].map(formatForDisplay)
displayResults(finalResults, true)
})
})()