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