Open History to see the last commit
1import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
2import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
3
4import { cn } from "~/lib/utils";
5import { Button } from "~/components/ui/button";
6import { refreshDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
7import { createCanvasFrameSink } from "@t3tools/client-runtime/device/frame";
8import { resolveDeviceShape } from "@t3tools/client-runtime/device/shape-profile";
9import { deviceKeyboard, deviceModel } from "./deviceModels";
10import { fitDeviceFrame } from "./deviceFrameLayout";
11import { DeviceDuoViewport } from "./DeviceDuoViewport";
12import { DeviceDuoControls } from "./DeviceDuoControls";
13import type { DuoControlState } from "@t3tools/client-runtime/device/duo-control";
14import { DevicePhoneViewport } from "./DevicePhoneViewport";
15import { DeviceLoadingView } from "./DeviceLoadingView";
16import { type DeviceAxElement, fetchDeviceAxTree } from "./deviceHubApi";
17import {
18 createDeviceStreamClient,
19 type DeviceHardwareButton,
20 type DeviceScreenSize,
21 type DeviceStreamClient,
22 type DeviceStreamStatus,
23} from "@t3tools/client-runtime/device/stream";
24
25const AX_POLL_INTERVAL_MS = 2_000;
26const CONTROLS_RAIL_WIDTH = 56;
27
28export interface DeviceViewControls {
29 readonly phone: boolean;
30 readonly streaming: boolean;
31 readonly phoneUnavailableReason: string | null;
32 readonly showPhone: () => void;
33 readonly showFlat: () => void;
34 readonly resetView: () => void;
35 readonly foldingControls?: ReactNode;
36 readonly keyboard: { readonly attached: boolean; readonly toggle: () => void } | null;
37}
38
39export interface DeviceStreamHandle {
40 readonly pressButton: (button: DeviceHardwareButton) => void;
41 readonly rotate: () => void;
42 /** False while the input socket is down; controls should disable. */
43 readonly inputConnected: boolean;
44}
45
46/**
47 * The live device screen. Pointer events map onto normalized coordinates in
48 * the displayed frame and go to the device; keyboard input is forwarded while
49 * the surface is focused. `visible=false` tears the stream down so a hidden
50 * panel decodes nothing.
51 */
52export function DeviceStreamView(props: {
53 readonly environmentId: EnvironmentId;
54 readonly platform: DevicePlatform;
55 readonly deviceId: string;
56 readonly deviceName?: string;
57 readonly deviceDescription?: string;
58 readonly visible: boolean;
59 readonly hostId: string;
60 /** The full panel opts into the phone spike; compact viewers retain their flat presentation. */
61 readonly allowPhoneView?: boolean;
62 readonly renderControls?: (view: DeviceViewControls) => ReactNode;
63 /** Draw accessibility element frames over the screen. */
64 readonly axOverlay?: boolean;
65 readonly onHandle?: (handle: DeviceStreamHandle | null) => void;
66 readonly onScreen?: (screen: DeviceScreenSize | null) => void;
67}) {
68 const [duoControl, setDuoControl] = useState<DuoControlState>({
69 pending: false,
70 requested: null,
71 error: null,
72 });
73 const model = deviceModel(props.platform, props.deviceName ?? "");
74 const isDuo = model?.id === "iphone-duo";
75 const [presentation, setPresentation] = useState<"phone" | "flat">("phone");
76 const [keyboardAttached, setKeyboardAttached] = useState(false);
77 const [phoneUnavailable, setPhoneUnavailable] = useState(false);
78 const onPhoneUnavailable = useCallback(() => setPhoneUnavailable(true), []);
79 const cancelPhoneInputRef = useRef<(() => void) | null>(null);
80 const cancelPhoneInput = useCallback(() => cancelPhoneInputRef.current?.(), []);
81 const resetViewRef = useRef<(() => void) | null>(null);
82 const onResetReady = useCallback((reset: (() => void) | null) => {
83 resetViewRef.current = reset;
84 }, []);
85 const frameListenerRef = useRef<(() => void) | null>(null);
86 const onFrameListener = useCallback((listener: (() => void) | null) => {
87 frameListenerRef.current = listener;
88 }, []);
89 const onInputCancel = useCallback((cancel: (() => void) | null) => {
90 cancelPhoneInputRef.current = cancel;
91 }, []);
92 const access = useDeviceHubAccess(props.environmentId, props.hostId);
93 const canvasRef = useRef<HTMLCanvasElement | null>(null);
94 const clientRef = useRef<DeviceStreamClient | null>(null);
95 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
96 const [detail, setDetail] = useState<string | undefined>(undefined);
97 const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
98 const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);
99 const [mjpegGeneration, setMjpegGeneration] = useState(0);
100 const attachMjpegImage = useCallback((image: HTMLImageElement | null) => {
101 clientRef.current?.setMjpegImage(image);
102 }, []);
103 const [inputState, setInputState] = useState<{ connected: boolean; detail?: string }>({
104 connected: false,
105 });
106 const { onHandle, onScreen } = props;
107
108 useEffect(() => {
109 const canvas = canvasRef.current;
110 if (!access || !canvas || !props.visible) {
111 setStatus("connecting");
112 onHandle?.(null);
113 return;
114 }
115 const client = createDeviceStreamClient(
116 { platform: props.platform, deviceId: props.deviceId, access },
117 createCanvasFrameSink(canvas, () => frameListenerRef.current?.()),
118 {
119 onDuoControl: setDuoControl,
120 onDuoUnavailable: onPhoneUnavailable,
121 onStatus: (next, nextDetail) => {
122 setStatus(next);
123 setDetail(nextDetail);
124 },
125 onScreen: (next) => {
126 setScreen(next);
127 onScreen?.(next);
128 },
129 onUnauthorized: () => {
130 // A fresh ticket re-runs this effect through the access dependency.
131 refreshDeviceHubAccess(props.environmentId);
132 },
133 onMjpegFallback: (url) => {
134 setMjpegUrl(url);
135 setMjpegGeneration((generation) => generation + 1);
136 },
137 onInputConnected: (connected, detail) => {
138 setInputState({ connected, ...(detail ? { detail } : {}) });
139 onHandle?.({
140 pressButton: client.pressButton,
141 rotate: client.rotate,
142 inputConnected: connected,
143 });
144 },
145 },
146 );
147 clientRef.current = client;
148 setMjpegUrl(null);
149 setInputState({ connected: false });
150 client.start();
151 onHandle?.({ pressButton: client.pressButton, rotate: client.rotate, inputConnected: false });
152 return () => {
153 cancelPhoneInput();
154 client.stop();
155 clientRef.current = null;
156 onHandle?.(null);
157 onScreen?.(null);
158 setScreen(null);
159 };
160 }, [
161 access,
162 cancelPhoneInput,
163 onHandle,
164 onPhoneUnavailable,
165 onScreen,
166 props.deviceId,
167 props.environmentId,
168 props.platform,
169 props.visible,
170 ]);
171
172 // Displayed aspect ratio (width / height) of the device as the user sees it.
173 const aspect = useMemo(() => {
174 if (!screen) return props.platform === "ios" ? 9 / 19.5 : 9 / 20;
175 const landscape =
176 screen.orientation === "landscape_left" || screen.orientation === "landscape_right";
177 const w = landscape
178 ? Math.max(screen.width, screen.height)
179 : Math.min(screen.width, screen.height);
180 const h = landscape
181 ? Math.min(screen.width, screen.height)
182 : Math.max(screen.width, screen.height);
183 return w / h;
184 }, [props.platform, screen]);
185
186 const showPhone =
187 props.allowPhoneView &&
188 status === "streaming" &&
189 props.visible &&
190 presentation === "phone" &&
191 !phoneUnavailable &&
192 !mjpegUrl &&
193 !props.axOverlay &&
194 (!isDuo || screen?.supportsHingeAngle === true);
195 const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
196
197 // The frame is the largest box at `aspect` that fits the container, so a
198 // narrow panel shows a shorter phone rather than a squeezed one. CSS
199 // `aspect-ratio` alone cannot do this: with the height pinned to 100% the
200 // width clamp wins and distorts the drawn frame.
201 const hostRef = useRef<HTMLDivElement | null>(null);
202 const [host, setHost] = useState({ width: 0, height: 0 });
203 useEffect(() => {
204 const element = hostRef.current;
205 if (!element) return;
206 const update = () => {
207 const rect = element.getBoundingClientRect();
208 setHost((current) =>
209 current.width === rect.width && current.height === rect.height
210 ? current
211 : { width: rect.width, height: rect.height },
212 );
213 };
214 update();
215 const observer = new ResizeObserver(update);
216 observer.observe(element);
217 return () => observer.disconnect();
218 }, []);
219 const frame = useMemo(() => {
220 return fitDeviceFrame(aspect, host.width, host.height, controlsInset);
221 }, [aspect, controlsInset, host]);
222
223 // serve-sim streams the raw framebuffer; rotate the display for a device
224 // that reports landscape while its frames stay portrait.
225 const rotation = useMemo(() => {
226 if (props.platform !== "ios" || !screen || screen.width > screen.height) return 0;
227 switch (screen.orientation) {
228 case "landscape_left":
229 return 90;
230 case "landscape_right":
231 return -90;
232 case "portrait_upside_down":
233 return 180;
234 default:
235 return 0;
236 }
237 }, [props.platform, screen]);
238
239 // A sideways rotation draws the raw portrait frame into a landscape box:
240 // the media element takes the transposed size and is rotated about the
241 // box's center.
242 const sideways = rotation === 90 || rotation === -90;
243 const mediaStyle: React.CSSProperties = sideways
244 ? {
245 width: frame.height,
246 height: frame.width,
247 left: (frame.width - frame.height) / 2,
248 top: (frame.height - frame.width) / 2,
249 transform: `rotate(${rotation}deg)`,
250 }
251 : {
252 width: frame.width,
253 height: frame.height,
254 ...(rotation ? { transform: `rotate(${rotation}deg)` } : {}),
255 };
256
257 // The accessibility tree is polled while the overlay is on; each poll is
258 // one JSON fetch, so there is nothing to repaint between polls.
259 const [axElements, setAxElements] = useState<ReadonlyArray<DeviceAxElement>>([]);
260 useEffect(() => {
261 if (!props.axOverlay || !access || !props.visible) return;
262 const target = { access, platform: props.platform, deviceId: props.deviceId };
263 let controller: AbortController | null = null;
264 let timer: ReturnType<typeof setTimeout> | null = null;
265 let stopped = false;
266 const poll = async () => {
267 controller = new AbortController();
268 try {
269 const tree = await fetchDeviceAxTree(target, controller.signal);
270 if (!stopped) setAxElements(tree.elements);
271 } catch {
272 // Keep the last good tree; the next poll retries.
273 }
274 if (!stopped) timer = setTimeout(() => void poll(), AX_POLL_INTERVAL_MS);
275 };
276 void poll();
277 return () => {
278 stopped = true;
279 controller?.abort();
280 if (timer) clearTimeout(timer);
281 setAxElements([]);
282 };
283 }, [access, props.axOverlay, props.deviceId, props.platform, props.visible]);
284
285 const pointerActive = useRef(false);
286 const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
287 const rect = event.currentTarget.getBoundingClientRect();
288 const x = (event.clientX - rect.left) / rect.width;
289 const y = (event.clientY - rect.top) / rect.height;
290 return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
291 };
292
293 const phoneUnavailableReason =
294 isDuo && !screen?.supportsHingeAngle
295 ? "iPhone Duo 3D requires Device Hub 0.11.0 or newer"
296 : phoneUnavailable
297 ? "3D is unavailable on this browser"
298 : mjpegUrl
299 ? "3D requires the H.264 stream"
300 : props.axOverlay
301 ? "Turn off accessibility frames to use 3D"
302 : null;
303
304 const keyboardSource = deviceKeyboard(props.platform, props.deviceName ?? "");
305 const resetView = useCallback(() => {
306 if (!isDuo) {
307 const orientation = keyboardAttached ? "landscape_right" : "portrait";
308 if (screen?.orientation !== orientation) clientRef.current?.setOrientation(orientation);
309 }
310 resetViewRef.current?.();
311 }, [isDuo, keyboardAttached, screen?.orientation]);
312 const profile = resolveDeviceShape({
313 platform: props.platform,
314 name: props.deviceName ?? "",
315 portraitAspect: Math.min(aspect, 1 / aspect),
316 });
317
318 return (
319 <div
320 className={cn(
321 "relative flex size-full min-h-0 min-w-0",
322 props.allowPhoneView ? "bg-background" : "bg-black/90",
323 )}
324 >
325 {props.renderControls ? (
326 <DeviceControlsSlot
327 renderControls={props.renderControls}
328 view={{
329 phone: !!showPhone,
330 streaming: status === "streaming",
331 phoneUnavailableReason,
332 foldingControls:
333 showPhone && isDuo && screen?.supportsHingeAngle ? (
334 <DeviceDuoControls
335 screen={screen}
336 state={duoControl}
337 enabled={inputState.connected}
338 onCommand={(command) => {
339 cancelPhoneInput();
340 clientRef.current?.controlDuo(command);
341 }}
342 />
343 ) : null,
344 keyboard:
345 showPhone && keyboardSource
346 ? {
347 attached: keyboardAttached,
348 toggle: () => {
349 cancelPhoneInput();
350 if (!keyboardAttached && screen?.orientation !== "landscape_right")
351 clientRef.current?.setOrientation("landscape_right");
352 setKeyboardAttached(!keyboardAttached);
353 },
354 }
355 : null,
356 showPhone: () => setPresentation("phone"),
357 showFlat: () => setPresentation("flat"),
358 }}
359 onResetView={resetView}
360 />
361 ) : null}
362 <div
363 ref={hostRef}
364 className={cn(
365 "relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
366 controlsInset && "pr-14",
367 )}
368 tabIndex={0}
369 role="application"
370 aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}
371 onKeyDown={(event) => {
372 if (event.target !== event.currentTarget) return;
373 if (event.metaKey && !["r", "R"].includes(event.key)) return;
374 event.preventDefault();
375 clientRef.current?.sendKey(event.nativeEvent, "down");
376 }}
377 onKeyUp={(event) => {
378 if (event.target !== event.currentTarget) return;
379 clientRef.current?.sendKey(event.nativeEvent, "up");
380 }}
381 >
382 <div
383 className={cn("relative select-none", showPhone && "invisible pointer-events-none")}
384 style={{ width: frame.width, height: frame.height }}
385 onPointerDown={(event) => {
386 event.currentTarget.setPointerCapture(event.pointerId);
387 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
388 pointerActive.current = true;
389 const { x, y } = normalizedPoint(event);
390 clientRef.current?.sendTouch("begin", x, y);
391 }}
392 onPointerMove={(event) => {
393 if (!pointerActive.current) return;
394 const { x, y } = normalizedPoint(event);
395 clientRef.current?.sendTouch("move", x, y);
396 }}
397 onPointerUp={(event) => {
398 if (!pointerActive.current) return;
399 pointerActive.current = false;
400 const { x, y } = normalizedPoint(event);
401 clientRef.current?.sendTouch("end", x, y);
402 }}
403 onPointerCancel={(event) => {
404 if (!pointerActive.current) return;
405 pointerActive.current = false;
406 const { x, y } = normalizedPoint(event);
407 clientRef.current?.sendTouch("end", x, y);
408 }}
409 >
410 <canvas
411 ref={canvasRef}
412 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
413 style={mediaStyle}
414 />
415 {props.visible && access && mjpegUrl ? (
416 <img
417 key={mjpegGeneration}
418 ref={attachMjpegImage}
419 alt=""
420 draggable={false}
421 className="absolute top-0 left-0 object-contain"
422 style={mediaStyle}
423 />
424 ) : null}
425 {axElements.length > 0 ? (
426 <div className="pointer-events-none absolute inset-0" aria-hidden>
427 {axElements.map((element) => (
428 <div
429 key={element.id}
430 className="absolute border border-info/80 bg-info/10"
431 style={{
432 left: `${element.x * 100}%`,
433 top: `${element.y * 100}%`,
434 width: `${element.width * 100}%`,
435 height: `${element.height * 100}%`,
436 }}
437 >
438 {element.label ? (
439 <span className="absolute -top-3.5 left-0 max-w-full truncate rounded-sm bg-info px-1 text-3xs leading-3.5 text-white">
440 {element.label}
441 </span>
442 ) : null}
443 </div>
444 ))}
445 </div>
446 ) : null}
447 </div>
448 {showPhone && isDuo && model ? (
449 <DeviceDuoViewport
450 onFrameListener={onFrameListener}
451 model={model}
452 controlError={duoControl.error}
453 hingePreview={
454 duoControl.requested?.control === "angle" ? duoControl.requested.value : null
455 }
456 source={canvasRef}
457 client={clientRef}
458 onInputCancel={onInputCancel}
459 onResetReady={onResetReady}
460 screen={screen}
461 onUnavailable={onPhoneUnavailable}
462 />
463 ) : showPhone ? (
464 <DevicePhoneViewport
465 profile={profile}
466 model={deviceModel(props.platform, props.deviceName ?? "")}
467 accessory={keyboardAttached ? keyboardSource : null}
468 source={canvasRef}
469 onFrameListener={onFrameListener}
470 client={clientRef}
471 onInputCancel={onInputCancel}
472 onResetReady={onResetReady}
473 screen={screen}
474 onUnavailable={onPhoneUnavailable}
475 />
476 ) : null}
477 {props.allowPhoneView && !props.renderControls && status === "streaming" ? (
478 <div className="absolute top-3 left-3 flex gap-1 rounded-lg border border-border/50 bg-background/90 p-1 shadow-sm">
479 <Button
480 variant={showPhone ? "secondary" : "ghost"}
481 size="xs"
482 aria-pressed={!!showPhone}
483 disabled={!!phoneUnavailableReason}
484 title={phoneUnavailableReason ?? "Show 3D phone"}
485 onClick={() => setPresentation("phone")}
486 >
487 3D
488 </Button>
489 <Button
490 variant={!showPhone ? "secondary" : "ghost"}
491 size="xs"
492 aria-pressed={!showPhone}
493 onClick={() => setPresentation("flat")}
494 >
495 Flat
496 </Button>
497 </div>
498 ) : null}
499 {status === "streaming" && !inputState.connected ? (
500 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
501 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
502 Input disconnected{inputState.detail ? ` (${inputState.detail})` : ""}, reconnecting…
503 </span>
504 </div>
505 ) : null}
506 {status !== "streaming" ? (
507 <div className="absolute inset-0">
508 <DeviceLoadingView
509 name={props.deviceName ?? "Device"}
510 description={props.deviceDescription ?? ""}
511 stage="stream"
512 message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
513 error={status === "error"}
514 >
515 {status === "error" ? (
516 <Button
517 size="sm"
518 variant="outline"
519 onClick={() => {
520 // An expired ticket surfaces as unauthorized on restart and
521 // refreshes access through the effect; no need to mint one here.
522 clientRef.current?.stop();
523 clientRef.current?.start();
524 }}
525 >
526 Reconnect
527 </Button>
528 ) : null}
529 </DeviceLoadingView>
530 </div>
531 ) : null}
532 </div>
533 </div>
534 );
535}
536
537function DeviceControlsSlot(props: {
538 renderControls: (view: DeviceViewControls) => ReactNode;
539 view: Omit<DeviceViewControls, "resetView">;
540 onResetView: () => void;
541}) {
542 return props.renderControls({ ...props.view, resetView: props.onResetView });
543}