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