Open History to see the last commit
1import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
2import { useEffect, useMemo, useRef, useState } from "react";
3
4import { cn } from "~/lib/utils";
5import { refreshDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
6import { DeviceLoadingView } from "./DeviceLoadingView";
7import { type DeviceAxElement, fetchDeviceAxTree } from "./deviceHubApi";
8import {
9 createDeviceStreamClient,
10 type DeviceHardwareButton,
11 type DeviceScreenSize,
12 type DeviceStreamClient,
13 type DeviceStreamStatus,
14} from "@t3tools/client-runtime/device/stream";
15
16const AX_POLL_INTERVAL_MS = 2_000;
17
18export interface DeviceStreamHandle {
19 readonly pressButton: (button: DeviceHardwareButton) => void;
20 readonly rotate: () => void;
21 /** False while the input socket is down; controls should disable. */
22 readonly inputConnected: boolean;
23}
24
25/**
26 * The live device screen. Pointer events map onto normalized coordinates in
27 * the displayed frame and go to the device; keyboard input is forwarded while
28 * the surface is focused. `visible=false` tears the stream down so a hidden
29 * panel decodes nothing.
30 */
31export function DeviceStreamView(props: {
32 readonly environmentId: EnvironmentId;
33 readonly platform: DevicePlatform;
34 readonly deviceId: string;
35 readonly deviceName?: string;
36 readonly deviceDescription?: string;
37 readonly visible: boolean;
38 readonly hostId: string;
39 /** Draw accessibility element frames over the screen. */
40 readonly axOverlay?: boolean;
41 readonly onHandle?: (handle: DeviceStreamHandle | null) => void;
42 readonly onScreen?: (screen: DeviceScreenSize | null) => void;
43}) {
44 const access = useDeviceHubAccess(props.environmentId, props.hostId);
45 const canvasRef = useRef<HTMLCanvasElement | null>(null);
46 const clientRef = useRef<DeviceStreamClient | null>(null);
47 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
48 const [detail, setDetail] = useState<string | undefined>(undefined);
49 const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
50 const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);
51 const [mjpegGeneration, setMjpegGeneration] = useState(0);
52 const [inputState, setInputState] = useState<{ connected: boolean; detail?: string }>({
53 connected: false,
54 });
55 const { onHandle, onScreen } = props;
56
57 useEffect(() => {
58 const canvas = canvasRef.current;
59 if (!access || !canvas || !props.visible) {
60 setStatus("connecting");
61 onHandle?.(null);
62 return;
63 }
64 const client = createDeviceStreamClient(
65 { platform: props.platform, deviceId: props.deviceId, access },
66 canvas,
67 {
68 onStatus: (next, nextDetail) => {
69 setStatus(next);
70 setDetail(nextDetail);
71 },
72 onScreen: (next) => {
73 setScreen(next);
74 onScreen?.(next);
75 },
76 onUnauthorized: () => {
77 // A fresh ticket re-runs this effect through the access dependency.
78 refreshDeviceHubAccess(props.environmentId);
79 },
80 onMjpegFallback: (url) => {
81 setMjpegUrl(url);
82 setMjpegGeneration((generation) => generation + 1);
83 },
84 onInputConnected: (connected, detail) => {
85 setInputState({ connected, ...(detail ? { detail } : {}) });
86 onHandle?.({
87 pressButton: client.pressButton,
88 rotate: client.rotate,
89 inputConnected: connected,
90 });
91 },
92 },
93 );
94 clientRef.current = client;
95 setMjpegUrl(null);
96 setInputState({ connected: false });
97 client.start();
98 onHandle?.({ pressButton: client.pressButton, rotate: client.rotate, inputConnected: false });
99 return () => {
100 client.stop();
101 clientRef.current = null;
102 onHandle?.(null);
103 onScreen?.(null);
104 setScreen(null);
105 };
106 }, [
107 access,
108 onHandle,
109 onScreen,
110 props.deviceId,
111 props.environmentId,
112 props.platform,
113 props.visible,
114 ]);
115
116 // Displayed aspect ratio (width / height) of the device as the user sees it.
117 const aspect = useMemo(() => {
118 if (!screen) return props.platform === "ios" ? 9 / 19.5 : 9 / 20;
119 const landscape =
120 screen.orientation === "landscape_left" || screen.orientation === "landscape_right";
121 const w = landscape
122 ? Math.max(screen.width, screen.height)
123 : Math.min(screen.width, screen.height);
124 const h = landscape
125 ? Math.min(screen.width, screen.height)
126 : Math.max(screen.width, screen.height);
127 return w / h;
128 }, [props.platform, screen]);
129
130 // The frame is the largest box at `aspect` that fits the container, so a
131 // narrow panel shows a shorter phone rather than a squeezed one. CSS
132 // `aspect-ratio` alone cannot do this: with the height pinned to 100% the
133 // width clamp wins and distorts the drawn frame.
134 const hostRef = useRef<HTMLDivElement | null>(null);
135 const [host, setHost] = useState({ width: 0, height: 0 });
136 useEffect(() => {
137 const element = hostRef.current;
138 if (!element) return;
139 const update = () => {
140 const rect = element.getBoundingClientRect();
141 setHost((current) =>
142 current.width === rect.width && current.height === rect.height
143 ? current
144 : { width: rect.width, height: rect.height },
145 );
146 };
147 update();
148 const observer = new ResizeObserver(update);
149 observer.observe(element);
150 return () => observer.disconnect();
151 }, []);
152 const frame = useMemo(() => {
153 if (host.width === 0 || host.height === 0) return { width: 0, height: 0 };
154 const byHeight = { width: host.height * aspect, height: host.height };
155 return byHeight.width <= host.width
156 ? byHeight
157 : { width: host.width, height: host.width / aspect };
158 }, [aspect, host]);
159
160 // serve-sim streams the raw framebuffer; rotate the display for a device
161 // that reports landscape while its frames stay portrait.
162 const rotation = useMemo(() => {
163 if (props.platform !== "ios" || !screen || screen.width > screen.height) return 0;
164 switch (screen.orientation) {
165 case "landscape_left":
166 return 90;
167 case "landscape_right":
168 return -90;
169 case "portrait_upside_down":
170 return 180;
171 default:
172 return 0;
173 }
174 }, [props.platform, screen]);
175
176 // A sideways rotation draws the raw portrait frame into a landscape box:
177 // the media element takes the transposed size and is rotated about the
178 // box's center.
179 const sideways = rotation === 90 || rotation === -90;
180 const mediaStyle: React.CSSProperties = sideways
181 ? {
182 width: frame.height,
183 height: frame.width,
184 left: (frame.width - frame.height) / 2,
185 top: (frame.height - frame.width) / 2,
186 transform: `rotate(${rotation}deg)`,
187 }
188 : {
189 width: frame.width,
190 height: frame.height,
191 ...(rotation ? { transform: `rotate(${rotation}deg)` } : {}),
192 };
193
194 // The accessibility tree is polled while the overlay is on; each poll is
195 // one JSON fetch, so there is nothing to repaint between polls.
196 const [axElements, setAxElements] = useState<ReadonlyArray<DeviceAxElement>>([]);
197 useEffect(() => {
198 if (!props.axOverlay || !access || !props.visible) return;
199 const target = { access, platform: props.platform, deviceId: props.deviceId };
200 let controller: AbortController | null = null;
201 let timer: ReturnType<typeof setTimeout> | null = null;
202 let stopped = false;
203 const poll = async () => {
204 controller = new AbortController();
205 try {
206 const tree = await fetchDeviceAxTree(target, controller.signal);
207 if (!stopped) setAxElements(tree.elements);
208 } catch {
209 // Keep the last good tree; the next poll retries.
210 }
211 if (!stopped) timer = setTimeout(() => void poll(), AX_POLL_INTERVAL_MS);
212 };
213 void poll();
214 return () => {
215 stopped = true;
216 controller?.abort();
217 if (timer) clearTimeout(timer);
218 setAxElements([]);
219 };
220 }, [access, props.axOverlay, props.deviceId, props.platform, props.visible]);
221
222 const pointerActive = useRef(false);
223 const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
224 const rect = event.currentTarget.getBoundingClientRect();
225 const x = (event.clientX - rect.left) / rect.width;
226 const y = (event.clientY - rect.top) / rect.height;
227 return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
228 };
229
230 return (
231 <div
232 ref={hostRef}
233 className="relative flex size-full items-center justify-center overflow-hidden bg-black/90 outline-none"
234 tabIndex={0}
235 role="application"
236 aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}
237 onKeyDown={(event) => {
238 if (event.metaKey && !["r", "R"].includes(event.key)) return;
239 event.preventDefault();
240 clientRef.current?.sendKey(event.nativeEvent, "down");
241 }}
242 onKeyUp={(event) => {
243 clientRef.current?.sendKey(event.nativeEvent, "up");
244 }}
245 >
246 <div
247 className="relative select-none"
248 style={{ width: frame.width, height: frame.height }}
249 onPointerDown={(event) => {
250 event.currentTarget.setPointerCapture(event.pointerId);
251 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
252 pointerActive.current = true;
253 const { x, y } = normalizedPoint(event);
254 clientRef.current?.sendTouch("begin", x, y);
255 }}
256 onPointerMove={(event) => {
257 if (!pointerActive.current) return;
258 const { x, y } = normalizedPoint(event);
259 clientRef.current?.sendTouch("move", x, y);
260 }}
261 onPointerUp={(event) => {
262 if (!pointerActive.current) return;
263 pointerActive.current = false;
264 const { x, y } = normalizedPoint(event);
265 clientRef.current?.sendTouch("end", x, y);
266 }}
267 onPointerCancel={(event) => {
268 if (!pointerActive.current) return;
269 pointerActive.current = false;
270 const { x, y } = normalizedPoint(event);
271 clientRef.current?.sendTouch("end", x, y);
272 }}
273 >
274 <canvas
275 ref={canvasRef}
276 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
277 style={mediaStyle}
278 />
279 {props.visible && access && mjpegUrl ? (
280 <img
281 key={mjpegGeneration}
282 src={mjpegUrl}
283 alt=""
284 draggable={false}
285 className="absolute top-0 left-0 object-contain"
286 style={mediaStyle}
287 />
288 ) : null}
289 {axElements.length > 0 ? (
290 <div className="pointer-events-none absolute inset-0" aria-hidden>
291 {axElements.map((element) => (
292 <div
293 key={element.id}
294 className="absolute border border-sky-400/80 bg-sky-400/10"
295 style={{
296 left: `${element.x * 100}%`,
297 top: `${element.y * 100}%`,
298 width: `${element.width * 100}%`,
299 height: `${element.height * 100}%`,
300 }}
301 >
302 {element.label ? (
303 <span className="absolute -top-3.5 left-0 max-w-full truncate rounded-sm bg-sky-500 px-1 text-[9px] leading-3.5 text-white">
304 {element.label}
305 </span>
306 ) : null}
307 </div>
308 ))}
309 </div>
310 ) : null}
311 </div>
312 {status === "streaming" && !inputState.connected ? (
313 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
314 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
315 Input disconnected{inputState.detail ? ` (${inputState.detail})` : ""}, reconnecting…
316 </span>
317 </div>
318 ) : null}
319 {status !== "streaming" ? (
320 <div className="pointer-events-none absolute inset-0">
321 <DeviceLoadingView
322 name={props.deviceName ?? "Device"}
323 description={props.deviceDescription ?? ""}
324 stage="stream"
325 message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
326 error={status === "error"}
327 />
328 </div>
329 ) : null}
330 </div>
331 );
332}