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

DeviceSourcesSettings.tsx

815 lines30.5 KB

1import { useAtomValue } from "@effect/atom-react";
2import { Fragment, useState, type ReactNode } from "react";
3import * as Cause from "effect/Cause";
4import * as Option from "effect/Option";
5import { AsyncResult } from "effect/reactivity";
6import {
7 AuthSettingsWriteScope,
8 type DevicePlatform,
9 type DevicePlatformAvailability,
10 type DeviceServiceState,
11 type EasDeviceHostConfig,
12 type EnvironmentId,
13 type ServerSettingsPatch,
14 type SimlockDeviceHostConfig,
15 type SshDeviceHostConfig,
16} from "@t3tools/contracts";
17import { ChevronDownIcon, MoreVertical, PlusIcon } from "lucide-react";
18​
19import { cn, randomUUID } from "../../lib/utils";
20import { deviceEnvironment } from "../../state/device";
21import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
22import { serverEnvironment } from "../../state/server";
23import { readEnvironmentScope } from "../../state/session";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { AndroidIcon, AppleIcon } from "../Icons";
26import { Button, InlineButton } from "../ui/button";
27import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
28import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
29import { Spinner } from "../ui/spinner";
30import { toastManager } from "../ui/toast";
31import { incompleteListings } from "../device/DeviceSetup";
32import { DeviceHostEditor } from "./DeviceHostEditor";
33import { updateDeviceHosts, groupDeviceHosts } from "./deviceHostsSettings.logic";
34import { EasDeviceHostEditor } from "./EasDeviceHostEditor";
35import {
36 easSessionLimits,
37 newEasDeviceHost,
38 updateEasDeviceHosts,
39} from "./easDeviceHostsSettings.logic";
40import { useSettingsScope } from "./SettingsScopeContext";
41import { SettingsSection } from "./settingsLayout";
42import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
43import { SimlockDeviceHostEditor } from "./SimlockDeviceHostEditor";
44import {
45 newSimlockDeviceHost,
46 planSimlockDeviceHostSave,
47 simlockLeaseLimits,
48 updateSimlockDeviceHosts,
49 type SimlockTokenEntry,
50} from "./simlockDeviceHostsSettings.logic";
51import { useHostConnectionChecks } from "./useHostConnectionChecks";
52​
53const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
54 deviceEnvironment.state({ environmentId, input: {} }),
55);
56​
57const failureMessage = (cause: Cause.Cause<unknown>) => {
58 const error = Cause.squash(cause);
59 return error instanceof Error ? error.message : String(error);
60};
61​
62/** Something on one environment that is in progress or needs a fix; a working source has none. */
63interface SourceStatus {
64 readonly tone: "pending" | "warning" | "error";
65 readonly label: string;
66 readonly detail?: string | undefined;
67 readonly action?: { readonly label: string; readonly run: () => void } | undefined;
69​
70/** A source on one environment whose devices are on. */
71interface SourceEnvironment {
72 readonly environmentId: EnvironmentId;
73 readonly label: string;
74 readonly added: boolean;
75 readonly status?: SourceStatus | undefined;
76 /** Unknown until the environment's hub has reached the source. */
77 readonly platforms?: ReadonlyArray<DevicePlatformAvailability> | undefined;
79​
80interface SourceRow {
81 readonly key: string;
82 readonly title: string;
83 readonly kind?: string;
84 readonly description: ReactNode;
85 readonly environments: ReadonlyArray<SourceEnvironment>;
86 /**
87 * One machine or account every environment reaches the same way (an SSH host, EAS, a Simlock
88 * pool), so its platforms are the same for all of them. Local simulators differ per machine.
89 */
90 readonly shared: boolean;
91 readonly actions?: ReactNode;
93​
94type Editing =
95 | {
96 readonly kind: "ssh";
97 readonly host: SshDeviceHostConfig;
98 readonly original: SshDeviceHostConfig | null;
99 /** Limits the save to these environments, for a host that differs between them. */
100 readonly only?: ReadonlySet<EnvironmentId>;
101 }
102 | {
103 readonly kind: "eas";
104 readonly host: EasDeviceHostConfig;
105 readonly isNew: boolean;
106 /** Where the editor checks the Expo account: an environment that holds the host. */
107 readonly environmentId: EnvironmentId;
108 }
109 | { readonly kind: "simlock"; readonly host: SimlockDeviceHostConfig; readonly isNew: boolean };
110​
111/** What a configured host is doing on one environment, when it is not simply working. */
112function hostStatus(
113 state: DeviceServiceState | undefined,
114 hostId: string,
115): SourceStatus | undefined {
116 if (!state) return { tone: "pending", label: "Loading" };
117 const status = state.hostStatuses[hostId];
118 switch (status?.status) {
119 case "ready": {
120 const incomplete = incompleteListings(status);
121 if (incomplete.length === 0) return undefined;
122 const list = incomplete.length > 1 ? "Device" : incomplete[0] === "ios" ? "iOS" : "Android";
123 return { tone: "warning", label: `${list} list may be incomplete`, detail: status.detail };
124 }
125 case "installing":
126 case "starting":
127 return { tone: "pending", label: "Starting", detail: status.detail };
128 case "failed":
129 return { tone: "error", label: "Failed", detail: status.detail };
130 default:
131 return undefined;
132 }
134​
135const hostPlatforms = (state: DeviceServiceState | undefined, hostId: string) =>
136 state?.hosts.find((host) => host.id === hostId)?.platforms;
137​
138/**
139 * Every device source the selected environments can open, one row each. A source configured on
140 * several environments is one row; how it stands on each lives in the row's breakdown.
141 */
142export function DeviceSourcesSettings(props: {
143 readonly supportsEas: boolean;
144 readonly supportsSimlock: boolean;
145}) {
146 const { scope, environments, connectedEnvironments, environment: primary } = useSettingsScope();
147 const projectScope = scope.kind === "project" || scope.kind === "checkout";
148 const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
149 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
150 const [editing, setEditing] = useState<Editing | null>(null);
151 const [busy, setBusy] = useState(false);
152 const label = (environment: (typeof environments)[number]) =>
153 settingsScopeEnvironmentLabel(environment, environments);
154 const targets = environments.map((environment) => ({
155 environmentId: environment.environmentId,
156 label: label(environment),
157 connected: environment.connection.phase === "connected",
158 }));
159 const { testConnection } = useHostConnectionChecks(targets);
160 const ids = connectedEnvironments.map((environment) => environment.environmentId);
161 const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(ids)));
162 const members = connectedEnvironments.map((environment, index) => {
163 const result = results[index];
164 return {
165 environmentId: environment.environmentId,
166 label: label(environment),
167 settings: environment.serverConfig?.settings,
168 state: result ? Option.getOrUndefined(AsyncResult.value(result)) : undefined,
169 };
170 });
171 // Environments with devices off are left out: the switch above already says so.
172 const active = members.filter((member) => member.settings?.enableDeviceSupport);
173 const simlockEnabled = members.some((member) => member.settings?.simlockDeviceHostsEnabled);
174 // Like every scoped setting, a change reaches the connected environments and skips the rest.
175 const disabled = projectScope || busy || members.length === 0;
176​
177 /** Writes one settings patch per environment; reports the environments it could not change. */
178 const write = async (
179 patches: ReadonlyArray<{ environmentId: EnvironmentId; patch: ServerSettingsPatch }>,
180 failedTitle: string,
181 ) => {
182 if (projectScope) return false;
183 const name = (environmentId: EnvironmentId) =>
184 members.find((member) => member.environmentId === environmentId)?.label ?? environmentId;
185 const unwritable = patches.filter(
186 (patch) => !readEnvironmentScope(patch.environmentId, AuthSettingsWriteScope),
187 );
188 if (unwritable.length > 0) {
189 toastManager.add({
190 type: "error",
191 title: failedTitle,
192 description: `This connection cannot change settings on ${unwritable.map((patch) => name(patch.environmentId)).join(", ")}.`,
193 });
194 return false;
195 }
196 setBusy(true);
197 const outcomes = await Promise.all(
198 patches.map((patch) =>
199 update({ environmentId: patch.environmentId, input: { patch: patch.patch } }),
200 ),
201 );
202 setBusy(false);
203 const failed = patches.flatMap((patch, index) => {
204 const outcome = outcomes[index];
205 return outcome && outcome._tag === "Failure"
206 ? [`${name(patch.environmentId)}: ${failureMessage(outcome.cause)}`]
207 : [];
208 });
209 if (failed.length === 0) return true;
210 toastManager.add({ type: "error", title: failedTitle, description: failed.join("\n") });
211 return false;
212 };
213​
214 const saveSsh = async (
215 host: SshDeviceHostConfig,
216 remove: boolean,
217 original = host,
218 only?: ReadonlySet<EnvironmentId>,
219 ) => {
220 try {
221 const saved = await write(
222 members
223 .filter((member) => !only || only.has(member.environmentId))
224 .map((member) => ({
225 environmentId: member.environmentId,
226 patch: {
227 deviceHosts: updateDeviceHosts(
228 member.settings?.deviceHosts ?? [],
229 host,
230 remove,
231 original,
232 ),
233 },
234 })),
235 remove ? "Device host not removed everywhere" : "Device host not saved everywhere",
236 );
237 if (saved) setEditing(null);
238 } catch (error) {
239 toastManager.add({
240 type: "error",
241 title: "Device host not saved",
242 description: error instanceof Error ? error.message : String(error),
243 });
244 }
245 };
246​
247 const saveEas = async (
248 host: EasDeviceHostConfig,
249 remove: boolean,
250 previous?: EasDeviceHostConfig,
251 ) => {
252 const keepToken = previous !== undefined && host.accessToken === previous.accessToken;
253 const saved = await write(
254 members.map((member) => ({
255 environmentId: member.environmentId,
256 patch: {
257 easDeviceHosts: updateEasDeviceHosts(
258 member.settings?.easDeviceHosts ?? [],
259 host,
260 remove,
261 keepToken,
262 ),
263 },
264 })),
265 remove ? "EAS host not removed everywhere" : "EAS host not saved everywhere",
266 );
267 if (saved) setEditing(null);
268 };
269​
270 const simlockEnvironments = members.map((member) => ({
271 environmentId: member.environmentId,
272 label: member.label,
273 hosts: member.settings?.simlockDeviceHosts ?? [],
274 }));
275 const saveSimlock = async (
276 host: SimlockDeviceHostConfig,
277 tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
278 ) => {
279 const plan = planSimlockDeviceHostSave(simlockEnvironments, host, tokens);
280 if ("problem" in plan) return;
281 const saved = await write(
282 plan.patches.map((patch) => ({
283 environmentId: patch.environmentId,
284 patch: { simlockDeviceHosts: patch.hosts },
285 })),
286 "Simlock host not saved everywhere",
287 );
288 if (saved) setEditing(null);
289 };
290 const removeSimlock = (host: SimlockDeviceHostConfig) =>
291 void write(
292 simlockEnvironments
293 .filter((environment) => environment.hosts.some((candidate) => candidate.id === host.id))
294 .map((environment) => ({
295 environmentId: environment.environmentId,
296 patch: { simlockDeviceHosts: updateSimlockDeviceHosts(environment.hosts, host, true) },
297 })),
298 "Simlock host not removed everywhere",
299 );
300​
301 const [testing, setTesting] = useState<ReadonlySet<string>>(new Set());
302 const testSsh = async (host: SshDeviceHostConfig) => {
303 setTesting((current) => new Set(current).add(host.id));
304 const checked = await testConnection(host).finally(() =>
305 setTesting((current) => {
306 const next = new Set(current);
307 next.delete(host.id);
308 return next;
309 }),
310 );
311 if (!checked) return;
312 const failed = targets.filter((target) => checked[target.environmentId]?.status === "failed");
313 toastManager.add({
314 type: failed.length ? "error" : "success",
315 title: failed.length
316 ? `${host.label}: ${failed.length} of ${targets.length} environments failed`
317 : `${host.label}: connection checks passed`,
318 description: failed.length
319 ? failed
320 .map((target) => {
321 const result = checked[target.environmentId];
322 return `${target.label}: ${result?.status === "failed" ? result.error : "failed"}`;
323 })
324 .join("\n")
325 : "Connected or already available locally on each selected environment.",
326 });
327 };
328​
329 const retry = (environmentId: EnvironmentId, hostId: string) =>
330 void list({ environmentId, input: { retryHostId: hostId } });
331​
332 const rowActions = (onEdit: () => void, onRemove: () => void, extra?: ReactNode) => (
333 <>
334 <Button size="sm" variant="outline" disabled={disabled} onClick={onEdit}>
335 Edit
336 </Button>
337 <Menu>
338 <MenuTrigger
339 render={
340 <Button size="icon-sm" variant="ghost-muted" disabled={disabled} aria-label="More" />
341 }
342 >
343 <MoreVertical />
344 </MenuTrigger>
345 <MenuPopup align="end">
346 {extra}
347 <MenuItem variant="destructive" onClick={onRemove}>
348 Remove
349 </MenuItem>
350 </MenuPopup>
351 </Menu>
352 </>
353 );
354​
355 const rows: SourceRow[] = [];
356​
357 rows.push({
358 key: "local",
359 shared: false,
360 title: "Local simulators",
361 description:
362 members.length > 1
363 ? "Simulators and emulators installed on each environment's own machine."
364 : "Simulators and emulators installed on this environment's machine.",
365 environments: active.map((member) => {
366 const local = member.state?.hosts.find((host) => host.kind === "local");
367 const status = local ? hostStatus(member.state, local.id) : hostStatus(member.state, "");
368 return {
369 environmentId: member.environmentId,
370 label: member.label,
371 added: true,
372 platforms: local?.platforms,
373 status:
374 status?.tone === "error"
375 ? {
376 ...status,
377 action: {
378 label: "Refresh",
379 run: () => void list({ environmentId: member.environmentId, input: {} }),
380 },
381 }
382 : status,
383 };
384 }),
385 });
386​
387 const grouped = groupDeviceHosts(
388 members.map((member) => ({
389 environmentId: member.environmentId,
390 label: member.label,
391 hosts: member.settings?.deviceHosts ?? [],
392 })),
393 );
394 const sshGroups =
395 grouped ??
396 // Hosts that cannot be matched across environments stay one row per environment.
397 members.flatMap((member) =>
398 (member.settings?.deviceHosts ?? []).map((host) => ({
399 host,
400 members: [{ environmentId: member.environmentId, label: member.label, host }],
401 })),
402 );
403 for (const group of sshGroups) {
404 const host = group.host;
405 const holders = new Set(group.members.map((member) => member.environmentId));
406 rows.push({
407 key: `ssh:${host.id}:${group.members.map((member) => member.environmentId).join(",")}`,
408 shared: true,
409 title: host.label,
410 kind: "SSH",
411 description: host.target,
412 environments: active.map((member) => {
413 const held = group.members.find(
414 (candidate) => candidate.environmentId === member.environmentId,
415 );
416 if (!held)
417 return { environmentId: member.environmentId, label: member.label, added: false };
418 const status = testing.has(host.id)
419 ? ({ tone: "pending", label: "Testing connection" } as const)
420 : hostStatus(member.state, held.host.id);
421 return {
422 environmentId: member.environmentId,
423 label: member.label,
424 added: true,
425 platforms: hostPlatforms(member.state, held.host.id),
426 status:
427 status?.tone === "error" && member.state?.supportsHostRetry
428 ? {
429 ...status,
430 label: "Can't connect",
431 action: { label: "Retry", run: () => retry(member.environmentId, held.host.id) },
432 }
433 : status,
434 };
435 }),
436 actions: rowActions(
437 () =>
438 setEditing({ kind: "ssh", host, original: host, ...(grouped ? {} : { only: holders }) }),
439 () => void saveSsh(host, true, host, holders),
440 <MenuItem onClick={() => void testSsh(host)}>Test connection</MenuItem>,
441 ),
442 });
443 }
444​
445 if (props.supportsEas) {
446 const easHosts = new Map<string, EasDeviceHostConfig>();
447 for (const member of members)
448 for (const host of member.settings?.easDeviceHosts ?? [])
449 if (!easHosts.has(host.id)) easHosts.set(host.id, host);
450 for (const host of easHosts.values()) {
451 const holders = members.filter((member) =>
452 (member.settings?.easDeviceHosts ?? []).some((candidate) => candidate.id === host.id),
453 );
454 const [firstHolder] = holders;
455 if (!firstHolder) continue;
456 const checkOn = (
457 holders.find((member) => member.environmentId === primary?.environmentId) ?? firstHolder
458 ).environmentId;
459 rows.push({
460 key: `eas:${host.id}`,
461 shared: true,
462 title: host.label,
463 kind: "EAS",
464 description: easSessionLimits(host),
465 environments: active.map((member) => {
466 const added = (member.settings?.easDeviceHosts ?? []).some(
467 (candidate) => candidate.id === host.id,
468 );
469 return {
470 environmentId: member.environmentId,
471 label: member.label,
472 added,
473 ...(added
474 ? {
475 status: hostStatus(member.state, host.id),
476 platforms: hostPlatforms(member.state, host.id),
477 }
478 : {}),
479 };
480 }),
481 actions: rowActions(
482 () => setEditing({ kind: "eas", host, isNew: false, environmentId: checkOn }),
483 () => void saveEas(host, true),
484 ),
485 });
486 }
487 }
488​
489 if (props.supportsSimlock && simlockEnabled) {
490 const simlockHosts = new Map<string, SimlockDeviceHostConfig>();
491 for (const environment of simlockEnvironments)
492 for (const host of environment.hosts)
493 if (!simlockHosts.has(host.id)) simlockHosts.set(host.id, host);
494 for (const host of simlockHosts.values()) {
495 const edit = () => setEditing({ kind: "simlock", host, isNew: false });
496 rows.push({
497 key: `simlock:${host.id}`,
498 shared: true,
499 title: host.label,
500 kind: "Simlock",
501 description: `${host.gatewayUrl.replace(/^https?:\/\//, "")} · ${simlockLeaseLimits(host)}`,
502 environments: active.map((member) => {
503 const held = (member.settings?.simlockDeviceHosts ?? []).find(
504 (candidate) => candidate.id === host.id,
505 );
506 if (!held)
507 return { environmentId: member.environmentId, label: member.label, added: false };
508 return {
509 environmentId: member.environmentId,
510 label: member.label,
511 added: true,
512 platforms: hostPlatforms(member.state, host.id),
513 // A blank token can still resolve to the machine's own, so the host's answer decides.
514 status: hostStatus(member.state, host.id),
515 };
516 }),
517 actions: rowActions(edit, () => removeSimlock(host)),
518 });
519 }
520 }
521​
522 const addMenu = (
523 <Menu>
524 <MenuTrigger
525 render={<Button size="sm" variant="outline" disabled={disabled || editing !== null} />}
526 >
527 <PlusIcon className="size-3.5" /> Add source
528 <ChevronDownIcon className="size-3.5" />
529 </MenuTrigger>
530 <MenuPopup align="end">
531 <MenuItem
532 onClick={() =>
533 setEditing({
534 kind: "ssh",
535 host: { kind: "ssh", id: randomUUID(), label: "", target: "" },
536 original: null,
537 })
538 }
539 >
540 Machine over SSH
541 </MenuItem>
542 {props.supportsEas ? (
543 <MenuItem
544 onClick={() =>
545 primary &&
546 setEditing({
547 kind: "eas",
548 host: newEasDeviceHost(randomUUID()),
549 isNew: true,
550 environmentId: primary.environmentId,
551 })
552 }
553 >
554 EAS Simulator
555 </MenuItem>
556 ) : null}
557 {props.supportsSimlock && simlockEnabled ? (
558 <MenuItem
559 onClick={() =>
560 setEditing({ kind: "simlock", host: newSimlockDeviceHost(randomUUID()), isNew: true })
561 }
562 >
563 Simlock pool (alpha)
564 </MenuItem>
565 ) : null}
566 </MenuPopup>
567 </Menu>
568 );
569​
570 return (
571 <SettingsSection id="device-sources" title="Device sources" headerAction={addMenu}>
572 {rows.map((row) => (
573 <DeviceSourceRow key={row.key} row={row} />
574 ))}
575 {editing?.kind === "ssh" ? (
576 <DeviceHostEditor
577 key={editing.host.id}
578 host={editing.host}
579 isNew={editing.original === null}
580 targets={targets}
581 busy={busy}
582 onSave={(host) => void saveSsh(host, false, editing.original ?? host, editing.only)}
583 onClose={() => setEditing(null)}
584 />
585 ) : editing?.kind === "eas" ? (
586 <EasDeviceHostEditor
587 key={editing.host.id}
588 environmentId={editing.environmentId}
589 host={editing.host}
590 isNew={editing.isNew}
591 busy={busy}
592 onSave={(host) => void saveEas(host, false, editing.isNew ? undefined : editing.host)}
593 onClose={() => setEditing(null)}
594 />
595 ) : editing?.kind === "simlock" ? (
596 <SimlockDeviceHostEditor
597 key={editing.host.id}
598 host={editing.host}
599 isNew={editing.isNew}
600 environments={simlockEnvironments}
601 busy={busy}
602 onSave={(host, tokens) => void saveSimlock(host, tokens)}
603 onClose={() => setEditing(null)}
604 />
605 ) : null}
606 </SettingsSection>
607 );
609​
610const PLATFORMS = [
611 { platform: "ios", label: "iOS", Icon: AppleIcon },
612 { platform: "android", label: "Android", Icon: AndroidIcon },
613] as const satisfies ReadonlyArray<{ platform: DevicePlatform; label: string; Icon: unknown }>;
614​
615/** The platforms a source offers: one icon each, solid where available, muted where not. */
616function SourcePlatforms(props: { row: SourceRow }) {
617 const added = props.row.environments.filter((environment) => environment.added);
618 const known = added.filter((environment) => environment.platforms !== undefined);
619 return PLATFORMS.filter(({ platform }) =>
620 known.some((environment) =>
621 environment.platforms?.some((candidate) => candidate.platform === platform),
622 ),
623 ).map((entry) => <PlatformIcon key={entry.platform} {...entry} row={props.row} known={known} />);
625​
626function PlatformIcon(props: {
627 platform: DevicePlatform;
628 label: string;
629 Icon: (typeof PLATFORMS)[number]["Icon"];
630 row: SourceRow;
631 known: ReadonlyArray<SourceEnvironment>;
632}) {
633 const availability = (environment: SourceEnvironment) =>
634 environment.platforms?.find((candidate) => candidate.platform === props.platform);
635 const availableOn = props.known.filter((environment) => availability(environment)?.available);
636 const several = props.row.environments.length > 1;
637 const available = availableOn.length > 0;
638 const partial = available && availableOn.length < props.known.length;
639 // A shared source usually answers the same everywhere, so its answer is given once. Each
640 // environment still signs in to it on its own, which is where they can differ.
641 const sharedAnswer = props.known.map(availability).find(Boolean);
642 const uniform = props.known.every(
643 (environment) =>
644 availability(environment)?.available === sharedAnswer?.available &&
645 availability(environment)?.reason === sharedAnswer?.reason,
646 );
647 const unavailableOn = props.known.filter((environment) => !availability(environment)?.available);
648 const connected = props.row.environments.filter((environment) => environment.added);
649 const notAdded = props.row.environments.filter((environment) => !environment.added);
650 return (
651 <Popover>
652 <PopoverTrigger
653 openOnHover
654 delay={150}
655 closeDelay={100}
656 render={
657 <button
658 type="button"
659 aria-label={`${props.row.title}: ${props.label} ${available ? "available" : "not available"}`}
660 className={cn(
661 "relative grid size-6 shrink-0 place-items-center rounded-md outline-hidden hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
662 available ? "text-foreground" : "text-muted-foreground/45",
663 )}
664 />
665 }
666 >
667 <props.Icon className={cn("size-3.5", props.platform === "ios" && "-translate-y-px")} />
668 {partial ? (
669 <span
670 aria-hidden
671 className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-warning ring-2 ring-background"
672 />
673 ) : null}
674 </PopoverTrigger>
675 <PopoverPopup side="top" align="end" width="sm">
676 <p className="text-sm font-medium">
677 {props.label}{" "}
678 {available ? (partial ? "available on some" : "available") : "not available"}
679 </p>
680 {props.row.shared ? (
681 <>
682 {uniform && !available && sharedAnswer?.reason ? (
683 <p className="mt-1 text-xs text-muted-foreground">{sharedAnswer.reason}</p>
684 ) : null}
685 {several ? (
686 <dl className="mt-2 space-y-1.5 text-xs">
687 {(
688 [
689 ...(uniform
690 ? ([["Connected", connected]] as const)
691 : ([
692 ["Available", availableOn],
693 ["Not available", unavailableOn],
694 ] as const)),
695 ["Not added", notAdded],
696 ] as const
697 ).map(([heading, environments]) =>
698 environments.length > 0 ? (
699 <div key={heading}>
700 <dt className="text-muted-foreground">{heading}</dt>
701 {environments.map((environment) => {
702 const reason =
703 heading === "Not available"
704 ? availability(environment)?.reason
705 : undefined;
706 return (
707 <dd key={environment.environmentId}>
708 <span className="block truncate">{environment.label}</span>
709 {reason ? (
710 <span className="block text-muted-foreground">{reason}</span>
711 ) : null}
712 </dd>
713 );
714 })}
715 </div>
716 ) : null,
717 )}
718 </dl>
719 ) : null}
720 </>
721 ) : several ? (
722 <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs">
723 {props.known.map((environment) => {
724 const entry = availability(environment);
725 return (
726 <Fragment key={environment.environmentId}>
727 <dt className="text-muted-foreground">{environment.label}</dt>
728 <dd className={entry?.available ? "" : "text-muted-foreground"}>
729 {entry?.available ? "Available" : (entry?.reason ?? "Not available")}
730 </dd>
731 </Fragment>
732 );
733 })}
734 </dl>
735 ) : !available ? (
736 <p className="mt-1 text-xs text-muted-foreground">
737 {availability(props.known[0]!)?.reason ?? "Not set up on this machine."}
738 </p>
739 ) : null}
740 </PopoverPopup>
741 </Popover>
742 );
744​
745function DeviceSourceRow(props: { row: SourceRow }) {
746 const { row } = props;
747 const several = row.environments.length > 1;
748 const issues = row.environments.filter(
749 (environment): environment is SourceEnvironment & { status: SourceStatus } =>
750 environment.status !== undefined,
751 );
752 const problems = issues.filter((environment) => environment.status.tone !== "pending");
753 const pending = issues.find((environment) => environment.status.tone === "pending");
754 return (
755 <div className="flex items-center gap-3 border-t border-border/60 px-3 py-3 first:border-t-0 sm:px-4">
756 <div className="min-w-0 flex-1">
757 <div className="flex min-w-0 items-center gap-1.5">
758 <p className="truncate text-sm font-medium">{row.title}</p>
759 {row.kind ? (
760 <span className="shrink-0 rounded border border-border px-1 text-3xs uppercase tracking-wide text-muted-foreground">
761 {row.kind}
762 </span>
763 ) : null}
764 </div>
765 <p className="truncate text-xs text-muted-foreground">{row.description}</p>
766 {problems.map((environment) => (
767 <p
768 key={environment.environmentId}
769 role="status"
770 className={cn(
771 "mt-1 flex flex-wrap items-center gap-1.5 text-xs",
772 environment.status.tone === "error" ? "text-destructive" : "text-warning",
773 )}
774 >
775 <span className="min-w-0 break-words">
776 {several ? `${environment.label}: ` : ""}
777 {environment.status.tone === "error" && !several && environment.status.detail
778 ? environment.status.detail
779 : environment.status.label}
780 </span>
781 {environment.status.tone === "warning" && environment.status.detail ? (
782 <Popover>
783 <PopoverTrigger render={<InlineButton />}>Details</PopoverTrigger>
784 <PopoverPopup side="bottom" align="start" width="lg" padding="compact">
785 <p className="whitespace-pre-wrap break-words font-mono text-xs text-muted-foreground">
786 {environment.status.detail}
787 </p>
788 </PopoverPopup>
789 </Popover>
790 ) : null}
791 {environment.status.action ? (
792 <InlineButton onClick={environment.status.action.run}>
793 {environment.status.action.label}
794 </InlineButton>
795 ) : null}
796 </p>
797 ))}
798 </div>
799 {pending ? (
800 <span
801 role="status"
802 className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
803 >
804 <Spinner size="xs" />
805 {pending.status.label}
806 </span>
807 ) : (
808 <div className="flex shrink-0 items-center gap-0.5">
809 <SourcePlatforms row={row} />
810 </div>
811 )}
812 {row.actions ? <div className="flex shrink-0 items-center gap-1">{row.actions}</div> : null}
813 </div>
814 );