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

DeviceSourcesSettings.tsx

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