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

AddProjectToMachineDialog.tsx

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