Open History to see the last commit
1import deviceStreamScript from "@t3tools/mobile-device-stream";
2import {
3 useEffect,
4 useEffectEvent,
5 useImperativeHandle,
6 useLayoutEffect,
7 useRef,
8 useState,
9 type Ref,
10} from "react";
11import { Platform, Pressable, 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(true);
98 const failed = useRef(false);
99 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
100 const [error, setError] = useState<string | null>(null);
101 const [started, setStarted] = useState(false);
102 const fail = (message: string) => {
103 if (!active.current || failed.current) return;
104 failed.current = true;
105 void onInputConnected(false);
106 webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
107 setError(message);
108 setStatus("error");
109 };
110 const bootstrapTimedOut = useEffectEvent(() =>
111 fail("Device viewer could not start. Reconnect to try again."),
112 );
113 useEffect(() => {
114 if (started) return;
115 const timer = setTimeout(bootstrapTimedOut, 15_000);
116 return () => clearTimeout(timer);
117 }, [started]);
118 const source = {
119 html: deviceStreamDocument(configuration, deviceStreamScript),
120 baseUrl,
121 };
122 const command = (button: keyof DeviceStreamRef) => {
123 webView.current?.injectJavaScript(
124 `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
125 );
126 };
127 useImperativeHandle(ref, () => ({
128 home: () => command("home"),
129 back: () => command("back"),
130 appSwitcher: () => command("appSwitcher"),
131 rotate: () => command("rotate"),
132 }));
133 const resetInput = useEffectEvent(() => void onInputConnected(false));
134 useLayoutEffect(() => {
135 active.current = true;
136 resetInput();
137 const view = webView.current;
138 return () => {
139 active.current = false;
140 view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
141 };
142 }, []);
143 const processTerminated = () => {
144 if (!active.current || failed.current) return;
145 void onInputConnected(false);
146 if (!onRecoverProcess()) fail("Device viewer stopped. Reconnect to try again.");
147 };
148 return (
149 <View className="flex-1" style={{ backgroundColor: background }}>
150 <WebView<object>
151 ref={webView}
152 source={source}
153 originWhitelist={["*"]}
154 scrollEnabled={false}
155 bounces={false}
156 mixedContentMode="always"
157 allowUniversalAccessFromFileURLs
158 contentInsetAdjustmentBehavior="never"
159 setSupportMultipleWindows={false}
160 style={{ flex: 1, backgroundColor: background }}
161 onError={() => fail("Device viewer could not load. Reconnect to try again.")}
162 onHttpError={() => fail("Device viewer could not load. Reconnect to try again.")}
163 onContentProcessDidTerminate={processTerminated}
164 onRenderProcessGone={processTerminated}
165 onShouldStartLoadWithRequest={(request) =>
166 request.url === "about:blank" || request.url === source.baseUrl
167 }
168 onMessage={(event) => {
169 if (!active.current || failed.current) return;
170 const message = deviceStreamMessage(event.nativeEvent.data);
171 if (message?.type === "unauthorized") void onUnauthorized();
172 else if (message?.type === "input") void onInputConnected(message.connected);
173 else if (message?.type === "retry") onRetry();
174 else if (message?.type === "status") {
175 setStarted(true);
176 if (message.status === "error") fail(message.detail ?? "Device stream failed.");
177 else {
178 setStatus(message.status);
179 if (message.status === "streaming") onStreaming();
180 }
181 }
182 }}
183 />
184 {status !== "streaming" ? (
185 <View
186 className="absolute inset-0 items-center justify-center gap-4 px-6"
187 style={{ backgroundColor: background }}
188 >
189 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
190 <AppText
191 accessibilityLiveRegion="polite"
192 className="text-center text-sm text-foreground-muted"
193 >
194 {status === "error" ? error : "Connecting to device..."}
195 </AppText>
196 {status === "error" ? (
197 <Pressable
198 accessibilityRole="button"
199 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
200 onPress={onRetry}
201 >
202 <AppText className="text-secondary-foreground">Reconnect</AppText>
203 </Pressable>
204 ) : null}
205 </View>
206 ) : null}
207 </View>
208 );
209}