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