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