Open History to see the last commit
1import type { DevicePlatform, EnvironmentId } from "@t3tools/contracts";
2import { useAtomValue } from "@effect/atom-react";
3import { AsyncResult, Atom } from "effect/reactivity";
4import { T, useGT } from "gt-react";
5import { useEffect, useId, useRef, useState, type ReactNode } from "react";
6
7import { cn } from "~/lib/utils";
8import { Button } from "~/components/ui/button";
9import { renewDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
10import { resolveDeviceShape } from "@t3tools/client-runtime/device/shape-profile";
11import { deviceKeyboard, deviceModel } from "./deviceModels";
12import { fitDeviceFrame } from "./deviceFrameLayout";
13import { DeviceDuoViewport } from "./DeviceDuoViewport";
14import { DeviceDuoControls } from "./DeviceDuoControls";
15import { DeviceAndroidFoldControls } from "./DeviceAndroidFoldControls";
16import { DevicePhoneViewport } from "./DevicePhoneViewport";
17import { DeviceLoadingView } from "./DeviceLoadingView";
18import type { DeviceAxElement } from "./deviceHubApi";
19import { androidFoldViewAtom, deviceAxElementsAtom } from "./deviceHubAtoms";
20import {
21 deviceScreenKey,
22 deviceStreamSessionAtom,
23 type DeviceStreamSession,
24 IDLE_DEVICE_STREAM_STATE,
25} from "./deviceStreamSession";
26import type { DeviceHardwareButton, DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
27import { observeResize } from "~/lib/observeResize";
28
29const NO_SESSION_ATOM = Atom.make<DeviceStreamSession | null>(null).pipe(
30 Atom.withLabel("device-stream:none"),
31);
32const NO_AX_ELEMENTS: ReadonlyArray<DeviceAxElement> = [];
33const NO_AX_ATOM = Atom.make(AsyncResult.initial<ReadonlyArray<DeviceAxElement>, never>()).pipe(
34 Atom.withLabel("device-ax-elements:none"),
35);
36const CONTROLS_RAIL_WIDTH = 56;
37
38function screenAspect(platform: DevicePlatform, screen: DeviceScreenSize | null): number {
39 if (!screen) return platform === "ios" ? 9 / 19.5 : 9 / 20;
40 const landscape =
41 screen.orientation === "landscape_left" || screen.orientation === "landscape_right";
42 const w = landscape
43 ? Math.max(screen.width, screen.height)
44 : Math.min(screen.width, screen.height);
45 const h = landscape
46 ? Math.min(screen.width, screen.height)
47 : Math.max(screen.width, screen.height);
48 return w / h;
49}
50
51// serve-sim sends raw portrait framebuffers even when iOS reports landscape; rotate the display.
52function screenRotation(platform: DevicePlatform, screen: DeviceScreenSize | null): number {
53 if (platform !== "ios" || !screen || screen.width > screen.height) return 0;
54 switch (screen.orientation) {
55 case "landscape_left":
56 return 90;
57 case "landscape_right":
58 return -90;
59 case "portrait_upside_down":
60 return 180;
61 default:
62 return 0;
63 }
64}
65
66export interface DeviceViewControls {
67 readonly phone: boolean;
68 readonly streaming: boolean;
69 readonly phoneUnavailableReason: string | null;
70 readonly showPhone: () => void;
71 readonly showFlat: () => void;
72 readonly resetView: () => void;
73 readonly foldingControls?: ReactNode;
74 readonly keyboard: { readonly attached: boolean; readonly toggle: () => void } | null;
75 readonly handle: DeviceStreamHandle | null;
76}
77
78export interface DeviceStreamHandle {
79 readonly pressButton: (button: DeviceHardwareButton) => void;
80 readonly rotate: () => void;
81 readonly inputConnected: boolean;
82}
83
84export function DeviceStreamView(props: {
85 readonly environmentId: EnvironmentId;
86 readonly platform: DevicePlatform;
87 readonly deviceId: string;
88 readonly deviceName?: string;
89 readonly deviceDescription?: string;
90 readonly visible: boolean;
91 readonly hostId: string;
92 readonly allowPhoneView?: boolean;
93 readonly renderControls?: (view: DeviceViewControls) => ReactNode;
94 readonly axOverlay?: boolean;
95 /** Lets a parent read this view's own stream state, such as its screen size. */
96 readonly viewId?: string;
97 /** The host serves only serve-sim's stream and input socket (Simlock). */
98 readonly serveSimOnly?: boolean;
99}) {
100 const model = deviceModel(props.platform, props.deviceName ?? "");
101 const isDuo = model?.id === "iphone-duo";
102 const gt = useGT();
103 // The Duo's fold and stand controls exist only in 3D view, so it still opens there.
104 const [presentation, setPresentation] = useState<"phone" | "flat">(isDuo ? "phone" : "flat");
105 const [keyboardAttached, setKeyboardAttached] = useState(false);
106 const cancelPhoneInputRef = useRef<(() => void) | null>(null);
107 const cancelPhoneInput = () => cancelPhoneInputRef.current?.();
108 const resetViewRef = useRef<(() => void) | null>(null);
109 const onResetReady = (reset: (() => void) | null) => {
110 resetViewRef.current = reset;
111 };
112 const onInputCancel = (cancel: (() => void) | null) => {
113 cancelPhoneInputRef.current = cancel;
114 };
115 const access = useDeviceHubAccess(props.environmentId, props.hostId);
116 const ownViewId = useId();
117 const viewId = props.viewId ?? ownViewId;
118 const session = useAtomValue(
119 access && props.visible
120 ? deviceStreamSessionAtom({
121 environmentId: props.environmentId,
122 hostId: props.hostId,
123 platform: props.platform,
124 deviceId: props.deviceId,
125 access,
126 serveSimOnly: props.serveSimOnly === true,
127 viewId,
128 })
129 : NO_SESSION_ATOM,
130 );
131 const client = session?.stream ?? null;
132 const canvas = session?.canvas ?? null;
133 const { status, detail, hasFrame, screen, mjpegUrl, mjpegGeneration, duoControl } =
134 session?.state ?? IDLE_DEVICE_STREAM_STATE;
135 const inputState = session?.state.input ?? IDLE_DEVICE_STREAM_STATE.input;
136 const phoneUnavailable = session?.state.phoneUnavailable ?? false;
137 const foldAngle = useAtomValue(
138 androidFoldViewAtom(deviceScreenKey(props.environmentId, props.hostId, props.deviceId)),
139 ).angle;
140 const attachMjpegImage = (image: HTMLImageElement | null) => {
141 if (!client || !image) return;
142 client.setMjpegImage(image);
143 return () => client.setMjpegImage(null);
144 };
145 const mountCanvas = (node: HTMLDivElement | null) => {
146 if (!node || !canvas) return;
147 node.append(canvas);
148 return () => canvas.remove();
149 };
150
151 const aspect = screenAspect(props.platform, screen);
152
153 const retainingFrame =
154 status === "connecting" && hasFrame && inputState.connected && screen !== null;
155 // MJPEG draws into an <img> that goes blank while it reconnects, so only a canvas is kept.
156 const retainingCanvasFrame = retainingFrame && !mjpegUrl;
157 const showPhone =
158 props.allowPhoneView &&
159 (status === "streaming" || retainingFrame) &&
160 props.visible &&
161 presentation === "phone" &&
162 !phoneUnavailable &&
163 !mjpegUrl &&
164 !props.axOverlay &&
165 (!isDuo || screen?.supportsHingeAngle === true);
166 const controlsInset = props.renderControls && !showPhone ? CONTROLS_RAIL_WIDTH : 0;
167
168 // Fit the frame in both dimensions; pinned CSS height plus a width clamp distorts aspect-ratio.
169 const [host, setHost] = useState({ width: 0, height: 0 });
170 const hostRef = (element: HTMLDivElement | null) => {
171 if (!element) return;
172 const update = () => {
173 const rect = element.getBoundingClientRect();
174 setHost((current) =>
175 current.width === rect.width && current.height === rect.height
176 ? current
177 : { width: rect.width, height: rect.height },
178 );
179 };
180 update();
181 return observeResize(element, update);
182 };
183 const frame = fitDeviceFrame(aspect, host.width, host.height, controlsInset);
184
185 const rotation = screenRotation(props.platform, screen);
186
187 const sideways = rotation === 90 || rotation === -90;
188 const mediaStyle: React.CSSProperties = sideways
189 ? {
190 width: frame.height,
191 height: frame.width,
192 left: (frame.width - frame.height) / 2,
193 top: (frame.height - frame.width) / 2,
194 transform: `rotate(${rotation}deg)`,
195 }
196 : {
197 width: frame.width,
198 height: frame.height,
199 ...(rotation ? { transform: `rotate(${rotation}deg)` } : {}),
200 };
201
202 const axResult = useAtomValue(
203 props.axOverlay && access && props.visible
204 ? deviceAxElementsAtom({ access, platform: props.platform, deviceId: props.deviceId })
205 : NO_AX_ATOM,
206 );
207 const axElements = AsyncResult.getOrElse(axResult, () => NO_AX_ELEMENTS);
208
209 const activePointer = useRef<{ id: number; x: number; y: number } | null>(null);
210 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears pointer ownership when its device input connection disconnects or is replaced
211 useEffect(() => {
212 if (!client || !inputState.connected) return;
213 return () => {
214 activePointer.current = null;
215 };
216 }, [client, inputState.connected]);
217 const normalizedPoint = (event: React.PointerEvent<HTMLElement>) => {
218 const rect = event.currentTarget.getBoundingClientRect();
219 const x = (event.clientX - rect.left) / rect.width;
220 const y = (event.clientY - rect.top) / rect.height;
221 return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) };
222 };
223
224 const endPointer = (event: React.PointerEvent<HTMLElement>) => {
225 const pointer = activePointer.current;
226 if (pointer?.id !== event.pointerId) return;
227 activePointer.current = null;
228 const { x, y } = event.type === "lostpointercapture" ? pointer : normalizedPoint(event);
229 client?.sendTouch("end", x, y);
230 };
231
232 const phoneUnavailableReason =
233 isDuo && !screen?.supportsHingeAngle
234 ? gt`iPhone Duo 3D requires Device Hub ${{ version: "0.11.0" }} or newer`
235 : phoneUnavailable
236 ? gt`3D is unavailable on this browser`
237 : mjpegUrl
238 ? gt`3D requires the H.264 stream`
239 : props.axOverlay
240 ? gt`Turn off accessibility frames to use 3D`
241 : null;
242
243 const keyboardSource = deviceKeyboard(props.platform, props.deviceName ?? "");
244 const resetView = () => {
245 if (!isDuo) {
246 const orientation = keyboardAttached ? "landscape_right" : "portrait";
247 if (screen?.orientation !== orientation) client?.setOrientation(orientation);
248 }
249 resetViewRef.current?.();
250 };
251 const profile = resolveDeviceShape({
252 platform: props.platform,
253 name: props.deviceName ?? "",
254 portraitAspect: Math.min(aspect, 1 / aspect),
255 });
256
257 return (
258 <div
259 className={cn(
260 "relative flex size-full min-h-0 min-w-0",
261 props.allowPhoneView ? "bg-background" : "bg-black/90",
262 )}
263 >
264 {props.renderControls ? (
265 <DeviceControlsSlot
266 renderControls={props.renderControls}
267 view={{
268 phone: !!showPhone,
269 streaming: status === "streaming",
270 phoneUnavailableReason,
271 foldingControls:
272 props.platform === "android" && access ? (
273 <DeviceAndroidFoldControls
274 key={`${props.hostId}:${props.deviceId}`}
275 access={access}
276 deviceId={props.deviceId}
277 visible={props.visible}
278 enabled={status === "streaming"}
279 screenWidth={screen?.width}
280 screenHeight={screen?.height}
281 deviceKey={deviceScreenKey(props.environmentId, props.hostId, props.deviceId)}
282 renewAccess={() => renewDeviceHubAccess(props.environmentId, props.hostId)}
283 />
284 ) : showPhone && isDuo && screen?.supportsHingeAngle ? (
285 <DeviceDuoControls
286 screen={screen}
287 state={duoControl}
288 enabled={inputState.connected}
289 onCommand={(command) => {
290 cancelPhoneInput();
291 client?.controlDuo(command);
292 }}
293 />
294 ) : null,
295 keyboard:
296 showPhone && keyboardSource
297 ? {
298 attached: keyboardAttached,
299 toggle: () => {
300 cancelPhoneInput();
301 if (!keyboardAttached && screen?.orientation !== "landscape_right")
302 client?.setOrientation("landscape_right");
303 setKeyboardAttached(!keyboardAttached);
304 },
305 }
306 : null,
307 showPhone: () => setPresentation("phone"),
308 showFlat: () => setPresentation("flat"),
309 handle: client
310 ? {
311 pressButton: client.pressButton,
312 rotate: client.rotate,
313 inputConnected: inputState.connected,
314 }
315 : null,
316 }}
317 onResetView={resetView}
318 />
319 ) : null}
320 <div
321 ref={hostRef}
322 className={cn(
323 "relative flex min-h-0 min-w-0 flex-1 items-center justify-center overflow-hidden outline-none",
324 // Overlay so the ring paints above the stream canvas.
325 "after:pointer-events-none after:absolute after:inset-0 after:z-10 focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring",
326 controlsInset && "pr-14",
327 )}
328 tabIndex={0}
329 role="application"
330 aria-label={
331 props.platform === "ios" ? gt`iOS Simulator screen` : gt`Android Emulator screen`
332 }
333 onKeyDown={(event) => {
334 if (event.target !== event.currentTarget) return;
335 if (event.metaKey && !["r", "R"].includes(event.key)) return;
336 // Let browser paste chords fire the paste event.
337 if (
338 (event.ctrlKey && (event.key === "v" || event.key === "V")) ||
339 (event.shiftKey && event.key === "Insert")
340 ) {
341 return;
342 }
343 event.preventDefault();
344 client?.sendKey(event.nativeEvent, "down");
345 }}
346 onPaste={(event) => {
347 if (event.target !== event.currentTarget) return;
348 event.preventDefault();
349 client?.sendText(event.clipboardData.getData("text/plain"));
350 }}
351 onKeyUp={(event) => {
352 if (event.target !== event.currentTarget) return;
353 client?.sendKey(event.nativeEvent, "up");
354 }}
355 >
356 <div
357 className={cn("relative select-none", showPhone && "invisible pointer-events-none")}
358 style={{ width: frame.width, height: frame.height }}
359 onPointerDown={(event) => {
360 if (event.button !== 0 || !inputState.connected || activePointer.current !== null)
361 return;
362 event.currentTarget.setPointerCapture(event.pointerId);
363 (event.currentTarget.parentElement as HTMLElement | null)?.focus();
364 const { x, y } = normalizedPoint(event);
365 activePointer.current = { id: event.pointerId, x, y };
366 client?.sendTouch("begin", x, y);
367 }}
368 onPointerMove={(event) => {
369 if (activePointer.current?.id !== event.pointerId) return;
370 const { x, y } = normalizedPoint(event);
371 activePointer.current = { id: event.pointerId, x, y };
372 client?.sendTouch("move", x, y);
373 }}
374 onPointerUp={endPointer}
375 onPointerCancel={endPointer}
376 onLostPointerCapture={endPointer}
377 >
378 <div
379 ref={mountCanvas}
380 className={cn("absolute top-0 left-0", mjpegUrl && "hidden")}
381 style={mediaStyle}
382 />
383 {props.visible && access && mjpegUrl ? (
384 <img
385 key={mjpegGeneration}
386 ref={attachMjpegImage}
387 alt=""
388 draggable={false}
389 className="absolute top-0 left-0 object-contain"
390 style={mediaStyle}
391 />
392 ) : null}
393 {axElements.length > 0 ? (
394 <div className="pointer-events-none absolute inset-0" aria-hidden>
395 {axElements.map((element) => (
396 <div
397 key={element.id}
398 className="absolute border border-info/80 bg-info/10"
399 style={{
400 left: `${element.x * 100}%`,
401 top: `${element.y * 100}%`,
402 width: `${element.width * 100}%`,
403 height: `${element.height * 100}%`,
404 }}
405 >
406 {element.label ? (
407 <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">
408 {element.label}
409 </span>
410 ) : null}
411 </div>
412 ))}
413 </div>
414 ) : null}
415 </div>
416 {session && showPhone && isDuo && model ? (
417 <DeviceDuoViewport
418 onFrameListener={session.setFrameListener}
419 onControlRejectedListener={session.setControlRejectedListener}
420 model={model}
421 hingePreview={
422 duoControl.requested?.control === "angle" ? duoControl.requested.value : null
423 }
424 source={session.canvas}
425 client={session.stream}
426 onInputCancel={onInputCancel}
427 onResetReady={onResetReady}
428 screen={screen}
429 onUnavailable={session.markPhoneUnavailable}
430 />
431 ) : session && showPhone ? (
432 <DevicePhoneViewport
433 profile={profile}
434 model={deviceModel(props.platform, props.deviceName ?? "")}
435 accessory={keyboardAttached ? keyboardSource : null}
436 source={session.canvas}
437 onFrameListener={session.setFrameListener}
438 client={session.stream}
439 onInputCancel={onInputCancel}
440 onResetReady={onResetReady}
441 screen={screen}
442 foldAngle={foldAngle}
443 onUnavailable={session.markPhoneUnavailable}
444 />
445 ) : null}
446 {props.allowPhoneView && !props.renderControls && status === "streaming" ? (
447 <div className="absolute top-3 left-3 flex gap-1 rounded-lg border border-border/50 bg-background/90 p-1 shadow-sm">
448 <Button
449 variant={showPhone ? "secondary" : "ghost"}
450 size="xs"
451 aria-pressed={!!showPhone}
452 disabled={!!phoneUnavailableReason}
453 title={phoneUnavailableReason ?? gt`Show 3D phone`}
454 onClick={() => setPresentation("phone")}
455 >
456 3D
457 </Button>
458 <Button
459 variant={!showPhone ? "secondary" : "ghost"}
460 size="xs"
461 aria-pressed={!showPhone}
462 onClick={() => setPresentation("flat")}
463 >
464 <T context="flat device view">Flat</T>
465 </Button>
466 </div>
467 ) : null}
468 {status === "streaming" && !inputState.connected ? (
469 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2">
470 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
471 {inputState.detail
472 ? gt`Input disconnected (${{ detail: inputState.detail }}), reconnecting…`
473 : gt`Input disconnected, reconnecting…`}
474 </span>
475 </div>
476 ) : null}
477 {retainingCanvasFrame ? (
478 // Shown only once the device has been silent for two seconds.
479 <div className="pointer-events-none absolute inset-x-0 bottom-0 flex justify-center p-2 transition-opacity delay-2000 duration-0 starting:opacity-0">
480 <span className="rounded-md bg-background/85 px-2 py-1 text-xs text-muted-foreground">
481 <T>Waiting for device video…</T>
482 </span>
483 </div>
484 ) : null}
485 {status !== "streaming" && !retainingCanvasFrame ? (
486 <div className="absolute inset-0">
487 <DeviceLoadingView
488 name={props.deviceName ?? gt`Device`}
489 description={props.deviceDescription ?? ""}
490 stage="stream"
491 message={status === "error" ? (detail ?? gt`Stream failed.`) : gt`Connecting video…`}
492 error={status === "error"}
493 >
494 {status === "error" ? (
495 <Button
496 size="sm"
497 variant="outline"
498 onClick={() => {
499 // An expired ticket surfaces as unauthorized on restart and
500 // refreshes access, which starts a new session.
501 session?.reconnect();
502 }}
503 >
504 <T>Reconnect</T>
505 </Button>
506 ) : null}
507 </DeviceLoadingView>
508 </div>
509 ) : null}
510 </div>
511 </div>
512 );
513}
514
515function DeviceControlsSlot(props: {
516 renderControls: (view: DeviceViewControls) => ReactNode;
517 view: Omit<DeviceViewControls, "resetView">;
518 onResetView: () => void;
519}) {
520 return props.renderControls({ ...props.view, resetView: props.onResetView });
521}