Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AttachmentFilePreview.tsx

340 lines13.3 KB

1import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
2import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
3import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
4import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5import { settlePromise } from "@t3tools/client-runtime/state/runtime";
6import * as AsyncResult from "effect/reactivity/AsyncResult";
7import * as Cause from "effect/Cause";
8import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
9import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";
10import { Check, Code2, Copy, Eye, Table2 } from "lucide";
11import { lazy, Suspense, useEffect, useRef, useState } from "react";
12​
13import { useAssetUrlRefresh } from "~/assets/assetUrls";
14import ChatMarkdown from "~/components/ChatMarkdown";
15import { MorphIcon } from "~/components/MorphIcon";
16import { ScrollArea } from "~/components/ui/scroll-area";
17import { toastManager } from "~/components/ui/toast";
18import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
19import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
20import { cn } from "~/lib/utils";
21​
22import { AudioPreview } from "./AudioPreview";
23import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
24import { DelimitedTablePreview } from "./DelimitedTablePreview";
25import {
26 FILE_SURFACE_SUBHEADER_CLASS,
27 FileSurfaceAction,
28 FileSurfaceFailure,
29 FileSurfaceLoading,
30 FileSurfaceNotice,
31} from "./fileSurfaceChrome";
32​
33const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
34​
35const STALE_URL_MS = 5 * 60_000;
36​
37export function ReadOnlySourcePreview(props: { name: string; text: string }) {
38 return (
39 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
40 <SourcePreview {...props} />
41 </Suspense>
42 );
44​
45function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
46 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
47 if (mode === "table") return rendered ? "Show source" : "Show table";
48 return rendered ? "Show HTML source" : "Show rendered page";
50​
51export function AttachmentFilePreview(props: {
52 name: string;
53 mimeType: string;
54 sizeBytes: number;
55 file?: Blob | null;
56 asset?: { environmentId: EnvironmentId; attachmentId: string };
57 htmlRender?: boolean;
58 threadRef?: ScopedThreadRef;
59 origin?: string;
60 onRemove?: () => void;
61 onClose?: () => void;
62}) {
63 const kind = filePreviewKind(props);
64 const delimiter = filePreviewDelimiter(props);
65 const renderedMode =
66 kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
67 const attachmentId = props.asset?.attachmentId;
68 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: props.name });
69 // useAssetUrlRefresh keys its callback on these objects, so they must stay cached.
70 const resource = attachmentId
71 ? {
72 _tag: "attachment" as const,
73 attachmentId,
74 fileName: props.name,
75 mimeType: props.mimeType,
76 disposition: "inline" as const,
77 }
78 : null;
79 const downloadResource = resource ? { ...resource, disposition: "attachment" as const } : null;
80 const refresh = useAssetUrlRefresh(
81 props.file ? null : (props.asset?.environmentId ?? null),
82 props.file ? null : resource,
83 );
84 const prepareDownload = useAssetUrlRefresh(props.asset?.environmentId ?? null, downloadResource);
85 const [saving, setSaving] = useState(false);
86 const [localUrl, setLocalUrl] = useState<string | null>(null);
87 const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
88 const [rendered, setRendered] = useState(true);
89 const [revision, setRevision] = useState(0);
90 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
91 const [error, setError] = useState<string | null>(null);
92 const [contentError, setContentError] = useState<string | null>(null);
93 const authorizedAt = useRef(0);
94 useEffect(() => {
95 if (!props.file) return;
96 const url = URL.createObjectURL(props.file);
97 // oxlint-disable-next-line react/set-state-in-effect -- Publish an object URL only after its cleanup is registered for this Blob.
98 setLocalUrl(url);
99 return () => URL.revokeObjectURL(url);
100 }, [props.file]);
101 useEffect(() => {
102 if (props.file) return;
103 let cancelled = false;
104 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
105 setRemoteUrl(null);
106 setError(null);
107 void refresh()
108 .then((url) => {
109 if (cancelled) return;
110 if (!url) throw new Error("Reconnect to the environment and try again.");
111 authorizedAt.current = Date.now();
112 setRemoteUrl(url);
113 })
114 .catch((cause: unknown) => {
115 if (!cancelled)
116 setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
117 });
118 return () => {
119 cancelled = true;
120 };
121 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
122 }, [props.file, refresh, revision]);
123 const url = props.file ? localUrl : remoteUrl;
124 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
125 useEffect(() => {
126 if (!needsText || !url) return;
127 const controller = new AbortController();
128 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
129 setContent(null);
130 setContentError(null);
131 const file = props.file;
132 void (async () => {
133 if (!file && Date.now() - authorizedAt.current > STALE_URL_MS) {
134 const target = await refresh();
135 if (controller.signal.aborted) return;
136 if (!target) throw new Error("Reconnect to the environment and try again.");
137 authorizedAt.current = Date.now();
138 if (target !== url) {
139 setRemoteUrl(target);
140 return;
141 }
142 }
143 const response = file
144 ? { ok: true, body: file.stream() }
145 : await fetch(url, {
146 signal: controller.signal,
147 ...(props.sizeBytes > 0
148 ? { headers: { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } }
149 : {}),
150 cache: revision === 0 ? "default" : "reload",
151 });
152 const result = await readFilePreviewResponse(response, controller.signal);
153 if (!controller.signal.aborted) setContent(result);
154 })().catch((cause: unknown) => {
155 if (!controller.signal.aborted)
156 setContentError(cause instanceof Error ? cause.message : "Could not load this file.");
157 });
158 return () => controller.abort();
159 }, [url, needsText, revision, props.sizeBytes, props.file, refresh]);
160 const failure = error ?? (needsText ? contentError : null);
161 const wordWrap = useClientSettings((settings) => settings.wordWrap);
162 const updateClientSettings = useUpdateClientSettings();
163 const showsRawText =
164 failure === null &&
165 needsText &&
166 content !== null &&
167 !(delimiter && rendered) &&
168 !(kind === "markdown" && rendered);
169​
170 const save = () => {
171 setSaving(true);
172 void settlePromise(async () => {
173 let file = props.file;
174 if (!file) {
175 const target = await prepareDownload();
176 if (!target) throw new Error("Reconnect to the environment and try again.");
177 const response = await fetch(target);
178 if (!response.ok) throw new Error("The file could not be loaded. Try again.");
179 file = await response.blob();
180 }
181 // A Blob keeps cross-origin downloads inside the desktop client instead of
182 // navigating its custom app scheme to an external browser.
183 const downloadUrl = URL.createObjectURL(file);
184 // Scheduled before the click so the URL is revoked even if the click throws.
185 setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000);
186 const anchor = document.createElement("a");
187 anchor.href = downloadUrl;
188 anchor.download = props.name;
189 anchor.click();
190 }).then((result) => {
191 if (!AsyncResult.isSuccess(result)) {
192 const cause = Cause.squash(result.cause);
193 toastManager.add({
194 type: "error",
195 title: "Could not save file",
196 description: cause instanceof Error ? cause.message : "Please try again.",
197 });
198 }
199 setSaving(false);
200 });
201 };
202​
203 const body = failure ? (
204 <FileSurfaceFailure
205 message={failure}
206 onRetry={() => {
207 setError(null);
208 setRevision((value) => value + 1);
209 }}
210 />
211 ) : !url || (needsText && !content) ? (
212 <FileSurfaceLoading />
213 ) : needsText && content ? (
214 delimiter && rendered ? (
215 <DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />
216 ) : kind === "markdown" && rendered ? (
217 <ScrollArea className="min-h-0 flex-1">
218 <ChatMarkdown text={content.text} cwd={undefined} className="mx-auto max-w-4xl px-6 py-5" />
219 </ScrollArea>
220 ) : (
221 <ReadOnlySourcePreview name={props.name} text={content.text} />
222 )
223 ) : kind === "pdf" || kind === "html" ? (
224 <BrowserDocumentFrame
225 src={url}
226 title={props.name}
227 pdf={kind === "pdf"}
228 htmlRender={props.htmlRender === true}
229 threadRef={props.threadRef}
230 />
231 ) : kind === "audio" ? (
232 <AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />
233 ) : kind === "video" ? (
234 <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
235 <video
236 controls
237 playsInline
238 src={url}
239 aria-label={props.name}
240 className="max-h-full max-w-full"
241 onError={() => setError("Unable to load video.")}
242 />
243 </div>
244 ) : kind === "image" ? (
245 // oxlint-disable-next-line t3code/require-centered-scroll-gutter -- The image is capped at max-h-full max-w-full, so this never scrolls.
246 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
247 <img
248 src={url}
249 alt={props.name}
250 className="max-h-full max-w-full object-contain"
251 onError={() => setError("Unable to load image.")}
252 />
253 </div>
254 ) : (
255 <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
256 <p className="text-sm font-medium">No preview for this file</p>
257 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
258 Save it to open in an app that supports {props.name.split(".").at(-1) || "this format"}{" "}
259 files.
260 </p>
261 </div>
262 );
263​
264 return (
265 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
266 <div className={cn(FILE_SURFACE_SUBHEADER_CLASS)} data-surface-subheader>
267 <div className="flex min-w-0 flex-1 items-center text-xs">
268 <span className="shrink-0 px-0.5 text-muted-foreground">
269 {props.origin ?? "Attachment"}
270 </span>
271 <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
272 <span aria-current="page" className="min-w-0 truncate px-0.5 font-medium text-foreground">
273 {props.name}
274 </span>
275 {props.sizeBytes > 0 ? (
276 <span className="ml-2 shrink-0 text-muted-foreground">
277 {formatAttachmentSize(props.sizeBytes)}
278 </span>
279 ) : null}
280 </div>
281 {renderedMode ? (
282 <FileSurfaceAction
283 label={renderedToggleLabel(renderedMode, rendered)}
284 pressed={rendered}
285 onPress={() => setRendered((value) => !value)}
286 >
287 <MorphIcon
288 className="size-3.5"
289 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
290 />
291 </FileSurfaceAction>
292 ) : null}
293 {showsRawText ? (
294 <FileSurfaceAction
295 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
296 pressed={wordWrap}
297 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
298 >
299 <WrapTextIcon className="size-3.5" />
300 </FileSurfaceAction>
301 ) : null}
302 {content ? (
303 <FileSurfaceAction
304 label={isCopied ? "Copied" : content.truncated ? "Copy preview" : "Copy contents"}
305 onPress={() => copyToClipboard(content.text, undefined)}
306 >
307 <MorphIcon className="size-3.5" icon={isCopied ? Check : Copy} />
308 </FileSurfaceAction>
309 ) : null}
310 {url ? (
311 <FileSurfaceAction
312 label={saving ? "Preparing file…" : "Save file"}
313 disabled={saving}
314 onPress={save}
315 >
316 <DownloadIcon className="size-3.5" />
317 </FileSurfaceAction>
318 ) : null}
319 {props.onRemove ? (
320 <FileSurfaceAction label="Remove from draft" onPress={props.onRemove}>
321 <Trash2Icon className="size-3.5" />
322 </FileSurfaceAction>
323 ) : null}
324 {props.onClose ? (
325 <FileSurfaceAction label="Close" onPress={props.onClose}>
326 <XIcon className="size-3.5" />
327 </FileSurfaceAction>
328 ) : null}
329 </div>
330 {content?.truncated ? (
331 <FileSurfaceNotice>
332 Preview limited to the first 1 MB
333 {props.sizeBytes > 0 ? ` of a ${props.sizeBytes.toLocaleString()} byte file` : ""}. Save
334 the file to read it in full.
335 </FileSurfaceNotice>
336 ) : null}
337 {body}
338 </div>
339 );