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

HtmlRenderWebView.tsx

289 lines10.6 KB

1import { useNavigation } from "@react-navigation/native";
2import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import {
4 htmlRenderFileName,
5 htmlRenderFrameHeight,
6 htmlRenderThemeFragment,
7 htmlRenderThemeMessage,
8 type HtmlRenderReference,
9 type HtmlRenderTheme,
10} from "@t3tools/shared/htmlRender";
11import { useEffect, useMemo, useRef, useState } from "react";
12import { ActivityIndicator, Platform, Pressable, View, type ColorValue } from "react-native";
13import { WebView, type WebViewMessageEvent } from "react-native-webview";
14​
15import { SymbolView } from "../../components/AppSymbol";
16import { AppText as Text } from "../../components/AppText";
17import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
18import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
19import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";
20import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
21​
22const ROW_BOTTOM_MARGIN = 8;
23const FULL_SCREEN_GUTTER = 16;
24​
25/** A render row is its frame's height plus spacing; the page's content never sizes it. */
26export function htmlRenderRowHeight(frameHeight: number) {
27 return frameHeight + ROW_BOTTOM_MARGIN;
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 );
45​
46function postTheme(view: WebView<object> | null, theme: HtmlRenderTheme) {
47 view?.injectJavaScript(
48 `window.postMessage(${JSON.stringify(htmlRenderThemeMessage(theme))}, "*"); true;`,
49 );
51​
52const OVERFLOW_MESSAGE_TYPE = "t3-html-render-overflow";
53​
54// Reports whether the page overflows its frame, so a feed row only takes scroll
55// gestures from a page that can use them.
56const OVERFLOW_SCRIPT = `(function(){var last;function report(){var d=document.documentElement,b=document.body;var o=Math.max(d.scrollHeight,b?b.scrollHeight:0)>window.innerHeight+1||Math.max(d.scrollWidth,b?b.scrollWidth:0)>window.innerWidth+1;if(o===last)return;last=o;window.ReactNativeWebView.postMessage(JSON.stringify({type:${JSON.stringify(OVERFLOW_MESSAGE_TYPE)},overflow:o}));}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;`;
57​
58function readOverflowMessage(data: string) {
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 "overflow" in message &&
66 typeof message.overflow === "boolean"
67 ? message.overflow
68 : null;
69 } catch {
70 return null;
71 }
73​
74const withoutFragment = (url: string) => url.split("#", 1)[0];
75​
76/**
77 * An agent's HTML page, themed before first paint and kept in step with the app theme.
78 * The page may move within its own document; links leave for the browser.
79 */
80export function HtmlRenderWebView(props: {
81 readonly uri: string;
82 readonly title: string;
83 /** Inside the feed, the page takes scroll gestures only when it overflows its frame. */
84 readonly nested: boolean;
85 readonly onLoadError?: () => void;
86}) {
87 const theme = useHtmlRenderTheme();
88 const [initialTheme] = useState(theme);
89 const [generation, setGeneration] = useState(0);
90 const [loaded, setLoaded] = useState(false);
91 const [overflows, setOverflows] = useState(false);
92 const webView = useRef<WebView<object>>(null);
93 const crashes = useRef(0);
94 // The theme the loaded document shows; null until it loads.
95 const shownTheme = useRef<HtmlRenderTheme | null>(null);
96 const source = useMemo(
97 () => ({ uri: props.uri + htmlRenderThemeFragment(initialTheme) }),
98 [props.uri, initialTheme],
99 );
100 useEffect(() => {
101 if (shownTheme.current === null || shownTheme.current === theme) return;
102 shownTheme.current = theme;
103 postTheme(webView.current, theme);
104 }, [theme]);
105 const restart = () => {
106 // A page that keeps crashing its web process is not reloaded forever.
107 crashes.current += 1;
108 if (crashes.current > 1) {
109 props.onLoadError?.();
110 return;
111 }
112 shownTheme.current = null;
113 setLoaded(false);
114 setOverflows(false);
115 setGeneration((value) => value + 1);
116 };
117 const scrollable = !props.nested || overflows;
118 // Pages have no horizontal padding of their own, so full screen adds the
119 // feed's gutter in the page's background color.
120 return (
121 <View
122 style={
123 props.nested
124 ? { flex: 1 }
125 : {
126 flex: 1,
127 paddingHorizontal: FULL_SCREEN_GUTTER,
128 backgroundColor: theme.variables["--background"],
129 }
130 }
131 >
132 <WebView<object>
133 key={generation}
134 ref={webView}
135 source={source}
136 accessibilityLabel={props.title}
137 style={{ flex: 1, backgroundColor: "transparent" }}
138 allowsInlineMediaPlayback
139 automaticallyAdjustContentInsets={!props.nested}
140 bounces={!props.nested}
141 showsVerticalScrollIndicator={!props.nested}
142 showsHorizontalScrollIndicator={!props.nested}
143 scrollEnabled={scrollable}
144 nestedScrollEnabled={props.nested && overflows}
145 overScrollMode={props.nested ? "never" : "always"}
146 // Only the page itself loads here; other top-frame navigations are
147 // dropped. A link the reader taps opens as a new window, which the
148 // platform allows only from a tap, and goes to the browser.
149 onShouldStartLoadWithRequest={(request) =>
150 request.isTopFrame === false ||
151 withoutFragment(request.url) === withoutFragment(props.uri)
152 }
153 onOpenWindow={(event) => {
154 const url = event.nativeEvent.targetUrl;
155 if (/^https?:/i.test(url)) void tryOpenExternalUrl(url, "html-render");
156 }}
157 onLoadEnd={() => {
158 setLoaded(true);
159 shownTheme.current = theme;
160 if (theme !== initialTheme) postTheme(webView.current, theme);
161 }}
162 onError={props.onLoadError}
163 onHttpError={props.onLoadError}
164 onContentProcessDidTerminate={restart}
165 onRenderProcessGone={restart}
166 {...(props.nested
167 ? {
168 injectedJavaScript: OVERFLOW_SCRIPT,
169 onMessage: (event: WebViewMessageEvent) => {
170 const overflow = readOverflowMessage(event.nativeEvent.data);
171 if (overflow !== null) setOverflows(overflow);
172 },
173 }
174 : {})}
175 />
176 {loaded ? null : (
177 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
178 <ActivityIndicator />
179 </View>
180 )}
181 </View>
182 );
184​
185/** A completed `html_render` call in the thread feed: the page itself, at a fixed height. */
186export function ThreadHtmlRender(props: {
187 readonly environmentId: EnvironmentId;
188 readonly threadId: ThreadId;
189 readonly render: HtmlRenderReference;
190 /** The feed's content width; the frame's height follows the page's measured height there. */
191 readonly frameWidth: number;
192 readonly iconColor: ColorValue;
193}) {
194 const navigation = useNavigation();
195 const { attachmentId, title } = props.render;
196 const height = htmlRenderFrameHeight(props.render, props.frameWidth);
197 const fileName = htmlRenderFileName(title);
198 const resource = useMemo(
199 () => ({
200 _tag: "attachment" as const,
201 attachmentId,
202 fileName,
203 mimeType: "text/html",
204 disposition: "inline" as const,
205 }),
206 [attachmentId, fileName],
207 );
208 const asset = useAssetUrlState(props.environmentId, resource);
209 const refresh = useRefreshAssetUrl(props.environmentId, resource);
210 // Signed URLs are re-minted periodically; following them would reload the page.
211 const [uri, setUri] = useState<string | null>(null);
212 if (uri === null && asset._tag === "Success") setUri(asset.url);
213 const [failed, setFailed] = useState(false);
214 // A failed load retries once with a fresh URL, or remounts on the same one,
215 // since the failure may have been the connection rather than the URL.
216 const [attempt, setAttempt] = useState(0);
217 const retried = useRef(false);
218 const handleLoadError = () => {
219 if (retried.current) {
220 setFailed(true);
221 return;
222 }
223 retried.current = true;
224 void refresh().then((next) => {
225 if (next === null) setFailed(true);
226 else if (next !== uri) setUri(next);
227 else setAttempt((value) => value + 1);
228 });
229 };
230​
231 return (
232 <View style={{ marginBottom: ROW_BOTTOM_MARGIN }}>
233 <View style={{ height }}>
234 {uri !== null && !failed ? (
235 <HtmlRenderWebView
236 key={`${uri}:${attempt}`}
237 uri={uri}
238 title={title}
239 nested
240 onLoadError={handleLoadError}
241 />
242 ) : failed || asset._tag === "Failure" ? (
243 <Pressable
244 accessibilityRole="button"
245 accessibilityLabel={`Reload ${title}`}
246 className="flex-1 items-center justify-center"
247 onPress={() => {
248 retried.current = false;
249 setFailed(false);
250 if (uri === null) void refresh().then((next) => next !== null && setUri(next));
251 }}
252 >
253 <Text className="text-sm text-foreground-muted">Page unavailable</Text>
254 </Pressable>
255 ) : (
256 <View className="flex-1 items-center justify-center">
257 <ActivityIndicator />
258 </View>
259 )}
260 {uri !== null && !failed ? (
261 <Pressable
262 accessibilityRole="button"
263 accessibilityLabel={`Open ${title}`}
264 hitSlop={8}
265 className="absolute right-1.5 top-1.5 h-7 w-7 items-center justify-center rounded-full border border-border/60 bg-surface/80"
266 onPress={() =>
267 navigation.navigate("ThreadAttachment", {
268 environmentId: String(props.environmentId),
269 threadId: String(props.threadId),
270 attachmentId,
271 name: fileName,
272 mimeType: "text/html",
273 sizeBytes: "0",
274 htmlRender: "1",
275 })
276 }
277 >
278 <SymbolView
279 name="arrow.up.left.and.arrow.down.right"
280 size={12}
281 tintColor={props.iconColor}
282 type="monochrome"
283 />
284 </Pressable>
285 ) : null}
286 </View>
287 </View>
288 );