|
| 1 | +import { useAtomValue } from "@effect/atom-react"; |
| 2 | +import { linkableMachines } from "@t3tools/client-runtime/link-request"; |
1 | 3 | import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; |
| 4 | +import type { EnvironmentId } from "@t3tools/contracts"; |
| 5 | +import { useEffect, useEffectEvent, useMemo } from "react"; |
2 | 6 |
|
3 | 7 | import { connectionAtomRuntime } from "../connection/runtime"; |
| 8 | +import { useEnvironments } from "./environments"; |
| 9 | +import { relayEnvironmentDiscovery } from "./relay"; |
| 10 | +import { useEnvironmentQuery } from "./query"; |
| 11 | +import { useAtomCommand } from "./use-atom-command"; |
4 | 12 |
|
5 | 13 | export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime); |
| 14 | + |
| 15 | +/** |
| 16 | + * The user's other machines, for picking one to link `environmentId` to, |
| 17 | + * including those only on their T3 Connect account. Reads that environment's |
| 18 | + * links only while `enabled`, since listing them asks every linked machine |
| 19 | + * whether it answers. |
| 20 | + */ |
| 21 | +export function useLinkableMachines(environmentId: EnvironmentId, enabled: boolean) { |
| 22 | + const { environments } = useEnvironments(); |
| 23 | + const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom); |
| 24 | + const refreshDiscovery = useAtomCommand(relayEnvironmentDiscovery.refresh, { |
| 25 | + reportFailure: false, |
| 26 | + }); |
| 27 | + // Connect hosts are listed only once something asked for them, so ask on open. |
| 28 | + const discoverIfUnasked = useEffectEvent(() => { |
| 29 | + if (discovery.environments.size === 0 && !discovery.refreshing) void refreshDiscovery(); |
| 30 | + }); |
| 31 | + // oxlint-disable-next-line t3code/react-effect-budget -- discovery follows the picker's visibility, which a card's mount or a dialog's open sets |
| 32 | + useEffect(() => { |
| 33 | + if (enabled) discoverIfUnasked(); |
| 34 | + }, [enabled]); |
| 35 | + const links = useEnvironmentQuery( |
| 36 | + enabled ? peerLinkEnvironment.list({ environmentId, input: {} }) : null, |
| 37 | + ); |
| 38 | + return useMemo( |
| 39 | + () => |
| 40 | + linkableMachines({ |
| 41 | + environments, |
| 42 | + threadEnvironmentId: environmentId, |
| 43 | + links: links.data?.links ?? [], |
| 44 | + connect: discovery.environments, |
| 45 | + }), |
| 46 | + [discovery.environments, environmentId, environments, links.data], |
| 47 | + ); |
| 48 | +} |
0 commit comments