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

ThreadMarkdownImage.tsx

221 lines7.8 KB

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