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, renewDeviceHubAccess, 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 renewAccess={() => renewDeviceHubAccess(props.environmentId, props.hostId)}
347 />
348 ) : showPhone && isDuo && screen?.supportsHingeAngle ? (
349 <DeviceDuoControls
350 screen={screen}
351 state={duoControl}
352 enabled={inputState.connected}
353 onCommand={(command) => {
354 cancelPhoneInput();
355 clientRef.current?.controlDuo(command);
356 }}
357 />
358 ) : null,
359 keyboard:
360 showPhone && keyboardSource
361 ? {
362 attached: keyboardAttached,
363 toggle: () => {
364 cancelPhoneInput();
365 if (!keyboardAttached && screen?.orientation !== "landscape_right")
366 clientRef.current?.setOrientation("landscape_right");
367 setKeyboardAttached(!keyboardAttached);
368 },
369 }
370 : null,
371 showPhone: () => setPresentation("phone"),
372 showFlat: () => setPresentation("flat"),
373 }}
374 onResetView={resetView}
375 />
376 ) : null}
377 <div
378 ref={hostRef}
379 className={cn(
380 "relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
381 // Overlay the stream; focus (including pointer-driven focus) marks keyboard capture.
382 "after:pointer-events-none after:absolute after:inset-0 after:z-10 focus:after:ring-2 focus:after:ring-inset focus:after:ring-ring",
383 controlsInset && "pr-14",
384 )}
385 tabIndex={0}
386 role="application"
387 aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}
388 onKeyDown={(event) => {
389 if (event.target !== event.currentTarget) return;
390 if (event.metaKey && !["r", "R"].includes(event.key)) return;
391 // Let browser paste chords fire the paste event.
392 if (
393 (event.ctrlKey && (event.key === "v" || event.key === "V")) ||
394 (event.shiftKey && event.key === "Insert")
395 ) {
396 return;
397 }
398 event.preventDefault();
399 clientRef.current?.sendKey(event.nativeEvent, "down");
400 }}
401 onPaste={(event) => {
402 if (event.target !== event.currentTarget) return;
403 event.preventDefault();
404 clientRef.current?.sendText(event.clipboardData.getData("text/plain"));
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 if (event.button !== 0) return;
416 event.currentTarget.setPointerCapture(event.pointerId);
417 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
418 pointerActive.current = true;
419 const { x, y } = normalizedPoint(event);
420 clientRef.current?.sendTouch("begin", x, y);
421 }}
422 onPointerMove={(event) => {
423 if (!pointerActive.current) return;
424 const { x, y } = normalizedPoint(event);
425 clientRef.current?.sendTouch("move", x, y);
426 }}
427 onPointerUp={(event) => {
428 if (!pointerActive.current) return;
429 pointerActive.current = false;
430 const { x, y } = normalizedPoint(event);
431 clientRef.current?.sendTouch("end", x, y);
432 }}
433 onPointerCancel={(event) => {
434 if (!pointerActive.current) return;
435 pointerActive.current = false;
436 const { x, y } = normalizedPoint(event);
437 clientRef.current?.sendTouch("end", x, y);
438 }}
439 >
440 <canvas
441 ref={canvasRef}
442 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
443 style={mediaStyle}
444 />
445 {props.visible && access && mjpegUrl ? (
446 <img
447 key={mjpegGeneration}
448 ref={attachMjpegImage}
449 alt=""
450 draggable={false}
451 className="absolute top-0 left-0 object-contain"
452 style={mediaStyle}
453 />
454 ) : null}
455 {axElements.length > 0 ? (
456 <div className="pointer-events-none absolute inset-0" aria-hidden>
457 {axElements.map((element) => (
458 <div
459 key={element.id}
460 className="absolute border border-info/80 bg-info/10"
461 style={{
462 left: `${element.x * 100}%`,
463 top: `${element.y * 100}%`,
464 width: `${element.width * 100}%`,
465 height: `${element.height * 100}%`,
466 }}
467 >
468 {element.label ? (
469 <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">
470 {element.label}
471 </span>
472 ) : null}
473 </div>
474 ))}
475 </div>
476 ) : null}
477 </div>
478 {showPhone && isDuo && model ? (
479 <DeviceDuoViewport
480 onFrameListener={onFrameListener}
481 model={model}
482 controlError={duoControl.error}
483 hingePreview={
484 duoControl.requested?.control === "angle" ? duoControl.requested.value : null
485 }
486 source={canvasRef}
487 client={clientRef}
488 onInputCancel={onInputCancel}
489 onResetReady={onResetReady}
490 screen={screen}
491 onUnavailable={onPhoneUnavailable}
492 />
493 ) : showPhone ? (
494 <DevicePhoneViewport
495 profile={profile}
496 model={deviceModel(props.platform, props.deviceName ?? "")}
497 accessory={keyboardAttached ? keyboardSource : null}
498 source={canvasRef}
499 onFrameListener={onFrameListener}
500 client={clientRef}
501 onInputCancel={onInputCancel}
502 onResetReady={onResetReady}
503 screen={screen}
504 foldAngle={foldAngle}
505 onUnavailable={onPhoneUnavailable}
506 />
507 ) : null}
508 {props.allowPhoneView && !props.renderControls && status === "streaming" ? (
509 <div className="absolute top-3 left-3 flex gap-1 rounded-lg border border-border/50 bg-background/90 p-1 shadow-sm">
510 <Button
511 variant={showPhone ? "secondary" : "ghost"}
512 size="xs"
513 aria-pressed={!!showPhone}
514 disabled={!!phoneUnavailableReason}
515 title={phoneUnavailableReason ?? "Show 3D phone"}
516 onClick={() => setPresentation("phone")}
517 >
518 3D
519 </Button>
520 <Button
521 variant={!showPhone ? "secondary" : "ghost"}
522 size="xs"
523 aria-pressed={!showPhone}
524 onClick={() => setPresentation("flat")}
525 >
526 Flat
527 </Button>
528 </div>
529 ) : null}
530 {status === "streaming" && !inputState.connected ? (
531 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
532 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
533 Input disconnected{inputState.detail ? ` (${inputState.detail})` : ""}, reconnecting…
534 </span>
535 </div>
536 ) : null}
537 {retainingFrame && showPhone && showRestartNotice ? (
538 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
539 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
540 Waiting for device video…
541 </span>
542 </div>
543 ) : null}
544 {status !== "streaming" && !(retainingFrame && showPhone) ? (
545 <div className="absolute inset-0">
546 <DeviceLoadingView
547 name={props.deviceName ?? "Device"}
548 description={props.deviceDescription ?? ""}
549 stage="stream"
550 message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
551 error={status === "error"}
552 >
553 {status === "error" ? (
554 <Button
555 size="sm"
556 variant="outline"
557 onClick={() => {
558 // An expired ticket surfaces as unauthorized on restart and
559 // refreshes access through the effect; no need to mint one here.
560 clientRef.current?.stop();
561 setPhoneUnavailable(false);
562 clientRef.current?.start();
563 }}
564 >
565 Reconnect
566 </Button>
567 ) : null}
568 </DeviceLoadingView>
569 </div>
570 ) : null}
571 </div>
572 </div>
573 );
574}
575
576function DeviceControlsSlot(props: {
577 renderControls: (view: DeviceViewControls) => ReactNode;
578 view: Omit<DeviceViewControls, "resetView">;
579 onResetView: () => void;
580}) {
581 return props.renderControls({ ...props.view, resetView: props.onResetView });
582}