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