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

DevicePanel.tsx

603 lines24.3 KB

1import { DeviceHostUpdates } from "./DeviceHostUpdates";
2import type {
3 DevicePlatform,
4 DeviceServiceState,
5 DeviceSummary,
6 ScopedThreadRef,
7} from "@t3tools/contracts";
8import { ArrowUpRight, CircleAlert, Play, Smartphone, Square, X } from "lucide-react";
9import { useAtomMount } from "@effect/atom-react";
10import { T, useGT, Var } from "gt-react";
11import { type ReactNode, useState } from "react";
12​
13import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
14import {
15 selectThreadRightPanelState,
16 useRightPanelStore,
17 type RightPanelSurface,
18} from "~/rightPanelStore";
19import { Button } from "~/components/ui/button";
20import { DiscoveryList } from "~/components/ui/discovery-list";
21import { Dialog } from "~/components/ui/dialog";
22import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
23import { WizardPopup } from "~/components/ui/wizard";
24import { Spinner } from "~/components/ui/spinner";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
26import { cn } from "~/lib/utils";
27import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
28import {
29 deviceEnvironment,
30 deviceHostProbeAtom,
31 NO_DEVICE_PROBE_ATOM,
32 useDeviceState,
33} from "~/state/device";
34import { formatEnvironmentQueryError } from "~/state/query";
35import { useAtomCommand } from "~/state/use-atom-command";
36import { DeviceLoadingView } from "./DeviceLoadingView";
37import {
38 DeviceSetup,
39 deviceHubReadiness,
40 incompleteListings,
41 isAndroidDiscoveryUncertain,
42} from "./DeviceSetup";
43import { DeviceWorkspace } from "./DeviceWorkspace";
44import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
45​
46const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
47 `${device.hostId}\u0000${device.id}`;
48​
49export function DevicePanel(props: {
50 readonly mode: PreviewPanelMode;
51 readonly threadRef: ScopedThreadRef;
52 readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
53 readonly visible: boolean;
54 readonly onDismissSetup: () => void;
55}) {
56 const { environmentId, threadId } = props.threadRef;
57 const gt = useGT();
58 const { state, loaded, error: stateError, refresh: refreshState } = useDeviceState(environmentId);
59 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
60 const open = useAtomCommand(deviceEnvironment.open);
61 const close = useAtomCommand(deviceEnvironment.close);
62 const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
63 // The panel stays mounted across thread switches, so an in-flight open or
64 // power-off is tagged with the thread it belongs to and only shown there.
65 const scope = `${environmentId}\u0000${threadId}`;
66 const [operation, setOperation] = useState<{
67 readonly scope: string;
68 readonly pending: DeviceSummary | null;
69 readonly error: string | null;
70 } | null>(null);
71 const pendingDevice = operation?.scope === scope ? operation.pending : null;
72 const operationError = operation?.scope === scope ? operation.error : null;
73 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
74 // Power-offs act on the environment, not the thread, so they outlive thread switches.
75 const [stopping, setStopping] = useState<ReadonlySet<string>>(() => new Set());
76 const [stopErrors, setStopErrors] = useState<Readonly<Record<string, string>>>({});
77 const stopError = stopErrors[environmentId];
78 const setStopError = (message: string | undefined) =>
79 setStopErrors((current) => {
80 const next = { ...current };
81 if (message === undefined) delete next[environmentId];
82 else next[environmentId] = message;
83 return next;
84 });
85 const stoppingKey = (device: DeviceSummary) => `${environmentId}\u0000${deviceKey(device)}`;
86 const isStopping = (device: DeviceSummary) => stopping.has(stoppingKey(device));
87​
88 const hostDisabled = state.hostStatus === "disabled";
89​
90 useAtomMount(
91 props.visible && loaded && !hostDisabled
92 ? deviceHostProbeAtom(environmentId)
93 : NO_DEVICE_PROBE_ATOM,
94 );
95​
96 const sessions = state.sessions.filter((session) => session.threadId === threadId);
97 const activeSession = props.surface.target
98 ? sessions.find(
99 (session) =>
100 session.deviceId === props.surface.target?.deviceId &&
101 session.hostId === props.surface.target.hostId,
102 )
103 : undefined;
104 const activeDevice = activeSession
105 ? state.devices.find(
106 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
107 )
108 : undefined;
109 const activeHost = activeDevice
110 ? state.hosts.find((host) => host.id === activeDevice.hostId)
111 : undefined;
112​
113 const grouped = groupDevices(state);
114 const stoppable = state.devices.filter((device) => device.booted && !device.physical);
115​
116 const startOperation = (pending: DeviceSummary | null) => {
117 const started = { scope, pending, error: null };
118 setOperation(started);
119 // Returning to the same thread can start a newer operation before this one settles.
120 return (error: string | null) =>
121 setOperation((current) =>
122 current === started ? { ...started, pending: null, error } : current,
123 );
124 };
125​
126 const selectDevice = async (value: string) => {
127 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
128 if (!device) return;
129 const settleOperation = startOperation(device);
130 const result = await open({
131 environmentId,
132 input: {
133 threadId,
134 hostId: device.hostId,
135 deviceId: device.id,
136 platform: device.platform,
137 },
138 });
139 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
140 else {
141 // The server opened the device for the starting thread, so its tab opens there.
142 useRightPanelStore.getState().openDevice(props.threadRef, {
143 hostId: result.value.hostId,
144 deviceId: result.value.deviceId,
145 platform: device.platform,
146 name: device.name,
147 });
148 settleOperation(null);
149 }
150 };
151​
152 const stopDevices = async (devices: readonly DeviceSummary[]) => {
153 setStopError(undefined);
154 setStopping((current) => new Set([...current, ...devices.map(stoppingKey)]));
155 const results = await Promise.all(
156 devices.map((device) =>
157 shutdown({
158 environmentId,
159 input: { hostId: device.hostId, deviceId: device.id, platform: device.platform },
160 }).finally(() =>
161 setStopping((current) => {
162 const next = new Set(current);
163 next.delete(stoppingKey(device));
164 return next;
165 }),
166 ),
167 ),
168 );
169 const failure = results.find((result) => result._tag === "Failure");
170 if (failure?._tag === "Failure") setStopError(formatEnvironmentQueryError(failure.cause));
171 };
172​
173 const floatActive = () => {
174 if (!activeDevice) return;
175 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
176 kind: "device",
177 hostId: activeDevice.hostId,
178 deviceId: activeDevice.id,
179 platform: activeDevice.platform,
180 name: activeDevice.name,
181 });
182 useRightPanelStore.getState().close(props.threadRef);
183 };
184​
185 const closeSurface = () => {
186 const store = useRightPanelStore.getState();
187 const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
188 store.closeSurface(props.threadRef, props.surface.id);
189 focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
190 };
191​
192 const closeActive = (powerOff: boolean) => {
193 if (!powerOff) {
194 closeSurface();
195 return;
196 }
197 if (!activeSession) return;
198 const settleOperation = startOperation(null);
199 void close({
200 environmentId,
201 input: {
202 threadId,
203 hostId: activeSession.hostId,
204 deviceId: activeSession.deviceId,
205 shutdown: powerOff,
206 },
207 }).then((result) => {
208 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
209 else closeSurface();
210 });
211 };
212​
213 const bootingDevices =
214 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
215 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
216 const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
217 // Without a first snapshot a failed subscription never settles on its own.
218 const loadError = loaded ? null : stateError;
219 const diagnostics = state.hosts.flatMap((host) => {
220 const status = state.hostStatuses[host.id];
221 const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
222 return detail && (status?.status ?? state.hostStatus) === "ready"
223 ? [
224 {
225 hostId: host.id,
226 label: host.label,
227 detail,
228 incompletePlatforms: incompleteListings(status),
229 },
230 ]
231 : [];
232 });
233 const unavailablePlatforms = state.hosts.flatMap((host) =>
234 host.platforms
235 .filter((platform) => !platform.available)
236 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
237 );
238​
239 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
240 return (
241 <Dialog
242 open={props.visible}
243 onOpenChange={(isOpen) => {
244 if (!isOpen) props.onDismissSetup();
245 }}
246 >
247 <WizardPopup>
248 <DeviceSetup environmentId={environmentId} state={state} />
249 </WizardPopup>
250 </Dialog>
251 );
252 }
253​
254 return (
255 <PreviewPanelShell mode={props.mode}>
256 <div className="relative flex min-h-0 flex-1 flex-col">
257 <div
258 className={cn(
259 "shrink-0 bg-background",
260 loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
261 )}
262 >
263 <div hidden={!!activeDevice}>
264 {diagnostics.map((diagnostic) => (
265 <DeviceDiscoveryWarning
266 key={`${environmentId}\u0000${diagnostic.hostId}`}
267 label={diagnostic.label}
268 detail={diagnostic.detail}
269 incompletePlatforms={diagnostic.incompletePlatforms}
270 onRetry={() => list({ environmentId, input: {} })}
271 />
272 ))}
273 </div>
274 <DeviceHostUpdates state={state} environmentId={environmentId} />
275 {bootingDevices.length > 0 ? (
276 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
277 <T>
278 Starting <Var>{bootingDevices.map((device) => device.name).join(", ")}</Var>… This
279 can take a minute.
280 </T>
281 </div>
282 ) : null}
283 {operationError ? (
284 <DeviceNotice onDismiss={() => setOperation(null)}>{operationError}</DeviceNotice>
285 ) : null}
286 {stopError !== undefined ? (
287 <DeviceNotice onDismiss={() => setStopError(undefined)}>{stopError}</DeviceNotice>
288 ) : null}
289 </div>
290 <div className="@container relative flex min-h-0 flex-1">
291 {activeDevice && activeSession ? (
292 <DeviceWorkspace
293 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
294 environmentId={environmentId}
295 device={activeDevice}
296 hostLabel={activeHost?.label ?? gt`Device host`}
297 hostKind={activeHost?.kind}
298 hostDiagnostics={
299 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
300 }
301 visible={props.visible}
302 onFloat={floatActive}
303 onClose={() => closeActive(false)}
304 onPowerOff={() => closeActive(true)}
305 />
306 ) : loading ? (
307 <DeviceLoadingView
308 name={pendingDevice?.name ?? gt`Devices`}
309 description={
310 pendingDevice
311 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? gt`Device host`} · ${pendingDevice.version}`
312 : ""
313 }
314 stage="opening"
315 message={
316 loadError ??
317 (pendingDevice
318 ? pendingDevice.booted
319 ? gt`Opening device…`
320 : gt`Starting device…`
321 : state.hostStatus === "installing"
322 ? (state.hostStatusDetail ?? gt`Installing device support…`)
323 : gt`Finding devices…`)
324 }
325 error={loadError !== null}
326 >
327 {loadError !== null ? (
328 <Button size="sm" variant="outline" onClick={refreshState}>
329 <T>Retry</T>
330 </Button>
331 ) : null}
332 </DeviceLoadingView>
333 ) : (
334 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
335 <div
336 className={cn(
337 "mx-auto flex w-full max-w-xl flex-col gap-6",
338 grouped.length === 0 && "my-auto items-center text-center",
339 )}
340 >
341 {grouped.length === 0 ? (
342 <>
343 <Smartphone className="size-6 opacity-60" />
344 <p
345 className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
346 tabIndex={state.hostStatus === "failed" ? 0 : undefined}
347 >
348 {state.hostStatus === "failed"
349 ? (state.hostStatusDetail ?? gt`The device hub failed to start.`)
350 : gt`No simulators or emulators were found on this environment.`}
351 </p>
352 </>
353 ) : null}
354 {hostReady && grouped.length > 0 ? (
355 <div className="w-full space-y-6 text-left">
356 {grouped.map((group) => (
357 <section key={group.platform} className="space-y-3">
358 <div className="flex items-center gap-2 text-sm text-muted-foreground">
359 <Smartphone className="size-4 shrink-0" />
360 <h3 className="font-medium">
361 {group.devices.some((device) => device.physical)
362 ? group.platform === "ios"
363 ? gt`iOS Devices`
364 : gt`Android Devices`
365 : group.platform === "ios"
366 ? gt`iOS Simulators`
367 : gt`Android Emulators`}
368 </h3>
369 </div>
370 <DiscoveryList>
371 {group.devices.map((device) => (
372 <div
373 key={deviceKey(device)}
374 className="flex items-center gap-3 px-3 py-3"
375 >
376 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
377 <Smartphone className="size-4" />
378 </span>
379 <div className="flex min-w-0 flex-1 flex-col">
380 <span className="truncate text-sm font-medium text-foreground">
381 {device.name}
382 </span>
383 <span className="flex min-w-0 gap-1 text-xs text-muted-foreground">
384 <span className="truncate">
385 {state.hosts.find((host) => host.id === device.hostId)?.label}
386 </span>
387 <span className="shrink-0">
388 {`· ${device.version} ${device.physical ? `· ${gt({ context: "physical device, not a simulator" })`Physical`} ` : ""}· ${device.booted ? gt({ context: "device state" })`Running` : gt({ context: "device state" })`Stopped`}`}
389 </span>
390 </span>
391 </div>
392 {device.booted && !device.physical ? (
393 <Tooltip>
394 <TooltipTrigger
395 render={
396 <Button
397 variant="outline"
398 size="icon-sm"
399 disabled={
400 isStopping(device) ||
401 pendingDeviceKey === deviceKey(device)
402 }
403 aria-label={gt`Stop ${{ name: device.name }}`}
404 onClick={() => void stopDevices([device])}
405 />
406 }
407 >
408 {isStopping(device) ? <Spinner size="xs" /> : <Square />}
409 </TooltipTrigger>
410 <TooltipPopup>
411 {gt({ context: "verb, powers off a running device" })`Stop`}
412 </TooltipPopup>
413 </Tooltip>
414 ) : null}
415 <Button
416 variant="outline"
417 size="sm"
418 disabled={pendingDeviceKey !== null || isStopping(device)}
419 aria-label={
420 device.booted
421 ? gt`Open ${{ name: device.name }}`
422 : gt`Start ${{ name: device.name }}`
423 }
424 onClick={() => void selectDevice(deviceKey(device))}
425 >
426 {pendingDeviceKey === deviceKey(device) ? (
427 <Spinner size="xs" />
428 ) : device.booted ? (
429 <ArrowUpRight />
430 ) : (
431 <Play />
432 )}
433 {device.booted
434 ? gt({ context: "verb, opens a running device" })`Open`
435 : gt({ context: "verb, boots a device" })`Start`}
436 </Button>
437 </div>
438 ))}
439 </DiscoveryList>
440 </section>
441 ))}
442 </div>
443 ) : null}
444 {hostReady &&
445 !isAndroidDiscoveryUncertain(state) &&
446 !state.devices.some((device) => device.platform === "android") &&
447 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
448 <p className="max-w-sm text-xs">
449 <T>
450 No Android virtual devices found. Create one in Android Studio's Device
451 Manager, then refresh.
452 </T>
453 </p>
454 ) : null}
455 {loaded && !hostBusy ? (
456 <div
457 className={cn(
458 "flex flex-wrap gap-2",
459 grouped.length > 0 ? "self-start" : "self-center",
460 )}
461 >
462 <Button
463 variant="outline"
464 size="sm"
465 onClick={() => void list({ environmentId, input: {} })}
466 >
467 <T>Refresh devices</T>
468 </Button>
469 {stoppable.length > 0 ? (
470 <Button
471 variant="outline"
472 size="sm"
473 disabled={stoppable.every(isStopping)}
474 onClick={() =>
475 void stopDevices(stoppable.filter((device) => !isStopping(device)))
476 }
477 >
478 <T>Stop all devices</T>
479 </Button>
480 ) : null}
481 </div>
482 ) : null}
483 </div>
484 </div>
485 )}
486 </div>
487 </div>
488 </PreviewPanelShell>
489 );
491​
492function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) {
493 const gt = useGT();
494 return (
495 <div
496 role="alert"
497 className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
498 >
499 <CircleAlert className="mt-1 size-3.5 shrink-0" />
500 <div
501 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
502 tabIndex={0}
503 >
504 {props.children}
505 </div>
506 <Button
507 size="icon-xs"
508 variant="ghost"
509 aria-label={gt`Dismiss device error`}
510 onClick={props.onDismiss}
511 >
512 <X />
513 </Button>
514 </div>
515 );
517​
518function DeviceDiscoveryWarning(props: {
519 readonly label: string;
520 readonly detail: string;
521 readonly incompletePlatforms: readonly DevicePlatform[];
522 readonly onRetry: () => Promise<unknown>;
523}) {
524 const gt = useGT();
525 const [open, setOpen] = useState(false);
526 const [retrying, setRetrying] = useState(false);
527 const [dismissedCause, setDismissedCause] = useState<string | null>(null);
528 const cause = `${props.incompletePlatforms.join()}\u0000${props.detail}`;
529 // A dismissal hides one occurrence; a cause that returns later shows again.
530 if (dismissedCause !== null && dismissedCause !== cause) setDismissedCause(null);
531 if (dismissedCause === cause) return null;
532 const platforms = props.incompletePlatforms.map((platform) =>
533 platform === "ios" ? "iOS" : "Android",
534 );
535 return (
536 <div
537 role="status"
538 className="flex flex-wrap items-center gap-x-2 gap-y-0.5 border-b px-3 py-1 text-xs text-muted-foreground"
539 >
540 <span className="flex min-w-0 flex-1 basis-56 items-start gap-2">
541 <CircleAlert className="mt-px size-3.5 shrink-0 text-warning-foreground" />
542 <span className="min-w-0">
543 {platforms.length > 1
544 ? gt`${{ first: platforms[0] }} and ${{ second: platforms[1] }} lists on ${{ host: props.label }} may be incomplete.`
545 : platforms.length === 1
546 ? gt`${{ platform: platforms[0] }} list on ${{ host: props.label }} may be incomplete.`
547 : gt`Device discovery on ${{ host: props.label }} reported a warning.`}
548 </span>
549 </span>
550 <span className="ml-auto flex shrink-0 items-center gap-0.5">
551 {platforms.length > 0 ? (
552 <Button
553 size="micro"
554 variant="ghost"
555 disabled={retrying}
556 aria-label={gt`Retry device discovery on ${{ host: props.label }}`}
557 onClick={() => {
558 setRetrying(true);
559 void props.onRetry().finally(() => setRetrying(false));
560 }}
561 >
562 {retrying ? gt`Retrying…` : gt`Retry`}
563 </Button>
564 ) : null}
565 <Popover open={open} onOpenChange={setOpen}>
566 <PopoverTrigger
567 aria-label={gt`Details for ${{ host: props.label }}`}
568 render={<Button size="micro" variant="ghost" />}
569 >
570 <T>Details</T>
571 </PopoverTrigger>
572 <PopoverPopup side="bottom" align="end" width="lg" padding="compact">
573 <p className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">
574 {props.detail}
575 </p>
576 </PopoverPopup>
577 </Popover>
578 <Button
579 size="icon-micro"
580 variant="ghost"
581 aria-label={gt`Dismiss device warning for ${{ host: props.label }}`}
582 onClick={() => {
583 setOpen(false);
584 setDismissedCause(cause);
585 }}
586 >
587 <X />
588 </Button>
589 </span>
590 </div>
591 );
593​
594function groupDevices(state: DeviceServiceState) {
595 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
596 for (const platform of ["ios", "android"] as const) {
597 const devices = state.devices
598 .filter((device) => device.platform === platform)
599 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
600 if (devices.length > 0) groups.push({ platform, devices });
601 }
602 return groups;