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