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

DevicePanel.tsx

425 lines15.9 KB

1import type {
2 DevicePlatform,
3 DeviceServiceState,
4 DeviceSummary,
5 ScopedThreadRef,
6} from "@t3tools/contracts";
7import {
8 ChevronLeft,
9 Home,
10 Power,
11 RotateCcw,
12 SlidersHorizontal,
13 Smartphone,
14 Square,
15 X,
16} from "lucide-react";
17import { useEffect, useMemo, useState } from "react";
18​
19import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
20import { Button } from "~/components/ui/button";
21import { DiscoveryList, DiscoveryListRow } from "~/components/ui/discovery-list";
22import { Dialog } from "~/components/ui/dialog";
23import { WizardPopup } from "~/components/ui/wizard";
24import { Spinner } from "~/components/ui/spinner";
25import { Toggle } from "~/components/ui/toggle";
26import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
27import { cn } from "~/lib/utils";
28import { deviceEnvironment, useDeviceHubAccess, useDeviceState } from "~/state/device";
29import { formatEnvironmentQueryError } from "~/state/query";
30import { useAtomCommand } from "~/state/use-atom-command";
31import { DeviceStreamView, type DeviceStreamHandle } from "./DeviceStreamView";
32import { DeviceLoadingView } from "./DeviceLoadingView";
33import { DeviceSetup } from "./DeviceSetup";
34import { DeviceToolsPanel } from "./DeviceToolsPanel";
35import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
36​
37const platformLabel = (platform: DevicePlatform) =>
38 platform === "ios" ? "iOS Simulators" : "Android Emulators";
39​
40const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
41 `${device.hostId}\u0000${device.id}`;
42​
43/** Each surface owns one host/device; only the visible surface streams. */
44export function DevicePanel(props: {
45 readonly mode: PreviewPanelMode;
46 readonly threadRef: ScopedThreadRef;
47 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
48 readonly visible: boolean;
49 readonly onDismissSetup: () => void;
50}) {
51 const { environmentId, threadId } = props.threadRef;
52 const { state, loaded } = useDeviceState(environmentId);
53 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
54 const open = useAtomCommand(deviceEnvironment.open);
55 const close = useAtomCommand(deviceEnvironment.close);
56 const [operationError, setOperationError] = useState<string | null>(null);
57 const [pendingDevice, setPendingDevice] = useState<DeviceSummary | null>(null);
58 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
59 const [handle, setHandle] = useState<DeviceStreamHandle | null>(null);
60 const [toolsOpen, setToolsOpen] = useState(false);
61 const [axOverlay, setAxOverlay] = useState(false);
62 const access = useDeviceHubAccess(environmentId);
63​
64 const hostDisabled = state.hostStatus === "disabled";
65​
66 // Opening setup never grants permission to install or start helpers.
67 useEffect(() => {
68 if (!props.visible || !loaded || hostDisabled) return;
69 void list({ environmentId, input: {} });
70 }, [environmentId, list, loaded, props.visible, hostDisabled]);
71​
72 const sessions = useMemo(
73 () => state.sessions.filter((session) => session.threadId === threadId),
74 [state.sessions, threadId],
75 );
76 const activeSession = props.surface.target
77 ? sessions.find(
78 (session) =>
79 session.deviceId === props.surface.target?.deviceId &&
80 session.hostId === props.surface.target.hostId,
81 )
82 : undefined;
83 const activeDevice = activeSession
84 ? state.devices.find(
85 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
86 )
87 : undefined;
88​
89 const grouped = useMemo(() => groupDevices(state), [state]);
90​
91 const selectDevice = async (value: string) => {
92 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
93 if (!device) return;
94 setOperationError(null);
95 setPendingDevice(device);
96 try {
97 const result = await open({
98 environmentId,
99 input: {
100 threadId,
101 hostId: device.hostId,
102 deviceId: device.id,
103 platform: device.platform,
104 },
105 });
106 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
107 else
108 useRightPanelStore.getState().openDevice(props.threadRef, {
109 hostId: result.value.hostId,
110 deviceId: result.value.deviceId,
111 platform: device.platform,
112 name: device.name,
113 });
114 } finally {
115 setPendingDevice(null);
116 }
117 };
118​
119 const closeActive = (powerOff: boolean) => {
120 if (!powerOff) {
121 useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
122 return;
123 }
124 if (!activeSession) return;
125 setOperationError(null);
126 void close({
127 environmentId,
128 input: {
129 threadId,
130 hostId: activeSession.hostId,
131 deviceId: activeSession.deviceId,
132 shutdown: powerOff,
133 },
134 }).then((result) => {
135 if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
136 else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
137 });
138 };
139​
140 const bootingDevices =
141 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
142 const hostReady = Object.values(state.hostStatuses).some((host) => host.status === "ready");
143 const hostBusy =
144 !hostReady &&
145 Object.values(state.hostStatuses).some(
146 (host) => host.status === "installing" || host.status === "starting",
147 );
148 const unavailablePlatforms = state.hosts.flatMap((host) =>
149 host.platforms
150 .filter((platform) => !platform.available)
151 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
152 );
153​
154 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
155 return (
156 <Dialog
157 open={props.visible}
158 onOpenChange={(isOpen) => {
159 if (!isOpen) props.onDismissSetup();
160 }}
161 >
162 <WizardPopup>
163 <DeviceSetup environmentId={environmentId} state={state} />
164 </WizardPopup>
165 </Dialog>
166 );
167 }
168​
169 return (
170 <PreviewPanelShell mode={props.mode}>
171 <div className="flex h-9 shrink-0 items-center gap-1.5 border-b px-2">
172 <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
173 {props.surface.target
174 ? `${state.hosts.find((host) => host.id === props.surface.target?.hostId)?.label ?? "Device host"} · ${activeDevice?.version ?? props.surface.target.platform}`
175 : (pendingDevice?.name ?? "Choose a device")}
176 </span>
177 {activeDevice ? (
178 <>
179 <DeviceButton
180 label="Home"
181 onClick={() => handle?.pressButton("home")}
182 disabled={!handle?.inputConnected}
183 >
184 <Home />
185 </DeviceButton>
186 {activeDevice.platform === "android" ? (
187 <>
188 <DeviceButton
189 label="Back"
190 onClick={() => handle?.pressButton("back")}
191 disabled={!handle?.inputConnected}
192 >
193 <ChevronLeft />
194 </DeviceButton>
195 <DeviceButton
196 label="Recents"
197 onClick={() => handle?.pressButton("recents")}
198 disabled={!handle?.inputConnected}
199 >
200 <Square />
201 </DeviceButton>
202 </>
203 ) : (
204 <DeviceButton
205 label="Rotate"
206 onClick={() => handle?.rotate()}
207 disabled={!handle?.inputConnected}
208 >
209 <RotateCcw />
210 </DeviceButton>
211 )}
212 <Toggle
213 aria-label="Tools"
214 variant="ghost"
215 size="xs"
216 pressed={toolsOpen}
217 onPressedChange={(pressed) => setToolsOpen(Boolean(pressed))}
218 >
219 <SlidersHorizontal />
220 </Toggle>
221 <DeviceButton label="Power off" onClick={() => closeActive(true)}>
222 <Power />
223 </DeviceButton>
224 <DeviceButton label="Close" onClick={() => closeActive(false)}>
225 <X />
226 </DeviceButton>
227 </>
228 ) : null}
229 </div>
230 {hostReady && state.hostStatusDetail ? (
231 <div
232 role="status"
233 className="whitespace-pre-line border-b px-3 py-2 text-xs text-muted-foreground"
234 >
235 {state.hostStatusDetail}
236 </div>
237 ) : null}
238 {bootingDevices.length > 0 ? (
239 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
240 Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a minute.
241 </div>
242 ) : null}
243 {operationError ? (
244 <div
245 role="alert"
246 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
247 >
248 <p className="min-w-0 flex-1 whitespace-pre-wrap break-words">{operationError}</p>
249 <Button
250 size="icon-xs"
251 variant="ghost"
252 aria-label="Dismiss device error"
253 onClick={() => setOperationError(null)}
254 >
255 <X className="size-3" />
256 </Button>
257 </div>
258 ) : null}
259 <div className="@container relative flex min-h-0 flex-1">
260 {activeDevice && activeSession ? (
261 <>
262 <div className="relative min-h-0 min-w-0 flex-1">
263 <DeviceStreamView
264 key={deviceKey(activeDevice)}
265 environmentId={environmentId}
266 platform={activeDevice.platform}
267 deviceName={activeDevice.name}
268 deviceDescription={`${state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"} · ${activeDevice.version}`}
269 deviceId={activeDevice.id}
270 hostId={activeDevice.hostId}
271 visible={props.visible}
272 axOverlay={axOverlay}
273 onHandle={setHandle}
274 />
275 </div>
276 {toolsOpen ? (
277 <DeviceToolsPanel
278 key={deviceKey(activeDevice)}
279 environmentId={environmentId}
280 device={activeDevice}
281 access={access}
282 axOverlay={axOverlay}
283 onAxOverlayChange={setAxOverlay}
284 onClose={() => setToolsOpen(false)}
285 className="absolute inset-y-0 right-0 z-10 w-full max-w-72 border-l shadow-lg @[560px]:static @[560px]:w-72 @[560px]:shrink-0 @[560px]:shadow-none"
286 />
287 ) : null}
288 </>
289 ) : pendingDevice || hostBusy || !loaded ? (
290 <DeviceLoadingView
291 name={pendingDevice?.name ?? "Devices"}
292 description={
293 pendingDevice
294 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
295 : ""
296 }
297 stage="opening"
298 message={
299 pendingDevice
300 ? pendingDevice.booted
301 ? "Opening device…"
302 : "Starting device…"
303 : state.hostStatus === "installing"
304 ? "Installing device support…"
305 : "Finding devices…"
306 }
307 />
308 ) : (
309 <div className="flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
310 <div
311 className={cn(
312 "mx-auto flex w-full max-w-xl flex-col gap-6",
313 grouped.length === 0 && "my-auto items-center text-center",
314 )}
315 >
316 {grouped.length === 0 ? (
317 <>
318 <Smartphone className="size-6 opacity-60" />
319 <p className="max-w-sm">
320 {state.hostStatus === "failed"
321 ? (state.hostStatusDetail ?? "The device hub failed to start.")
322 : "No simulators or emulators were found on this environment."}
323 </p>
324 </>
325 ) : null}
326 {hostReady && grouped.length > 0 ? (
327 <div className="w-full space-y-6 text-left">
328 {grouped.map((group) => (
329 <section key={group.platform} className="space-y-3">
330 <div className="flex items-center gap-2 text-sm text-muted-foreground">
331 <Smartphone className="size-4 shrink-0" />
332 <h3 className="font-medium">{platformLabel(group.platform)}</h3>
333 </div>
334 <DiscoveryList>
335 {group.devices.map((device) => (
336 <DiscoveryListRow
337 key={deviceKey(device)}
338 icon={
339 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
340 <Smartphone className="size-4" />
341 </span>
342 }
343 title={device.name}
344 description={`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
345 disabled={pendingDeviceKey !== null}
346 aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
347 onClick={() => void selectDevice(deviceKey(device))}
348 action={
349 pendingDeviceKey === deviceKey(device) ? (
350 <Spinner className="size-3" />
351 ) : (
352 <span className="text-xs text-muted-foreground">
353 {device.booted ? "Open" : "Start"}
354 </span>
355 )
356 }
357 />
358 ))}
359 </DiscoveryList>
360 </section>
361 ))}
362 </div>
363 ) : null}
364 {hostReady &&
365 !state.devices.some((device) => device.platform === "android") &&
366 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
367 <p className="max-w-sm text-xs">
368 No Android virtual devices found. Create one in Android Studio's Device Manager,
369 then refresh.
370 </p>
371 ) : null}
372 {loaded && !hostBusy ? (
373 <Button
374 className="self-start"
375 variant={grouped.length > 0 ? "ghost" : "outline"}
376 size="sm"
377 onClick={() => void list({ environmentId, input: {} })}
378 >
379 Refresh devices
380 </Button>
381 ) : null}
382 </div>
383 </div>
384 )}
385 </div>
386 </PreviewPanelShell>
387 );
389​
390function DeviceButton(props: {
391 readonly label: string;
392 readonly onClick: () => void;
393 readonly disabled?: boolean;
394 readonly children: React.ReactNode;
395}) {
396 return (
397 <Tooltip>
398 <TooltipTrigger
399 render={
400 <Button
401 size="icon-xs"
402 variant="ghost-muted"
403 aria-label={props.label}
404 onClick={props.onClick}
405 disabled={props.disabled ?? false}
406 />
407 }
408 >
409 {props.children}
410 </TooltipTrigger>
411 <TooltipPopup>{props.label}</TooltipPopup>
412 </Tooltip>
413 );
415​
416function groupDevices(state: DeviceServiceState) {
417 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
418 for (const platform of ["ios", "android"] as const) {
419 const devices = state.devices
420 .filter((device) => device.platform === platform)
421 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
422 if (devices.length > 0) groups.push({ platform, devices });
423 }
424 return groups;