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

DevicePanel.tsx

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