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

AddProjectToMachineDialog.tsx

493 lines19.7 KB

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