@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 437 lines 17.2 KB
Raw
1 /* oxlint-disable react/no-array-index-key -- Read-only cells retain their database row and column positions. */
2 import {
3 decodeFilePreviewText,
4 filePreviewKind,
5 hostPreviewMimeTypeFromExtension,
6 } from "@t3tools/shared/filePreview";
7 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
8 import { ChevronLeftIcon, ChevronRightIcon, FileIcon, FolderIcon } from "lucide-react";
9 import { msg, T, useGT, useMessages } from "gt-react";
10 import { lazy, Suspense, useEffect, useRef, useState } from "react";
11 import { m } from "~/i18n/messages";
12
13 import {
14 Select,
15 SelectTrigger,
16 SelectValue,
17 SelectPopup,
18 SelectItem,
19 } from "~/components/ui/select";
20
21 import {
22 FileSurfaceAction,
23 FileSurfaceFailure,
24 FileSurfaceLoading,
25 FileSurfaceNotice,
26 } from "./fileSurfaceChrome";
27 import {
28 SQLITE_PAGE_SIZE,
29 type BinaryWorkerRequest,
30 type BinaryWorkerResult,
31 } from "./binaryPreviewProtocol";
32 import { PreviewImage } from "./PreviewImage";
33 import { readBinaryPreview } from "./readBinaryPreview";
34 import { previewErrorText, previewFailureText } from "./previewFailureMessages";
35
36 const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
37 type Archive = Extract<BinaryWorkerResult, { type: "archive" }>;
38 type Database = Extract<BinaryWorkerResult, { type: "sqlite" }>;
39 type Rows = Extract<BinaryWorkerResult, { type: "rows" }>;
40
41 const rowsLabel = (count: number, gt: ReturnType<typeof useGT>) =>
42 gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", {
43 count,
44 formatted: count.toLocaleString(),
45 });
46 const columnsLabel = (count: number, gt: ReturnType<typeof useGT>) =>
47 gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", {
48 count,
49 formatted: count.toLocaleString(),
50 });
51 const entriesLabel = (count: number, gt: ReturnType<typeof useGT>) =>
52 gt("{count, plural, one {{formatted} entry} other {{formatted} entries}}", {
53 count,
54 formatted: count.toLocaleString(),
55 });
56
57 function ArchiveFile(props: { readonly path: string; readonly bytes: Uint8Array<ArrayBuffer> }) {
58 const gt = useGT();
59 const [url, setUrl] = useState<string | null>(null);
60 const kind = filePreviewKind({ name: props.path });
61 const text = (() => {
62 if (!["text", "markdown", "html", "mermaid"].includes(kind)) return null;
63 try {
64 return decodeFilePreviewText(props.bytes);
65 } catch {
66 return null;
67 }
68 })();
69 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Create an object URL for the extracted image and revoke it when the entry changes or unmounts.
70 useEffect(() => {
71 if (kind !== "image") return;
72 const extension = props.path.slice(props.path.lastIndexOf("."));
73 const objectUrl = URL.createObjectURL(
74 new Blob([props.bytes], {
75 type: hostPreviewMimeTypeFromExtension(extension) ?? "application/octet-stream",
76 }),
77 );
78 // oxlint-disable-next-line react/set-state-in-effect -- Publish a Blob URL only after registering its cleanup.
79 setUrl(objectUrl);
80 return () => URL.revokeObjectURL(objectUrl);
81 }, [props.bytes, props.path, kind]);
82 if (kind === "image")
83 return url ? <PreviewImage key={url} src={url} name={props.path} /> : <FileSurfaceLoading />;
84 if (!text)
85 return (
86 <FileSurfaceFailure
87 message={gt("Only UTF-8 text and images can be opened inside an archive.")}
88 />
89 );
90 return (
91 <>
92 {text.truncated ? (
93 <FileSurfaceNotice>
94 <T>Preview limited to the first 1 MB.</T>
95 </FileSurfaceNotice>
96 ) : null}
97 <Suspense fallback={<FileSurfaceLoading />}>
98 <SourcePreview name={props.path} text={text.text} />
99 </Suspense>
100 </>
101 );
102 }
103
104 export default function BinaryViewer(props: {
105 readonly src: string;
106 readonly name: string;
107 readonly kind: "archive" | "sqlite";
108 readonly onRetry?: () => void;
109 }) {
110 const gt = useGT();
111 const messages = useMessages();
112 const [sizeBytes, setSizeBytes] = useState<number | null>(null);
113 const [archive, setArchive] = useState<Archive | null>(null);
114 const [database, setDatabase] = useState<Database | null>(null);
115 const [rows, setRows] = useState<Rows | null>(null);
116 const [entry, setEntry] = useState<Extract<BinaryWorkerResult, { type: "entry" }> | null>(null);
117 const [folder, setFolder] = useState("");
118 const [selectedPath, setSelectedPath] = useState<string | null>(null);
119 const [selectedTable, setSelectedTable] = useState("");
120 const [page, setPage] = useState(0);
121 const [busy, setBusy] = useState(true);
122 const [error, setError] = useState<string | null>(null);
123 const workerRef = useRef<Worker | null>(null);
124 const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
125 const send = (request: BinaryWorkerRequest) => {
126 setBusy(true);
127 setError(null);
128 if (timerRef.current) clearTimeout(timerRef.current);
129 timerRef.current = setTimeout(() => {
130 setError(m(msg("This file took too long to preview. Close it and try again.")));
131 setBusy(false);
132 workerRef.current?.terminate();
133 workerRef.current = null;
134 }, 15_000);
135 workerRef.current?.postMessage(request);
136 };
137 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the binary fetch, archive or database worker, message subscription, and request timeout for this file.
138 useEffect(() => {
139 const controller = new AbortController();
140 const worker = new Worker(new URL("./binaryPreview.worker.ts", import.meta.url), {
141 type: "module",
142 });
143 workerRef.current = worker;
144 const fail = (message: string) => {
145 if (controller.signal.aborted) return;
146 setError(message);
147 setBusy(false);
148 controller.abort();
149 worker.terminate();
150 workerRef.current = null;
151 if (timerRef.current) clearTimeout(timerRef.current);
152 };
153 timerRef.current = setTimeout(
154 () => fail(m(msg("This file took too long to preview. Close it and try again."))),
155 30_000,
156 );
157 worker.addEventListener("error", () =>
158 fail(m(msg("Could not load the file viewer. Close it and try again."))),
159 );
160 worker.addEventListener("message", (event: MessageEvent<BinaryWorkerResult>) => {
161 if (controller.signal.aborted) return;
162 if (timerRef.current) clearTimeout(timerRef.current);
163 const result = event.data;
164 setBusy(false);
165 if (result.type === "error") setError(previewFailureText(result));
166 else if (result.type === "archive") setArchive(result);
167 else if (result.type === "entry") setEntry(result);
168 else if (result.type === "rows") setRows(result);
169 else {
170 setDatabase(result);
171 const table = result.tables[0];
172 if (table) {
173 setSelectedTable(table.name);
174 send({ type: "rows", table: table.name, page: 0 });
175 }
176 }
177 });
178 void readBinaryPreview(props.src, controller.signal)
179 .then((bytes) => {
180 if (!controller.signal.aborted) {
181 setSizeBytes(bytes.byteLength);
182 worker.postMessage({ type: "open", name: props.name, kind: props.kind, bytes }, [bytes]);
183 }
184 })
185 .catch((cause: unknown) =>
186 fail(previewErrorText(cause, m(msg("Could not read this file.")))),
187 );
188 return () => {
189 controller.abort();
190 worker.terminate();
191 workerRef.current = null;
192 if (timerRef.current) clearTimeout(timerRef.current);
193 };
194 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- One worker owns this keyed file and its message stream.
195 }, [props.src, props.kind, props.name]);
196 const table = database?.tables.find((item) => item.name === selectedTable);
197 const selectPage = (next: number, name = selectedTable) => {
198 setSelectedTable(name);
199 setPage(next);
200 setRows(null);
201 send({ type: "rows", table: name, page: next });
202 };
203 const children = new Map<
204 string,
205 { path: string; directory: boolean; size: number; modified: string | null }
206 >();
207 for (const item of archive?.entries ?? []) {
208 if (!item.path.startsWith(folder)) continue;
209 const rest = item.path.slice(folder.length).replace(/\/$/, "");
210 if (!rest) continue;
211 const slash = rest.indexOf("/");
212 const path = slash < 0 ? item.path.replace(/\/$/, "") : `${folder}${rest.slice(0, slash)}`;
213 const directory = slash >= 0 || item.directory;
214 const key = `${path}${directory ? "/" : ""}`;
215 const previous = children.get(key);
216 if (previous) previous.size += item.size;
217 else children.set(key, { path, directory, size: item.size, modified: item.modified });
218 }
219 return (
220 <div className="flex min-h-0 flex-1 flex-col overflow-hidden">
221 {archive ? (
222 <div className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3 text-xs">
223 <FileSurfaceAction
224 label={selectedPath ? gt("Back to archive") : gt("Parent folder")}
225 disabled={!selectedPath && !folder}
226 onPress={() => {
227 setError(null);
228 setEntry(null);
229 if (selectedPath) setSelectedPath(null);
230 else setFolder(folder.replace(/(?:[^/]+)?\/$/, ""));
231 }}
232 >
233 <ChevronLeftIcon className="size-3.5" />
234 </FileSurfaceAction>
235 <span className="min-w-0 flex-1 truncate">
236 {selectedPath ?? (folder || gt("Archive contents"))}
237 </span>
238 <span className="shrink-0 text-muted-foreground">
239 {entriesLabel(archive.entries.length, gt)}
240 {sizeBytes !== null ? ` · ${formatAttachmentSize(sizeBytes, messages)}` : ""}
241 </span>
242 </div>
243 ) : null}
244 {database && table ? (
245 <>
246 <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-2 border-b border-border/60 px-3 py-1 text-xs">
247 <div className="min-w-32 flex-1">
248 <Select
249 value={selectedTable}
250 onValueChange={(value) => {
251 if (!busy && value !== null) selectPage(0, value);
252 }}
253 >
254 <SelectTrigger
255 aria-label={gt("Table", { $context: "noun, database table picker" })}
256 aria-disabled={busy}
257 aria-busy={busy}
258 size="xs"
259 >
260 <SelectValue>
261 {table.name} ({rowsLabel(table.count, gt)})
262 </SelectValue>
263 </SelectTrigger>
264 <SelectPopup>
265 {database.tables.map((item) => (
266 <SelectItem key={item.name} value={item.name}>
267 {item.name} ({rowsLabel(item.count, gt)})
268 </SelectItem>
269 ))}
270 </SelectPopup>
271 </Select>
272 </div>
273 <FileSurfaceAction
274 label={gt("Previous rows")}
275 disabled={busy || page === 0}
276 onPress={() => selectPage(page - 1)}
277 >
278 <ChevronLeftIcon className="size-3.5" />
279 </FileSurfaceAction>
280 <span className="shrink-0 tabular-nums" aria-live="polite">
281 {table.count === 0
282 ? gt("0 rows")
283 : gt("{start}–{end} of {total}", {
284 start: String(page * SQLITE_PAGE_SIZE + 1),
285 end: String(Math.min(table.count, (page + 1) * SQLITE_PAGE_SIZE)),
286 total: table.count.toLocaleString(),
287 })}
288 </span>
289 <FileSurfaceAction
290 label={gt("Next rows")}
291 disabled={busy || (page + 1) * SQLITE_PAGE_SIZE >= table.count}
292 onPress={() => selectPage(page + 1)}
293 >
294 <ChevronRightIcon className="size-3.5" />
295 </FileSurfaceAction>
296 </div>
297 <div
298 className="border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums"
299 role="status"
300 >
301 {rowsLabel(table.count, gt)} ·{" "}
302 {rows ? columnsLabel(rows.columns.length, gt) : gt("… columns")}
303 {sizeBytes !== null ? ` · ${formatAttachmentSize(sizeBytes, messages)}` : ""}
304 </div>
305 <FileSurfaceNotice>
306 <T>
307 Read-only. Up to 50 columns and 1,024 characters per cell. Blob contents are omitted.
308 </T>
309 </FileSurfaceNotice>
310 </>
311 ) : null}
312 {error ? (
313 <FileSurfaceFailure
314 message={error}
315 {...(props.onRetry ? { onRetry: props.onRetry } : {})}
316 />
317 ) : busy ? (
318 <FileSurfaceLoading />
319 ) : selectedPath ? (
320 entry ? (
321 <ArchiveFile key={entry.path} path={entry.path} bytes={entry.bytes} />
322 ) : null
323 ) : archive ? (
324 <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
325 <table
326 aria-label={gt("Archive entries")}
327 className="w-full border-separate border-spacing-0 text-xs"
328 >
329 <thead className="sticky top-0 bg-background text-muted-foreground">
330 <tr>
331 <th scope="col" className="px-3 py-2 text-left font-normal">
332 <T $context="column header, file name">Name</T>
333 </th>
334 <th scope="col" className="px-3 py-2 text-right font-normal">
335 <T $context="column header, file size">Size</T>
336 </th>
337 <th scope="col" className="px-3 py-2 text-right font-normal">
338 <T $context="column header, last modified date">Modified</T>
339 </th>
340 </tr>
341 </thead>
342 <tbody>
343 {[...children.values()]
344 .sort(
345 (a, b) =>
346 Number(b.directory) - Number(a.directory) || a.path.localeCompare(b.path),
347 )
348 .map((item) => (
349 <tr
350 key={`${item.path}${item.directory ? "/" : ""}`}
351 className="hover:bg-muted/40"
352 >
353 <td className="max-w-0 border-b border-border/60">
354 <button
355 type="button"
356 className="flex w-full items-center gap-2 px-3 py-2 text-left hover:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
357 onClick={() => {
358 if (item.directory) setFolder(`${item.path}/`);
359 else {
360 setSelectedPath(item.path);
361 setEntry(null);
362 send({ type: "entry", path: item.path });
363 }
364 }}
365 >
366 {item.directory ? (
367 <FolderIcon className="size-4 shrink-0 text-muted-foreground" />
368 ) : (
369 <FileIcon className="size-4 shrink-0 text-muted-foreground" />
370 )}
371 <span className="truncate">{item.path.slice(folder.length)}</span>
372 </button>
373 </td>
374 <td className="w-20 border-b border-border/60 px-3 py-2 text-right whitespace-nowrap text-muted-foreground tabular-nums">
375 {formatAttachmentSize(item.size, messages)}
376 </td>
377 <td className="w-28 border-b border-border/60 px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
378 {item.modified ? new Date(item.modified).toLocaleDateString() : "-"}
379 </td>
380 </tr>
381 ))}
382 </tbody>
383 </table>
384 {children.size === 0 ? (
385 <p className="p-6 text-xs text-muted-foreground">
386 <T>This folder is empty.</T>
387 </p>
388 ) : null}
389 </div>
390 ) : rows ? (
391 <div className="scrollbar-gutter-both min-h-0 flex-1 overflow-auto">
392 <table
393 aria-label={`${props.name}: ${rows.table}`}
394 className="min-w-full border-separate border-spacing-0 text-xs"
395 >
396 <thead className="sticky top-0 bg-background">
397 <tr>
398 {rows.columns.map((name) => (
399 <th
400 key={name}
401 scope="col"
402 className="border-r border-b border-border/60 px-3 py-2 text-left font-medium whitespace-nowrap"
403 >
404 {name}
405 </th>
406 ))}
407 </tr>
408 </thead>
409 <tbody>
410 {rows.rows.map((row, index) => (
411 <tr key={index} className="even:bg-muted/30">
412 {row.map((cell, column) => (
413 <td
414 key={column}
415 className="max-w-80 min-w-32 border-r border-b border-border/60 px-3 py-1.5 align-top whitespace-pre-wrap break-words tabular-nums"
416 >
417 {cell}
418 </td>
419 ))}
420 </tr>
421 ))}
422 </tbody>
423 </table>
424 {rows.rows.length === 0 ? (
425 <p className="p-6 text-xs text-muted-foreground">
426 <T>This table is empty.</T>
427 </p>
428 ) : null}
429 </div>
430 ) : (
431 <p className="p-6 text-xs text-muted-foreground">
432 <T>This database has no readable tables.</T>
433 </p>
434 )}
435 </div>
436 );
437 }