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 { T, useGT } from "gt-react-native";
13import { useEffect, useRef, useState } from "react";
14import { Platform, Pressable, View, type ColorValue } from "react-native";
15import { WebView, type WebViewMessageEvent } from "react-native-webview";
16
17import { SymbolView } from "../../components/ui/AppSymbol";
18import { AppText as Text } from "../../components/ui/AppText";
19import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme";
20import { useOpenPullRequest } from "../../native/useOpenPullRequest";
21import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets";
22import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
23import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate";
24
25const ROW_BOTTOM_MARGIN = 8;
26const ACTION_ROW_HEIGHT = 32;
27const FULL_SCREEN_GUTTER = 16;
28
29export function htmlRenderRowHeight(frameHeight: number) {
30 return ACTION_ROW_HEIGHT + frameHeight + ROW_BOTTOM_MARGIN;
31}
32
33function useHtmlRenderTheme() {
34 const { themeId, themeAppearance, themeVariables, systemColorsActive } =
35 useAppearancePreferences();
36 return mobileHtmlRenderTheme({
37 themeId,
38 appearance: themeAppearance,
39 variables: themeVariables,
40 systemColors: systemColorsActive,
41 platform: Platform.OS,
42 });
43}
44
45function postTheme(view: WebView<object> | null, theme: HtmlRenderTheme) {
46 view?.injectJavaScript(
47 `window.postMessage(${JSON.stringify(htmlRenderThemeMessage(theme))}, "*"); true;`,
48 );
49}
50
51const OVERFLOW_MESSAGE_TYPE = "t3-html-render-overflow";
52
53const 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;`;
54
55type Overflow = { readonly x: boolean; readonly y: boolean };
56
57const NO_OVERFLOW: Overflow = { x: false, y: false };
58
59function readOverflowMessage(data: string): Overflow | null {
60 try {
61 const message: unknown = JSON.parse(data);
62 return typeof message === "object" &&
63 message !== null &&
64 "type" in message &&
65 message.type === OVERFLOW_MESSAGE_TYPE &&
66 "x" in message &&
67 typeof message.x === "boolean" &&
68 "y" in message &&
69 typeof message.y === "boolean"
70 ? { x: message.x, y: message.y }
71 : null;
72 } catch {
73 return null;
74 }
75}
76
77const withoutFragment = (url: string) => url.split("#", 1)[0];
78
79export function HtmlRenderWebView(props: {
80 readonly uri: string;
81 readonly title: string;
82 readonly nested: boolean;
83 readonly onLoadError?: () => void;
84}) {
85 const theme = useHtmlRenderTheme();
86 const openLink = useOpenPullRequest();
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 = { uri: props.uri + htmlRenderThemeFragment(initialTheme) };
95 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts theme changes into the already loaded WebView
96 useEffect(() => {
97 if (shownTheme.current === null || shownTheme.current === theme) return;
98 shownTheme.current = theme;
99 postTheme(webView.current, theme);
100 }, [theme]);
101 const restart = () => {
102 crashes.current += 1;
103 if (crashes.current > 1) {
104 props.onLoadError?.();
105 return;
106 }
107 shownTheme.current = null;
108 setLoaded(false);
109 setOverflow(NO_OVERFLOW);
110 setGeneration((value) => value + 1);
111 };
112 const scrollable = !props.nested || overflow.x || overflow.y;
113 return (
114 <View
115 style={
116 props.nested
117 ? { flex: 1 }
118 : {
119 flex: 1,
120 paddingHorizontal: FULL_SCREEN_GUTTER,
121 backgroundColor: theme.variables["--background"],
122 }
123 }
124 >
125 <WebView<object>
126 key={generation}
127 ref={webView}
128 source={source}
129 accessibilityLabel={props.title}
130 style={{ flex: 1, backgroundColor: "transparent" }}
131 allowsInlineMediaPlayback
132 contentInsetAdjustmentBehavior={props.nested ? "never" : "automatic"}
133 bounces={!props.nested}
134 showsVerticalScrollIndicator={!props.nested}
135 showsHorizontalScrollIndicator={!props.nested}
136 scrollEnabled={scrollable}
137 decelerationRate={webViewDecelerationRate}
138 // Android's patched WebView always keeps horizontal drags. Only pages
139 // with vertical overflow hold vertical drags until they reach an edge.
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 openLink(url);
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 gt = useGT();
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 = {
191 _tag: "attachment" as const,
192 attachmentId,
193 fileName,
194 mimeType: "text/html",
195 disposition: "inline" as const,
196 };
197 const asset = useAssetUrlState(props.environmentId, resource);
198 const refresh = useRefreshAssetUrl(props.environmentId, resource);
199 // Signed URLs are re-minted periodically; following them would reload the page.
200 const [uri, setUri] = useState<string | null>(null);
201 if (uri === null && asset._tag === "Success") setUri(asset.url);
202 const [failed, setFailed] = useState(false);
203 const [attempt, setAttempt] = useState(0);
204 const retried = useRef(false);
205 const handleLoadError = () => {
206 if (retried.current) {
207 setFailed(true);
208 return;
209 }
210 retried.current = true;
211 void refresh().then((next) => {
212 if (next === null) setFailed(true);
213 else if (next !== uri) setUri(next);
214 else setAttempt((value) => value + 1);
215 });
216 };
217
218 return (
219 <View style={{ marginBottom: ROW_BOTTOM_MARGIN }}>
220 <View style={{ height: ACTION_ROW_HEIGHT }} className="flex-row items-start justify-end">
221 {uri !== null && !failed ? (
222 <Pressable
223 accessibilityRole="button"
224 accessibilityLabel={gt("Open {title}", { title })}
225 hitSlop={8}
226 className="h-7 w-7 items-center justify-center rounded-full border border-border/60 bg-card/80"
227 onPress={() =>
228 navigation.navigate("ThreadAttachment", {
229 environmentId: String(props.environmentId),
230 threadId: String(props.threadId),
231 attachmentId,
232 name: fileName,
233 mimeType: "text/html",
234 sizeBytes: "0",
235 htmlRender: "1",
236 })
237 }
238 >
239 <SymbolView
240 name="arrow.up.left.and.arrow.down.right"
241 size={12}
242 tintColor={props.iconColor}
243 type="monochrome"
244 />
245 </Pressable>
246 ) : null}
247 </View>
248 <View style={{ height }}>
249 {uri !== null && !failed ? (
250 <HtmlRenderWebView
251 key={`${uri}:${attempt}`}
252 uri={uri}
253 title={title}
254 nested
255 onLoadError={handleLoadError}
256 />
257 ) : failed || asset._tag === "Failure" ? (
258 <Pressable
259 accessibilityRole="button"
260 accessibilityLabel={gt("Reload {title}", { title })}
261 className="flex-1 items-center justify-center"
262 onPress={() => {
263 retried.current = false;
264 setFailed(false);
265 if (uri === null) void refresh().then((next) => next !== null && setUri(next));
266 }}
267 >
268 <Text className="text-sm text-foreground-muted">
269 <T>Page unavailable</T>
270 </Text>
271 </Pressable>
272 ) : (
273 <View className="flex-1 items-center justify-center">
274 <AppActivityIndicator />
275 </View>
276 )}
277 </View>
278 </View>
279 );
280}