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

DevicePanel.tsx

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