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

ChatMarkdownMedia.tsx

487 lines16.8 KB

1import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
2import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
3import type { AssetResource, EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
4import { TriangleAlertIcon } from "lucide-react";
5import {
6 createContext,
7 memo,
8 use,
9 useState,
10 type ComponentProps,
11 type CSSProperties,
12 type KeyboardEvent as ReactKeyboardEvent,
13 type MouseEvent as ReactMouseEvent,
14} from "react";
15​
16import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
17import { cn } from "../../lib/utils";
18import { useRightPanelStore } from "../../rightPanelStore";
19import { MediaActions, type MediaActionSource } from "../media/MediaActions";
20import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
21import type { ExpandedImagePreview } from "./ExpandedImagePreview";
22import { markdownImageGallery, markdownImageItems } from "./markdownImageGallery";
23​
24const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]";
25const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn(
26 "max-h-[30rem]",
27 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
28);
29const CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME = "inline-block!";
30const CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME = "rounded-lg border border-border/40";
31const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME = cn(
32 "h-auto w-auto object-contain",
33 CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
34);
35​
36export function markdownImageCopy(alt: string, src: string, title: string | undefined): string {
37 const escapedAlt = alt.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]");
38 const titleSuffix =
39 title === undefined ? "" : ` "${title.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
40 return `![${escapedAlt}](${markdownDestination(src)}${titleSuffix})`;
42​
43// Raw HTML sources keep spaces and parentheses that a bare Markdown destination cannot hold.
44function markdownDestination(src: string): string {
45 if (!/[\s<>()]/.test(src)) return src;
46 const escaped = src
47 .replaceAll("\\", "\\\\")
48 .replaceAll("<", "\\<")
49 .replaceAll(">", "\\>")
50 .replaceAll("\n", "%0A")
51 .replaceAll("\r", "%0D");
52 return `<${escaped}>`;
54​
55function parseImageDimension(value: string | number | undefined): number {
56 return Number(typeof value === "string" ? value.trim().replace(/px$/i, "") : value);
58​
59/**
60 * `maxHeightRem` folds a height cap into the width bound: `max-height` alone
61 * would not feed back through `aspect-ratio` once `width` is definite, so a
62 * tall image would keep a box wider than the picture it draws.
63 */
64export function authoredImageSizeStyle(
65 width: string | number | undefined,
66 height: string | number | undefined,
67 maxHeightRem = 30,
68): CSSProperties | undefined {
69 const parsedWidth = parseImageDimension(width);
70 const parsedHeight = parseImageDimension(height);
71 const hasWidth = Number.isFinite(parsedWidth) && parsedWidth > 0;
72 const hasHeight = Number.isFinite(parsedHeight) && parsedHeight > 0;
73 if (hasWidth && hasHeight) {
74 return {
75 width: parsedWidth,
76 height: "auto",
77 aspectRatio: `${parsedWidth} / ${parsedHeight}`,
78 maxWidth: `min(100%, 30rem, ${(maxHeightRem * parsedWidth) / parsedHeight}rem)`,
79 };
80 }
81 if (hasWidth) return { maxWidth: `min(100%, 30rem, ${parsedWidth}px)` };
82 if (hasHeight) return { maxHeight: `min(30rem, ${parsedHeight}px)` };
83 return undefined;
85​
86const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
87 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
88 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
89);
90export const MarkdownLinkContext = createContext(false);
91/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
92export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
93​
94function expandableMarkdownImageProps(
95 onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined,
96 alt: string,
97) {
98 if (!onImageExpand) return {};
99 const previewName = alt.trim() || "image";
100 const expand = (event: ReactMouseEvent | ReactKeyboardEvent) => {
101 if (event.currentTarget.closest("a")) return;
102 event.preventDefault();
103 event.stopPropagation();
104 const item = markdownImageItems.get(event.currentTarget);
105 if (item) onImageExpand(markdownImageGallery(event.currentTarget, item));
106 };
107 return {
108 role: "button" as const,
109 tabIndex: 0,
110 "aria-label": `Preview ${previewName}`,
111 onClick: expand,
112 onKeyDown: (event: ReactKeyboardEvent) => {
113 if (event.key === "Enter" || event.key === " ") expand(event);
114 },
115 };
117​
118function ChatMarkdownMediaUnavailableLabel(props: {
119 readonly alt: string;
120 readonly kind?: "image" | "video" | "audio" | undefined;
121 readonly detail?: string | undefined;
122}) {
123 const label =
124 props.kind === "audio"
125 ? "Audio unavailable"
126 : props.kind === "video"
127 ? "Video unavailable"
128 : "Image unavailable";
129 return (
130 <span data-thread-find-ignore className="inline-flex items-center gap-1.5">
131 <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
132 {[label, props.alt, props.detail].filter(Boolean).join(" · ")}
133 </span>
134 );
136​
137export function ChatMarkdownImageFallback(props: {
138 readonly alt: string;
139 readonly copyMarkdown?: string | undefined;
140 readonly kind?: "image" | "video" | "audio";
141 readonly actionsSource?: MediaActionSource | undefined;
142 readonly detail?: string | undefined;
143}) {
144 const content = (
145 <span
146 data-markdown-copy={props.copyMarkdown}
147 className={cn(
148 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
149 "rounded-md border border-border/40 bg-muted/40 px-2 py-1 text-xs text-muted-foreground",
150 )}
151 >
152 <ChatMarkdownMediaUnavailableLabel alt={props.alt} kind={props.kind} detail={props.detail} />
153 </span>
154 );
155 return props.actionsSource ? (
156 <MediaActions source={props.actionsSource}>{content}</MediaActions>
157 ) : (
158 content
159 );
161​
162const CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME = cn(
163 "aspect-video w-full overflow-hidden bg-muted/60",
164 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
165 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
166);
167​
168/**
169 * Callers key this on the file's identity, not its URL: a re-signed URL for
170 * the same file keeps the decoded image on screen while the new bytes arrive,
171 * and a different file starts from the slot again.
172 */
173export function ChatMarkdownImage(props: {
174 readonly src: string | null;
175 readonly sourceFailed?: boolean | undefined;
176 readonly unavailableDetail?: string | undefined;
177 readonly alt: string;
178 readonly copyMarkdown: string | undefined;
179 readonly standalone: boolean;
180 readonly className?: string | undefined;
181 readonly style?: CSSProperties | undefined;
182 readonly imageProps?:
183 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
184 | undefined;
185 readonly actionsSource: MediaActionSource;
186 readonly originalUrl?: string | undefined;
187 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
188}) {
189 const [loadedSrc, setLoadedSrc] = useState<string | null>(null);
190 const [failedSrc, setFailedSrc] = useState<string | null>(null);
191 const src = props.src ?? loadedSrc;
192 const failed = props.sourceFailed === true || (src !== null && failedSrc === src);
193 const settled = src !== null && !failed && (!props.standalone || loadedSrc !== null);
194 // Cached images are complete before `onLoad` can fire.
195 const markLoadedIfComplete = (image: HTMLImageElement | null) => {
196 if (!image) return;
197 if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src);
198 markdownImageItems.set(image, {
199 src,
200 name: props.alt.trim() || "image",
201 actionsSource: props.actionsSource,
202 ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),
203 });
204 };
205 const imageEvents = (loadingSrc: string) => ({
206 onLoad: () => {
207 setLoadedSrc(loadingSrc);
208 setFailedSrc(null);
209 },
210 onError: () => {
211 setFailedSrc(loadingSrc);
212 setLoadedSrc(null);
213 },
214 });
215​
216 if (settled) {
217 return (
218 <MediaActions source={props.actionsSource}>
219 <img
220 {...props.imageProps}
221 ref={markLoadedIfComplete}
222 src={src}
223 alt={props.alt}
224 data-markdown-copy={props.copyMarkdown}
225 decoding="async"
226 loading="lazy"
227 draggable={false}
228 className={cn(
229 CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
230 props.className,
231 props.onImageExpand && "cursor-zoom-in",
232 )}
233 style={props.style}
234 {...expandableMarkdownImageProps(props.onImageExpand, props.alt)}
235 {...imageEvents(src)}
236 />
237 </MediaActions>
238 );
239 }
240 if (!props.standalone) {
241 return failed ? (
242 <ChatMarkdownImageFallback
243 alt={props.alt}
244 copyMarkdown={props.copyMarkdown}
245 actionsSource={props.actionsSource}
246 detail={props.unavailableDetail}
247 />
248 ) : (
249 <span
250 id={props.imageProps?.id}
251 data-markdown-copy={props.copyMarkdown}
252 role="status"
253 aria-label="Loading image"
254 className={CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME}
255 />
256 );
257 }
258 return (
259 <MediaActions source={props.actionsSource}>
260 <span
261 id={props.imageProps?.id}
262 data-markdown-copy={props.copyMarkdown}
263 className={cn(
264 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
265 CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME,
266 "relative",
267 )}
268 style={props.style}
269 {...(failed
270 ? { role: "alert" as const }
271 : { role: "status" as const, "aria-label": "Loading image" })}
272 >
273 {failed ? (
274 <span className="flex size-full items-center justify-center p-2 text-center text-xs text-muted-foreground">
275 <ChatMarkdownMediaUnavailableLabel alt={props.alt} detail={props.unavailableDetail} />
276 </span>
277 ) : src !== null ? (
278 <img
279 ref={markLoadedIfComplete}
280 src={src}
281 alt={props.alt}
282 decoding="async"
283 loading="lazy"
284 draggable={false}
285 className="invisible absolute inset-0 size-full"
286 {...imageEvents(src)}
287 />
288 ) : null}
289 </span>
290 </MediaActions>
291 );
293​
294export function ChatMarkdownVideo(props: {
295 readonly src: string | null;
296 readonly alt: string;
297 readonly copyMarkdown: string | undefined;
298 readonly originalUrl?: string | undefined;
299 readonly sourceFailed?: boolean | undefined;
300 readonly unavailableDetail?: string | undefined;
301 readonly style?: CSSProperties | undefined;
302 readonly mediaIdentity?: string | undefined;
303 readonly actionsSource?: MediaActionSource | undefined;
304 readonly onRetry?: (() => Promise<unknown>) | undefined;
305}) {
306 return (
307 <MediaVideoPlayer
308 key={props.mediaIdentity ?? props.copyMarkdown ?? props.src}
309 src={props.src}
310 sourceFailed={props.sourceFailed}
311 unavailableDetail={props.unavailableDetail}
312 label={props.alt}
313 originalUrl={props.originalUrl}
314 style={props.style}
315 copyMarkdown={props.copyMarkdown}
316 className={cn(
317 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
318 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
319 "w-full",
320 )}
321 videoClassName={cn(
322 CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
323 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
324 )}
325 onRetry={props.onRetry}
326 actionsSource={props.actionsSource}
327 />
328 );
330​
331type ChatMarkdownAssetResource = Extract<
332 AssetResource,
333 {
334 readonly _tag:
335 | "attachment"
336 | "workspace-file"
337 | "media-file"
338 | typeof SOURCE_CONTROL_MEDIA_ASSET
339 | "tool-output-image";
340 }
341>;
342​
343export function assetMediaActionsSource(input: {
344 readonly environmentId: EnvironmentId;
345 readonly resource: ChatMarkdownAssetResource;
346 readonly kind: "image" | "video";
347 readonly name: string;
348 readonly src: string | null;
349 readonly workspaceRoot?: string | undefined;
350 readonly originalUrl?: string | undefined;
351 readonly downloadable?: boolean | undefined;
352}): MediaActionSource {
353 const { environmentId, resource } = input;
354 const path =
355 resource._tag === "media-file"
356 ? resource.path
357 : resource._tag === "workspace-file" && input.workspaceRoot
358 ? `${input.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}`
359 : undefined;
360 const reference = path
361 ? mediaFileReference(path, input.workspaceRoot)
362 : input.originalUrl
363 ? mediaUrlReference(input.originalUrl)
364 : undefined;
365 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
366 return {
367 kind: input.kind,
368 name: input.name,
369 src: input.src,
370 ...(input.downloadable === false ? {} : { asset: { environmentId, resource } }),
371 ...(reference ? { reference } : {}),
372 ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file")
373 ? {
374 onOpenFile: () =>
375 useRightPanelStore
376 .getState()
377 .openFile({ environmentId, threadId: resource.threadId }, relativePath),
378 }
379 : {}),
380 };
382​
383export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: {
384 readonly environmentId: EnvironmentId;
385 readonly resource: ChatMarkdownAssetResource;
386 readonly kind?: "image" | "video";
387 readonly alt: string;
388 readonly copyMarkdown?: string;
389 readonly srcFragment?: string;
390 readonly standalone?: boolean | undefined;
391 readonly maxHeightRem?: number | undefined;
392 readonly style?: CSSProperties | undefined;
393 readonly className?: string | undefined;
394 readonly imageProps?:
395 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
396 | undefined;
397 readonly originalUrl?: string | undefined;
398 readonly framed?: boolean | undefined;
399 readonly fallbackSrc?: string | undefined;
400 readonly workspaceRoot?: string | undefined;
401 readonly workspaceMutationId?: string | null | undefined;
402 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
403}) {
404 const resource = props.resource;
405 const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
406 const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
407 const assetUrl = useAssetUrlState(
408 props.environmentId,
409 resource,
410 workspaceMutationId !== undefined &&
411 props.kind !== "video" &&
412 (resource._tag === "media-file" || resource._tag === "workspace-file")
413 ? workspaceMutationId
414 : undefined,
415 );
416 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
417 const fallbackSrc = assetUrl._tag === "Failure" ? props.fallbackSrc : undefined;
418 const missingFileAccess =
419 assetUrl._tag === "Failure" &&
420 assetUrl.reason === "missing-file-access" &&
421 fallbackSrc === undefined;
422 const unavailableDetail = missingFileAccess ? MISSING_FILE_ACCESS_MESSAGE : undefined;
423 const src =
424 assetUrl._tag === "Success"
425 ? assetUrl.url + (props.srcFragment ?? "")
426 : fallbackSrc === undefined
427 ? null
428 : fallbackSrc + (props.srcFragment ?? "");
429 const knownSize = assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined;
430 const maxHeightRem = props.maxHeightRem ?? 30;
431 const style =
432 props.style ??
433 (knownSize
434 ? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem)
435 : maxHeightRem !== 30
436 ? { maxHeight: `${maxHeightRem}rem` }
437 : undefined);
438 const actionsSource = assetMediaActionsSource({
439 environmentId: props.environmentId,
440 resource,
441 kind: props.kind ?? "image",
442 name: props.alt || (props.kind ?? "image"),
443 src,
444 workspaceRoot: props.workspaceRoot,
445 originalUrl: props.originalUrl,
446 downloadable: fallbackSrc === undefined,
447 });
448​
449 if (props.kind === "video") {
450 return (
451 <ChatMarkdownVideo
452 src={src}
453 sourceFailed={assetUrl._tag === "Failure" && fallbackSrc === undefined}
454 unavailableDetail={unavailableDetail}
455 alt={props.alt}
456 copyMarkdown={props.copyMarkdown}
457 originalUrl={props.originalUrl}
458 style={props.style}
459 mediaIdentity={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
460 // Re-signing cannot grant the file access this connection lacks.
461 onRetry={missingFileAccess ? undefined : refreshAssetUrl}
462 actionsSource={actionsSource}
463 />
464 );
465 }
466​
467 return (
468 <ChatMarkdownImage
469 key={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
470 src={src}
471 sourceFailed={assetUrl._tag === "Failure" && fallbackSrc === undefined}
472 unavailableDetail={unavailableDetail}
473 alt={props.alt}
474 copyMarkdown={props.copyMarkdown}
475 standalone={props.standalone ?? true}
476 className={cn(
477 props.framed === false ? undefined : CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME,
478 props.className,
479 )}
480 style={style}
481 imageProps={props.imageProps}
482 actionsSource={actionsSource}
483 originalUrl={props.originalUrl}
484 onImageExpand={props.onImageExpand}
485 />
486 );
487});