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