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