-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (53 loc) · 1.82 KB
/
index.js
File metadata and controls
67 lines (53 loc) · 1.82 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { writable } from "svelte/store";
import FlexSearch from "flexsearch";
const searching = writable(false);
const searchTerm = writable("");
let postsIndex;
let posts = [];
function createPostsIndex(data) {
try {
postsIndex = new FlexSearch.Index({ tokenize: "full" });
data.forEach((post, i) => {
const item = `${post.title} ${post.content}`;
postsIndex.add(i, sanitizeContent(item));
});
posts = data;
} catch (error) {
console.error("Error creating posts index:", error);
posts = [];
}
}
function searchPostsIndex(searchText) {
if (!searchText.trim() || !/\w/.test(searchText)) return [];
try {
const results = postsIndex.search(searchText, { limit: 10 });
return results.map((idx) => formatPostResult(posts[idx], searchText));
} catch (error) {
console.error("Error searching posts:", error);
return [];
}
}
function formatPostResult(post, searchText) {
return {
slug: post.slug,
title: highlightText(post.title, searchText),
content: getExcerptWithHighlight(post.content, searchText),
};
}
function getExcerptWithHighlight(text, searchText) {
const matchPosition = text.toLowerCase().indexOf(searchText.toLowerCase());
if (matchPosition === -1) return "";
const start = Math.max(0, matchPosition - 20);
const end = Math.min(text.length, matchPosition + searchText.length + 80);
const excerpt = text.substring(start, end).trim();
const highlightedText = highlightText(excerpt, searchText);
return `...${highlightedText}...`;
}
function highlightText(text, searchText) {
const regex = new RegExp(`(${searchText})`, "gi");
return text.replace(regex, `<mark>$1</mark>`);
}
function sanitizeContent(content) {
return content.replace(/</g, "<").replace(/>/g, ">");
}
export { searching, searchTerm, createPostsIndex, searchPostsIndex };