返回 CodeWhale
explorer.tsx
根目录 / web / components / ratatui / explorer.tsx
1 "use client";
2
3 import { useEffect, useMemo, useRef, useState } from "react";
4 import Link from "next/link";
5 import { useRouter } from "next/navigation";
6 import { Icon } from "@/components/icon";
7 import type { RatatuiCopy } from "@/lib/content/ratatui";
8 import { pickText } from "@/lib/i18n/dictionaries";
9 import { motionId, previewAssetPath, searchEntries, type Catalogue, type EntryPreview } from "@/lib/ratatui/catalogue";
10 import { TASKS, displayApi, filterByTask, getGuidance } from "@/lib/ratatui/learning";
11 import { CodeBlock } from "./highlight";
12 import { getRecipe, recipeSourceUrl, learningGuideUrl } from "@/lib/ratatui/recipes";
13 import "./explorer.css";
14
15 type MotionTrack = {
16 id: string;
17 title: string;
18 profile: string;
19 width: number;
20 height: number;
21 frameMs: number;
22 frames: string[];
23 source: string;
24 };
25
26 export function CopyButton({ text, copy }: { text: string; copy: RatatuiCopy }) {
27 const [result, setResult] = useState<{ kind: "copied" | "error"; text: string } | null>(null);
28 const status = result && result.text === text ? result.kind : "idle";
29 useEffect(() => {
30 if (!result) return;
31 const timer = window.setTimeout(() => setResult(null), 2400);
32 return () => window.clearTimeout(timer);
33 }, [result]);
34 return (
35 <span className="rat-copy">
36 <button className="rat-button" type="button" disabled={!text} onClick={async () => {
37 try {
38 if (typeof navigator === "undefined" || !navigator.clipboard) throw new Error("unavailable");
39 await navigator.clipboard.writeText(text);
40 setResult({ kind: "copied", text });
41 } catch {
42 setResult({ kind: "error", text });
43 }
44 }}><Icon name={status === "copied" ? "check" : "copy"} />{status === "copied" ? copy.copied : copy.copy}</button>
45 <span className="rat-copy-status" role="status">{status === "error" ? copy.copyFailed : ""}</span>
46 </span>
47 );
48 }
49
50 /** SVGs are actual library buffers, displayed as isolated images rather than injected markup. */
51 function TerminalImage({ svg, label, fit, width, height }: { svg: string; label: string; fit: boolean; width: number; height: number }) {
52 const [url, setUrl] = useState("");
53 useEffect(() => {
54 const objectUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
55 setUrl(objectUrl);
56 return () => URL.revokeObjectURL(objectUrl);
57 }, [svg]);
58 // Small buffers would sit tiny in a wide panel; vector SVGs scale without blur.
59 // Stylesheet width beats the sizing attributes, so scaled renders set it.
60 const scale = fit && width <= 60 ? 2 : 1;
61 return <div className={`rat-terminal${fit ? " rat-terminal-fit" : ""}${scale > 1 ? " rat-terminal-scaled" : ""}`} role="region" aria-label={label} tabIndex={0} dir="ltr">
62 {/* next/image cannot optimize browser-owned blob URLs; the SVG retains its precise cell grid. */}
63 {/* eslint-disable-next-line @next/next/no-img-element */}
64 {url && <img src={url} alt={label} width={width * 10 * scale} height={height * 20 * scale} style={scale > 1 ? { width: width * 10 * scale, height: "auto" } : undefined} />}
65 </div>;
66 }
67
68 function MotionPlayer({ id, copy, fit }: { id: string; copy: RatatuiCopy; fit: boolean }) {
69 const [track, setTrack] = useState<MotionTrack | null>(null);
70 const [error, setError] = useState(false);
71 const [attempt, setAttempt] = useState(0);
72 const [frame, setFrame] = useState(0);
73 const [playing, setPlaying] = useState(false);
74 const [speed, setSpeed] = useState(1);
75 const [reduced, setReduced] = useState(false);
76 useEffect(() => {
77 const media = window.matchMedia("(prefers-reduced-motion: reduce)");
78 const update = () => { setReduced(media.matches); if (media.matches) setPlaying(false); };
79 update(); media.addEventListener("change", update);
80 const hidden = () => { if (document.hidden) setPlaying(false); };
81 document.addEventListener("visibilitychange", hidden);
82 return () => { media.removeEventListener("change", update); document.removeEventListener("visibilitychange", hidden); };
83 }, []);
84 useEffect(() => {
85 const controller = new AbortController();
86 setTrack(null); setError(false); setPlaying(false); setFrame(0);
87 fetch(`/ratatui/motion/${id}.json`, { signal: controller.signal })
88 .then((response) => { if (!response.ok) throw new Error("Motion unavailable"); return response.json(); })
89 .then((data: MotionTrack) => {
90 if (data.id !== id || !Array.isArray(data.frames) || data.frames.length < 2 || !data.frameMs) throw new Error("Invalid motion track");
91 setTrack(data);
92 }).catch(() => { if (!controller.signal.aborted) setError(true); });
93 return () => controller.abort();
94 }, [id, attempt]);
95 useEffect(() => {
96 if (!playing || !track) return;
97 const timer = window.setInterval(() => setFrame((value) => (value + 1) % track.frames.length), track.frameMs / speed);
98 return () => window.clearInterval(timer);
99 }, [playing, track, speed]);
100 if (error) return <div className="rat-load" role="alert"><p>{copy.previewError}</p><button className="rat-button" onClick={() => setAttempt((value) => value + 1)}>{copy.retry}</button></div>;
101 if (!track) return <div className="rat-load" role="status">{copy.loading}</div>;
102 return <div className="rat-motion">
103 <div className="rat-motion-intro"><p>{copy.relatedMotion}: {track.title}</p><span>{track.profile} · {copy.frameCount.replace("{count}", String(track.frames.length))}</span></div>
104 <TerminalImage svg={track.frames[frame]} label={`${track.title} · ${copy.frame} ${frame + 1}`} fit={fit} width={track.width} height={track.height} />
105 <div className="rat-motion-controls">
106 <button type="button" className="rat-button rat-button-primary" onClick={() => setPlaying(!playing)} aria-pressed={playing}>{playing ? copy.pause : copy.play}</button>
107 <button type="button" className="rat-button" onClick={() => { setFrame(0); setPlaying(false); }}>{copy.reset}</button>
108 <label className="rat-scrubber">{copy.frame}<input aria-label={copy.frame} type="range" min="0" max={track.frames.length - 1} value={frame} onChange={(event) => { setPlaying(false); setFrame(Number(event.target.value)); }} /><output>{frame + 1}/{track.frames.length}</output></label>
109 <label className="rat-field">{copy.speed}<select aria-label={copy.speed} value={speed} onChange={(event) => setSpeed(Number(event.target.value))}><option value="0.5">0.5×</option><option value="1">1×</option><option value="2">2×</option></select></label>
110 </div>
111 <p className="rat-note">{reduced ? copy.reducedMotionNote : copy.motionDescription} <a href={track.source}>{copy.openSource}<Icon name="external" /></a></p>
112 </div>;
113 }
114
115 /** This explorer switches captured library output; the interactive native host is the Cargo example. */
116 export function RatatuiExplorer({ catalogue, locale, copy, initialEntry, detail }: { catalogue: Catalogue; locale: string; copy: RatatuiCopy; initialEntry?: string; detail?: boolean }) {
117 const first = catalogue.entries.find((entry) => entry.name === (initialEntry ?? "showcase-work")) ?? catalogue.entries[0];
118 const router = useRouter();
119 const [selected, setSelected] = useState(first.name);
120 const [query, setQuery] = useState("");
121 const [family, setFamily] = useState("all");
122 const [task, setTask] = useState("all");
123 const [browserExpanded, setBrowserExpanded] = useState(true);
124 const [mobile, setMobile] = useState(false);
125 const [profile, setProfile] = useState("dark-truecolor");
126 const [size, setSize] = useState("native");
127 const [fit, setFit] = useState(true);
128 const [tab, setTab] = useState<"preview" | "use" | "code" | "motion">("preview");
129 useEffect(() => {
130 const requested = new URLSearchParams(window.location.search).get("tab");
131 if (requested === "use" || requested === "code" || requested === "motion") setTab(requested);
132 }, []);
133 useEffect(() => {
134 const url = new URL(window.location.href);
135 if (tab === "preview") url.searchParams.delete("tab");
136 else url.searchParams.set("tab", tab);
137 window.history.replaceState(null, "", url);
138 }, [tab]);
139 const [data, setData] = useState<EntryPreview | null>(null);
140 const [error, setError] = useState(false);
141 const [attempt, setAttempt] = useState(0);
142 const searchRef = useRef<HTMLInputElement>(null);
143 const familyEntries = useMemo(() => catalogue.entries.filter((item) => item.family === first.family), [catalogue.entries, first.family]);
144 const filtered = useMemo(() => detail
145 ? familyEntries
146 : searchEntries(filterByTask(catalogue.entries, task), query, family),
147 [catalogue.entries, query, family, task, detail, familyEntries]);
148 const entry = filtered.find((item) => item.name === selected) ?? filtered[0] ?? first;
149 const collection = catalogue.families.find((item) => item.id === entry.family);
150 const guidance = getGuidance(entry, locale);
151 const recipe = getRecipe(guidance.recipeId);
152 const animation = motionId(entry, profile);
153 const activeTab = tab === "motion" && !animation ? "preview" : tab;
154 const currentIndex = filtered.findIndex((item) => item.name === entry.name);
155 const svg = data?.previews[profile]?.[size];
156 const label = copy.terminalPreviewLabel.replace("{name}", entry.title);
157 const sourceUrl = entry.source.url;
158 const columns = size === "native" ? entry.width : Number(size);
159 useEffect(() => {
160 const controller = new AbortController();
161 setData(null); setError(false);
162 fetch(previewAssetPath(entry), { signal: controller.signal })
163 .then((response) => { if (!response.ok) throw new Error("Preview unavailable"); return response.json(); })
164 .then((preview: EntryPreview) => {
165 if (preview.name !== entry.name || !preview.previews) throw new Error("Invalid preview");
166 setData(preview);
167 }).catch(() => { if (!controller.signal.aborted) setError(true); });
168 return () => controller.abort();
169 }, [entry, attempt]);
170 useEffect(() => {
171 const focusSearch = (event: KeyboardEvent) => {
172 const target = event.target as HTMLElement;
173 if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey && !target.closest("input,textarea,select,[contenteditable]")) {
174 event.preventDefault(); searchRef.current?.focus();
175 }
176 };
177 window.addEventListener("keydown", focusSearch);
178 return () => window.removeEventListener("keydown", focusSearch);
179 }, []);
180 useEffect(() => {
181 const media = window.matchMedia("(max-width: 760px)");
182 const update = () => { setMobile(media.matches); setBrowserExpanded(!media.matches); if (media.matches) setSize("40"); };
183 update(); media.addEventListener("change", update);
184 return () => media.removeEventListener("change", update);
185 }, []);
186 const choose = (name: string) => {
187 if (detail) {
188 const params = tab === "preview" ? "" : `?tab=${tab}`;
189 router.push(`/${locale}/ratatui/${name}${params}`);
190 return;
191 }
192 setSelected(name); setTab("preview"); if (mobile) setBrowserExpanded(false);
193 };
194 const helpers = data?.fixture.helpers?.map((helper) => helper.code).join("\n\n") ?? "";
195 const example = data ? [data.fixture.imports, data.fixture.code, helpers].filter(Boolean).join("\n\n") : "";
196 const clearFilters = () => { setQuery(""); setFamily("all"); setTask("all"); };
197 return <section id="ratatui-explorer" className={`rat-explorer${detail ? " rat-detail" : ""}`} aria-label={copy.title}>
198 {!detail && <div className="rat-task-picker">
199 <div><h2>{copy.tasksTitle}</h2><p>{copy.tasksDescription}</p></div>
200 <div className="rat-task-options" role="group" aria-label={copy.tasksTitle}>
201 <button type="button" className="rat-button" aria-pressed={task === "all"} onClick={clearFilters}>{copy.allComponents}</button>
202 {TASKS.map((item) => <button key={item.id} type="button" className="rat-button" aria-pressed={task === item.id} onClick={() => {
203 setTask(item.id); setFamily("all"); setQuery("");
204 choose(item.recommended.find((name) => catalogue.entries.some((candidate) => candidate.name === name)) ?? first.name);
205 }}>{pickText(item.label, locale)}</button>)}
206 </div>
207 {task !== "all" && <p className="rat-task-description">{pickText(TASKS.find((item) => item.id === task)!.description, locale)}</p>}
208 </div>}
209 {detail ? <aside className="rat-browser rat-family-index" aria-label={collection?.title ?? copy.componentNavLabel}>
210 <h2>{collection?.title}</h2>
211 <p className="rat-count" role="status">{copy.familyPosition.replace("{index}", String(currentIndex + 1)).replace("{count}", String(filtered.length))}</p>
212 <nav className="rat-entry-list" aria-label={collection?.title}>
213 {filtered.map((candidate) => <Link key={candidate.name} href={`/${locale}/ratatui/${candidate.name}`} className="rat-entry" aria-current={candidate.name === entry.name ? "page" : undefined}><span>{candidate.title}</span><span className="rat-entry-width">{candidate.width}</span></Link>)}
214 </nav>
215 <Link href={`/${locale}/ratatui`} className="rat-link rat-index-back">{copy.back}<Icon name="arrow-right" className="rat-prev-icon" /></Link>
216 </aside> : <aside className="rat-browser" aria-label={copy.componentNavLabel}>
217 <label className="rat-search" htmlFor="rat-search"><span>{copy.searchLabel}</span><div><Icon name="search" /><input id="rat-search" ref={searchRef} type="search" value={query} placeholder={copy.searchPlaceholder} onChange={(event) => { setQuery(event.target.value); if (mobile) setBrowserExpanded(true); }} onKeyDown={(event) => { if (event.key === "Escape") setQuery(""); }} /><kbd>/</kbd></div></label>
218 <label className="rat-family-field" htmlFor="rat-family">{copy.families}<select id="rat-family" value={family} onChange={(event) => { setFamily(event.target.value); setTask("all"); if (mobile) setBrowserExpanded(true); }}><option value="all">{copy.allComponents}</option>{catalogue.families.map((item) => <option key={item.id} value={item.id}>{item.title} ({item.count})</option>)}</select></label>
219 <p className="rat-count" role="status">{copy.visibleCount.replace("{visible}", String(filtered.length)).replace("{total}", String(catalogue.entries.length))}</p>
220 <details className="rat-browser-results" open={browserExpanded} onToggle={(event) => setBrowserExpanded(event.currentTarget.open)}><summary>{copy.allComponents}<Icon name="chevron-down" /></summary>
221 <nav className="rat-entry-list" aria-label={copy.resultsLabel}>
222 {catalogue.families.map((item) => {
223 const entries = filtered.filter((candidate) => candidate.family === item.id);
224 return entries.length ? <div className="rat-family" key={item.id}><h3>{item.title} <span className="rat-family-count">{entries.length}</span></h3>{entries.map((candidate) => <button type="button" key={candidate.name} className="rat-entry" aria-current={candidate.name === entry.name ? "true" : undefined} onClick={() => choose(candidate.name)}><span>{candidate.title}</span><span className="rat-entry-width">{candidate.width}</span></button>)}</div> : null;
225 })}
226 </nav></details>
227 </aside>}
228 {filtered.length === 0 ? <div className="rat-study rat-empty-study"><h2>{copy.emptyTitle}</h2><p>{copy.emptyDescription}</p><button className="rat-button" onClick={clearFilters}>{copy.clearSearch}</button></div> : <div className="rat-study">
229 {!detail && <><div className="rat-study-heading"><div><p>{collection?.title}</p><h2>{entry.title}</h2></div>{initialEntry !== entry.name && <Link href={`/${locale}/ratatui/${entry.name}`} className="rat-link" title={copy.share}>{copy.share}<Icon name="arrow-right" /></Link>}</div>
230 <p className="rat-description">{entry.description}</p></>}
231 <div className="rat-study-tabs" role="group" aria-label={copy.preview}>
232 <button type="button" aria-pressed={activeTab === "preview"} onClick={() => setTab("preview")}>{copy.preview}</button>
233 <button type="button" aria-pressed={activeTab === "use"} onClick={() => setTab("use")}>{copy.use}</button>
234 <button type="button" aria-pressed={activeTab === "code"} onClick={() => setTab("code")}>{copy.code}</button>
235 {animation && <button type="button" aria-pressed={activeTab === "motion"} onClick={() => { setTab("motion"); if (profile !== "light-truecolor") setProfile("dark-truecolor"); }}>{copy.motion}</button>}
236 <div className="rat-pager"><button type="button" aria-label={copy.previous} disabled={currentIndex <= 0} onClick={() => choose(filtered[currentIndex - 1].name)}><Icon name="arrow-right" className="rat-prev-icon" /></button><button type="button" aria-label={copy.next} disabled={currentIndex < 0 || currentIndex >= filtered.length - 1} onClick={() => choose(filtered[currentIndex + 1].name)}><Icon name="arrow-right" /></button></div>
237 </div>
238 {(activeTab === "preview" || activeTab === "motion") && <div className="rat-preview-controls">{(activeTab !== "motion" || !["whale", "habitat"].includes(animation ?? "")) && <label className="rat-field">{copy.profile}<select aria-label={copy.profile} value={profile} onChange={(event) => setProfile(event.target.value)}>{catalogue.profiles.filter((item) => activeTab !== "motion" || ["dark-truecolor", "light-truecolor"].includes(item.id)).map((item) => <option key={item.id} value={item.id}>{item.label}</option>)}</select></label>}{activeTab === "preview" && <label className="rat-field">{copy.size}<select aria-label={copy.size} value={size} onChange={(event) => setSize(event.target.value)}>{catalogue.sizes.map((item) => <option key={item.id} value={item.id}>{item.id === "native" ? copy.nativeSize : copy.columns.replace("{count}", item.id)}</option>)}</select></label>}<button type="button" className="rat-button rat-scale" onClick={() => setFit(!fit)} aria-pressed={!fit}>{fit ? copy.actualSize : copy.fit}</button></div>}
239 {activeTab === "use" ? <div className="rat-code-panel rat-usage-panel">
240 <p>{guidance.description}</p><p className="rat-note">{guidance.hostNote}</p>
241 {recipe && <><div className="rat-code-heading"><h4>{copy.use}</h4><CopyButton text={recipe.code} copy={copy} /></div><CodeBlock code={recipe.code} language="rust" /><p className="rat-note">{copy.recipeNote} <a href={recipeSourceUrl(recipe.line)}>{copy.openSource}<Icon name="external" /></a></p></>}
242 <div className="rat-usage-links"><a className="rat-link" href={learningGuideUrl(guidance.guideAnchor)}>{copy.guide}<Icon name="external" /></a><Link className="rat-link" href={`/${locale}/ratatui#ratatui-install`}>{copy.gettingStarted}<Icon name="arrow-right" /></Link></div>
243 <p className="rat-note">{copy.runExample}</p><CodeBlock code={`cargo run --locked --example ${recipe ? "recipes" : guidance.example.replace(/^examples\//, "").replace(/\.rs$/, "")}`} language="sh" />{recipe && <p className="rat-note">{copy.recipeControls}</p>}
244 </div> :
245 activeTab === "motion" && animation ? <MotionPlayer key={animation} id={animation} copy={copy} fit={fit} /> : activeTab === "code" ? <div className="rat-code-panel"><div className="rat-code-heading"><h3>{copy.fixtureTitle}</h3><CopyButton text={example} copy={copy} /></div>{data ? <CodeBlock code={example} language="rust" /> : <div className="rat-load" role={error ? "alert" : "status"}><p>{error ? copy.previewError : copy.loading}</p>{error && <button className="rat-button" onClick={() => setAttempt((value) => value + 1)}>{copy.retry}</button>}</div>}<p className="rat-note">{copy.fixtureNote} <a href={sourceUrl}>{copy.openSource}<Icon name="external" /></a></p></div> : <>
246 {error ? <div className="rat-load" role="alert"><p>{copy.previewError}</p><button className="rat-button" type="button" onClick={() => setAttempt((value) => value + 1)}>{copy.retry}</button></div> : svg ? <TerminalImage svg={svg} label={label} fit={fit} width={columns} height={entry.height} /> : <div className="rat-load" role="status">{copy.previewLoading}</div>}
247 <div className="rat-preview-meta"><span>{columns} × {entry.height}</span><span>{profile}</span>{svg && <a className="rat-link" href={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`} download={`${entry.name}.${profile}.${size}.svg`}>{copy.downloadSvg}<Icon name="external" /></a>}</div>
248 <p className="rat-note">{copy.renderedPreviewNote}</p>
249 </>}
250 <div className="rat-api"><h3>{copy.api}</h3><div>{displayApi(entry).map((symbol) => <a key={symbol} href={sourceUrl}><code>{symbol}</code></a>)}</div><p>{copy.hostNote}</p></div>
251 </div>}
252 </section>;
253 }
254
254 lines Plain Text