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

DevicePanel.tsx

336 lines13.4 KB

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