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

DeviceStreamView.tsx

575 lines21.8 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 sends raw portrait framebuffers even when iOS reports landscape; rotate the display.
45function screenRotation(platform: DevicePlatform, screen: DeviceScreenSize | null): number {
46 if (platform !== "ios" || !screen || screen.width > screen.height) return 0;
47 switch (screen.orientation) {
48 case "landscape_left":
49 return 90;
50 case "landscape_right":
51 return -90;
52 case "portrait_upside_down":
53 return 180;
54 default:
55 return 0;
56 }
58​
59export interface DeviceViewControls {
60 readonly phone: boolean;
61 readonly streaming: boolean;
62 readonly phoneUnavailableReason: string | null;
63 readonly showPhone: () => void;
64 readonly showFlat: () => void;
65 readonly resetView: () => void;
66 readonly foldingControls?: ReactNode;
67 readonly keyboard: { readonly attached: boolean; readonly toggle: () => void } | null;
69​
70export interface DeviceStreamHandle {
71 readonly pressButton: (button: DeviceHardwareButton) => void;
72 readonly rotate: () => void;
73 readonly inputConnected: boolean;
75​
76export function DeviceStreamView(props: {
77 readonly environmentId: EnvironmentId;
78 readonly platform: DevicePlatform;
79 readonly deviceId: string;
80 readonly deviceName?: string;
81 readonly deviceDescription?: string;
82 readonly visible: boolean;
83 readonly hostId: string;
84 readonly allowPhoneView?: boolean;
85 readonly renderControls?: (view: DeviceViewControls) => ReactNode;
86 readonly axOverlay?: boolean;
87 readonly onHandle?: (handle: DeviceStreamHandle | null) => void;
88 readonly onScreen?: (screen: DeviceScreenSize | null) => void;
89}) {
90 const [duoControl, setDuoControl] = useState<DuoControlState>({
91 pending: false,
92 requested: null,
93 error: null,
94 });
95 const model = deviceModel(props.platform, props.deviceName ?? "");
96 const isDuo = model?.id === "iphone-duo";
97 const [presentation, setPresentation] = useState<"phone" | "flat">("phone");
98 const [keyboardAttached, setKeyboardAttached] = useState(false);
99 const [phoneUnavailable, setPhoneUnavailable] = useState(false);
100 const onPhoneUnavailable = useStableCallback(() => setPhoneUnavailable(true));
101 const cancelPhoneInputRef = useRef<(() => void) | null>(null);
102 const cancelPhoneInput = useStableCallback(() => cancelPhoneInputRef.current?.());
103 const resetViewRef = useRef<(() => void) | null>(null);
104 const onResetReady = useStableCallback((reset: (() => void) | null) => {
105 resetViewRef.current = reset;
106 });
107 const frameListenerRef = useRef<(() => void) | null>(null);
108 const onFrameListener = useStableCallback((listener: (() => void) | null) => {
109 frameListenerRef.current = listener;
110 });
111 const onInputCancel = useStableCallback((cancel: (() => void) | null) => {
112 cancelPhoneInputRef.current = cancel;
113 });
114 const access = useDeviceHubAccess(props.environmentId, props.hostId);
115 const canvasRef = useRef<HTMLCanvasElement | null>(null);
116 const clientRef = useRef<DeviceStreamClient | null>(null);
117 const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
118 const [hasFrame, setHasFrame] = useState(false);
119 const [detail, setDetail] = useState<string | undefined>(undefined);
120 const [showRestartNotice, setShowRestartNotice] = useState(false);
121 const [screen, setScreen] = useState<DeviceScreenSize | null>(null);
122 const [foldAngle, setFoldAngle] = useState<number | null>(null);
123 const [mjpegUrl, setMjpegUrl] = useState<string | null>(null);
124 const [mjpegGeneration, setMjpegGeneration] = useState(0);
125 const attachMjpegImage = useStableCallback((image: HTMLImageElement | null) => {
126 clientRef.current?.setMjpegImage(image);
127 });
128 const [inputState, setInputState] = useState<{ connected: boolean; detail?: string }>({
129 connected: false,
130 });
131 const { onHandle, onScreen } = props;
132​
133 useEffect(() => {
134 const canvas = canvasRef.current;
135 if (!access || !canvas || !props.visible) {
136 setStatus("connecting");
137 onHandle?.(null);
138 return;
139 }
140 const client = createDeviceStreamClient(
141 { platform: props.platform, deviceId: props.deviceId, access },
142 createCanvasFrameSink(canvas, () => frameListenerRef.current?.()),
143 {
144 onDuoControl: setDuoControl,
145 onDuoUnavailable: onPhoneUnavailable,
146 onStatus: (next, nextDetail) => {
147 setStatus(next);
148 if (next === "streaming") setHasFrame(true);
149 setDetail(nextDetail);
150 if (next !== "connecting") setShowRestartNotice(false);
151 },
152 onScreen: (next) => {
153 setScreen(next);
154 onScreen?.(next);
155 },
156 onUnauthorized: () => {
157 refreshDeviceHubAccess(props.environmentId);
158 },
159 onMjpegFallback: (url) => {
160 setMjpegUrl(url);
161 setMjpegGeneration((generation) => generation + 1);
162 },
163 onCanvasVideo: () => setMjpegUrl(null),
164 onInputConnected: (connected, detail) => {
165 setInputState({ connected, ...(detail ? { detail } : {}) });
166 if (!connected) setShowRestartNotice(false);
167 onHandle?.({
168 pressButton: client.pressButton,
169 rotate: client.rotate,
170 inputConnected: connected,
171 });
172 },
173 },
174 );
175 clientRef.current = client;
176 setPhoneUnavailable(false);
177 setHasFrame(false);
178 setMjpegUrl(null);
179 setInputState({ connected: false });
180 client.start();
181 onHandle?.({ pressButton: client.pressButton, rotate: client.rotate, inputConnected: false });
182 return () => {
183 cancelPhoneInput();
184 client.stop();
185 clientRef.current = null;
186 onHandle?.(null);
187 onScreen?.(null);
188 setScreen(null);
189 };
190 }, [
191 access,
192 cancelPhoneInput,
193 onHandle,
194 onPhoneUnavailable,
195 onScreen,
196 props.deviceId,
197 props.environmentId,
198 props.platform,
199 props.visible,
200 ]);
201​
202 const aspect = screenAspect(props.platform, screen);
203​
204 const retainingFrame =
205 status === "connecting" && hasFrame && inputState.connected && screen !== null;
206 const showPhone =
207 props.allowPhoneView &&
208 (status === "streaming" || retainingFrame) &&
209 props.visible &&
210 presentation === "phone" &&
211 !phoneUnavailable &&
212 !mjpegUrl &&
213 !props.axOverlay &&
214 (!isDuo || screen?.supportsHingeAngle === true);
215 useEffect(() => {
216 if (!retainingFrame || !showPhone) return;
217 const timeout = window.setTimeout(() => setShowRestartNotice(true), 2_000);
218 return () => window.clearTimeout(timeout);
219 }, [retainingFrame, showPhone]);
220 const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
221​
222 // Fit the frame in both dimensions; pinned CSS height plus a width clamp distorts aspect-ratio.
223 const hostRef = useRef<HTMLDivElement | null>(null);
224 const [host, setHost] = useState({ width: 0, height: 0 });
225 useEffect(() => {
226 const element = hostRef.current;
227 if (!element) return;
228 const update = () => {
229 const rect = element.getBoundingClientRect();
230 setHost((current) =>
231 current.width === rect.width && current.height === rect.height
232 ? current
233 : { width: rect.width, height: rect.height },
234 );
235 };
236 update();
237 return observeResize(element, update);
238 }, []);
239 const frame = fitDeviceFrame(aspect, host.width, host.height, controlsInset);
240​
241 const rotation = screenRotation(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 = () => {
303 if (!isDuo) {
304 const orientation = keyboardAttached ? "landscape_right" : "portrait";
305 if (screen?.orientation !== orientation) clientRef.current?.setOrientation(orientation);
306 }
307 resetViewRef.current?.();
308 };
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 renewAccess={() => renewDeviceHubAccess(props.environmentId, props.hostId)}
341 />
342 ) : showPhone && isDuo && screen?.supportsHingeAngle ? (
343 <DeviceDuoControls
344 screen={screen}
345 state={duoControl}
346 enabled={inputState.connected}
347 onCommand={(command) => {
348 cancelPhoneInput();
349 clientRef.current?.controlDuo(command);
350 }}
351 />
352 ) : null,
353 keyboard:
354 showPhone && keyboardSource
355 ? {
356 attached: keyboardAttached,
357 toggle: () => {
358 cancelPhoneInput();
359 if (!keyboardAttached && screen?.orientation !== "landscape_right")
360 clientRef.current?.setOrientation("landscape_right");
361 setKeyboardAttached(!keyboardAttached);
362 },
363 }
364 : null,
365 showPhone: () => setPresentation("phone"),
366 showFlat: () => setPresentation("flat"),
367 }}
368 onResetView={resetView}
369 />
370 ) : null}
371 <div
372 ref={hostRef}
373 className={cn(
374 "relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
375 // Overlay the stream; focus (including pointer-driven focus) marks keyboard capture.
376 "after:pointer-events-none after:absolute after:inset-0 after:z-10 focus:after:ring-2 focus:after:ring-inset focus:after:ring-ring",
377 controlsInset && "pr-14",
378 )}
379 tabIndex={0}
380 role="application"
381 aria-label={`${props.platform === "ios" ? "iOS Simulator" : "Android Emulator"} screen`}
382 onKeyDown={(event) => {
383 if (event.target !== event.currentTarget) return;
384 if (event.metaKey && !["r", "R"].includes(event.key)) return;
385 // Let browser paste chords fire the paste event.
386 if (
387 (event.ctrlKey && (event.key === "v" || event.key === "V")) ||
388 (event.shiftKey && event.key === "Insert")
389 ) {
390 return;
391 }
392 event.preventDefault();
393 clientRef.current?.sendKey(event.nativeEvent, "down");
394 }}
395 onPaste={(event) => {
396 if (event.target !== event.currentTarget) return;
397 event.preventDefault();
398 clientRef.current?.sendText(event.clipboardData.getData("text/plain"));
399 }}
400 onKeyUp={(event) => {
401 if (event.target !== event.currentTarget) return;
402 clientRef.current?.sendKey(event.nativeEvent, "up");
403 }}
404 >
405 <div
406 className={cn("relative select-none", showPhone && "invisible pointer-events-none")}
407 style={{ width: frame.width, height: frame.height }}
408 onPointerDown={(event) => {
409 if (event.button !== 0) return;
410 event.currentTarget.setPointerCapture(event.pointerId);
411 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
412 pointerActive.current = true;
413 const { x, y } = normalizedPoint(event);
414 clientRef.current?.sendTouch("begin", x, y);
415 }}
416 onPointerMove={(event) => {
417 if (!pointerActive.current) return;
418 const { x, y } = normalizedPoint(event);
419 clientRef.current?.sendTouch("move", x, y);
420 }}
421 onPointerUp={(event) => {
422 if (!pointerActive.current) return;
423 pointerActive.current = false;
424 const { x, y } = normalizedPoint(event);
425 clientRef.current?.sendTouch("end", x, y);
426 }}
427 onPointerCancel={(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 >
434 <canvas
435 ref={canvasRef}
436 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
437 style={mediaStyle}
438 />
439 {props.visible && access && mjpegUrl ? (
440 <img
441 key={mjpegGeneration}
442 ref={attachMjpegImage}
443 alt=""
444 draggable={false}
445 className="absolute top-0 left-0 object-contain"
446 style={mediaStyle}
447 />
448 ) : null}
449 {axElements.length > 0 ? (
450 <div className="pointer-events-none absolute inset-0" aria-hidden>
451 {axElements.map((element) => (
452 <div
453 key={element.id}
454 className="absolute border border-info/80 bg-info/10"
455 style={{
456 left: `${element.x * 100}%`,
457 top: `${element.y * 100}%`,
458 width: `${element.width * 100}%`,
459 height: `${element.height * 100}%`,
460 }}
461 >
462 {element.label ? (
463 <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">
464 {element.label}
465 </span>
466 ) : null}
467 </div>
468 ))}
469 </div>
470 ) : null}
471 </div>
472 {showPhone && isDuo && model ? (
473 <DeviceDuoViewport
474 onFrameListener={onFrameListener}
475 model={model}
476 controlError={duoControl.error}
477 hingePreview={
478 duoControl.requested?.control === "angle" ? duoControl.requested.value : null
479 }
480 source={canvasRef}
481 client={clientRef}
482 onInputCancel={onInputCancel}
483 onResetReady={onResetReady}
484 screen={screen}
485 onUnavailable={onPhoneUnavailable}
486 />
487 ) : showPhone ? (
488 <DevicePhoneViewport
489 profile={profile}
490 model={deviceModel(props.platform, props.deviceName ?? "")}
491 accessory={keyboardAttached ? keyboardSource : null}
492 source={canvasRef}
493 onFrameListener={onFrameListener}
494 client={clientRef}
495 onInputCancel={onInputCancel}
496 onResetReady={onResetReady}
497 screen={screen}
498 foldAngle={foldAngle}
499 onUnavailable={onPhoneUnavailable}
500 />
501 ) : null}
502 {props.allowPhoneView && !props.renderControls && status === "streaming" ? (
503 <div className="absolute top-3 left-3 flex gap-1 rounded-lg border border-border/50 bg-background/90 p-1 shadow-sm">
504 <Button
505 variant={showPhone ? "secondary" : "ghost"}
506 size="xs"
507 aria-pressed={!!showPhone}
508 disabled={!!phoneUnavailableReason}
509 title={phoneUnavailableReason ?? "Show 3D phone"}
510 onClick={() => setPresentation("phone")}
511 >
512 3D
513 </Button>
514 <Button
515 variant={!showPhone ? "secondary" : "ghost"}
516 size="xs"
517 aria-pressed={!showPhone}
518 onClick={() => setPresentation("flat")}
519 >
520 Flat
521 </Button>
522 </div>
523 ) : null}
524 {status === "streaming" && !inputState.connected ? (
525 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
526 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
527 Input disconnected{inputState.detail ? ` (${inputState.detail})` : ""}, reconnecting…
528 </span>
529 </div>
530 ) : null}
531 {retainingFrame && showPhone && showRestartNotice ? (
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 Waiting for device video…
535 </span>
536 </div>
537 ) : null}
538 {status !== "streaming" && !(retainingFrame && showPhone) ? (
539 <div className="absolute inset-0">
540 <DeviceLoadingView
541 name={props.deviceName ?? "Device"}
542 description={props.deviceDescription ?? ""}
543 stage="stream"
544 message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
545 error={status === "error"}
546 >
547 {status === "error" ? (
548 <Button
549 size="sm"
550 variant="outline"
551 onClick={() => {
552 // Restart's unauthorized response renews expired tickets through the effect.
553 clientRef.current?.stop();
554 setPhoneUnavailable(false);
555 clientRef.current?.start();
556 }}
557 >
558 Reconnect
559 </Button>
560 ) : null}
561 </DeviceLoadingView>
562 </div>
563 ) : null}
564 </div>
565 </div>
566 );
568​
569function DeviceControlsSlot(props: {
570 renderControls: (view: DeviceViewControls) => ReactNode;
571 view: Omit<DeviceViewControls, "resetView">;
572 onResetView: () => void;
573}) {
574 return props.renderControls({ ...props.view, resetView: props.onResetView });