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