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