Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceStreamWebView.tsx

210 lines6.9 KB

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 { ActivityIndicator, Platform, Pressable, View } from "react-native";
13import { WebView } from "react-native-webview";
14import type { DeviceStreamStatus } from "@t3tools/client-runtime/device/stream";
15​
16import { AppText } from "../../components/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;
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 );
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 // The shared transport owns video timeouts once the document acknowledges startup.
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" ? <ActivityIndicator 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 );