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

ThreadMarkdownImage.tsx

193 lines6.4 KB

1import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
2import { 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 { MARKDOWN_IMAGE_MAX_WIDTH, resolveMarkdownImageDisplaySize } from "./markdownImageSize";
19​
20export function ThreadMarkdownImageView(props: {
21 readonly uri: string | null;
22 readonly sourceKey: string;
23 readonly unavailable: boolean;
24 readonly alt: string | null;
25 readonly actionsSource?: MediaActionsSource;
26 readonly onPressPreview: (source: FilePreviewSource) => void;
27}) {
28 const sourceIdentifier = useId();
29 const mediaActions = useMediaActions(props.actionsSource);
30 const [availableWidth, setAvailableWidth] = useState(0);
31 const [sourceSize, setSourceSize] = useState<{ width: number; height: number } | null>(null);
32 const [failedUri, setFailedUri] = useState<string | null>(null);
33​
34 useEffect(() => {
35 setSourceSize(null);
36 }, [props.sourceKey]);
37​
38 useEffect(() => {
39 setFailedUri(null);
40 }, [props.uri]);
41​
42 const displaySize =
43 sourceSize === null
44 ? null
45 : resolveMarkdownImageDisplaySize({
46 sourceWidth: sourceSize.width,
47 sourceHeight: sourceSize.height,
48 availableWidth,
49 });
50 const failed = props.unavailable || (props.uri !== null && failedUri === props.uri);
51 const placeholderWidth: ViewStyle["width"] =
52 availableWidth > 0 ? Math.min(availableWidth, MARKDOWN_IMAGE_MAX_WIDTH) : "100%";
53 const frameStyle: ViewStyle = displaySize ?? { width: placeholderWidth, aspectRatio: 16 / 9 };
54​
55 return (
56 <View
57 onLayout={(event) => setAvailableWidth(event.nativeEvent.layout.width)}
58 style={{ alignSelf: "stretch", gap: 6 }}
59 >
60 {props.uri === null || failed ? (
61 <MediaActionsMenu media={mediaActions}>
62 <Pressable
63 accessibilityRole="imagebutton"
64 accessibilityLabel={props.alt ?? "Markdown image"}
65 accessibilityHint={
66 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
67 }
68 className="items-center justify-center rounded-[10px] bg-md-code-bg"
69 style={frameStyle}
70 >
71 {failed ? (
72 <Text className="text-xs text-foreground-muted">Image unavailable</Text>
73 ) : (
74 <ActivityIndicator />
75 )}
76 </Pressable>
77 </MediaActionsMenu>
78 ) : (
79 <PresentationSource identifier={sourceIdentifier} style={{ alignSelf: "flex-start" }}>
80 <MediaActionsMenu media={mediaActions}>
81 <Pressable
82 accessibilityRole="imagebutton"
83 accessibilityLabel={props.alt ?? "Markdown image"}
84 accessibilityHint={
85 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
86 }
87 onPress={() =>
88 props.onPressPreview({
89 kind: "image",
90 uri: props.uri!,
91 name: props.actionsSource?.name ?? props.alt ?? "Image",
92 sourceIdentifier,
93 actionsSource: props.actionsSource,
94 })
95 }
96 style={{ alignSelf: "flex-start" }}
97 >
98 <View
99 className="items-center justify-center overflow-hidden rounded-[10px] bg-md-code-bg"
100 style={{
101 ...frameStyle,
102 }}
103 >
104 <ThreadMarkdownImageRequest
105 key={props.uri}
106 uri={props.uri}
107 onLoad={setSourceSize}
108 onError={() => setFailedUri(props.uri)}
109 />
110 </View>
111 </Pressable>
112 </MediaActionsMenu>
113 </PresentationSource>
114 )}
115 {props.alt ? (
116 <Text selectable className="text-xs text-foreground-muted">
117 {props.alt}
118 </Text>
119 ) : null}
120 </View>
121 );
123​
124function ThreadMarkdownImageRequest(props: {
125 readonly uri: string;
126 readonly onLoad: (sourceSize: { width: number; height: number }) => void;
127 readonly onError: () => void;
128}) {
129 const [loaded, setLoaded] = useState(false);
130​
131 return (
132 <>
133 <Image
134 source={{ uri: props.uri }}
135 resizeMode="contain"
136 accessible={false}
137 onLoad={(event) => {
138 setLoaded(true);
139 props.onLoad(event.nativeEvent.source);
140 }}
141 onError={props.onError}
142 style={{ width: "100%", height: "100%", opacity: loaded ? 1 : 0 }}
143 />
144 {loaded ? null : (
145 <View
146 pointerEvents="none"
147 style={[StyleSheet.absoluteFill, { alignItems: "center", justifyContent: "center" }]}
148 >
149 <Text className="text-xs text-foreground-muted">Loading image…</Text>
150 </View>
151 )}
152 </>
153 );
155​
156/** Environment-hosted image that loads through a signed asset URL. */
157export function ThreadMarkdownImage(props: {
158 readonly environmentId: EnvironmentId;
159 readonly resource: Extract<AssetResource, { readonly _tag: "attachment" | "media-file" }>;
160 readonly alt: string | null;
161 readonly srcFragment?: string;
162 readonly actionsSource?: MediaActionsSource;
163 readonly onPressPreview: (source: FilePreviewSource) => void;
164}) {
165 const assetUrl = useAssetUrlState(props.environmentId, props.resource);
166​
167 return (
168 <ThreadMarkdownImageView
169 uri={assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : null}
170 sourceKey={
171 props.resource._tag === "attachment"
172 ? `attachment:${props.resource.attachmentId}`
173 : `workspace:${props.resource.path}`
174 }
175 unavailable={assetUrl._tag === "Failure"}
176 alt={props.alt}
177 actionsSource={props.actionsSource}
178 onPressPreview={props.onPressPreview}
179 />
180 );
182​
183export function ThreadMarkdownImageUnavailable(props: { readonly alt: string | null }) {
184 return (
185 <ThreadMarkdownImageView
186 uri={null}
187 sourceKey="unavailable"
188 unavailable
189 alt={props.alt}
190 onPressPreview={() => undefined}
191 />
192 );