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

DeviceStreamWebView.tsx

245 lines8.4 KB

1import { Button } from "../../components/ui/Button";
2import deviceStreamScript from "@t3tools/mobile-device-stream";
3import {
4 useEffectEvent,
5 useImperativeHandle,
6 useLayoutEffect,
7 useRef,
8 useState,
9 type Ref,
10} from "react";
11import { isMarked, type Marked } from "@t3tools/client-runtime/errors";
12import { msg, useGT } from "gt-react-native";
13import { Platform, View } from "react-native";
14import { WebView } from "react-native-webview";
15import type { DeviceStreamStatus } from "@t3tools/client-runtime/device/stream";
16​
17import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
18import { AppText } from "../../components/ui/AppText";
19import { m, type MessageResolver } from "../../i18n/messages";
20​
21import {
22 deviceStreamBaseUrl,
23 deviceStreamDocument,
24 deviceStreamMessage,
25 type DeviceStreamConfiguration,
26} from "./device-stream-document";
27​
28/** Resolves a status detail the WebView left marked, including marked values inside it. */
29function streamDetailText(detail: Marked, resolve: MessageResolver): string {
30 if (typeof detail === "string") return detail;
31 return resolve({
32 ...detail,
33 values: Object.fromEntries(
34 Object.entries(detail.values).map(([name, value]) => [
35 name,
36 typeof value === "object" && isMarked(value) ? streamDetailText(value, resolve) : value,
37 ]),
38 ),
39 });
41​
42export interface DeviceStreamRef {
43 home: () => void;
44 back: () => void;
45 appSwitcher: () => void;
46 rotate: () => void;
48​
49type NativeStreamBridge = {
50 readonly ref?: Ref<DeviceStreamRef>;
51 readonly onUnauthorized: () => Promise<void>;
52 readonly onInputConnected: (connected: boolean) => Promise<void>;
53};
54​
55export function DeviceStreamWebView({
56 ref,
57 ...props
58}: Omit<DeviceStreamConfiguration, "labels"> & NativeStreamBridge) {
59 const gt = useGT();
60 const [attempt, setAttempt] = useState(0);
61 const processRetried = useRef(false);
62 const configuration = JSON.stringify({
63 access: props.access,
64 platform: props.platform,
65 deviceId: props.deviceId,
66 ...(props.serveSimOnly ? { serveSimOnly: true } : {}),
67 colors: props.colors,
68 labels: {
69 screen: props.platform === "ios" ? gt`iOS Simulator screen` : gt`Android Emulator screen`,
70 reconnectingControls: gt`Reconnecting device controls...`,
71 },
72 } satisfies DeviceStreamConfiguration);
73 return (
74 <DeviceStreamDocumentView
75 key={`${attempt}:${configuration}`}
76 ref={ref}
77 configuration={configuration}
78 baseUrl={deviceStreamBaseUrl(Platform.OS, props.platform, props.access.httpBase)}
79 background={props.colors.background}
80 onUnauthorized={props.onUnauthorized}
81 onInputConnected={props.onInputConnected}
82 onRetry={() => {
83 processRetried.current = false;
84 setAttempt((attempt) => attempt + 1);
85 void props.onUnauthorized();
86 }}
87 onStreaming={() => {
88 processRetried.current = false;
89 }}
90 onRecoverProcess={() => {
91 if (processRetried.current) return false;
92 processRetried.current = true;
93 setAttempt((attempt) => attempt + 1);
94 void props.onUnauthorized();
95 return true;
96 }}
97 />
98 );
100​
101function DeviceStreamDocumentView({
102 ref,
103 configuration,
104 baseUrl,
105 background,
106 onUnauthorized,
107 onInputConnected,
108 onRetry,
109 onStreaming,
110 onRecoverProcess,
111}: NativeStreamBridge & {
112 readonly configuration: string;
113 readonly baseUrl: string;
114 readonly background: string;
115 readonly onRetry: () => void;
116 readonly onStreaming: () => void;
117 readonly onRecoverProcess: () => boolean;
118}) {
119 const webView = useRef<WebView<object>>(null);
120 const gt = useGT();
121 const active = useRef(false);
122 const failed = useRef(false);
123 const bootstrapTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
124 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
125 const [error, setError] = useState<string | null>(null);
126 const clearBootstrapTimer = () => {
127 if (bootstrapTimer.current === null) return;
128 clearTimeout(bootstrapTimer.current);
129 bootstrapTimer.current = null;
130 };
131 const fail = (message: string) => {
132 if (!active.current || failed.current) return;
133 failed.current = true;
134 clearBootstrapTimer();
135 void onInputConnected(false);
136 webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
137 setError(message);
138 setStatus("error");
139 };
140 const bootstrapTimedOut = useEffectEvent(() =>
141 fail(m(msg("Device viewer could not start. Reconnect to try again."))),
142 );
143 const resetInput = useEffectEvent(() => void onInputConnected(false));
144 // The stream lives exactly as long as this view.
145 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the bootstrap timeout and stops the WebView device stream when this view unmounts
146 useLayoutEffect(() => {
147 active.current = true;
148 resetInput();
149 const view = webView.current;
150 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
151 return () => {
152 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
153 bootstrapTimer.current = null;
154 active.current = false;
155 view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
156 resetInput();
157 };
158 }, []);
159 const source = {
160 html: deviceStreamDocument(
161 configuration,
162 deviceStreamScript,
163 gt`Device viewer stopped unexpectedly.`,
164 ),
165 baseUrl,
166 };
167 const command = (button: keyof DeviceStreamRef) => {
168 webView.current?.injectJavaScript(
169 `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
170 );
171 };
172 useImperativeHandle(ref, () => ({
173 home: () => command("home"),
174 back: () => command("back"),
175 appSwitcher: () => command("appSwitcher"),
176 rotate: () => command("rotate"),
177 }));
178 const processTerminated = () => {
179 if (!active.current || failed.current) return;
180 void onInputConnected(false);
181 if (!onRecoverProcess()) fail(m(msg("Device viewer stopped. Reconnect to try again.")));
182 };
183 return (
184 <View className="flex-1" style={{ backgroundColor: background }}>
185 <WebView<object>
186 ref={webView}
187 source={source}
188 originWhitelist={["*"]}
189 scrollEnabled={false}
190 bounces={false}
191 mixedContentMode="always"
192 allowUniversalAccessFromFileURLs
193 contentInsetAdjustmentBehavior="never"
194 setSupportMultipleWindows={false}
195 style={{ flex: 1, backgroundColor: background }}
196 onError={() => fail(m(msg("Device viewer could not load. Reconnect to try again.")))}
197 onHttpError={() => fail(m(msg("Device viewer could not load. Reconnect to try again.")))}
198 onContentProcessDidTerminate={processTerminated}
199 onRenderProcessGone={processTerminated}
200 onShouldStartLoadWithRequest={(request) =>
201 request.url === "about:blank" || request.url === source.baseUrl
202 }
203 onMessage={(event) => {
204 if (!active.current || failed.current) return;
205 const message = deviceStreamMessage(event.nativeEvent.data);
206 if (message?.type === "unauthorized") void onUnauthorized();
207 else if (message?.type === "input") void onInputConnected(message.connected);
208 else if (message?.type === "retry") onRetry();
209 else if (message?.type === "status") {
210 clearBootstrapTimer();
211 if (message.status === "error")
212 fail(
213 message.detail === undefined
214 ? m(msg("Device stream failed."))
215 : streamDetailText(message.detail, m),
216 );
217 else {
218 setStatus(message.status);
219 if (message.status === "streaming") onStreaming();
220 }
221 }
222 }}
223 />
224 {status !== "streaming" ? (
225 <View
226 className="absolute inset-0 items-center justify-center gap-4 px-6"
227 style={{ backgroundColor: background }}
228 >
229 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
230 <AppText
231 accessibilityLiveRegion="polite"
232 className="text-center text-sm text-foreground-muted"
233 >
234 {status === "error" ? error : gt`Connecting to device...`}
235 </AppText>
236 {status === "error" ? (
237 <View className="items-center">
238 <Button label={gt`Reconnect`} tone="secondary" onPress={onRetry} />
239 </View>
240 ) : null}
241 </View>
242 ) : null}
243 </View>
244 );