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

AddProjectToMachineDialog.tsx

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