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

ConnectionsSettings.logic.ts

64 lines2.5 KB

1import type { AdvertisedEndpoint, DesktopBridge, DesktopWslState } from "@t3tools/contracts";
2​
3type WslEnableBridge = Pick<DesktopBridge, "setWslBackendEnabled" | "setWslDistro" | "setWslOnly">;
4​
5/**
6 * A QR code encoding a loopback URL makes the scanning device dial itself, so
7 * loopback endpoints stay copyable from the endpoint menu but are never
8 * offered as QR targets.
9 */
10export function isQrShareableEndpoint(endpoint: AdvertisedEndpoint): boolean {
11 return endpoint.status !== "unavailable" && endpoint.reachability !== "loopback";
13​
14export type QrEndpointOption = {
15 /** Unique per endpoint instance (AdvertisedEndpoint.id); safe as a React key. */
16 readonly id: string;
17 /**
18 * Stable per endpoint *type* (endpointDefaultPreferenceKey). Multiple
19 * endpoints can share one, so it is only used to match the saved default.
20 */
21 readonly preferenceKey: string;
22 /** False for endpoints that stay copyable but must never render as a QR. */
23 readonly qrShareable: boolean;
24};
25​
26/**
27 * Resolves which endpoint the share panel shows: the user's explicit pick,
28 * else the saved default endpoint, else the first QR-shareable option (so the
29 * panel never opens on a loopback QR), else the first option. A stale
30 * selectedId (endpoint disappeared) falls back rather than blanking the panel.
31 */
32export function selectQrEndpointOption<T extends QrEndpointOption>(
33 options: ReadonlyArray<T>,
34 selectedId: string | null,
35 defaultPreferenceKey: string | null,
36): T | null {
37 return (
38 (selectedId !== null ? options.find((option) => option.id === selectedId) : undefined) ??
39 (defaultPreferenceKey !== null
40 ? options.find((option) => option.preferenceKey === defaultPreferenceKey)
41 : undefined) ??
42 options.find((option) => option.qrShareable) ??
43 options[0] ??
44 null
45 );
47​
48export async function applyWslEnableSelection(input: {
49 readonly bridge: WslEnableBridge;
50 readonly mode: "both" | "wsl-only";
51 readonly nextDistro: string | null;
52 readonly persistedDistro: string | null;
53}): Promise<DesktopWslState> {
54 const { bridge, mode, nextDistro, persistedDistro } = input;
55​
56 // Stage every preference before enabling. The desktop only relaunches for
57 // mode/distro changes while WSL is active, so the final enable observes the
58 // complete selection and is the only call that may relaunch.
59 await bridge.setWslOnly(mode === "wsl-only");
60 if (persistedDistro !== nextDistro) {
61 await bridge.setWslDistro(nextDistro);
62 }
63 return await bridge.setWslBackendEnabled(true);