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