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

CommandPalettePortForwardItems.tsx

209 lines7.8 KB

1import {
2 AuthTerminalOperateScope,
3 type DesktopPortForward,
4 type EnvironmentId,
5 type ThreadId,
6} from "@t3tools/contracts";
7import { useAtomValue } from "@effect/atom-react";
8import { useGT } from "gt-react";
9import { CableIcon, ClipboardCopyIcon, ExternalLinkIcon, SquareIcon } from "lucide-react";
10​
11import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
12import { readLocalApi } from "../localApi";
13import { useThreadDiscoveredPorts } from "../portDiscoveryState";
14import { useEnvironments } from "../state/environments";
15import {
16 canForwardPorts,
17 findPortForward,
18 forwardedUrl,
19 forwardPort,
20 forwardLocalitiesAtom,
21 stopPortForward,
22 usePortForwards,
23} from "../state/portForwards";
24import { environmentIdsKey } from "../state/environmentAtomList";
25import { useEnvironmentsWithScope } from "../state/session";
26import {
27 ADDON_ICON_CLASS,
28 ITEM_ICON_CLASS,
29 type CommandPaletteActionItem,
30 type CommandPaletteGroup,
31 type CommandPaletteSubmenuItem,
32} from "./CommandPalette.logic";
33import { toastManager } from "./ui/toast";
34​
35/** Prefix of this submenu's group values; the palette rebuilds them live while it is open. */
36export const PORT_FORWARD_GROUP_PREFIX = "port-forwards:";
37​
38const parsePort = (query: string) => {
39 const trimmed = query.trim();
40 if (!/^\d{1,5}$/.test(trimmed)) return null;
41 const port = Number(trimmed);
42 return port >= 1 && port <= 65_535 ? port : null;
43};
44​
45/** "Forwarded ports": each forward with its actions, then ports to forward from the thread or the query. */
46export function useCommandPalettePortForwardItem(input: {
47 readonly activeThread: {
48 readonly environmentId: EnvironmentId;
49 readonly id: ThreadId;
50 } | null;
51 readonly query: string;
52}): CommandPaletteSubmenuItem | null {
53 const gt = useGT();
54 const forwards = usePortForwards();
55 const { environments } = useEnvironments();
56 const reachable = environments.filter(
57 (environment) => environment.connection.phase === "connected" && canForwardPorts(environment),
58 );
59 const tunnelling = useEnvironmentsWithScope(reachable, AuthTerminalOperateScope);
60 const tunnelled = reachable.filter((environment) => tunnelling.has(environment.environmentId));
61 const localities = useAtomValue(
62 forwardLocalitiesAtom(environmentIdsKey(tunnelled.map(({ environmentId }) => environmentId))),
63 );
64 const sources = tunnelled.filter((_, index) => localities[index] === "remote");
65 // Only a forwardable thread's servers are listed, so other clients never subscribe to them.
66 const threadEnvironmentId = sources.some(
67 (environment) => environment.environmentId === input.activeThread?.environmentId,
68 )
69 ? (input.activeThread?.environmentId ?? null)
70 : null;
71 const threadServers = useThreadDiscoveredPorts({
72 environmentId: threadEnvironmentId,
73 threadId: threadEnvironmentId === null ? null : (input.activeThread?.id ?? null),
74 });
75 if (forwards.length === 0 && sources.length === 0) return null;
76​
77 const labelOf = (environmentId: EnvironmentId) =>
78 environments.find((environment) => environment.environmentId === environmentId)?.label ??
79 environmentId;
80​
81 const start = async (environmentId: EnvironmentId, remotePort: number) => {
82 const forward = await forwardPort(environmentId, remotePort);
83 toastManager.add({
84 type: "success",
85 title: gt`Forwarded port ${{ port: remotePort }}`,
86 description: gt`Apps on this machine reach it at localhost:${{ port: forward.localPort }}.`,
87 });
88 };
89​
90 const forwardedItem = (forward: DesktopPortForward): CommandPaletteSubmenuItem => {
91 const address = `localhost:${forward.localPort}`;
92 const environment = labelOf(forward.environmentId);
93 return {
94 kind: "submenu",
95 value: `port-forward:${forward.environmentId}:${forward.remotePort}`,
96 title: address,
97 description: gt`Port ${{ port: forward.remotePort }} on ${{ environment }}`,
98 searchTerms: [address, String(forward.remotePort), environment, "forwarded port"],
99 icon: <CableIcon className={ITEM_ICON_CLASS} />,
100 addonIcon: <CableIcon className={ADDON_ICON_CLASS} />,
101 groups: [
102 {
103 value: "port-forward-actions",
104 label: address,
105 items: [
106 {
107 kind: "action",
108 value: "port-forward:open",
109 title: gt`Open in browser`,
110 searchTerms: ["open", "browser"],
111 icon: <ExternalLinkIcon className={ITEM_ICON_CLASS} />,
112 run: async () => {
113 await readLocalApi()?.shell.openExternal(forwardedUrl(forward));
114 },
115 },
116 {
117 kind: "action",
118 value: "port-forward:copy",
119 title: gt`Copy address`,
120 searchTerms: ["copy", "address", "url"],
121 icon: <ClipboardCopyIcon className={ITEM_ICON_CLASS} />,
122 run: async () => {
123 await writeTextToClipboard(forwardedUrl(forward));
124 },
125 },
126 {
127 kind: "action",
128 value: "port-forward:stop",
129 title: gt`Stop forwarding`,
130 searchTerms: ["stop", "remove", "close"],
131 icon: <SquareIcon className={ITEM_ICON_CLASS} />,
132 run: () => stopPortForward(forward.environmentId, forward.remotePort),
133 },
134 ],
135 },
136 ],
137 };
138 };
139​
140 const startItems: CommandPaletteActionItem[] = [];
141 for (const server of threadServers) {
142 const environmentId = threadEnvironmentId;
143 if (environmentId === null) break;
144 if (findPortForward(forwards, environmentId, server.port)) continue;
145 startItems.push({
146 kind: "action",
147 value: `port-forward:start:${environmentId}:${server.port}`,
148 title: gt`Forward localhost:${{ port: server.port }}`,
149 description: [labelOf(environmentId), server.processName].filter(Boolean).join(" · "),
150 searchTerms: [String(server.port), server.processName ?? "", "forward"],
151 icon: <CableIcon className={ITEM_ICON_CLASS} />,
152 run: () => start(environmentId, server.port),
153 });
154 }
155 const typedPort = parsePort(input.query);
156 if (typedPort !== null) {
157 for (const environment of sources) {
158 if (findPortForward(forwards, environment.environmentId, typedPort)) continue;
159 if (
160 startItems.some((item) => item.value.endsWith(`:${environment.environmentId}:${typedPort}`))
161 )
162 continue;
163 startItems.push({
164 kind: "action",
165 value: `port-forward:start:${environment.environmentId}:${typedPort}`,
166 title: gt`Forward port ${{ port: typedPort }} from ${{ environment: environment.label }}`,
167 searchTerms: [String(typedPort), "forward"],
168 icon: <CableIcon className={ITEM_ICON_CLASS} />,
169 run: () => start(environment.environmentId, typedPort),
170 });
171 }
172 }
173​
174 const groups: CommandPaletteGroup[] = [];
175 if (forwards.length > 0) {
176 groups.push({
177 value: `${PORT_FORWARD_GROUP_PREFIX}forwarded`,
178 label: gt`Forwarded`,
179 items: forwards.map(forwardedItem),
180 });
181 }
182 if (startItems.length === 0 && sources.length > 0) {
183 startItems.push({
184 kind: "action",
185 value: "port-forward:hint",
186 title: gt`Type a port number to forward it`,
187 searchTerms: [],
188 icon: <CableIcon className={ITEM_ICON_CLASS} />,
189 disabled: true,
190 run: async () => {},
191 });
192 }
193 // Always present, so the open submenu keeps a group to be recognized by.
194 groups.push({
195 value: `${PORT_FORWARD_GROUP_PREFIX}start`,
196 label: startItems.length > 0 ? gt`Forward a port` : "",
197 items: startItems,
198 });
199​
200 return {
201 kind: "submenu",
202 value: "action:port-forwards",
203 title: gt`Forwarded ports`,
204 searchTerms: ["forward port", "port forwarding", "forwarded ports", "ports", "tunnel"],
205 icon: <CableIcon className={ITEM_ICON_CLASS} />,
206 addonIcon: <CableIcon className={ADDON_ICON_CLASS} />,
207 groups,
208 };