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

ChatMarkdownMedia.tsx

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