-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathdocs-search.tsx
More file actions
172 lines (158 loc) · 5.27 KB
/
Copy pathdocs-search.tsx
File metadata and controls
172 lines (158 loc) · 5.27 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"use client";
import { useEffect, useRef, useState } from "react";
import { useTrack } from "@/lib/analytics";
// Client-side docs search backed by Pagefind. The index is produced by the
// `postbuild` script (package.json) from the prerendered HTML in
// `.next/server/app` and served from `/pagefind/`. Pages opt in via the
// `data-pagefind-body` attribute (/docs and blog articles). In `next dev`
// no index exists — the box renders a "built at build time" hint instead.
type PagefindSearchResult = {
id: string;
data: () => Promise<{
url: string;
excerpt: string;
meta: { title?: string };
}>;
};
type Pagefind = {
search: (query: string) => Promise<{ results: PagefindSearchResult[] }>;
};
type ResultRow = { id: string; url: string; title: string; excerpt: string };
// Pagefind indexes `.next/server/app/**/*.html`, so raw result URLs look
// like `/docs.html` or `/blog/<slug>.html` — map them back to routes.
function cleanUrl(url: string): string {
return url.replace(/\.html$/, "").replace(/\/index$/, "/");
}
let pagefindPromise: Promise<Pagefind | null> | null = null;
// The specifier is a runtime variable (not a literal) so neither TypeScript
// nor the bundler tries to resolve it — the script only exists after the
// postbuild Pagefind run.
const PAGEFIND_URL = "/pagefind/pagefind.js";
function loadPagefind(): Promise<Pagefind | null> {
pagefindPromise ??= import(
/* webpackIgnore: true */ /* turbopackIgnore: true */ PAGEFIND_URL
)
.then((mod) => mod as Pagefind)
.catch(() => null);
return pagefindPromise;
}
export function DocsSearch() {
const [query, setQuery] = useState("");
const [results, setResults] = useState<ResultRow[]>([]);
const [open, setOpen] = useState(false);
const [unavailable, setUnavailable] = useState(false);
const track = useTrack();
const rootRef = useRef<HTMLDivElement>(null);
const trackTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
// Run the search (debounced) whenever the query changes.
useEffect(() => {
if (!query.trim()) {
setResults([]);
setOpen(false);
return;
}
let cancelled = false;
const timer = setTimeout(async () => {
const pagefind = await loadPagefind();
if (cancelled) return;
if (!pagefind) {
setUnavailable(true);
setOpen(true);
return;
}
const res = await pagefind.search(query);
const rows = await Promise.all(
res.results.slice(0, 8).map(async (r) => {
const d = await r.data();
return {
id: r.id,
url: cleanUrl(d.url),
title: d.meta.title ?? cleanUrl(d.url),
excerpt: d.excerpt,
};
}),
);
if (cancelled) return;
setResults(rows);
setOpen(true);
// Report the query once typing settles, not per keystroke.
if (trackTimer.current) clearTimeout(trackTimer.current);
trackTimer.current = setTimeout(() => {
track("docs-search-query", {
query,
results: res.results.length,
});
}, 1200);
}, 200);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [query, track]);
// Close on click-away / Escape.
useEffect(() => {
function onPointerDown(e: PointerEvent) {
if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
document.addEventListener("pointerdown", onPointerDown);
document.addEventListener("keydown", onKeyDown);
return () => {
document.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("keydown", onKeyDown);
};
}, []);
return (
<div
className="docs-search"
ref={rootRef}
role="search"
data-pagefind-ignore
>
<input
type="search"
className="docs-search-input"
placeholder="Search the docs…"
aria-label="Search the docs"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => {
void loadPagefind();
if (results.length > 0 || unavailable) setOpen(true);
}}
/>
{open && (
<div className="docs-search-results">
{unavailable ? (
<p className="docs-search-empty">
Search index unavailable — it’s generated at build time
(<code>npm run build</code>).
</p>
) : results.length === 0 ? (
<p className="docs-search-empty">
No results for “{query}”.
</p>
) : (
<ul>
{results.map((r) => (
<li key={r.id}>
<a href={r.url} onClick={() => setOpen(false)}>
<span className="docs-search-title">{r.title}</span>
<span
className="docs-search-excerpt"
// Pagefind escapes page content and only injects its
// own <mark> highlight tags — safe to render.
dangerouslySetInnerHTML={{ __html: r.excerpt }}
/>
</a>
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}