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

DeviceSourcesSettings.tsx

879 lines32.8 KB

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