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

DeviceStreamView.tsx

501 lines19.3 KB

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