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

DeviceStreamView.tsx

502 lines19.3 KB

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