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

DevicePanel.tsx

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