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