@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 524 lines 19.2 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
3 import type { AssetResource, EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
4 import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
5 import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
6 import { settlePromise } from "@t3tools/client-runtime/state/runtime";
7 import * as AsyncResult from "effect/reactivity/AsyncResult";
8 import * as Cause from "effect/Cause";
9 import {
10 filePreviewKind,
11 officePreviewKind,
12 FILE_TEXT_PREVIEW_MAX_BYTES,
13 } from "@t3tools/shared/filePreview";
14 import {
15 ChevronRightIcon,
16 DownloadIcon,
17 Trash2Icon,
18 WrapTextIcon,
19 XIcon,
20 CheckIcon,
21 Code2Icon,
22 CopyIcon,
23 EyeIcon,
24 Table2Icon,
25 } from "lucide-react";
26 import { msg, T, useGT, useMessages, Var } from "gt-react";
27 import { lazy, Suspense, useEffect, useRef, useState } from "react";
28 import { m, type MessageResolver } from "~/i18n/messages";
29
30 import { useAssetUrlRefresh } from "~/assets/assetUrls";
31 import ChatMarkdown from "~/components/ChatMarkdown";
32 import { maskMarkdownFrontmatter } from "@t3tools/shared/markdownFrontmatter";
33 import { ScrollArea } from "~/components/ui/scroll-area";
34 import { toastManager } from "~/components/ui/toast";
35 import { namedClipboardTarget, useCopyToClipboard } from "~/hooks/useCopyToClipboard";
36 import { useClientSettings } from "~/hooks/useSettings";
37 import { cn } from "~/lib/utils";
38
39 import { BinaryFilePreview } from "./BinaryFilePreview";
40 import { PreviewImage } from "./PreviewImage";
41 import { AudioPreview } from "./AudioPreview";
42 import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
43 import { DelimitedTablePreview } from "./DelimitedTablePreview";
44 import {
45 FILE_SURFACE_SUBHEADER_CLASS,
46 FileSurfaceAction,
47 FileSurfaceFailure,
48 FileSurfaceLoading,
49 FileSurfaceNotice,
50 } from "./fileSurfaceChrome";
51
52 const LargeTextViewer = lazy(() => import("./LargeTextViewer"));
53
54 const OfficeFilePreview = lazy(() =>
55 import("./OfficeFilePreview").then((module) => ({ default: module.OfficeFilePreview })),
56 );
57
58 const FontFilePreview = lazy(() =>
59 import("./FontFilePreview").then((module) => ({ default: module.FontFilePreview })),
60 );
61
62 const MermaidFilePreview = lazy(() =>
63 import("./MermaidFilePreview").then((module) => ({ default: module.MermaidFilePreview })),
64 );
65
66 const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
67
68 const STALE_URL_MS = 5 * 60_000;
69
70 const blobKeys = new WeakMap<Blob, string>();
71 let nextBlobKey = 0;
72
73 function blobKey(blob: Blob) {
74 const key = blobKeys.get(blob) ?? `blob:${nextBlobKey++}`;
75 blobKeys.set(blob, key);
76 return key;
77 }
78
79 export function ReadOnlySourcePreview(props: { name: string; text: string; wordWrap?: boolean }) {
80 return (
81 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
82 <SourcePreview {...props} />
83 </Suspense>
84 );
85 }
86
87 function renderedToggleLabel(
88 mode: "markdown" | "mermaid" | "html" | "table",
89 rendered: boolean,
90 resolve: MessageResolver,
91 ): string {
92 if (mode === "mermaid")
93 return rendered ? resolve(msg("Show Mermaid source")) : resolve(msg("Show rendered diagram"));
94 if (mode === "markdown")
95 return rendered ? resolve(msg("Show markdown source")) : resolve(msg("Show rendered markdown"));
96 if (mode === "table") return rendered ? resolve(msg("Show source")) : resolve(msg("Show table"));
97 return rendered ? resolve(msg("Show HTML source")) : resolve(msg("Show rendered page"));
98 }
99
100 export function AttachmentFilePreview(props: {
101 name: string;
102 mimeType: string;
103 sizeBytes: number;
104 file?: Blob | null;
105 asset?:
106 | { environmentId: EnvironmentId; attachmentId: string }
107 | {
108 environmentId: EnvironmentId;
109 resource: Extract<AssetResource, { _tag: "media-file" | "draft-workspace-file" }>;
110 };
111 htmlRender?: boolean;
112 threadRef?: ScopedThreadRef;
113 origin?: string;
114 onRemove?: () => void;
115 onClose?: () => void;
116 }) {
117 const kind = filePreviewKind(props);
118 const officeKind = officePreviewKind(props);
119 const delimiter = filePreviewDelimiter(props);
120 const renderedMode =
121 kind === "mermaid"
122 ? "mermaid"
123 : kind === "markdown"
124 ? "markdown"
125 : kind === "html"
126 ? "html"
127 : delimiter
128 ? "table"
129 : null;
130 const attachmentId =
131 props.asset && "attachmentId" in props.asset ? props.asset.attachmentId : undefined;
132 const gt = useGT();
133 const messages = useMessages();
134 const { copyToClipboard, isCopied } = useCopyToClipboard({
135 target: namedClipboardTarget(props.name),
136 });
137 // useAssetUrlRefresh keys its callback on these objects, so they must stay cached. Parents
138 // rebuild `asset` on every render, so the attachment resource derives only from its fields.
139 const assetResource = props.asset && "resource" in props.asset ? props.asset.resource : null;
140 const attachmentResource = attachmentId
141 ? {
142 _tag: "attachment" as const,
143 attachmentId,
144 fileName: props.name,
145 mimeType: props.mimeType,
146 disposition: "inline" as const,
147 }
148 : null;
149 const resource = assetResource ?? attachmentResource;
150 const downloadResource = resource
151 ? resource._tag === "draft-workspace-file"
152 ? resource
153 : { ...resource, disposition: "attachment" as const }
154 : null;
155 const refresh = useAssetUrlRefresh(
156 props.file ? null : (props.asset?.environmentId ?? null),
157 props.file ? null : resource,
158 );
159 const prepareDownload = useAssetUrlRefresh(props.asset?.environmentId ?? null, downloadResource);
160 const [saving, setSaving] = useState(false);
161 const [localUrl, setLocalUrl] = useState<string | null>(null);
162 const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
163 const [rendered, setRendered] = useState(true);
164 const [revision, setRevision] = useState(0);
165 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
166 const [error, setError] = useState<string | null>(null);
167 const [contentError, setContentError] = useState<string | null>(null);
168 const copyContents = useRef<(() => Promise<string>) | null>(null);
169 const authorizedAt = useRef(0);
170 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- creates an object URL for the local file and revokes it on cleanup
171 useEffect(() => {
172 if (!props.file) return;
173 const url = URL.createObjectURL(props.file);
174 // oxlint-disable-next-line react/set-state-in-effect -- Publish an object URL only after its cleanup is registered for this Blob.
175 setLocalUrl(url);
176 return () => URL.revokeObjectURL(url);
177 }, [props.file]);
178 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- authorizes a remote attachment URL from the server and ignores the result after cleanup
179 useEffect(() => {
180 if (props.file) return;
181 let cancelled = false;
182 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
183 setRemoteUrl(null);
184 setError(null);
185 void refresh()
186 .then((url) => {
187 if (cancelled) return;
188 if (!url) throw new Error(m(msg("Reconnect to the environment and try again.")));
189 authorizedAt.current = Date.now();
190 setRemoteUrl(url);
191 })
192 .catch((cause: unknown) => {
193 if (!cancelled)
194 setError(thrownErrorMessage(cause, m) ?? m(msg("The attachment is unavailable.")));
195 });
196 return () => {
197 cancelled = true;
198 };
199 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
200 }, [props.file, refresh, revision]);
201 const url = props.file ? localUrl : remoteUrl;
202 const streamsText =
203 kind === "text" &&
204 (props.sizeBytes > FILE_TEXT_PREVIEW_MAX_BYTES ||
205 (props.sizeBytes === 0 && (!resource || resource._tag === "attachment")));
206 const needsText =
207 kind === "text" || kind === "markdown" || kind === "mermaid" || (kind === "html" && !rendered);
208 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches the file's text from its URL or Blob stream and aborts the request on cleanup
209 useEffect(() => {
210 if (!needsText || streamsText || !url) return;
211 const controller = new AbortController();
212 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
213 setContent(null);
214 setContentError(null);
215 const file = props.file;
216 void (async () => {
217 if (!file && Date.now() - authorizedAt.current > STALE_URL_MS) {
218 const target = await refresh();
219 if (controller.signal.aborted) return;
220 if (!target) throw new Error(m(msg("Reconnect to the environment and try again.")));
221 authorizedAt.current = Date.now();
222 if (target !== url) {
223 setRemoteUrl(target);
224 return;
225 }
226 }
227 const response = file
228 ? { ok: true, body: file.stream() }
229 : await fetch(url, {
230 signal: controller.signal,
231 ...(props.sizeBytes > 0
232 ? { headers: { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } }
233 : {}),
234 cache: revision === 0 ? "default" : "reload",
235 });
236 const result = await readFilePreviewResponse(response, controller.signal);
237 if (!controller.signal.aborted) setContent(result);
238 })().catch((cause: unknown) => {
239 if (!controller.signal.aborted)
240 setContentError(thrownErrorMessage(cause, m) ?? m(msg("Could not load this file.")));
241 });
242 return () => controller.abort();
243 }, [url, needsText, streamsText, revision, props.sizeBytes, props.file, refresh]);
244 const failure = error ?? (needsText ? contentError : null);
245 const defaultWordWrap = useClientSettings((settings) => settings.wordWrap);
246 const [wordWrapOverride, setWordWrapOverride] = useState<boolean | null>(null);
247 const wordWrap = wordWrapOverride ?? defaultWordWrap;
248 const showsRawText =
249 failure === null &&
250 needsText &&
251 (content !== null || streamsText) &&
252 !(delimiter && rendered) &&
253 !((kind === "markdown" || kind === "mermaid") && rendered);
254
255 const save = () => {
256 setSaving(true);
257 void settlePromise(async () => {
258 let file = props.file;
259 if (!file) {
260 const target = await prepareDownload();
261 if (!target) throw new Error(gt("Reconnect to the environment and try again."));
262 const response = await fetch(target);
263 if (!response.ok) throw new Error(gt("The file could not be loaded. Try again."));
264 file = await response.blob();
265 }
266 // Blob downloads keep desktop's custom app scheme from navigating to an external browser.
267 const downloadUrl = URL.createObjectURL(file);
268 // Scheduled before the click so the URL is revoked even if the click throws.
269 setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000);
270 const anchor = document.createElement("a");
271 anchor.href = downloadUrl;
272 anchor.download = props.name;
273 anchor.click();
274 }).then((result) => {
275 if (!AsyncResult.isSuccess(result)) {
276 const cause = Cause.squash(result.cause);
277 toastManager.add({
278 type: "error",
279 title: gt("Could not save file"),
280 description: thrownErrorMessage(cause, m) ?? gt("Please try again."),
281 });
282 }
283 setSaving(false);
284 });
285 };
286
287 const body = failure ? (
288 <FileSurfaceFailure
289 message={failure}
290 onRetry={() => {
291 setError(null);
292 setRevision((value) => value + 1);
293 }}
294 />
295 ) : streamsText && url ? (
296 <Suspense fallback={<FileSurfaceLoading />}>
297 <LargeTextViewer
298 key={`${url}:${rendered}:${revision}`}
299 name={props.name}
300 src={url}
301 sizeBytes={props.sizeBytes}
302 onRetry={() => setRevision((value) => value + 1)}
303 delimiter={rendered ? delimiter : null}
304 copyContents={copyContents}
305 wordWrap={wordWrap}
306 />
307 </Suspense>
308 ) : !url || (needsText && !content) ? (
309 <FileSurfaceLoading />
310 ) : needsText && content ? (
311 delimiter && rendered ? (
312 <DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />
313 ) : kind === "mermaid" && rendered ? (
314 <Suspense fallback={<FileSurfaceLoading />}>
315 <MermaidFilePreview text={content.text} />
316 </Suspense>
317 ) : kind === "markdown" && rendered ? (
318 <ScrollArea className="min-h-0 flex-1">
319 <ChatMarkdown
320 text={maskMarkdownFrontmatter(content.text)}
321 cwd={undefined}
322 className="mx-auto max-w-4xl px-6 py-5"
323 />
324 </ScrollArea>
325 ) : (
326 <ReadOnlySourcePreview name={props.name} text={content.text} wordWrap={wordWrap} />
327 )
328 ) : kind === "archive" || kind === "sqlite" ? (
329 <BinaryFilePreview
330 key={revision}
331 src={url}
332 name={props.name}
333 kind={kind}
334 onRetry={() => setRevision((value) => value + 1)}
335 />
336 ) : kind === "font" ? (
337 <Suspense fallback={<FileSurfaceLoading />}>
338 <FontFilePreview src={url} name={props.name} />
339 </Suspense>
340 ) : officeKind ? (
341 <Suspense fallback={<FileSurfaceLoading />}>
342 <OfficeFilePreview
343 src={url}
344 name={props.name}
345 kind={officeKind}
346 sizeBytes={props.sizeBytes}
347 />
348 </Suspense>
349 ) : kind === "pdf" || kind === "html" ? (
350 <BrowserDocumentFrame
351 src={url}
352 title={props.name}
353 pdf={kind === "pdf"}
354 htmlRender={props.htmlRender === true}
355 threadRef={props.threadRef}
356 // Each mount signs or creates a new URL, so the URL cannot identify the file across visits.
357 // A draft keeps its Blob key after upload, so finishing the upload does not reload the PDF.
358 documentKey={
359 kind !== "pdf"
360 ? undefined
361 : props.file
362 ? blobKey(props.file)
363 : props.asset && "attachmentId" in props.asset
364 ? `${props.asset.environmentId}:${props.asset.attachmentId}`
365 : undefined
366 }
367 />
368 ) : kind === "audio" ? (
369 <AudioPreview
370 src={url}
371 name={props.name}
372 onError={() => setError(gt("Unable to load audio."))}
373 />
374 ) : kind === "video" ? (
375 <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
376 <video
377 controls
378 playsInline
379 src={url}
380 aria-label={props.name}
381 className="max-h-full max-w-full"
382 onError={() => setError(gt("Unable to load video."))}
383 />
384 </div>
385 ) : kind === "image" ? (
386 <PreviewImage
387 key={url}
388 src={url}
389 name={props.name}
390 mimeType={props.mimeType}
391 onError={() => setError(gt("Unable to load image."))}
392 />
393 ) : (
394 <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
395 <p className="text-sm font-medium">
396 <T>No preview for this file</T>
397 </p>
398 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
399 {props.name.split(".").at(-1) ? (
400 <T>
401 Save it to open in an app that supports <Var>{props.name.split(".").at(-1)}</Var> files.
402 </T>
403 ) : (
404 <T>Save it to open in an app that supports this format files.</T>
405 )}
406 </p>
407 </div>
408 );
409
410 return (
411 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
412 <div className={cn(FILE_SURFACE_SUBHEADER_CLASS)} data-surface-subheader>
413 <div className="flex min-w-0 flex-1 items-center text-xs">
414 <span className="shrink-0 px-0.5 text-muted-foreground">
415 {props.origin ?? gt("Attachment")}
416 </span>
417 <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
418 <span aria-current="page" className="min-w-0 truncate px-0.5 font-medium text-foreground">
419 {props.name}
420 </span>
421 {props.sizeBytes > 0 ? (
422 <span className="ml-2 shrink-0 text-muted-foreground">
423 {formatAttachmentSize(props.sizeBytes, messages)}
424 </span>
425 ) : null}
426 </div>
427 {renderedMode ? (
428 <FileSurfaceAction
429 label={renderedToggleLabel(renderedMode, rendered, messages)}
430 pressed={rendered}
431 onPress={() => setRendered((value) => !value)}
432 >
433 {rendered ? (
434 <Code2Icon className="size-3.5" />
435 ) : renderedMode === "table" ? (
436 <Table2Icon className="size-3.5" />
437 ) : (
438 <EyeIcon className="size-3.5" />
439 )}
440 </FileSurfaceAction>
441 ) : null}
442 {showsRawText ? (
443 <FileSurfaceAction
444 label={wordWrap ? gt("Disable word wrap") : gt("Enable word wrap")}
445 pressed={wordWrap}
446 onPress={() => setWordWrapOverride(!wordWrap)}
447 >
448 <WrapTextIcon className="size-3.5" />
449 </FileSurfaceAction>
450 ) : null}
451 {content || streamsText ? (
452 <FileSurfaceAction
453 label={
454 isCopied
455 ? gt("Copied")
456 : content?.truncated
457 ? gt("Copy preview")
458 : gt("Copy contents")
459 }
460 onPress={() => {
461 if (content) {
462 void copyToClipboard(content.text, undefined);
463 return;
464 }
465 const copy = copyContents.current;
466 if (!copy) {
467 toastManager.add({
468 type: "error",
469 title: gt("Could not copy file"),
470 description: gt("Wait for the file to finish loading before copying."),
471 });
472 return;
473 }
474 void copy()
475 .then((text) => copyToClipboard(text, undefined))
476 .catch((cause: unknown) =>
477 toastManager.add({
478 type: "error",
479 title: gt("Could not copy file"),
480 description: thrownErrorMessage(cause, m) ?? gt("Try again."),
481 }),
482 );
483 }}
484 >
485 {isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
486 </FileSurfaceAction>
487 ) : null}
488 {url ? (
489 <FileSurfaceAction
490 label={saving ? gt("Preparing file…") : gt("Save file")}
491 disabled={saving}
492 onPress={save}
493 >
494 <DownloadIcon className="size-3.5" />
495 </FileSurfaceAction>
496 ) : null}
497 {props.onRemove ? (
498 <FileSurfaceAction label={gt("Remove from draft")} onPress={props.onRemove}>
499 <Trash2Icon className="size-3.5" />
500 </FileSurfaceAction>
501 ) : null}
502 {props.onClose ? (
503 <FileSurfaceAction
504 label={gt("Close", { $context: "button, closes the file preview" })}
505 onPress={props.onClose}
506 >
507 <XIcon className="size-3.5" />
508 </FileSurfaceAction>
509 ) : null}
510 </div>
511 {content?.truncated ? (
512 <FileSurfaceNotice>
513 {props.sizeBytes > 0
514 ? gt(
515 "Preview limited to the first 1 MB of a {size} byte file. Save the file to read it in full.",
516 { size: props.sizeBytes.toLocaleString() },
517 )
518 : gt("Preview limited to the first 1 MB. Save the file to read it in full.")}
519 </FileSurfaceNotice>
520 ) : null}
521 {body}
522 </div>
523 );
524 }