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

AddProjectToMachineDialog.tsx

558 lines22.5 KB

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