Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

HtmlRenderWebView.tsx

269 lines9.6 KB

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