Open History to see the last commit
1import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
2import { createContext, useContext, useEffect, useId, useState } from "react";
3import {
4 ActivityIndicator,
5 Image,
6 Pressable,
7 StyleSheet,
8 View,
9 type ViewStyle,
10} from "react-native";
11
12import { AppText as Text } from "../../components/AppText";
13import type { FilePreviewSource } from "../../components/FilePreviewModal";
14import { MediaActionsMenu } from "../../components/MediaActionsMenu";
15import { PresentationSource } from "../../components/NativePresentation";
16import { useMediaActions } from "../../state/mediaActions";
17import { type MediaActionsSource } from "../../lib/mediaActionsSource";
18import { useAssetUrlState } from "../../state/assets";
19import {
20 MARKDOWN_IMAGE_MAX_WIDTH,
21 type MarkdownImageDisplaySize,
22 resolveMarkdownImageDisplaySize,
23} from "./markdownImageSize";
24
25/**
26 * Width the feed lays markdown out in. The feed already knows this from its
27 * viewport, so an image can size its frame on the first render instead of
28 * waiting for its own onLayout, which would change the row's height once
29 * more after the list has positioned the rows below it. It is an upper
30 * bound: a list item or blockquote indents its column, and the measured
31 * width takes over once it is known.
32 */
33export const MarkdownImageAvailableWidthContext = createContext(0);
34
35export function ThreadMarkdownImageView(props: {
36 readonly uri: string | null;
37 readonly sourceKey: string;
38 readonly unavailable: boolean;
39 readonly alt: string | null;
40 /** Pixel size from the server, when it could read the header; the frame is final from the first render. */
41 readonly knownSize?: { readonly width: number; readonly height: number } | undefined;
42 readonly actionsSource?: MediaActionsSource;
43 readonly onPressPreview: (source: FilePreviewSource) => void;
44}) {
45 const sourceIdentifier = useId();
46 const mediaActions = useMediaActions(props.actionsSource);
47 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
48 const [measuredWidth, setMeasuredWidth] = useState(0);
49 const availableWidth =
50 measuredWidth > 0 && contextWidth > 0
51 ? Math.min(contextWidth, measuredWidth)
52 : contextWidth || measuredWidth;
53 const [decodedSize, setDecodedSize] = useState<{ width: number; height: number } | null>(null);
54 const [failedUri, setFailedUri] = useState<string | null>(null);
55
56 useEffect(() => {
57 setDecodedSize(null);
58 }, [props.sourceKey]);
59
60 useEffect(() => {
61 setFailedUri(null);
62 }, [props.uri]);
63
64 // The decoded size is what the platform actually drew, so it wins over the
65 // server's header hint once it exists.
66 const sourceSize = decodedSize ?? props.knownSize ?? null;
67 const displaySize: MarkdownImageDisplaySize | null =
68 sourceSize === null || availableWidth <= 0
69 ? null
70 : resolveMarkdownImageDisplaySize({
71 sourceWidth: sourceSize.width,
72 sourceHeight: sourceSize.height,
73 availableWidth,
74 });
75 const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
76 const placeholderWidth: ViewStyle["width"] =
77 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
78 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
79
80 return (
81 <View
82 onLayout={(event) => setMeasuredWidth(event.nativeEvent.layout.width)}
83 style={{ alignSelf: "stretch", gap: 6 }}
84 >
85 {props.uri === null || failed ? (
86 <MediaActionsMenu media={mediaActions}>
87 <Pressable
88 accessibilityRole="imagebutton"
89 accessibilityLabel={props.alt ?? "Markdown image"}
90 accessibilityHint={
91 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
92 }
93 className="items-center justify-center rounded-[10px] bg-md-code-bg"
94 style={frameStyle}
95 >
96 {failed ? (
97 <Text className="text-xs text-foreground-muted">Image unavailable</Text>
98 ) : (
99 <ActivityIndicator />
100 )}
101 </Pressable>
102 </MediaActionsMenu>
103 ) : (
104 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
105 <MediaActionsMenu media={mediaActions}>
106 <Pressable
107 accessibilityRole="imagebutton"
108 accessibilityLabel={props.alt ?? "Markdown image"}
109 accessibilityHint={
110 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
111 }
112 onPress={() =>
113 props.onPressPreview({
114 kind: "image",
115 uri: props.uri!,
116 name: props.actionsSource?.name ?? props.alt ?? "Image",
117 sourceIdentifier,
118 actionsSource: props.actionsSource,
119 })
120 }
121 style={{ alignSelf: "flex-start" }}
122 >
123 <View
124 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
125 style={frameStyle}
126 >
127 <ThreadMarkdownImageRequest
128 key={props.uri}
129 uri={props.uri}
130 onLoad={setDecodedSize}
131 onError={() => setFailedUri(props.uri)}
132 />
133 </View>
134 </Pressable>
135 </MediaActionsMenu>
136 </PresentationSource>
137 )}
138 {props.alt ? (
139 <Text selectable className="text-xs text-foreground-muted">
140 {props.alt}
141 </Text>
142 ) : null}
143 </View>
144 );
145}
146
147function ThreadMarkdownImageRequest(props: {
148 readonly uri: string;
149 readonly onLoad: (sourceSize: { width: number; height: number }) => void;
150 readonly onError: () => void;
151}) {
152 const [loaded, setLoaded] = useState(false);
153
154 return (
155 <>
156 <Image
157 source={{ uri: props.uri }}
158 resizeMode="contain"
159 accessible={false}
160 onLoad={(event) => {
161 setLoaded(true);
162 props.onLoad(event.nativeEvent.source);
163 }}
164 onError={props.onError}
165 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
166 />
167 {loaded ? null : (
168 <View
169 pointerEvents="none"
170 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
171 >
172 <Text className="text-xs text-foreground-muted">Loading image…</Text>
173 </View>
174 )}
175 </>
176 );
177}
178
179/** Environment-hosted image that loads through a signed asset URL. */
180export function ThreadMarkdownImage(props: {
181 readonly environmentId: EnvironmentId;
182 readonly resource: Extract<
183 AssetResource,
184 { readonly _tag: "attachment" | "media-file" | "tool-output-image" }
185 >;
186 readonly alt: string | null;
187 readonly srcFragment?: string;
188 readonly actionsSource?: MediaActionsSource;
189 readonly onPressPreview: (source: FilePreviewSource) => void;
190}) {
191 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
192
193 return (
194 <ThreadMarkdownImageView
195 uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}
196 sourceKey={
197 props.resource._tag === "attachment"
198 ? `attachment:${props.resource.attachmentId}`
199 : props.resource._tag === "tool-output-image"
200 ? `tool-output:${props.resource.itemId}:${props.resource.index}`
201 : `workspace:${props.resource.path}`
202 }
203 unavailable={assetUrl._tag === "Failure"}
204 knownSize={assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined}
205 alt={props.alt}
206 actionsSource={props.actionsSource}
207 onPressPreview={props.onPressPreview}
208 />
209 );
210}
211
212export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
213 return (
214 <ThreadMarkdownImageView
215 uri={null}
216 sourceKey="unavailable"
217 unavailable
218 alt={props.alt}
219 onPressPreview={() => undefined}
220 />
221 );
222}