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

DeviceStreamView.tsx

353 lines12.9 KB

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