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