-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pagefind.tsx
64 lines (52 loc) · 1.7 KB
/
pagefind.tsx
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
import { useEffect, useRef } from "react";
// A generic pagefind Component
export const PageFind = ({ id }: {id?: string}) => {
const loaded = useRef<boolean>(false);
// the search input to replace with the pagefind elements
const targetID = id ?? "search"
useEffect(() => {
if (!loaded.current) {
loaded.current = true;
let observer: MutationObserver;
const PagefindUI =
// @ts-ignore
typeof window.PagefindUI !== "undefined" && window.PagefindUI;
if (PagefindUI) {
try {
new PagefindUI({
element: `#${targetID}`,
resetStyles: false,
showImages: false,
showEmptyFilters: false,
});
// delete the observer code below if you did step 2 and target production websites
const pagefindDrawer = document.querySelector(".pagefind-ui__drawer");
// replace the .html from links with path
if (pagefindDrawer) {
const callback = () => {
const links: NodeListOf<HTMLAnchorElement> =
document.querySelectorAll(".pagefind-ui__result-link");
for (const link of links) {
link.href = link.href.replace(".html", "");
}
};
observer = new MutationObserver(callback);
observer.observe(pagefindDrawer, {
attributes: false,
childList: true,
subtree: true,
});
}
} catch (e) {
console.error(e);
}
}
return () => {
if (observer) {
observer.disconnect();
}
};
}
}, [loaded, targetID]);
return <div id={targetID}></div>;
};