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 useLayoutEffect(() => {
122 active.current = true;
123 resetInput();
124 const view = webView.current;
125 bootstrapTimer.current = setTimeout(bootstrapTimedOut, 15_000);
126 return () => {
127 if (bootstrapTimer.current !== null) clearTimeout(bootstrapTimer.current);
128 bootstrapTimer.current = null;
129 active.current = false;
130 view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
131 resetInput();
132 };
133 }, []);
134 const source = {
135 html: deviceStreamDocument(configuration, deviceStreamScript),
136 baseUrl,
137 };
138 const command = (button: keyof DeviceStreamRef) => {
139 webView.current?.injectJavaScript(
140 `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
141 );
142 };
143 useImperativeHandle(ref, () => ({
144 home: () => command("home"),
145 back: () => command("back"),
146 appSwitcher: () => command("appSwitcher"),
147 rotate: () => command("rotate"),
148 }));
149 const processTerminated = () => {
150 if (!active.current || failed.current) return;
151 void onInputConnected(false);
152 if (!onRecoverProcess()) fail("Device viewer stopped. Reconnect to try again.");
153 };
154 return (
155 <View className="flex-1" style={{ backgroundColor: background }}>
156 <WebView<object>
157 ref={webView}
158 source={source}
159 originWhitelist={["*"]}
160 scrollEnabled={false}
161 bounces={false}
162 mixedContentMode="always"
163 allowUniversalAccessFromFileURLs
164 contentInsetAdjustmentBehavior="never"
165 setSupportMultipleWindows={false}
166 style={{ flex: 1, backgroundColor: background }}
167 onError={() => fail("Device viewer could not load. Reconnect to try again.")}
168 onHttpError={() => fail("Device viewer could not load. Reconnect to try again.")}
169 onContentProcessDidTerminate={processTerminated}
170 onRenderProcessGone={processTerminated}
171 onShouldStartLoadWithRequest={(request) =>
172 request.url === "about:blank" || request.url === source.baseUrl
173 }
174 onMessage={(event) => {
175 if (!active.current || failed.current) return;
176 const message = deviceStreamMessage(event.nativeEvent.data);
177 if (message?.type === "unauthorized") void onUnauthorized();
178 else if (message?.type === "input") void onInputConnected(message.connected);
179 else if (message?.type === "retry") onRetry();
180 else if (message?.type === "status") {
181 clearBootstrapTimer();
182 if (message.status === "error") fail(message.detail ?? "Device stream failed.");
183 else {
184 setStatus(message.status);
185 if (message.status === "streaming") onStreaming();
186 }
187 }
188 }}
189 />
190 {status !== "streaming" ? (
191 <View
192 className="absolute inset-0 items-center justify-center gap-4 px-6"
193 style={{ backgroundColor: background }}
194 >
195 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
196 <AppText
197 accessibilityLiveRegion="polite"
198 className="text-center text-sm text-foreground-muted"
199 >
200 {status === "error" ? error : "Connecting to device..."}
201 </AppText>
202 {status === "error" ? (
203 <View className="items-center">
204 <Button label="Reconnect" tone="secondary" onPress={onRetry} />
205 </View>
206 ) : null}
207 </View>
208 ) : null}
209 </View>
210 );
211}