Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceStreamView.tsx

583 lines22.3 KB

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;
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 }
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;
70​
71export interface DeviceStreamHandle {
72 readonly pressButton: (button: DeviceHardwareButton) => void;
73 readonly rotate: () => void;
74 readonly inputConnected: boolean;
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 onCanvasVideo: () => setMjpegUrl(null),
168 onInputConnected: (connected, detail) => {
169 setInputState({ connected, ...(detail ? { detail } : {}) });
170 if (!connected) setShowRestartNotice(false);
171 onHandle?.({
172 pressButton: client.pressButton,
173 rotate: client.rotate,
174 inputConnected: connected,
175 });
176 },
177 },
178 );
179 clientRef.current = client;
180 setPhoneUnavailable(false);
181 setHasFrame(false);
182 setMjpegUrl(null);
183 setInputState({ connected: false });
184 client.start();
185 onHandle?.({ pressButton: client.pressButton, rotate: client.rotate, inputConnected: false });
186 return () => {
187 cancelPhoneInput();
188 client.stop();
189 clientRef.current = null;
190 onHandle?.(null);
191 onScreen?.(null);
192 setScreen(null);
193 };
194 }, [
195 access,
196 cancelPhoneInput,
197 onHandle,
198 onPhoneUnavailable,
199 onScreen,
200 props.deviceId,
201 props.environmentId,
202 props.platform,
203 props.visible,
204 ]);
205​
206 const aspect = screenAspect(props.platform, screen);
207​
208 const retainingFrame =
209 status === "connecting" && hasFrame && inputState.connected && screen !== null;
210 const showPhone =
211 props.allowPhoneView &&
212 (status === "streaming" || retainingFrame) &&
213 props.visible &&
214 presentation === "phone" &&
215 !phoneUnavailable &&
216 !mjpegUrl &&
217 !props.axOverlay &&
218 (!isDuo || screen?.supportsHingeAngle === true);
219 useEffect(() => {
220 if (!retainingFrame || !showPhone) return;
221 const timeout = window.setTimeout(() => setShowRestartNotice(true), 2_000);
222 return () => window.clearTimeout(timeout);
223 }, [retainingFrame, showPhone]);
224 const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
225​
226 // The frame is the largest box at `aspect` that fits the container, so a
227 // narrow panel shows a shorter phone rather than a squeezed one. CSS
228 // `aspect-ratio` alone cannot do this: with the height pinned to 100% the
229 // width clamp wins and distorts the drawn frame.
230 const hostRef = useRef<HTMLDivElement | null>(null);
231 const [host, setHost] = useState({ width: 0, height: 0 });
232 useEffect(() => {
233 const element = hostRef.current;
234 if (!element) return;
235 const update = () => {
236 const rect = element.getBoundingClientRect();
237 setHost((current) =>
238 current.width === rect.width && current.height === rect.height
239 ? current
240 : { width: rect.width, height: rect.height },
241 );
242 };
243 update();
244 return observeResize(element, update);
245 }, []);
246 const frame = fitDeviceFrame(aspect, host.width, host.height, controlsInset);
247​
248 const rotation = screenRotation(props.platform, screen);
249​
250 const sideways = rotation === 90 || rotation === -90;
251 const mediaStyle: React.CSSProperties = sideways
252 ? {
253 width: frame.height,
254 height: frame.width,
255 left: (frame.width - frame.height) / 2,
256 top: (frame.height - frame.width) / 2,
257 transform: `rotate(${rotation}deg)`,
258 }
259 : {
260 width: frame.width,
261 height: frame.height,
262 ...(rotation ? { transform: `rotate(${rotation}deg)` } : {}),
263 };
264​
265 const [axElements, setAxElements] = useState<ReadonlyArray<DeviceAxElement>>([]);
266 useEffect(() => {
267 if (!props.axOverlay || !access || !props.visible) return;
268 const target = { access, platform: props.platform, deviceId: props.deviceId };
269 let controller: AbortController | null = null;
270 let timer: ReturnType<typeof setTimeout> | null = null;
271 let stopped = false;
272 const poll = async () => {
273 controller = new AbortController();
274 try {
275 const tree = await fetchDeviceAxTree(target, controller.signal);
276 if (!stopped) setAxElements(tree.elements);
277 } catch {}
278 if (!stopped) timer = setTimeout(() => void poll(), AX_POLL_INTERVAL_MS);
279 };
280 void poll();
281 return () => {
282 stopped = true;
283 controller?.abort();
284 if (timer) clearTimeout(timer);
285 setAxElements([]);
286 };
287 }, [access, props.axOverlay, props.deviceId, props.platform, props.visible]);
288​
289 const pointerActive = useRef(false);
290 const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
291 const rect = event.currentTarget.getBoundingClientRect();
292 const x = (event.clientX - rect.left) / rect.width;
293 const y = (event.clientY - rect.top) / rect.height;
294 return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
295 };
296​
297 const phoneUnavailableReason =
298 isDuo && !screen?.supportsHingeAngle
299 ? "iPhone Duo 3D requires Device Hub 0.11.0 or newer"
300 : phoneUnavailable
301 ? "3D is unavailable on this browser"
302 : mjpegUrl
303 ? "3D requires the H.264 stream"
304 : props.axOverlay
305 ? "Turn off accessibility frames to use 3D"
306 : null;
307​
308 const keyboardSource = deviceKeyboard(props.platform, props.deviceName ?? "");
309 const resetView = () => {
310 if (!isDuo) {
311 const orientation = keyboardAttached ? "landscape_right" : "portrait";
312 if (screen?.orientation !== orientation) clientRef.current?.setOrientation(orientation);
313 }
314 resetViewRef.current?.();
315 };
316 const profile = resolveDeviceShape({
317 platform: props.platform,
318 name: props.deviceName ?? "",
319 portraitAspect: Math.min(aspect, 1 / aspect),
320 });
321​
322 return (
323 <div
324 className={cn(
325 "relative flex size-full min-h-0 min-w-0",
326 props.allowPhoneView ? "bg-background" : "bg-black/90",
327 )}
328 >
329 {props.renderControls ? (
330 <DeviceControlsSlot
331 renderControls={props.renderControls}
332 view={{
333 phone: !!showPhone,
334 streaming: status === "streaming",
335 phoneUnavailableReason,
336 foldingControls:
337 props.platform === "android" && access ? (
338 <DeviceAndroidFoldControls
339 key={`${props.hostId}:${props.deviceId}`}
340 access={access}
341 deviceId={props.deviceId}
342 visible={props.visible}
343 enabled={status === "streaming"}
344 screenWidth={screen?.width}
345 screenHeight={screen?.height}
346 onFoldAngle={setFoldAngle}
347 renewAccess={() => renewDeviceHubAccess(props.environmentId, props.hostId)}
348 />
349 ) : showPhone && isDuo && screen?.supportsHingeAngle ? (
350 <DeviceDuoControls
351 screen={screen}
352 state={duoControl}
353 enabled={inputState.connected}
354 onCommand={(command) => {
355 cancelPhoneInput();
356 clientRef.current?.controlDuo(command);
357 }}
358 />
359 ) : null,
360 keyboard:
361 showPhone && keyboardSource
362 ? {
363 attached: keyboardAttached,
364 toggle: () => {
365 cancelPhoneInput();
366 if (!keyboardAttached && screen?.orientation !== "landscape_right")
367 clientRef.current?.setOrientation("landscape_right");
368 setKeyboardAttached(!keyboardAttached);
369 },
370 }
371 : null,
372 showPhone: () => setPresentation("phone"),
373 showFlat: () => setPresentation("flat"),
374 }}
375 onResetView={resetView}
376 />
377 ) : null}
378 <div
379 ref={hostRef}
380 className={cn(
381 "relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
382 // Overlay the stream; focus (including pointer-driven focus) marks keyboard capture.
383 "after:pointer-events-none after:absolute after:inset-0 after:z-10 focus:after:ring-2 focus:after:ring-inset focus:after:ring-ring",
384 controlsInset && "pr-14",
385 )}
386 tabIndex={0}
387 role="application"
388 aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}
389 onKeyDown={(event) => {
390 if (event.target !== event.currentTarget) return;
391 if (event.metaKey && !["r", "R"].includes(event.key)) return;
392 // Let browser paste chords fire the paste event.
393 if (
394 (event.ctrlKey && (event.key === "v" || event.key === "V")) ||
395 (event.shiftKey && event.key === "Insert")
396 ) {
397 return;
398 }
399 event.preventDefault();
400 clientRef.current?.sendKey(event.nativeEvent, "down");
401 }}
402 onPaste={(event) => {
403 if (event.target !== event.currentTarget) return;
404 event.preventDefault();
405 clientRef.current?.sendText(event.clipboardData.getData("text/plain"));
406 }}
407 onKeyUp={(event) => {
408 if (event.target !== event.currentTarget) return;
409 clientRef.current?.sendKey(event.nativeEvent, "up");
410 }}
411 >
412 <div
413 className={cn("relative select-none", showPhone && "invisible pointer-events-none")}
414 style={{ width: frame.width, height: frame.height }}
415 onPointerDown={(event) => {
416 if (event.button !== 0) return;
417 event.currentTarget.setPointerCapture(event.pointerId);
418 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
419 pointerActive.current = true;
420 const { x, y } = normalizedPoint(event);
421 clientRef.current?.sendTouch("begin", x, y);
422 }}
423 onPointerMove={(event) => {
424 if (!pointerActive.current) return;
425 const { x, y } = normalizedPoint(event);
426 clientRef.current?.sendTouch("move", x, y);
427 }}
428 onPointerUp={(event) => {
429 if (!pointerActive.current) return;
430 pointerActive.current = false;
431 const { x, y } = normalizedPoint(event);
432 clientRef.current?.sendTouch("end", x, y);
433 }}
434 onPointerCancel={(event) => {
435 if (!pointerActive.current) return;
436 pointerActive.current = false;
437 const { x, y } = normalizedPoint(event);
438 clientRef.current?.sendTouch("end", x, y);
439 }}
440 >
441 <canvas
442 ref={canvasRef}
443 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
444 style={mediaStyle}
445 />
446 {props.visible && access && mjpegUrl ? (
447 <img
448 key={mjpegGeneration}
449 ref={attachMjpegImage}
450 alt=""
451 draggable={false}
452 className="absolute top-0 left-0 object-contain"
453 style={mediaStyle}
454 />
455 ) : null}
456 {axElements.length > 0 ? (
457 <div className="pointer-events-none absolute inset-0" aria-hidden>
458 {axElements.map((element) => (
459 <div
460 key={element.id}
461 className="absolute border border-info/80 bg-info/10"
462 style={{
463 left: `${element.x * 100}%`,
464 top: `${element.y * 100}%`,
465 width: `${element.width * 100}%`,
466 height: `${element.height * 100}%`,
467 }}
468 >
469 {element.label ? (
470 <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">
471 {element.label}
472 </span>
473 ) : null}
474 </div>
475 ))}
476 </div>
477 ) : null}
478 </div>
479 {showPhone && isDuo && model ? (
480 <DeviceDuoViewport
481 onFrameListener={onFrameListener}
482 model={model}
483 controlError={duoControl.error}
484 hingePreview={
485 duoControl.requested?.control === "angle" ? duoControl.requested.value : null
486 }
487 source={canvasRef}
488 client={clientRef}
489 onInputCancel={onInputCancel}
490 onResetReady={onResetReady}
491 screen={screen}
492 onUnavailable={onPhoneUnavailable}
493 />
494 ) : showPhone ? (
495 <DevicePhoneViewport
496 profile={profile}
497 model={deviceModel(props.platform, props.deviceName ?? "")}
498 accessory={keyboardAttached ? keyboardSource : null}
499 source={canvasRef}
500 onFrameListener={onFrameListener}
501 client={clientRef}
502 onInputCancel={onInputCancel}
503 onResetReady={onResetReady}
504 screen={screen}
505 foldAngle={foldAngle}
506 onUnavailable={onPhoneUnavailable}
507 />
508 ) : null}
509 {props.allowPhoneView && !props.renderControls && status === "streaming" ? (
510 <div className="absolute top-3 left-3 flex gap-1 rounded-lg border border-border/50 bg-background/90 p-1 shadow-sm">
511 <Button
512 variant={showPhone ? "secondary" : "ghost"}
513 size="xs"
514 aria-pressed={!!showPhone}
515 disabled={!!phoneUnavailableReason}
516 title={phoneUnavailableReason ?? "Show 3D phone"}
517 onClick={() => setPresentation("phone")}
518 >
519 3D
520 </Button>
521 <Button
522 variant={!showPhone ? "secondary" : "ghost"}
523 size="xs"
524 aria-pressed={!showPhone}
525 onClick={() => setPresentation("flat")}
526 >
527 Flat
528 </Button>
529 </div>
530 ) : null}
531 {status === "streaming" && !inputState.connected ? (
532 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
533 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
534 Input disconnected{inputState.detail ? ` (${inputState.detail})` : ""}, reconnecting…
535 </span>
536 </div>
537 ) : null}
538 {retainingFrame && showPhone && showRestartNotice ? (
539 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
540 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
541 Waiting for device video…
542 </span>
543 </div>
544 ) : null}
545 {status !== "streaming" && !(retainingFrame && showPhone) ? (
546 <div className="absolute inset-0">
547 <DeviceLoadingView
548 name={props.deviceName ?? "Device"}
549 description={props.deviceDescription ?? ""}
550 stage="stream"
551 message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
552 error={status === "error"}
553 >
554 {status === "error" ? (
555 <Button
556 size="sm"
557 variant="outline"
558 onClick={() => {
559 // An expired ticket surfaces as unauthorized on restart and
560 // refreshes access through the effect; no need to mint one here.
561 clientRef.current?.stop();
562 setPhoneUnavailable(false);
563 clientRef.current?.start();
564 }}
565 >
566 Reconnect
567 </Button>
568 ) : null}
569 </DeviceLoadingView>
570 </div>
571 ) : null}
572 </div>
573 </div>
574 );
576​
577function DeviceControlsSlot(props: {
578 renderControls: (view: DeviceViewControls) => ReactNode;
579 view: Omit<DeviceViewControls, "resetView">;
580 onResetView: () => void;
581}) {
582 return props.renderControls({ ...props.view, resetView: props.onResetView });