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

DevicePanel.tsx

418 lines16.1 KB

1import { DeviceHostUpdates } from "./DeviceHostUpdates";
2import type {
3 DevicePlatform,
4 DeviceServiceState,
5 DeviceSummary,
6 ScopedThreadRef,
7} from "@t3tools/contracts";
8import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
9import { useAtomMount } from "@effect/atom-react";
10import { type ReactNode, useState } from "react";
11​
12import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
13import {
14 selectThreadRightPanelState,
15 useRightPanelStore,
16 type RightPanelSurface,
17} from "~/rightPanelStore";
18import { Button } from "~/components/ui/button";
19import { DiscoveryList } from "~/components/ui/discovery-list";
20import { Dialog } from "~/components/ui/dialog";
21import { WizardPopup } from "~/components/ui/wizard";
22import { Spinner } from "~/components/ui/spinner";
23import { cn } from "~/lib/utils";
24import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
25import {
26 deviceEnvironment,
27 deviceHostProbeAtom,
28 NO_DEVICE_PROBE_ATOM,
29 useDeviceState,
30} from "~/state/device";
31import { formatEnvironmentQueryError } from "~/state/query";
32import { useAtomCommand } from "~/state/use-atom-command";
33import { DeviceLoadingView } from "./DeviceLoadingView";
34import { DeviceSetup, deviceHubReadiness, isAndroidDiscoveryUncertain } from "./DeviceSetup";
35import { DeviceWorkspace } from "./DeviceWorkspace";
36import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
37​
38const platformLabel = (platform: DevicePlatform) =>
39 platform === "ios" ? "iOS Simulators" : "Android Emulators";
40​
41const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
42 `${device.hostId}\u0000${device.id}`;
43​
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 // The panel stays mounted across thread switches, so an in-flight open or
57 // power-off is tagged with the thread it belongs to and only shown there.
58 const scope = `${environmentId}\u0000${threadId}`;
59 const [operation, setOperation] = useState<{
60 readonly scope: string;
61 readonly pending: DeviceSummary | null;
62 readonly error: string | null;
63 } | null>(null);
64 const pendingDevice = operation?.scope === scope ? operation.pending : null;
65 const operationError = operation?.scope === scope ? operation.error : null;
66 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
67​
68 const hostDisabled = state.hostStatus === "disabled";
69​
70 useAtomMount(
71 props.visible && loaded && !hostDisabled
72 ? deviceHostProbeAtom(environmentId)
73 : NO_DEVICE_PROBE_ATOM,
74 );
75​
76 const sessions = state.sessions.filter((session) => session.threadId === threadId);
77 const activeSession = props.surface.target
78 ? sessions.find(
79 (session) =>
80 session.deviceId === props.surface.target?.deviceId &&
81 session.hostId === props.surface.target.hostId,
82 )
83 : undefined;
84 const activeDevice = activeSession
85 ? state.devices.find(
86 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
87 )
88 : undefined;
89​
90 const grouped = groupDevices(state);
91​
92 const startOperation = (pending: DeviceSummary | null) => {
93 const started = { scope, pending, error: null };
94 setOperation(started);
95 // Returning to the same thread can start a newer operation before this one settles.
96 return (error: string | null) =>
97 setOperation((current) =>
98 current === started ? { ...started, pending: null, error } : current,
99 );
100 };
101​
102 const selectDevice = async (value: string) => {
103 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
104 if (!device) return;
105 const settleOperation = startOperation(device);
106 const result = await open({
107 environmentId,
108 input: {
109 threadId,
110 hostId: device.hostId,
111 deviceId: device.id,
112 platform: device.platform,
113 },
114 });
115 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
116 else {
117 // The server opened the device for the starting thread, so its tab opens there.
118 useRightPanelStore.getState().openDevice(props.threadRef, {
119 hostId: result.value.hostId,
120 deviceId: result.value.deviceId,
121 platform: device.platform,
122 name: device.name,
123 });
124 settleOperation(null);
125 }
126 };
127​
128 const floatActive = () => {
129 if (!activeDevice) return;
130 usePreviewMiniPlayerStore.getState().open(props.threadRef, {
131 kind: "device",
132 hostId: activeDevice.hostId,
133 deviceId: activeDevice.id,
134 platform: activeDevice.platform,
135 name: activeDevice.name,
136 });
137 useRightPanelStore.getState().close(props.threadRef);
138 };
139​
140 const closeSurface = () => {
141 const store = useRightPanelStore.getState();
142 const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
143 store.closeSurface(props.threadRef, props.surface.id);
144 focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
145 };
146​
147 const closeActive = (powerOff: boolean) => {
148 if (!powerOff) {
149 closeSurface();
150 return;
151 }
152 if (!activeSession) return;
153 const settleOperation = startOperation(null);
154 void close({
155 environmentId,
156 input: {
157 threadId,
158 hostId: activeSession.hostId,
159 deviceId: activeSession.deviceId,
160 shutdown: powerOff,
161 },
162 }).then((result) => {
163 if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
164 else closeSurface();
165 });
166 };
167​
168 const bootingDevices =
169 state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
170 const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
171 const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
172 const diagnostics = state.hosts.flatMap((host) => {
173 const status = state.hostStatuses[host.id];
174 const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
175 return detail && (status?.status ?? state.hostStatus) === "ready"
176 ? [{ hostId: host.id, label: host.label, detail }]
177 : [];
178 });
179 const unavailablePlatforms = state.hosts.flatMap((host) =>
180 host.platforms
181 .filter((platform) => !platform.available)
182 .map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
183 );
184​
185 if (loaded && (!state.onboardingCompleted || hostDisabled)) {
186 return (
187 <Dialog
188 open={props.visible}
189 onOpenChange={(isOpen) => {
190 if (!isOpen) props.onDismissSetup();
191 }}
192 >
193 <WizardPopup>
194 <DeviceSetup environmentId={environmentId} state={state} />
195 </WizardPopup>
196 </Dialog>
197 );
198 }
199​
200 return (
201 <PreviewPanelShell mode={props.mode}>
202 <div className="relative flex min-h-0 flex-1 flex-col">
203 <div
204 className={cn(
205 "shrink-0 bg-background",
206 loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
207 )}
208 >
209 <div hidden={!!activeDevice}>
210 {diagnostics.map((diagnostic) => (
211 <DeviceDiscoveryWarning
212 key={`${environmentId}\u0000${diagnostic.hostId}\u0000${diagnostic.detail}`}
213 label={diagnostic.label}
214 detail={diagnostic.detail}
215 />
216 ))}
217 </div>
218 <DeviceHostUpdates state={state} environmentId={environmentId} />
219 {bootingDevices.length > 0 ? (
220 <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
221 Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a
222 minute.
223 </div>
224 ) : null}
225 {operationError ? (
226 <DeviceNotice tone="error" onDismiss={() => setOperation(null)}>
227 {operationError}
228 </DeviceNotice>
229 ) : null}
230 </div>
231 <div className="@container relative flex min-h-0 flex-1">
232 {activeDevice && activeSession ? (
233 <DeviceWorkspace
234 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
235 environmentId={environmentId}
236 device={activeDevice}
237 hostLabel={
238 state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
239 }
240 hostDiagnostics={
241 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
242 }
243 visible={props.visible}
244 onFloat={floatActive}
245 onClose={() => closeActive(false)}
246 onPowerOff={() => closeActive(true)}
247 />
248 ) : loading ? (
249 <DeviceLoadingView
250 name={pendingDevice?.name ?? "Devices"}
251 description={
252 pendingDevice
253 ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
254 : ""
255 }
256 stage="opening"
257 message={
258 pendingDevice
259 ? pendingDevice.booted
260 ? "Opening device…"
261 : "Starting device…"
262 : state.hostStatus === "installing"
263 ? (state.hostStatusDetail ?? "Installing device support…")
264 : "Finding devices…"
265 }
266 />
267 ) : (
268 <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
269 <div
270 className={cn(
271 "mx-auto flex w-full max-w-xl flex-col gap-6",
272 grouped.length === 0 && "my-auto items-center text-center",
273 )}
274 >
275 {grouped.length === 0 ? (
276 <>
277 <Smartphone className="size-6 opacity-60" />
278 <p
279 className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
280 tabIndex={state.hostStatus === "failed" ? 0 : undefined}
281 >
282 {state.hostStatus === "failed"
283 ? (state.hostStatusDetail ?? "The device hub failed to start.")
284 : "No simulators or emulators were found on this environment."}
285 </p>
286 </>
287 ) : null}
288 {hostReady && grouped.length > 0 ? (
289 <div className="w-full space-y-6 text-left">
290 {grouped.map((group) => (
291 <section key={group.platform} className="space-y-3">
292 <div className="flex items-center gap-2 text-sm text-muted-foreground">
293 <Smartphone className="size-4 shrink-0" />
294 <h3 className="font-medium">{platformLabel(group.platform)}</h3>
295 </div>
296 <DiscoveryList>
297 {group.devices.map((device) => (
298 <div
299 key={deviceKey(device)}
300 className="flex items-center gap-3 px-3 py-3"
301 >
302 <span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
303 <Smartphone className="size-4" />
304 </span>
305 <div className="flex min-w-0 flex-1 flex-col">
306 <span className="truncate text-sm font-medium text-foreground">
307 {device.name}
308 </span>
309 <span className="truncate text-xs text-muted-foreground">
310 {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
311 </span>
312 </div>
313 <Button
314 variant="outline"
315 size="sm"
316 disabled={pendingDeviceKey !== null}
317 aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
318 onClick={() => void selectDevice(deviceKey(device))}
319 >
320 {pendingDeviceKey === deviceKey(device) ? (
321 <Spinner size="xs" />
322 ) : device.booted ? (
323 <ArrowUpRight />
324 ) : (
325 <Play />
326 )}
327 {device.booted ? "Open" : "Start"}
328 </Button>
329 </div>
330 ))}
331 </DiscoveryList>
332 </section>
333 ))}
334 </div>
335 ) : null}
336 {hostReady &&
337 !isAndroidDiscoveryUncertain(state) &&
338 !state.devices.some((device) => device.platform === "android") &&
339 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
340 <p className="max-w-sm text-xs">
341 No Android virtual devices found. Create one in Android Studio's Device Manager,
342 then refresh.
343 </p>
344 ) : null}
345 {loaded && !hostBusy ? (
346 <Button
347 className={grouped.length > 0 ? "self-start" : "self-center"}
348 variant="outline"
349 size="sm"
350 onClick={() => void list({ environmentId, input: {} })}
351 >
352 Refresh devices
353 </Button>
354 ) : null}
355 </div>
356 </div>
357 )}
358 </div>
359 </div>
360 </PreviewPanelShell>
361 );
363​
364function DeviceNotice(props: {
365 readonly tone: "warning" | "error";
366 readonly onDismiss: () => void;
367 readonly children: ReactNode;
368}) {
369 return (
370 <div
371 role="alert"
372 className={cn(
373 "flex items-start gap-2 border-b px-3 py-2 text-xs",
374 props.tone === "warning"
375 ? "bg-warning-surface text-warning-foreground"
376 : "bg-destructive/5 text-destructive",
377 )}
378 >
379 <CircleAlert className="mt-1 size-3.5 shrink-0" />
380 <div
381 className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
382 tabIndex={0}
383 >
384 {props.children}
385 </div>
386 <Button
387 size="icon-xs"
388 variant="ghost"
389 aria-label={props.tone === "warning" ? "Dismiss device warning" : "Dismiss device error"}
390 onClick={props.onDismiss}
391 >
392 <X />
393 </Button>
394 </div>
395 );
397​
398function DeviceDiscoveryWarning(props: { readonly label: string; readonly detail: string }) {
399 const [dismissed, setDismissed] = useState(false);
400 if (dismissed) return null;
401 return (
402 <DeviceNotice tone="warning" onDismiss={() => setDismissed(true)}>
403 <p className="font-medium">Device discovery warning · {props.label}</p>
404 {props.detail}
405 </DeviceNotice>
406 );
408​
409function groupDevices(state: DeviceServiceState) {
410 const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
411 for (const platform of ["ios", "android"] as const) {
412 const devices = state.devices
413 .filter((device) => device.platform === platform)
414 .toSorted((a, b) => Number(b.booted) - Number(a.booted) || a.name.localeCompare(b.name));
415 if (devices.length > 0) groups.push({ platform, devices });
416 }
417 return groups;