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

AddProjectToMachineDialog.tsx

442 lines17.5 KB

1import { useParams } from "@tanstack/react-router";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 getAddProjectInitialQuery,
5 getCloneDestinationPath,
6 getCloneDirectoryName,
7} from "@t3tools/client-runtime/operations/projects";
8import {
9 type EnvironmentId,
10 type ProjectIgnoredFile,
11 type ScopedProjectRef,
12 resolveEnvironmentMachineKind,
13} from "@t3tools/contracts";
14import {
15 type CloneProtocol,
16 cloneUrlForProtocol,
17 cloneUrlProtocol,
18} from "@t3tools/shared/cloneUrl";
19import { ArrowRightIcon } from "lucide-react";
20import { useId, useState } from "react";
21import { create } from "zustand";
22​
23import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
24import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
25import { useNewThreadHandler } from "../hooks/useHandleNewThread";
26import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
27import {
28 COPYABLE_FILE_MAX_BYTES,
29 addProjectToMachine,
30 isDefaultCopiedFile,
31} from "../lib/addProjectToMachine";
32import { formatBytes } from "../lib/formatBytes";
33import { newProjectId } from "../lib/utils";
34import { readProject, subscribeProject, useProject } from "../state/entities";
35import { useEnvironments } from "../state/environments";
36import { projectEnvironment } from "../state/projects";
37import { useEnvironmentQuery } from "../state/query";
38import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
39import { Button } from "./ui/button";
40import { Checkbox } from "./ui/checkbox";
41import {
42 Dialog,
43 DialogDescription,
44 DialogFooter,
45 DialogHeader,
46 DialogPanel,
47 DialogPopup,
48 DialogTitle,
49} from "./ui/dialog";
50import { Input } from "./ui/input";
51import { Label } from "./ui/label";
52import { MiddleTruncate } from "./ui/middle-truncate";
53import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
54import { Toggle, ToggleGroup } from "./ui/toggle-group";
55​
56interface AddProjectToMachineRequest {
57 readonly projectRef: ScopedProjectRef;
58 readonly targetEnvironmentId: EnvironmentId | null;
60​
61const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
62 request: null,
63 session: 0,
64}));
65​
66let endRequestWithProject: (() => void) | null = null;
67​
68/** Opens the dialog that clones a project onto another connected machine. */
69export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
70 if (readProject(request.projectRef) === null) return;
71 endRequestWithProject?.();
72 // The request ends when its project goes away, so a project that comes back
73 // later cannot reopen a dialog nobody asked for.
74 endRequestWithProject = subscribeProject(request.projectRef, (project) => {
75 if (project === null) close();
76 });
77 useRequest.setState((state) => ({ request, session: state.session + 1 }));
79​
80function close() {
81 endRequestWithProject?.();
82 endRequestWithProject = null;
83 useRequest.setState({ request: null });
85​
86export function AddProjectToMachineDialogHost() {
87 const request = useRequest((state) => state.request);
88 const session = useRequest((state) => state.session);
89 return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
91​
92function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
93 const id = useId();
94 const project = useProject(request.projectRef);
95 const handleNewThread = useNewThreadHandler();
96 const { draftId: routeDraftId } = useParams({ strict: false });
97 const { environments } = useEnvironments();
98 const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
99 const [targetId, setTargetId] = useState(request.targetEnvironmentId);
100 const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
101 const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
102 const sourceUrl =
103 project?.repositoryIdentity?.origin?.remoteUrl ??
104 project?.repositoryIdentity?.locator.remoteUrl ??
105 "";
106 const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
107 const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
108 const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
109 const remoteUrl =
110 (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
111​
112 const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
113 const defaultPath = getCloneDestinationPath(
114 getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
115 getCloneDirectoryName(sourceUrl),
116 );
117 const [pathOverride, setPathOverride] = useState<string | null>(null);
118 const destinationPath = pathOverride ?? defaultPath;
119​
120 const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
121 const ignoredFiles = useEnvironmentQuery(
122 project && canListFiles
123 ? projectEnvironment.listIgnoredFiles({
124 environmentId: project.environmentId,
125 input: { cwd: project.workspaceRoot },
126 })
127 : null,
128 );
129 const files = ignoredFiles.data?.files ?? [];
130 const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
131 const selectedFiles = selected ?? defaultSelection(files);
132 const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
133 const selectedBytes = files
134 .filter((file) => selectedFiles.has(file.path))
135 .reduce((total, file) => total + file.byteLength, 0);
136​
137 const [submitting, setSubmitting] = useState(false);
138 const [error, setError] = useState<string | null>(null);
139​
140 // The project or every target can vanish while the dialog is open. Submitting
141 // before the file list loads would silently skip the default .env copies.
142 const unavailable =
143 project === null ||
144 target === null ||
145 (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
146 const toggleFile = (path: string, checked: boolean) => {
147 const next = new Set(selectedFiles);
148 if (checked) next.add(path);
149 else next.delete(path);
150 setSelected(next);
151 };
152​
153 // Lands the user on the new machine right away; its composer shows the clone
154 // and holds sends until it finishes. A draft open on the source project moves
155 // over with whatever was typed in it.
156 const openClonedProject = (targetRef: ScopedProjectRef) => {
157 const drafts = useComposerDraftStore.getState();
158 const draftId = routeDraftId as DraftId | undefined;
159 const draft = draftId ? drafts.getDraftSession(draftId) : null;
160 if (
161 draftId &&
162 draft &&
163 !draft.promotedTo &&
164 draft.environmentId === request.projectRef.environmentId &&
165 draft.projectId === request.projectRef.projectId
166 ) {
167 drafts.setDraftThreadContext(draftId, {
168 projectRef: targetRef,
169 environmentSelection: "manual",
170 loadBalancedEnvironmentId: null,
171 });
172 return;
173 }
174 void handleNewThread(targetRef);
175 };
176​
177 const submit = async () => {
178 if (!project || !target || submitting) return;
179 if (destinationPath.trim().length === 0) {
180 setError("Choose a folder on the other machine.");
181 return;
182 }
183 setSubmitting(true);
184 setError(null);
185 const projectId = newProjectId();
186 try {
187 await addProjectToMachine({
188 source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
189 subdirectory: projectSubdirectory(
190 project.repositoryIdentity?.rootPath,
191 project.workspaceRoot,
192 ),
193 target: { environmentId: target.environmentId, label: target.label },
194 projectId,
195 title: project.title,
196 remoteUrl,
197 destinationPath: destinationPath.trim(),
198 files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
199 });
200 close();
201 openClonedProject(scopeProjectRef(target.environmentId, projectId));
202 } catch (cause) {
203 setError(cause instanceof Error ? cause.message : "Could not start the clone.");
204 setSubmitting(false);
205 }
206 };
207​
208 return (
209 <Dialog
210 open
211 onOpenChange={(open) => {
212 if (!open) close();
213 }}
214 >
215 <DialogPopup className="sm:max-w-xl">
216 <form
217 className="flex min-h-0 flex-col"
218 onSubmit={(event) => {
219 event.preventDefault();
220 void submit();
221 }}
222 >
223 <DialogHeader>
224 <DialogTitle>Add to another machine</DialogTitle>
225 <DialogDescription>
226 Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
227 files git does not track.
228 </DialogDescription>
229 </DialogHeader>
230 <DialogPanel>
231 <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
232 <div className="flex min-w-0 flex-col gap-1">
233 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
234 <EnvironmentMachineIcon
235 kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
236 className="size-3.5 shrink-0"
237 />
238 <span className="truncate">{source?.label ?? "This machine"}</span>
239 </span>
240 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
241 <MiddleTruncate value={project?.workspaceRoot ?? ""} />
242 </span>
243 </div>
244 <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
245 <span>git clone</span>
246 <span className="flex w-full items-center">
247 <span className="h-px flex-1 bg-border" />
248 <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
249 </span>
250 <span>
251 {selectedFiles.size === 0
252 ? "no files"
253 : `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
254 </span>
255 </div>
256 <div className="flex min-w-0 flex-col gap-1">
257 {targets.length > 1 ? (
258 <Select
259 value={target?.environmentId ?? null}
260 onValueChange={(value) => {
261 if (value) setTargetId(value);
262 }}
263 items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
264 >
265 <SelectTrigger size="sm" aria-label="Machine to add the project to">
266 {target ? (
267 <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
268 ) : null}
269 <SelectValue />
270 </SelectTrigger>
271 <SelectPopup>
272 {targets.map((t) => (
273 <SelectItem key={t.environmentId} value={t.environmentId}>
274 <span className="inline-flex items-center gap-1.5">
275 <EnvironmentMachineIcon kind={t.machine} className="size-3" />
276 {t.label}
277 </span>
278 </SelectItem>
279 ))}
280 </SelectPopup>
281 </Select>
282 ) : (
283 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
284 {target ? (
285 <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
286 ) : null}
287 <span className="truncate">{target?.label ?? "No machine available"}</span>
288 </span>
289 )}
290 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
291 <MiddleTruncate value={destinationPath} />
292 </span>
293 </div>
294 </div>
295​
296 <div className="flex flex-col gap-1.5">
297 <Label>Clone over</Label>
298 {sshUrl && httpsUrl ? (
299 <ToggleGroup
300 aria-label="Clone protocol"
301 value={protocol ? [protocol] : []}
302 onValueChange={(next) => {
303 const value = next[0];
304 if (value === "ssh" || value === "https") setProtocol(value);
305 }}
306 >
307 <Toggle value="ssh">SSH</Toggle>
308 <Toggle value="https">HTTPS</Toggle>
309 </ToggleGroup>
310 ) : null}
311 <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
312 </div>
313​
314 <div className="flex flex-col gap-1.5">
315 <Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
316 <Input
317 id={`${id}-path`}
318 value={destinationPath}
319 onChange={(event) => setPathOverride(event.target.value)}
320 spellCheck={false}
321 autoComplete="off"
322 />
323 </div>
324​
325 {canListFiles ? (
326 <div className="flex flex-col gap-1.5">
327 <div className="flex items-center gap-2">
328 <Label className="flex-1">Copy ignored files</Label>
329 {copyable.length > 0 ? (
330 <>
331 <span className="text-muted-foreground text-xs">
332 {selectedFiles.size} of {files.length}
333 {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
334 </span>
335 <Button
336 type="button"
337 variant="ghost"
338 size="xs"
339 onClick={() =>
340 setSelected(
341 selectedFiles.size === copyable.length
342 ? new Set()
343 : new Set(copyable.map((file) => file.path)),
344 )
345 }
346 >
347 {selectedFiles.size === copyable.length ? "None" : "All"}
348 </Button>
349 </>
350 ) : null}
351 </div>
352 {ignoredFiles.error ? (
353 <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
354 ) : files.length === 0 ? (
355 <p className="text-muted-foreground text-xs">
356 {ignoredFiles.isSuccess
357 ? "No ignored files to copy."
358 : "Finding ignored files…"}
359 </p>
360 ) : (
361 <div className="max-h-52 overflow-y-auto rounded-md border">
362 {files.map((file) => (
363 <IgnoredFileRow
364 key={file.path}
365 file={file}
366 checked={selectedFiles.has(file.path)}
367 onCheckedChange={(checked) => toggleFile(file.path, checked)}
368 />
369 ))}
370 </div>
371 )}
372 {ignoredFiles.data?.truncated ? (
373 <p className="text-muted-foreground text-xs">
374 Showing the first {files.length} files.
375 </p>
376 ) : null}
377 <p className="text-muted-foreground text-xs">
378 Files are copied after the clone finishes. Folders git ignores whole, like
379 node_modules, are left out.
380 </p>
381 </div>
382 ) : null}
383​
384 {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
385 </DialogPanel>
386 <DialogFooter>
387 <Button type="button" variant="outline" onClick={close}>
388 Cancel
389 </Button>
390 <Button type="submit" disabled={unavailable || submitting}>
391 {submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
392 </Button>
393 </DialogFooter>
394 </form>
395 </DialogPopup>
396 </Dialog>
397 );
399​
400/**
401 * A project can be rooted below its repository's top folder. The clone lands
402 * at the top, so copied files keep the same path below it.
403 */
404function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
405 if (!repositoryRoot) return "";
406 const prefix = repositoryRoot.replace(/[\\/]+$/, "");
407 const rest = workspaceRoot.slice(prefix.length);
408 return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
409 ? rest.slice(1).replaceAll("\\", "/")
410 : "";
412​
413function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
414 return new Set(
415 files
416 .filter(
417 (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
418 )
419 .map((file) => file.path),
420 );
422​
423function IgnoredFileRow({
424 file,
425 checked,
426 onCheckedChange,
427}: {
428 file: ProjectIgnoredFile;
429 checked: boolean;
430 onCheckedChange: (checked: boolean) => void;
431}) {
432 const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
433 return (
434 <label className="flex cursor-pointer items-center gap-2 px-2.5 py-1.5 text-sm not-last:border-b has-disabled:cursor-not-allowed has-disabled:opacity-64">
435 <Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
436 <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
437 <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
438 {tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
439 </span>
440 </label>
441 );