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

ChatMarkdownMedia.tsx

525 lines18.3 KB

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