Elffuss BraidHub

kikocis/utopia public

dev · 13.8 KiBRawPermalink
1/* 内置文档:随应用打包(私有部署离线可用),版本与部署一致。
2 公开路由——不依赖会话,登录前也可读(开发者接接口时未必有账号)。 */
3import { useEffect, useRef, useState } from "react";
4import { useQuery } from "@tanstack/react-query";
5import ReactMarkdown from "react-markdown";
6import remarkGfm from "remark-gfm";
7import { Link, useNavigate, useParams } from "@tanstack/react-router";
8import { Command, Search } from "lucide-react";
9import { api } from "../api";
10import { S } from "../i18n";
11import { GithubMark, SectionMark } from "../ui";
12import { UserMenu } from "./UserMenu";
13import { usePageTitle } from "../useTitle";
14import ingestMd from "../docs/ingest.md?raw";
15
16/** 文档清单:slug → 标题 + 内容(构建期打进 bundle) */
17const DOCS: { slug: string; title: string; body: string }[] = [
18 { slug: "ingest", title: "Ingest interfaces", body: ingestMd },
19];
20
21/** 全文检索(客户端,文档已在 bundle 里):命中行 → 文档 + 以命中词为中心的摘录 */
22function searchDocs(q: string): { slug: string; title: string; snippet: string }[] {
23 const needle = q.trim().toLowerCase();
24 if (needle.length < 2) return [];
25 const hits: { slug: string; title: string; snippet: string }[] = [];
26 for (const d of DOCS) {
27 for (const line of d.body.split("\n")) {
28 const cleaned = line.replace(/[#`*|>-]/g, " ").replace(/\s+/g, " ").trim();
29 const idx = cleaned.toLowerCase().indexOf(needle);
30 if (idx < 0) continue;
31 // 摘录窗口以命中词为中心,避免命中被 90 字截断截丢
32 const start = Math.max(0, idx - 30);
33 const snippet = (start > 0 ? "…" : "") + cleaned.slice(start, start + 100);
34 hits.push({ slug: d.slug, title: d.title, snippet });
35 if (hits.length >= 8) return hits;
36 }
37 }
38 return hits;
39}
40
41/** 摘录内高亮命中词(不区分大小写,全部命中都标) */
42function Highlighted({ text, q }: { text: string; q: string }) {
43 const needle = q.trim();
44 if (!needle) return <>{text}</>;
45 const parts = text.split(new RegExp(`(${needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})`, "ig"));
46 return (
47 <>
48 {parts.map((p, i) =>
49 p.toLowerCase() === needle.toLowerCase() ? (
50 /* 命中词用警示琥珀:结果列表里一眼定位到匹配处 */
51 <mark
52 key={i}
53 className="rounded-[3px] bg-[rgba(242,182,109,0.16)] px-0.5 text-[var(--u-warn)]"
54 >
55 {p}
56 </mark>
57 ) : (
58 <span key={i}>{p}</span>
59 ),
60 )}
61 </>
62 );
63}
64
65/** 标题 → 锚点 id(TOC 与正文用同一函数保证对得上) */
66function slugify(s: string): string {
67 return s
68 .toLowerCase()
69 .replace(/[^a-z0-9一-龥]+/g, "-")
70 .replace(/(^-+|-+$)/g, "");
71}
72
73/** React children → 纯文本(h2/h3 里可能嵌 code/strong) */
74// eslint-disable-next-line @typescript-eslint/no-explicit-any
75function textOf(children: any): string {
76 if (typeof children === "string") return children;
77 if (Array.isArray(children)) return children.map(textOf).join("");
78 if (children && typeof children === "object" && "props" in children)
79 return textOf(children.props.children);
80 return "";
81}
82
83/** 从 markdown 源提取 h2/h3 目录 */
84function tocOf(body: string): { id: string; text: string; level: 2 | 3 }[] {
85 const out: { id: string; text: string; level: 2 | 3 }[] = [];
86 for (const line of body.split("\n")) {
87 const m = /^(#{2,3})\s+(.+)$/.exec(line);
88 if (!m) continue;
89 const text = m[2].replace(/[`*]/g, "").trim();
90 out.push({ id: slugify(text), text, level: m[1].length as 2 | 3 });
91 }
92 return out;
93}
94
95const IS_MAC = navigator.platform.toUpperCase().includes("MAC");
96
97export function DocsPage() {
98 const { slug } = useParams({ from: "/docs/$slug" });
99 const doc = DOCS.find((d) => d.slug === slug) ?? DOCS[0];
100 const navigate = useNavigate();
101 const [q, setQ] = useState("");
102 const searchRef = useRef<HTMLDivElement>(null);
103 const inputRef = useRef<HTMLInputElement>(null);
104 const results = searchDocs(q);
105 const toc = tocOf(doc.body);
106 const mainRef = useRef<HTMLElement>(null);
107 const [activeHeading, setActiveHeading] = useState<string | null>(null);
108 // 标题:`Utopia | {文章名}`——Charter 是门脸字标,标题直接给文章
109 usePageTitle(S.app.name, doc.title);
110 // 公开页也感知登录态:已登录给用户菜单,未登录给 Sign in
111 const me = useQuery({ queryKey: ["me"], queryFn: api.me, retry: false });
112 const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });
113
114 // 滚动跟随:视口上沿之上最近的标题为当前小节;
115 // 滚到底强制激活最后一节(短末节永远越不过判定线)
116 const onScrollSpy = () => {
117 const main = mainRef.current;
118 if (!main) return;
119 const top = main.getBoundingClientRect().top;
120 let current: string | null = null;
121 for (const h of toc) {
122 const el = document.getElementById(h.id);
123 if (el && el.getBoundingClientRect().top - top <= 96) current = h.id;
124 }
125 if (main.scrollTop + main.clientHeight >= main.scrollHeight - 8 && toc.length)
126 current = toc[toc.length - 1].id;
127 setActiveHeading(current);
128 };
129
130 useEffect(() => {
131 if (!q) return;
132 const onDown = (e: MouseEvent) => {
133 if (searchRef.current && !searchRef.current.contains(e.target as Node)) setQ("");
134 };
135 const onKey = (e: KeyboardEvent) => {
136 if (e.key === "Escape") setQ("");
137 };
138 document.addEventListener("mousedown", onDown);
139 document.addEventListener("keydown", onKey);
140 return () => {
141 document.removeEventListener("mousedown", onDown);
142 document.removeEventListener("keydown", onKey);
143 };
144 }, [q]);
145
146 // 键盘呼起:⌘K / Ctrl+K 任何时候生效;`/` 仅在焦点不在输入框时(别劫持打字)
147 useEffect(() => {
148 const onKey = (e: KeyboardEvent) => {
149 const el = document.activeElement;
150 const typing =
151 el instanceof HTMLInputElement ||
152 el instanceof HTMLTextAreaElement ||
153 (el instanceof HTMLElement && el.isContentEditable);
154 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
155 e.preventDefault();
156 inputRef.current?.focus();
157 inputRef.current?.select();
158 } else if (e.key === "/" && !typing) {
159 e.preventDefault();
160 inputRef.current?.focus();
161 } else if (e.key === "Escape" && el === inputRef.current) {
162 inputRef.current?.blur();
163 }
164 };
165 document.addEventListener("keydown", onKey);
166 return () => document.removeEventListener("keydown", onKey);
167 }, []);
168
169 return (
170 <div className="h-screen flex flex-col overflow-hidden">
171 <header className="glass-strong relative z-40 border-x-0 border-t-0 h-14 shrink-0 flex items-center px-5">
172 <SectionMark text={S.docs.brand} title={S.docs.backTitle} />
173 {/* 居中搜索:检索打包在本地的全部文档;宽度对齐正文栏(max-w-3xl 去掉 px-8) */}
174 <div
175 ref={searchRef}
176 className="absolute left-1/2 -translate-x-1/2 w-[min(44rem,55vw)]"
177 >
178 <div className="relative">
179 <Search
180 size={13}
181 className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500 pointer-events-none"
182 />
183 <input
184 ref={inputRef}
185 className="input-dark w-full pr-14 py-1.5 text-[13px]"
186 style={{ paddingLeft: "2.1rem" }}
187 placeholder={S.docs.searchPlaceholder}
188 value={q}
189 onChange={(e) => setQ(e.target.value)}
190 />
191 {/* 快捷键提示:输入中不占视线。⌘ 用 lucide 图标;
192 Ctrl 无图形符号(⌘ 是 Mac 专属键符),Windows 规范写法就是文字 */}
193 {!q && (
194 <kbd className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1 rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-sans text-[10px] text-neutral-600">
195 {IS_MAC ? <Command size={9} /> : <span>Ctrl</span>}
196 <span>K</span>
197 </kbd>
198 )}
199 </div>
200 {q.trim().length >= 2 && (
201 <div className="u-pop u-pop-in u-pop-in-tl absolute inset-x-0 top-full mt-2 rounded-xl shadow-2xl overflow-hidden">
202 {results.length === 0 ? (
203 <p className="px-3.5 py-3 text-xs text-neutral-500">{S.docs.noResults}</p>
204 ) : (
205 results.map((r, i) => (
206 <button
207 key={i}
208 onClick={() => {
209 setQ("");
210 navigate({ to: "/docs/$slug", params: { slug: r.slug } });
211 }}
212 className="w-full text-left px-3.5 py-2.5 hover:bg-white/[0.06] border-b border-white/5 last:border-0"
213 >
214 <div className="text-[11px] text-neutral-500">{r.title}</div>
215 <div className="text-[13px] text-neutral-200 truncate">
216 <Highlighted text={r.snippet} q={q} />
217 </div>
218 </button>
219 ))
220 )}
221 </div>
222 )}
223 </div>
224
225 {/* 右侧:显式返回(与字标双路回城)+ GitHub·版本胶囊 + 登录态 */}
226 <div className="ml-auto flex items-center gap-1.5">
227 <Link
228 to="/"
229 className="px-2 py-1 rounded-lg text-[12.5px] text-neutral-500 hover:text-neutral-200 hover:bg-white/[0.05] transition-colors"
230 >
231 {S.account.backToApp}
232 </Link>
233 <a
234 href={S.login.githubUrl}
235 target="_blank"
236 rel="noreferrer"
237 title="GitHub"
238 className="flex items-center gap-1.5 rounded-full border border-white/10 px-2.5 py-1 text-neutral-500 hover:text-neutral-200 hover:border-white/25 transition-colors"
239 >
240 <GithubMark size={13} />
241 {health.data && <span className="u-num text-[11px]">v{health.data.version}</span>}
242 </a>
243 {me.data ? (
244 <div className="ml-1">
245 <UserMenu user={me.data} />
246 </div>
247 ) : me.isError ? (
248 <Link
249 to="/login"
250 className="u-btn u-btn-ghost px-3 py-1.5 text-xs"
251 >
252 {S.login.signIn}
253 </Link>
254 ) : null}
255 </div>
256 </header>
257
258 {/* 整页滚动(滚动条贴窗口最右),侧栏 sticky 钉住——正规文档站布局 */}
259 <main
260 ref={mainRef}
261 onScroll={onScrollSpy}
262 className="flex-1 min-h-0 overflow-y-auto u-scroll"
263 >
264 <div className="flex items-start">
265 <aside className="w-64 shrink-0 sticky top-0 h-[calc(100vh-3.5rem)] glass-strong border-y-0 border-l-0 p-3 space-y-0.5">
266 {DOCS.map((d) => (
267 <Link
268 key={d.slug}
269 to="/docs/$slug"
270 params={{ slug: d.slug }}
271 className={`block rounded-lg px-3 py-2 text-[13px] ${
272 d.slug === doc.slug
273 ? "u-nav-active"
274 : "text-neutral-400 hover:bg-white/[0.05] hover:text-neutral-200"
275 }`}
276 >
277 {d.title}
278 </Link>
279 ))}
280 </aside>
281
282 {/* 上下都留足空白:标题不顶着头,末段内容能滚到屏幕中部——人读屏幕中间。
283 排版交给官方 @tailwindcss/typography(prose,16px 基准),
284 自定义只剩:标题锚点 id、外链新开、表格横向滚动容器 */}
285 {/* prose-neutral:默认 gray 阶带蓝相(oklch 258°),违反 chrome 零色偏 */}
286 <article className="prose prose-neutral prose-invert prose-headings:scroll-mt-6 prose-code:before:content-none prose-code:after:content-none flex-1 min-w-0 max-w-3xl mx-auto px-8 pt-16 pb-[40vh]">
287 <ReactMarkdown
288 remarkPlugins={[remarkGfm]}
289 components={{
290 h2: ({ children, ...p }) => (
291 <h2 id={slugify(textOf(children))} {...p}>
292 {children}
293 </h2>
294 ),
295 h3: ({ children, ...p }) => (
296 <h3 id={slugify(textOf(children))} {...p}>
297 {children}
298 </h3>
299 ),
300 a: (p) => <a target="_blank" rel="noreferrer" {...p} />,
301 // 不加 u-scroll:overscroll-contain 会把竖向滚轮困在块内,页面滚不动
302 table: (p) => (
303 <div className="overflow-x-auto">
304 <table {...p} />
305 </div>
306 ),
307 }}
308 >
309 {doc.body}
310 </ReactMarkdown>
311 </article>
312
313 {/* 右侧目录:sticky 钉住,与正文标题同一水平线起头 */}
314 {toc.length > 0 && (
315 <aside className="hidden lg:block w-64 shrink-0 sticky top-0 pt-16 pr-8">
316 <nav className="space-y-0.5">
317 {toc.map((h) => (
318 <button
319 key={h.id}
320 onClick={() =>
321 document.getElementById(h.id)?.scrollIntoView({ behavior: "smooth" })
322 }
323 className={`block w-full text-left px-2 py-1.5 text-sm leading-snug transition-colors ${
324 h.level === 3 ? "pl-5" : ""
325 } ${
326 activeHeading === h.id
327 ? "text-white"
328 : "text-neutral-500 hover:text-neutral-300"
329 }`}
330 >
331 {h.text}
332 </button>
333 ))}
334 </nav>
335 </aside>
336 )}
337 </div>
338 </main>
339 </div>
340 );
341}