Open History to see the last commit
1import {
2 createDeviceStreamClient,
3 type DeviceScreenSize,
4} from "@t3tools/client-runtime/device/stream";
5
6import type { DeviceStreamConfiguration } from "./device-stream-document";
7
8declare global {
9 interface Window {
10 ReactNativeWebView: { postMessage: (message: string) => void };
11 }
12}
13
14let activeClient: ReturnType<typeof createDeviceStreamClient> | null = null;
15let activeImage: HTMLImageElement | null = null;
16
17export function stop() {
18 activeClient?.stop();
19 activeClient = null;
20 activeImage?.removeAttribute("src");
21 activeImage = null;
22}
23
24export function command(button: "home" | "back" | "appSwitcher" | "rotate") {
25 if (button === "rotate") activeClient?.rotate();
26 else activeClient?.pressButton(button);
27}
28
29/** Bundled into the existing native WebView without React or Expo's web runtime. */
30export function start(configuration: DeviceStreamConfiguration) {
31 stop();
32 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- The native WebView bridge takes one string.
33 const post = (message: object) => window.ReactNativeWebView.postMessage(JSON.stringify(message));
34 const { colors, platform } = configuration;
35 Object.assign(document.documentElement.style, { height: "100%", overflow: "hidden" });
36 Object.assign(document.body.style, {
37 margin: "0",
38 height: "100%",
39 overflow: "hidden",
40 background: colors.background,
41 color: colors.foreground,
42 fontFamily: "system-ui",
43 });
44 const container = document.createElement("div");
45 Object.assign(container.style, {
46 position: "fixed",
47 inset: "0",
48 containerType: "size",
49 display: "flex",
50 alignItems: "center",
51 justifyContent: "center",
52 });
53 const frame = document.createElement("div");
54 frame.setAttribute("role", "application");
55 frame.setAttribute(
56 "aria-label",
57 platform === "ios" ? "iOS Simulator screen" : "Android Emulator screen",
58 );
59 frame.tabIndex = 0;
60 Object.assign(frame.style, {
61 position: "relative",
62 touchAction: "none",
63 userSelect: "none",
64 webkitUserSelect: "none",
65 webkitTouchCallout: "none",
66 outline: "none",
67 });
68 const canvas = document.createElement("canvas");
69 const image = document.createElement("img");
70 image.alt = "";
71 image.draggable = false;
72 image.style.display = "none";
73 const overlay = document.createElement("div");
74 overlay.setAttribute("role", "status");
75 Object.assign(overlay.style, {
76 position: "fixed",
77 inset: "0",
78 display: "flex",
79 flexDirection: "column",
80 alignItems: "center",
81 justifyContent: "center",
82 gap: "16px",
83 padding: "24px",
84 textAlign: "center",
85 background: colors.background,
86 });
87 const detail = document.createElement("span");
88 const retry = document.createElement("button");
89 retry.textContent = "Retry";
90 Object.assign(retry.style, {
91 padding: "12px 24px",
92 borderRadius: "20px",
93 border: `1px solid ${colors.buttonBorder}`,
94 background: colors.buttonBackground,
95 color: colors.buttonForeground,
96 font: "inherit",
97 display: "none",
98 });
99 retry.addEventListener("click", () => post({ type: "retry" }));
100 overlay.append(detail, retry);
101 const inputStatus = document.createElement("div");
102 inputStatus.setAttribute("role", "status");
103 inputStatus.textContent = "Reconnecting device controls...";
104 Object.assign(inputStatus.style, {
105 position: "fixed",
106 bottom: "12px",
107 left: "0",
108 right: "0",
109 textAlign: "center",
110 pointerEvents: "none",
111 fontSize: "13px",
112 color: colors.muted,
113 background: colors.background,
114 });
115 frame.append(canvas, image);
116 container.append(frame);
117 document.body.replaceChildren(container, overlay, inputStatus);
118
119 let pointerId: number | null = null;
120 let inputConnected = false;
121 let streaming = false;
122 const layout = (screen: DeviceScreenSize | null) => {
123 const landscape =
124 screen?.orientation === "landscape_left" || screen?.orientation === "landscape_right";
125 const aspect = screen
126 ? landscape
127 ? Math.max(screen.width, screen.height) / Math.min(screen.width, screen.height)
128 : Math.min(screen.width, screen.height) / Math.max(screen.width, screen.height)
129 : 9 / 19.5;
130 const rotation =
131 platform === "ios" && screen && screen.width <= screen.height
132 ? screen.orientation === "landscape_left"
133 ? 90
134 : screen.orientation === "landscape_right"
135 ? -90
136 : screen.orientation === "portrait_upside_down"
137 ? 180
138 : 0
139 : 0;
140 const sideways = Math.abs(rotation) === 90;
141 frame.style.width = `min(100cqw, ${aspect * 100}cqh)`;
142 frame.style.height = `min(100cqh, ${100 / aspect}cqw)`;
143 for (const media of [canvas, image]) {
144 Object.assign(media.style, {
145 position: "absolute",
146 width: sideways ? `${100 / aspect}%` : "100%",
147 height: sideways ? `${100 * aspect}%` : "100%",
148 left: "50%",
149 top: "50%",
150 transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
151 pointerEvents: "none",
152 });
153 }
154 };
155 layout(null);
156 const unauthorized = () => {
157 if (activeClient === client) post({ type: "unauthorized" });
158 };
159 const client = createDeviceStreamClient(
160 { ...configuration, preferMjpeg: platform === "ios" },
161 canvas,
162 {
163 onStatus: (status, message) => {
164 streaming = status === "streaming";
165 overlay.style.display = streaming ? "none" : "flex";
166 inputStatus.style.display = streaming && !inputConnected ? "block" : "none";
167 detail.textContent =
168 status === "error" ? (message ?? "Device stream failed.") : "Connecting to device...";
169 retry.style.display = status === "error" ? "block" : "none";
170 },
171 onScreen: layout,
172 onMjpegFallback: (url) => {
173 canvas.style.display = "none";
174 image.style.display = "block";
175 image.src = url;
176 },
177 onUnauthorized: unauthorized,
178 onInputConnected: (connected) => {
179 inputConnected = connected;
180 inputStatus.style.display = streaming && !connected ? "block" : "none";
181 post({ type: "input", connected });
182 },
183 },
184 );
185 activeClient = client;
186 activeImage = image;
187 image.addEventListener("error", unauthorized);
188 const touch = (event: PointerEvent, phase: "begin" | "move" | "end") => {
189 const rect = frame.getBoundingClientRect();
190 client.sendTouch(
191 phase,
192 Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
193 Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)),
194 );
195 };
196 frame.addEventListener("pointerdown", (event) => {
197 if (!inputConnected || pointerId !== null) return;
198 event.preventDefault();
199 pointerId = event.pointerId;
200 frame.setPointerCapture(event.pointerId);
201 frame.focus();
202 touch(event, "begin");
203 });
204 frame.addEventListener("pointermove", (event) => {
205 if (pointerId === event.pointerId) touch(event, "move");
206 });
207 const endTouch = (event: PointerEvent) => {
208 if (pointerId !== event.pointerId) return;
209 pointerId = null;
210 touch(event, "end");
211 };
212 frame.addEventListener("pointerup", endTouch);
213 frame.addEventListener("pointercancel", endTouch);
214 frame.addEventListener("lostpointercapture", endTouch);
215 frame.addEventListener("keydown", (event) => {
216 event.preventDefault();
217 client.sendKey(event, "down");
218 });
219 frame.addEventListener("keyup", (event) => client.sendKey(event, "up"));
220 window.addEventListener("pagehide", stop, { once: true });
221 post({ type: "input", connected: false });
222 client.start();
223}