Open History to see the last commit
1import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
2import { useNavigation } from "@react-navigation/native";
3import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import {
5 HTML_RENDER_NATIVE_OPEN_IMAGE_SCRIPT,
6 htmlRenderFileName,
7 htmlRenderFrameHeight,
8 htmlRenderThemeFragment,
9 htmlRenderThemeMessage,
10 readHtmlRenderImageRequest,
11 type HtmlRenderReference,
12 type HtmlRenderTheme,
13} from "@t3tools/shared/htmlRender";
14import { T, useGT } from "gt-react-native";
15import { useEffect, useRef, useState } from "react";
16import { Platform, Pressable, View, type ColorValue } from "react-native";
17import { WebView, type WebViewMessageEvent } from "react-native-webview";
18
19import { SymbolView } from "../../components/ui/AppSymbol";
20import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
21import { AppText as Text } from "../../components/ui/AppText";
22import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
23import { useOpenPullRequest } from "../../native/useOpenPullRequest";
24import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";
25import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
26import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate";
27
28const ROW_BOTTOM_MARGIN = 8;
29const ACTION_ROW_HEIGHT = 32;
30const FULL_SCREEN_GUTTER = 16;
31
32export function htmlRenderRowHeight(frameHeight: number) {
33 return ACTION_ROW_HEIGHT + frameHeight + ROW_BOTTOM_MARGIN;
34}
35
36export function useHtmlRenderTheme() {
37 const { themeId, themeAppearance, themeVariables, systemColorsActive } =
38 useAppearancePreferences();
39 return mobileHtmlRenderTheme({
40 themeId,
41 appearance: themeAppearance,
42 variables: themeVariables,
43 systemColors: systemColorsActive,
44 platform: Platform.OS,
45 });
46}
47
48function postTheme(view: WebView<object> | null, theme: HtmlRenderTheme) {
49 view?.injectJavaScript(
50 `window.postMessage(${JSON.stringify(htmlRenderThemeMessage(theme))}, "*"); true;`,
51 );
52}
53
54const OVERFLOW_MESSAGE_TYPE = "t3-html-render-overflow";
55
56const OVERFLOW_SCRIPT = `(function(){var last;function report(){var d=document.documentElement,b=document.body;var x=Math.max(d.scrollWidth,b?b.scrollWidth:0)>window.innerWidth+1,y=Math.max(d.scrollHeight,b?b.scrollHeight:0)>window.innerHeight+1,o=x+","+y;if(o===last)return;last=o;window.ReactNativeWebView.postMessage(JSON.stringify({type:${JSON.stringify(OVERFLOW_MESSAGE_TYPE)},x:x,y:y}));}report();if(window.ResizeObserver){var r=new ResizeObserver(report);r.observe(document.documentElement);if(document.body)r.observe(document.body);}window.addEventListener("resize",report);})();true;`;
57
58type Overflow = { readonly x: boolean; readonly y: boolean };
59
60const NO_OVERFLOW: Overflow = { x: false, y: false };
61
62function readOverflowMessage(message: unknown): Overflow | null {
63 return typeof message === "object" &&
64 message !== null &&
65 "type" in message &&
66 message.type === OVERFLOW_MESSAGE_TYPE &&
67 "x" in message &&
68 typeof message.x === "boolean" &&
69 "y" in message &&
70 typeof message.y === "boolean"
71 ? { x: message.x, y: message.y }
72 : null;
73}
74
75function parseMessage(data: string): unknown {
76 try {
77 return JSON.parse(data);
78 } catch {
79 return null;
80 }
81}
82
83function imagePreviewSource(message: unknown): FilePreviewSource | null {
84 const request = readHtmlRenderImageRequest(message);
85 if (request === undefined) return null;
86 const gallery = request.images.map((image) => ({
87 kind: "image" as const,
88 uri: image.src,
89 name: image.name,
90 }));
91 const selected = gallery[request.index];
92 return selected ? { ...selected, gallery } : null;
93}
94
95const withoutFragment = (url: string) => url.split("#", 1)[0];
96
97export function HtmlRenderWebView(props: {
98 readonly uri: string;
99 readonly title: string;
100 readonly nested: boolean;
101 readonly onLoadError?: () => void;
102}) {
103 const theme = useHtmlRenderTheme();
104 const openLink = useOpenPullRequest();
105 const [initialTheme] = useState(theme);
106 const [generation, setGeneration] = useState(0);
107 const [loaded, setLoaded] = useState(false);
108 const [overflow, setOverflow] = useState(NO_OVERFLOW);
109 const [preview, setPreview] = useState<FilePreviewSource | null>(null);
110 const webView = useRef<WebView<object>>(null);
111 const crashes = useRef(0);
112 const shownTheme = useRef<HtmlRenderTheme | null>(null);
113 const source = { uri: props.uri + htmlRenderThemeFragment(initialTheme) };
114 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts theme changes into the already loaded WebView
115 useEffect(() => {
116 if (shownTheme.current === null || shownTheme.current === theme) return;
117 shownTheme.current = theme;
118 postTheme(webView.current, theme);
119 }, [theme]);
120 const restart = () => {
121 crashes.current += 1;
122 if (crashes.current > 1) {
123 props.onLoadError?.();
124 return;
125 }
126 shownTheme.current = null;
127 setLoaded(false);
128 setOverflow(NO_OVERFLOW);
129 setGeneration((value) => value + 1);
130 };
131 const scrollable = !props.nested || overflow.x || overflow.y;
132 return (
133 <View
134 style={
135 props.nested
136 ? { flex: 1 }
137 : {
138 flex: 1,
139 paddingHorizontal: FULL_SCREEN_GUTTER,
140 backgroundColor: theme.variables["--background"],
141 }
142 }
143 >
144 <WebView<object>
145 key={generation}
146 ref={webView}
147 source={source}
148 accessibilityLabel={props.title}
149 style={{ flex: 1, backgroundColor: "transparent" }}
150 allowsInlineMediaPlayback
151 contentInsetAdjustmentBehavior={props.nested ? "never" : "automatic"}
152 bounces={!props.nested}
153 showsVerticalScrollIndicator={!props.nested}
154 showsHorizontalScrollIndicator={!props.nested}
155 scrollEnabled={scrollable}
156 decelerationRate={webViewDecelerationRate}
157 // Android's patched WebView always keeps horizontal drags. Only pages
158 // with vertical overflow hold vertical drags until they reach an edge.
159 nestedScrollEnabled={props.nested && overflow.y}
160 overScrollMode={props.nested ? "never" : "always"}
161 onShouldStartLoadWithRequest={(request) =>
162 request.isTopFrame === false ||
163 withoutFragment(request.url) === withoutFragment(props.uri)
164 }
165 onOpenWindow={(event) => {
166 const url = event.nativeEvent.targetUrl;
167 if (/^https?:/i.test(url)) void openLink(url);
168 }}
169 onLoadEnd={() => {
170 setLoaded(true);
171 shownTheme.current = theme;
172 if (theme !== initialTheme) postTheme(webView.current, theme);
173 }}
174 onError={props.onLoadError}
175 onHttpError={props.onLoadError}
176 onContentProcessDidTerminate={restart}
177 onRenderProcessGone={restart}
178 injectedJavaScript={
179 props.nested
180 ? OVERFLOW_SCRIPT + HTML_RENDER_NATIVE_OPEN_IMAGE_SCRIPT
181 : HTML_RENDER_NATIVE_OPEN_IMAGE_SCRIPT
182 }
183 onMessage={(event: WebViewMessageEvent) => {
184 const message = parseMessage(event.nativeEvent.data);
185 const image = imagePreviewSource(message);
186 if (image !== null) {
187 setPreview(image);
188 return;
189 }
190 const next = props.nested ? readOverflowMessage(message) : null;
191 if (next !== null) setOverflow(next);
192 }}
193 />
194 <FilePreviewModal source={preview} onRequestClose={() => setPreview(null)} />
195 {loaded ? null : (
196 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
197 <AppActivityIndicator />
198 </View>
199 )}
200 </View>
201 );
202}
203
204export function ThreadHtmlRender(props: {
205 readonly environmentId: EnvironmentId;
206 readonly threadId: ThreadId;
207 readonly render: HtmlRenderReference;
208 readonly frameWidth: number;
209 readonly iconColor: ColorValue;
210}) {
211 const gt = useGT();
212 const navigation = useNavigation();
213 const { attachmentId, title } = props.render;
214 const height = htmlRenderFrameHeight(props.render, props.frameWidth);
215 const fileName = htmlRenderFileName(title);
216 const resource = {
217 _tag: "attachment" as const,
218 attachmentId,
219 fileName,
220 mimeType: "text/html",
221 disposition: "inline" as const,
222 };
223 const asset = useAssetUrlState(props.environmentId, resource);
224 const refresh = useRefreshAssetUrl(props.environmentId, resource);
225 // Signed URLs are re-minted periodically; following them would reload the page.
226 const [uri, setUri] = useState<string | null>(null);
227 if (uri === null && asset._tag === "Success") setUri(asset.url);
228 const [failed, setFailed] = useState(false);
229 const [attempt, setAttempt] = useState(0);
230 const retried = useRef(false);
231 const handleLoadError = () => {
232 if (retried.current) {
233 setFailed(true);
234 return;
235 }
236 retried.current = true;
237 void refresh().then((next) => {
238 if (next === null) setFailed(true);
239 else if (next !== uri) setUri(next);
240 else setAttempt((value) => value + 1);
241 });
242 };
243
244 return (
245 <View style={{ marginBottom: ROW_BOTTOM_MARGIN }}>
246 <View style={{ height: ACTION_ROW_HEIGHT }} className="flex-row items-start justify-end">
247 {uri !== null && !failed ? (
248 <Pressable
249 accessibilityRole="button"
250 accessibilityLabel={gt`Open ${{ title }}`}
251 hitSlop={8}
252 className="h-7 w-7 items-center justify-center rounded-full border border-border/60 bg-card/80"
253 onPress={() =>
254 navigation.navigate("ThreadAttachment", {
255 environmentId: String(props.environmentId),
256 threadId: String(props.threadId),
257 attachmentId,
258 name: fileName,
259 mimeType: "text/html",
260 sizeBytes: "0",
261 htmlRender: "1",
262 })
263 }
264 >
265 <SymbolView
266 name="arrow.up.left.and.arrow.down.right"
267 size={12}
268 tintColor={props.iconColor}
269 type="monochrome"
270 />
271 </Pressable>
272 ) : null}
273 </View>
274 <View style={{ height }}>
275 {uri !== null && !failed ? (
276 <HtmlRenderWebView
277 key={`${uri}:${attempt}`}
278 uri={uri}
279 title={title}
280 nested
281 onLoadError={handleLoadError}
282 />
283 ) : failed || asset._tag === "Failure" ? (
284 <Pressable
285 accessibilityRole="button"
286 accessibilityLabel={gt`Reload ${{ title }}`}
287 className="flex-1 items-center justify-center"
288 onPress={() => {
289 retried.current = false;
290 setFailed(false);
291 if (uri === null) void refresh().then((next) => next !== null && setUri(next));
292 }}
293 >
294 <Text className="text-sm text-foreground-muted">
295 <T>Page unavailable</T>
296 </Text>
297 </Pressable>
298 ) : (
299 <View className="flex-1 items-center justify-center">
300 <AppActivityIndicator />
301 </View>
302 )}
303 </View>
304 </View>
305 );
306}