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