Open History to see the last commit
1import deviceStreamScript from "@t3tools/mobile-device-stream";
2import {
3 useEffect,
4 useEffectEvent,
5 useImperativeHandle,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 useState,
10 type Ref,
11} from "react";
12import { Platform, Pressable, View } from "react-native";
13import { WebView } from "react-native-webview";
14import type { DeviceStreamStatus } from "@t3tools/client-runtime/device/stream";
15
16import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
17import { AppText } from "../../components/ui/AppText";
18
19import {
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 background={props.colors.background}
56 onUnauthorized={props.onUnauthorized}
57 onInputConnected={props.onInputConnected}
58 onRetry={() => {
59 processRetried.current = false;
60 setAttempt((attempt) => attempt + 1);
61 void props.onUnauthorized();
62 }}
63 onStreaming={() => {
64 processRetried.current = false;
65 }}
66 onRecoverProcess={() => {
67 if (processRetried.current) return false;
68 processRetried.current = true;
69 setAttempt((attempt) => attempt + 1);
70 void props.onUnauthorized();
71 return true;
72 }}
73 />
74 );
75}
76
77function DeviceStreamDocumentView({
78 ref,
79 configuration,
80 background,
81 onUnauthorized,
82 onInputConnected,
83 onRetry,
84 onStreaming,
85 onRecoverProcess,
86}: NativeStreamBridge & {
87 readonly configuration: string;
88 readonly background: string;
89 readonly onRetry: () => void;
90 readonly onStreaming: () => void;
91 readonly onRecoverProcess: () => boolean;
92}) {
93 const webView = useRef<WebView<object>>(null);
94 const active = useRef(true);
95 const failed = useRef(false);
96 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
97 const [error, setError] = useState<string | null>(null);
98 const [started, setStarted] = useState(false);
99 const fail = (message: string) => {
100 if (!active.current || failed.current) return;
101 failed.current = true;
102 void onInputConnected(false);
103 webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
104 setError(message);
105 setStatus("error");
106 };
107 const bootstrapTimedOut = useEffectEvent(() =>
108 fail("Device viewer could not start. Reconnect to try again."),
109 );
110 useEffect(() => {
111 if (started) return;
112 const timer = setTimeout(bootstrapTimedOut, 15_000);
113 return () => clearTimeout(timer);
114 }, [started]);
115 const source = useMemo(
116 () => ({
117 html: deviceStreamDocument(configuration, deviceStreamScript),
118 // Android WebCodecs needs a secure document; streams still use the environment's URLs.
119 baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
120 }),
121 [configuration],
122 );
123 const command = (button: keyof DeviceStreamRef) => {
124 webView.current?.injectJavaScript(
125 `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
126 );
127 };
128 useImperativeHandle(ref, () => ({
129 home: () => command("home"),
130 back: () => command("back"),
131 appSwitcher: () => command("appSwitcher"),
132 rotate: () => command("rotate"),
133 }));
134 const resetInput = useEffectEvent(() => void onInputConnected(false));
135 useLayoutEffect(() => {
136 active.current = true;
137 resetInput();
138 const view = webView.current;
139 return () => {
140 active.current = false;
141 view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
142 };
143 }, []);
144 const processTerminated = () => {
145 if (!active.current || failed.current) return;
146 void onInputConnected(false);
147 if (!onRecoverProcess()) fail("Device viewer stopped. Reconnect to try again.");
148 };
149 return (
150 <View className="flex-1" style={{ backgroundColor: background }}>
151 <WebView<object>
152 ref={webView}
153 source={source}
154 originWhitelist={["*"]}
155 scrollEnabled={false}
156 bounces={false}
157 mixedContentMode="always"
158 allowUniversalAccessFromFileURLs
159 contentInsetAdjustmentBehavior="never"
160 setSupportMultipleWindows={false}
161 style={{ flex: 1, backgroundColor: background }}
162 onError={() => fail("Device viewer could not load. Reconnect to try again.")}
163 onHttpError={() => fail("Device viewer could not load. Reconnect to try again.")}
164 onContentProcessDidTerminate={processTerminated}
165 onRenderProcessGone={processTerminated}
166 onShouldStartLoadWithRequest={(request) =>
167 request.url === "about:blank" || request.url === source.baseUrl
168 }
169 onMessage={(event) => {
170 if (!active.current || failed.current) return;
171 const message = deviceStreamMessage(event.nativeEvent.data);
172 if (message?.type === "unauthorized") void onUnauthorized();
173 else if (message?.type === "input") void onInputConnected(message.connected);
174 else if (message?.type === "retry") onRetry();
175 else if (message?.type === "status") {
176 setStarted(true);
177 if (message.status === "error") fail(message.detail ?? "Device stream failed.");
178 else {
179 setStatus(message.status);
180 if (message.status === "streaming") onStreaming();
181 }
182 }
183 }}
184 />
185 {status !== "streaming" ? (
186 <View
187 className="absolute inset-0 items-center justify-center gap-4 px-6"
188 style={{ backgroundColor: background }}
189 >
190 {status === "connecting" ? <AppActivityIndicator colorClassName="accent-icon" /> : null}
191 <AppText
192 accessibilityLiveRegion="polite"
193 className="text-center text-sm text-foreground-muted"
194 >
195 {status === "error" ? error : "Connecting to device..."}
196 </AppText>
197 {status === "error" ? (
198 <Pressable
199 accessibilityRole="button"
200 className="rounded-full border border-secondary-border bg-secondary px-6 py-3"
201 onPress={onRetry}
202 >
203 <AppText className="text-secondary-foreground">Reconnect</AppText>
204 </Pressable>
205 ) : null}
206 </View>
207 ) : null}
208 </View>
209 );
210}