The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; |
| 2 | import { useNavigation } from "@react-navigation/native"; |
| 3 | import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 4 | import { |
| 5 | htmlRenderFileName, |
| 6 | htmlRenderFrameHeight, |
| 7 | htmlRenderThemeFragment, |
| 8 | htmlRenderThemeMessage, |
| 9 | type HtmlRenderReference, |
| 10 | type HtmlRenderTheme, |
| 11 | } from "@t3tools/shared/htmlRender"; |
| 12 | import { T, useGT } from "gt-react-native"; |
| 13 | import { useEffect, useRef, useState } from "react"; |
| 14 | import { Platform, Pressable, View, type ColorValue } from "react-native"; |
| 15 | import { WebView, type WebViewMessageEvent } from "react-native-webview"; |
| 16 | |
| 17 | import { SymbolView } from "../../components/ui/AppSymbol"; |
| 18 | import { AppText as Text } from "../../components/ui/AppText"; |
| 19 | import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; |
| 20 | import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; |
| 21 | import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; |
| 22 | import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; |
| 23 | import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; |
| 24 | |
| 25 | const ROW_BOTTOM_MARGIN = 8; |
| 26 | const ACTION_ROW_HEIGHT = 32; |
| 27 | const FULL_SCREEN_GUTTER = 16; |
| 28 | |
| 29 | export function htmlRenderRowHeight(frameHeight: number) { |
| 30 | return ACTION_ROW_HEIGHT + frameHeight + ROW_BOTTOM_MARGIN; |
| 31 | } |
| 32 | |
| 33 | function 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 | |
| 45 | function postTheme(view: WebView<object> | null, theme: HtmlRenderTheme) { |
| 46 | view?.injectJavaScript( |
| 47 | `window.postMessage(${JSON.stringify(htmlRenderThemeMessage(theme))}, "*"); true;`, |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | const OVERFLOW_MESSAGE_TYPE = "t3-html-render-overflow"; |
| 52 | |
| 53 | const 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 | |
| 55 | type Overflow = { readonly x: boolean; readonly y: boolean }; |
| 56 | |
| 57 | const NO_OVERFLOW: Overflow = { x: false, y: false }; |
| 58 | |
| 59 | function 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 | |
| 77 | const withoutFragment = (url: string) => url.split("#", 1)[0]; |
| 78 | |
| 79 | export 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 [initialTheme] = useState(theme); |
| 87 | const [generation, setGeneration] = useState(0); |
| 88 | const [loaded, setLoaded] = useState(false); |
| 89 | const [overflow, setOverflow] = useState(NO_OVERFLOW); |
| 90 | const webView = useRef<WebView<object>>(null); |
| 91 | const crashes = useRef(0); |
| 92 | const shownTheme = useRef<HtmlRenderTheme | null>(null); |
| 93 | const source = { uri: props.uri + htmlRenderThemeFragment(initialTheme) }; |
| 94 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts theme changes into the already loaded WebView |
| 95 | useEffect(() => { |
| 96 | if (shownTheme.current === null || shownTheme.current === theme) return; |
| 97 | shownTheme.current = theme; |
| 98 | postTheme(webView.current, theme); |
| 99 | }, [theme]); |
| 100 | const restart = () => { |
| 101 | crashes.current += 1; |
| 102 | if (crashes.current > 1) { |
| 103 | props.onLoadError?.(); |
| 104 | return; |
| 105 | } |
| 106 | shownTheme.current = null; |
| 107 | setLoaded(false); |
| 108 | setOverflow(NO_OVERFLOW); |
| 109 | setGeneration((value) => value + 1); |
| 110 | }; |
| 111 | const scrollable = !props.nested || overflow.x || overflow.y; |
| 112 | return ( |
| 113 | <View |
| 114 | style={ |
| 115 | props.nested |
| 116 | ? { flex: 1 } |
| 117 | : { |
| 118 | flex: 1, |
| 119 | paddingHorizontal: FULL_SCREEN_GUTTER, |
| 120 | backgroundColor: theme.variables["--background"], |
| 121 | } |
| 122 | } |
| 123 | > |
| 124 | <WebView<object> |
| 125 | key={generation} |
| 126 | ref={webView} |
| 127 | source={source} |
| 128 | accessibilityLabel={props.title} |
| 129 | style={{ flex: 1, backgroundColor: "transparent" }} |
| 130 | allowsInlineMediaPlayback |
| 131 | contentInsetAdjustmentBehavior={props.nested ? "never" : "automatic"} |
| 132 | bounces={!props.nested} |
| 133 | showsVerticalScrollIndicator={!props.nested} |
| 134 | showsHorizontalScrollIndicator={!props.nested} |
| 135 | scrollEnabled={scrollable} |
| 136 | decelerationRate={webViewDecelerationRate} |
| 137 | // Android's patched WebView always keeps horizontal drags. Only pages |
| 138 | // with vertical overflow hold vertical drags until they reach an edge. |
| 139 | nestedScrollEnabled={props.nested && overflow.y} |
| 140 | overScrollMode={props.nested ? "never" : "always"} |
| 141 | onShouldStartLoadWithRequest={(request) => |
| 142 | request.isTopFrame === false || |
| 143 | withoutFragment(request.url) === withoutFragment(props.uri) |
| 144 | } |
| 145 | onOpenWindow={(event) => { |
| 146 | const url = event.nativeEvent.targetUrl; |
| 147 | if (/^https?:/i.test(url)) void tryOpenExternalUrl(url, "html-render"); |
| 148 | }} |
| 149 | onLoadEnd={() => { |
| 150 | setLoaded(true); |
| 151 | shownTheme.current = theme; |
| 152 | if (theme !== initialTheme) postTheme(webView.current, theme); |
| 153 | }} |
| 154 | onError={props.onLoadError} |
| 155 | onHttpError={props.onLoadError} |
| 156 | onContentProcessDidTerminate={restart} |
| 157 | onRenderProcessGone={restart} |
| 158 | {...(props.nested |
| 159 | ? { |
| 160 | injectedJavaScript: OVERFLOW_SCRIPT, |
| 161 | onMessage: (event: WebViewMessageEvent) => { |
| 162 | const next = readOverflowMessage(event.nativeEvent.data); |
| 163 | if (next !== null) setOverflow(next); |
| 164 | }, |
| 165 | } |
| 166 | : {})} |
| 167 | /> |
| 168 | {loaded ? null : ( |
| 169 | <View pointerEvents="none" className="absolute inset-0 items-center justify-center"> |
| 170 | <AppActivityIndicator /> |
| 171 | </View> |
| 172 | )} |
| 173 | </View> |
| 174 | ); |
| 175 | } |
| 176 | |
| 177 | export function ThreadHtmlRender(props: { |
| 178 | readonly environmentId: EnvironmentId; |
| 179 | readonly threadId: ThreadId; |
| 180 | readonly render: HtmlRenderReference; |
| 181 | readonly frameWidth: number; |
| 182 | readonly iconColor: ColorValue; |
| 183 | }) { |
| 184 | const gt = useGT(); |
| 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 = { |
| 190 | _tag: "attachment" as const, |
| 191 | attachmentId, |
| 192 | fileName, |
| 193 | mimeType: "text/html", |
| 194 | disposition: "inline" as const, |
| 195 | }; |
| 196 | const asset = useAssetUrlState(props.environmentId, resource); |
| 197 | const refresh = useRefreshAssetUrl(props.environmentId, resource); |
| 198 | // Signed URLs are re-minted periodically; following them would reload the page. |
| 199 | const [uri, setUri] = useState<string | null>(null); |
| 200 | if (uri === null && asset._tag === "Success") setUri(asset.url); |
| 201 | const [failed, setFailed] = useState(false); |
| 202 | const [attempt, setAttempt] = useState(0); |
| 203 | const retried = useRef(false); |
| 204 | const handleLoadError = () => { |
| 205 | if (retried.current) { |
| 206 | setFailed(true); |
| 207 | return; |
| 208 | } |
| 209 | retried.current = true; |
| 210 | void refresh().then((next) => { |
| 211 | if (next === null) setFailed(true); |
| 212 | else if (next !== uri) setUri(next); |
| 213 | else setAttempt((value) => value + 1); |
| 214 | }); |
| 215 | }; |
| 216 | |
| 217 | return ( |
| 218 | <View style={{ marginBottom: ROW_BOTTOM_MARGIN }}> |
| 219 | <View style={{ height: ACTION_ROW_HEIGHT }} className="flex-row items-start justify-end"> |
| 220 | {uri !== null && !failed ? ( |
| 221 | <Pressable |
| 222 | accessibilityRole="button" |
| 223 | accessibilityLabel={gt("Open {title}", { title })} |
| 224 | hitSlop={8} |
| 225 | className="h-7 w-7 items-center justify-center rounded-full border border-border/60 bg-card/80" |
| 226 | onPress={() => |
| 227 | navigation.navigate("ThreadAttachment", { |
| 228 | environmentId: String(props.environmentId), |
| 229 | threadId: String(props.threadId), |
| 230 | attachmentId, |
| 231 | name: fileName, |
| 232 | mimeType: "text/html", |
| 233 | sizeBytes: "0", |
| 234 | htmlRender: "1", |
| 235 | }) |
| 236 | } |
| 237 | > |
| 238 | <SymbolView |
| 239 | name="arrow.up.left.and.arrow.down.right" |
| 240 | size={12} |
| 241 | tintColor={props.iconColor} |
| 242 | type="monochrome" |
| 243 | /> |
| 244 | </Pressable> |
| 245 | ) : null} |
| 246 | </View> |
| 247 | <View style={{ height }}> |
| 248 | {uri !== null && !failed ? ( |
| 249 | <HtmlRenderWebView |
| 250 | key={`${uri}:${attempt}`} |
| 251 | uri={uri} |
| 252 | title={title} |
| 253 | nested |
| 254 | onLoadError={handleLoadError} |
| 255 | /> |
| 256 | ) : failed || asset._tag === "Failure" ? ( |
| 257 | <Pressable |
| 258 | accessibilityRole="button" |
| 259 | accessibilityLabel={gt("Reload {title}", { title })} |
| 260 | className="flex-1 items-center justify-center" |
| 261 | onPress={() => { |
| 262 | retried.current = false; |
| 263 | setFailed(false); |
| 264 | if (uri === null) void refresh().then((next) => next !== null && setUri(next)); |
| 265 | }} |
| 266 | > |
| 267 | <Text className="text-sm text-foreground-muted"> |
| 268 | <T>Page unavailable</T> |
| 269 | </Text> |
| 270 | </Pressable> |
| 271 | ) : ( |
| 272 | <View className="flex-1 items-center justify-center"> |
| 273 | <AppActivityIndicator /> |
| 274 | </View> |
| 275 | )} |
| 276 | </View> |
| 277 | </View> |
| 278 | ); |
| 279 | } |