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