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

AddProjectToMachineDialog.tsx

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