Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import deviceStreamScript from "@t3tools/mobile-device-stream";
3import {
4 useEffect,
5 useEffectEvent,
6 useImperativeHandle,
7 useLayoutEffect,
8 useRef,
9 useState,
10 type Ref,
11} from "react";
12import { Platform, 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 deviceStreamBaseUrl,
21 deviceStreamDocument,
22 deviceStreamMessage,
23 type DeviceStreamConfiguration,
24} from "./device-stream-document";
25
26export interface DeviceStreamRef {
27 home: () => void;
28 back: () => void;
29 appSwitcher: () => void;
30 rotate: () => void;
31}
32
33type NativeStreamBridge = {
34 readonly ref?: Ref<DeviceStreamRef>;
35 readonly onUnauthorized: () => Promise<void>;
36 readonly onInputConnected: (connected: boolean) => Promise<void>;
37};
38
39export function DeviceStreamWebView({
40 ref,
41 ...props
42}: DeviceStreamConfiguration & NativeStreamBridge) {
43 const [attempt, setAttempt] = useState(0);
44 const processRetried = useRef(false);
45 const configuration = JSON.stringify({
46 access: props.access,
47 platform: props.platform,
48 deviceId: props.deviceId,
49 colors: props.colors,
50 });
51 return (
52 <DeviceStreamDocumentView
53 key={`${attempt}:${configuration}`}
54 ref={ref}
55 configuration={configuration}
56 baseUrl={deviceStreamBaseUrl(Platform.OS, props.platform, props.access.httpBase)}
57 background={props.colors.background}
58 onUnauthorized={props.onUnauthorized}
59 onInputConnected={props.onInputConnected}
60 onRetry={() => {
61 processRetried.current = false;
62 setAttempt((attempt) => attempt + 1);
63 void props.onUnauthorized();
64 }}
65 onStreaming={() => {
66 processRetried.current = false;
67 }}
68 onRecoverProcess={() => {
69 if (processRetried.current) return false;
70 processRetried.current = true;
71 setAttempt((attempt) => attempt + 1);
72 void props.onUnauthorized();
73 return true;
74 }}
75 />
76 );
77}
78
79function DeviceStreamDocumentView({
80 ref,
81 configuration,
82 baseUrl,
83 background,
84 onUnauthorized,
85 onInputConnected,
86 onRetry,
87 onStreaming,
88 onRecoverProcess,
89}: NativeStreamBridge & {
90 readonly configuration: string;
91 readonly baseUrl: string;
92 readonly background: string;
93 readonly onRetry: () => void;
94 readonly onStreaming: () => void;
95 readonly onRecoverProcess: () => boolean;
96}) {
97 const webView = useRef<WebView<object>>(null);
98 const active = useRef(true);
99 const failed = useRef(false);
100 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
101 const [error, setError] = useState<string | null>(null);
102 const [started, setStarted] = useState(false);
103 const fail = (message: string) => {
104 if (!active.current || failed.current) return;
105 failed.current = true;
106 void onInputConnected(false);
107 webView.current?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
108 setError(message);
109 setStatus("error");
110 };
111 const bootstrapTimedOut = useEffectEvent(() =>
112 fail("Device viewer could not start. Reconnect to try again."),
113 );
114 useEffect(() => {
115 if (started) return;
116 const timer = setTimeout(bootstrapTimedOut, 15_000);
117 return () => clearTimeout(timer);
118 }, [started]);
119 const source = {
120 html: deviceStreamDocument(configuration, deviceStreamScript),
121 baseUrl,
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 <View className="items-center">
199 <Button label="Reconnect" tone="secondary" onPress={onRetry} />
200 </View>
201 ) : null}
202 </View>
203 ) : null}
204 </View>
205 );
206}