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

DeviceSourcesSettings.tsx

802 lines29.7 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 // A blank token can still resolve to the machine's own, so the host's answer decides.
511 status: hostStatus(member.state, host.id),
512 };
513 }),
514 actions: rowActions(edit, () => removeSimlock(host)),
515 });
516 }
517 }
518​
519 const addMenu = (
520 <Menu>
521 <MenuTrigger
522 render={<Button size="sm" variant="outline" disabled={disabled || editing !== null} />}
523 >
524 <PlusIcon className="size-3.5" /> Add source
525 <ChevronDownIcon className="size-3.5" />
526 </MenuTrigger>
527 <MenuPopup align="end">
528 <MenuItem
529 onClick={() =>
530 setEditing({
531 kind: "ssh",
532 host: { kind: "ssh", id: randomUUID(), label: "", target: "" },
533 original: null,
534 })
535 }
536 >
537 Machine over SSH
538 </MenuItem>
539 {props.supportsEas ? (
540 <MenuItem
541 onClick={() =>
542 primary &&
543 setEditing({
544 kind: "eas",
545 host: newEasDeviceHost(randomUUID()),
546 isNew: true,
547 environmentId: primary.environmentId,
548 })
549 }
550 >
551 EAS Simulator
552 </MenuItem>
553 ) : null}
554 {props.supportsSimlock && simlockEnabled ? (
555 <MenuItem
556 onClick={() =>
557 setEditing({ kind: "simlock", host: newSimlockDeviceHost(randomUUID()), isNew: true })
558 }
559 >
560 Simlock pool (alpha)
561 </MenuItem>
562 ) : null}
563 </MenuPopup>
564 </Menu>
565 );
566​
567 return (
568 <SettingsSection id="device-sources" title="Device sources" headerAction={addMenu}>
569 {rows.map((row) => (
570 <DeviceSourceRow key={row.key} row={row} />
571 ))}
572 {editing?.kind === "ssh" ? (
573 <DeviceHostEditor
574 key={editing.host.id}
575 host={editing.host}
576 isNew={editing.original === null}
577 targets={targets}
578 busy={busy}
579 onSave={(host) => void saveSsh(host, false, editing.original ?? host, editing.only)}
580 onClose={() => setEditing(null)}
581 />
582 ) : editing?.kind === "eas" ? (
583 <EasDeviceHostEditor
584 key={editing.host.id}
585 environmentId={editing.environmentId}
586 host={editing.host}
587 isNew={editing.isNew}
588 busy={busy}
589 onSave={(host) => void saveEas(host, false, editing.isNew ? undefined : editing.host)}
590 onClose={() => setEditing(null)}
591 />
592 ) : editing?.kind === "simlock" ? (
593 <SimlockDeviceHostEditor
594 key={editing.host.id}
595 host={editing.host}
596 isNew={editing.isNew}
597 environments={simlockEnvironments}
598 busy={busy}
599 onSave={(host, tokens) => void saveSimlock(host, tokens)}
600 onClose={() => setEditing(null)}
601 />
602 ) : null}
603 </SettingsSection>
604 );
606​
607const PLATFORMS = [
608 { platform: "ios", label: "iOS", Icon: AppleIcon },
609 { platform: "android", label: "Android", Icon: AndroidIcon },
610] as const satisfies ReadonlyArray<{ platform: DevicePlatform; label: string; Icon: unknown }>;
611​
612/** The platforms a source offers: one icon each, solid where available, muted where not. */
613function SourcePlatforms(props: { row: SourceRow }) {
614 const added = props.row.environments.filter((environment) => environment.added);
615 const known = added.filter((environment) => environment.platforms !== undefined);
616 return PLATFORMS.filter(({ platform }) =>
617 known.some((environment) =>
618 environment.platforms?.some((candidate) => candidate.platform === platform),
619 ),
620 ).map((entry) => <PlatformIcon key={entry.platform} {...entry} row={props.row} known={known} />);
622​
623function PlatformIcon(props: {
624 platform: DevicePlatform;
625 label: string;
626 Icon: (typeof PLATFORMS)[number]["Icon"];
627 row: SourceRow;
628 known: ReadonlyArray<SourceEnvironment>;
629}) {
630 const availability = (environment: SourceEnvironment) =>
631 environment.platforms?.find((candidate) => candidate.platform === props.platform);
632 const availableOn = props.known.filter((environment) => availability(environment)?.available);
633 const several = props.row.environments.length > 1;
634 const available = availableOn.length > 0;
635 const partial = available && availableOn.length < props.known.length;
636 // A shared source usually answers the same everywhere, so its answer is given once. Each
637 // environment still signs in to it on its own, which is where they can differ.
638 const sharedAnswer = props.known.map(availability).find(Boolean);
639 const uniform = props.known.every(
640 (environment) =>
641 availability(environment)?.available === sharedAnswer?.available &&
642 availability(environment)?.reason === sharedAnswer?.reason,
643 );
644 const unavailableOn = props.known.filter((environment) => !availability(environment)?.available);
645 const connected = props.row.environments.filter((environment) => environment.added);
646 const notAdded = props.row.environments.filter((environment) => !environment.added);
647 return (
648 <Popover>
649 <PopoverTrigger
650 openOnHover
651 delay={150}
652 closeDelay={100}
653 render={
654 <button
655 type="button"
656 aria-label={`${props.row.title}: ${props.label} ${available ? "available" : "not available"}`}
657 className={cn(
658 "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",
659 available ? "text-foreground" : "text-muted-foreground/45",
660 )}
661 />
662 }
663 >
664 <props.Icon className={cn("size-3.5", props.platform === "ios" && "-translate-y-px")} />
665 {partial ? (
666 <span
667 aria-hidden
668 className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-warning ring-2 ring-background"
669 />
670 ) : null}
671 </PopoverTrigger>
672 <PopoverPopup side="top" align="end" width="sm">
673 <p className="text-sm font-medium">
674 {props.label}{" "}
675 {available ? (partial ? "available on some" : "available") : "not available"}
676 </p>
677 {props.row.shared ? (
678 <>
679 {uniform && !available && sharedAnswer?.reason ? (
680 <p className="mt-1 text-xs text-muted-foreground">{sharedAnswer.reason}</p>
681 ) : null}
682 {several ? (
683 <dl className="mt-2 space-y-1.5 text-xs">
684 {(
685 [
686 ...(uniform
687 ? ([["Connected", connected]] as const)
688 : ([
689 ["Available", availableOn],
690 ["Not available", unavailableOn],
691 ] as const)),
692 ["Not added", notAdded],
693 ] as const
694 ).map(([heading, environments]) =>
695 environments.length > 0 ? (
696 <div key={heading}>
697 <dt className="text-muted-foreground">{heading}</dt>
698 {environments.map((environment) => {
699 const reason =
700 heading === "Not available"
701 ? availability(environment)?.reason
702 : undefined;
703 return (
704 <dd key={environment.environmentId}>
705 <span className="block truncate">{environment.label}</span>
706 {reason ? (
707 <span className="block text-muted-foreground">{reason}</span>
708 ) : null}
709 </dd>
710 );
711 })}
712 </div>
713 ) : null,
714 )}
715 </dl>
716 ) : null}
717 </>
718 ) : several ? (
719 <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs">
720 {props.known.map((environment) => {
721 const entry = availability(environment);
722 return (
723 <Fragment key={environment.environmentId}>
724 <dt className="text-muted-foreground">{environment.label}</dt>
725 <dd className={entry?.available ? "" : "text-muted-foreground"}>
726 {entry?.available ? "Available" : (entry?.reason ?? "Not available")}
727 </dd>
728 </Fragment>
729 );
730 })}
731 </dl>
732 ) : !available ? (
733 <p className="mt-1 text-xs text-muted-foreground">
734 {availability(props.known[0]!)?.reason ?? "Not set up on this machine."}
735 </p>
736 ) : null}
737 </PopoverPopup>
738 </Popover>
739 );
741​
742function DeviceSourceRow(props: { row: SourceRow }) {
743 const { row } = props;
744 const several = row.environments.length > 1;
745 const issues = row.environments.filter(
746 (environment): environment is SourceEnvironment & { status: SourceStatus } =>
747 environment.status !== undefined,
748 );
749 const problems = issues.filter((environment) => environment.status.tone !== "pending");
750 const pending = issues.find((environment) => environment.status.tone === "pending");
751 return (
752 <div className="flex items-center gap-3 border-t border-border/60 px-3 py-3 first:border-t-0 sm:px-4">
753 <div className="min-w-0 flex-1">
754 <div className="flex min-w-0 items-center gap-1.5">
755 <p className="truncate text-sm font-medium">{row.title}</p>
756 {row.kind ? (
757 <span className="shrink-0 rounded border border-border px-1 text-3xs uppercase tracking-wide text-muted-foreground">
758 {row.kind}
759 </span>
760 ) : null}
761 </div>
762 <p className="truncate text-xs text-muted-foreground">{row.description}</p>
763 {problems.map((environment) => (
764 <p
765 key={environment.environmentId}
766 role="status"
767 className={cn(
768 "mt-1 flex flex-wrap items-center gap-1.5 text-xs",
769 environment.status.tone === "error" ? "text-destructive" : "text-warning",
770 )}
771 >
772 <span className="min-w-0 break-words">
773 {several ? `${environment.label}: ` : ""}
774 {!several && environment.status.detail
775 ? environment.status.detail
776 : environment.status.label}
777 </span>
778 {environment.status.action ? (
779 <InlineButton onClick={environment.status.action.run}>
780 {environment.status.action.label}
781 </InlineButton>
782 ) : null}
783 </p>
784 ))}
785 </div>
786 {pending ? (
787 <span
788 role="status"
789 className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
790 >
791 <Spinner size="xs" />
792 {pending.status.label}
793 </span>
794 ) : (
795 <div className="flex shrink-0 items-center gap-0.5">
796 <SourcePlatforms row={row} />
797 </div>
798 )}
799 {row.actions ? <div className="flex shrink-0 items-center gap-1">{row.actions}</div> : null}
800 </div>
801 );