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