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

AddProjectToMachineDialog.tsx

579 lines23.3 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, plural, part } 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`${plural(
321 { count: selectedFiles.size },
322 {
323 one: part`+ ${{ count: selectedFiles.size }} file`,
324 other: part`+ ${{ count: selectedFiles.size }} files`,
325 },
326 )}`}
327 </span>
328 </div>
329 <div className="flex min-w-0 flex-col gap-1">
330 {targets.length > 1 ? (
331 <Select
332 value={target?.environmentId ?? null}
333 onValueChange={(value) => {
334 if (!value) return;
335 setTargetId(value);
336 setError(null);
337 }}
338 items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
339 >
340 <SelectTrigger size="sm" aria-label={gt`Machine to add the project to`}>
341 {target ? (
342 <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
343 ) : null}
344 <SelectValue />
345 </SelectTrigger>
346 <SelectPopup>
347 {targets.map((t) => (
348 <SelectItem key={t.environmentId} value={t.environmentId}>
349 <span className="inline-flex items-center gap-1.5">
350 <EnvironmentMachineIcon kind={t.machine} className="size-3" />
351 {t.label}
352 </span>
353 </SelectItem>
354 ))}
355 </SelectPopup>
356 </Select>
357 ) : (
358 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
359 {target ? (
360 <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
361 ) : null}
362 <span className="truncate">{target?.label ?? gt`No machine available`}</span>
363 </span>
364 )}
365 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
366 <MiddleTruncate value={destinationPath} />
367 </span>
368 </div>
369 </div>
370​
371 <div className="flex flex-col gap-1.5">
372 <Label>
373 <T>Clone over</T>
374 </Label>
375 {sshUrl && httpsUrl ? (
376 <ToggleGroup
377 aria-label={gt`Clone protocol`}
378 value={protocol ? [protocol] : []}
379 onValueChange={(next) => {
380 const value = next[0];
381 if (value !== "ssh" && value !== "https") return;
382 setProtocol(value);
383 setError(null);
384 }}
385 >
386 <Toggle value="ssh">SSH</Toggle>
387 <Toggle value="https">HTTPS</Toggle>
388 </ToggleGroup>
389 ) : null}
390 <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
391 </div>
392​
393 <div className="flex flex-col gap-1.5">
394 <Label htmlFor={`${id}-path`}>
395 {target
396 ? gt`Folder on ${{ machine: target.label }}`
397 : gt`Folder on the other machine`}
398 </Label>
399 <Input
400 id={`${id}-path`}
401 value={destinationPath}
402 onChange={(event) => {
403 setPathOverride(resolvePastedPath(destinationPath, event.target.value));
404 setError(null);
405 }}
406 spellCheck={false}
407 autoComplete="off"
408 />
409 </div>
410​
411 {canListFiles ? (
412 <div className="flex flex-col gap-1.5">
413 <div className="flex items-center gap-2">
414 <Label className="flex-1">
415 <T>Copy ignored files</T>
416 </Label>
417 {copyable.length > 0 ? (
418 <>
419 <span className="text-muted-foreground text-xs">
420 {gt`${{ selected: selectedFiles.size }} of ${{ total: allIgnoredFiles.data?.files.length ?? 0 }}`}
421 {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
422 </span>
423 <Button type="button" variant="ghost" size="xs" onClick={toggleShownFiles}>
424 {allCopyableSelected
425 ? gt({ context: "select no files" })`None`
426 : gt({ context: "select all files" })`All`}
427 </Button>
428 </>
429 ) : null}
430 </div>
431 {canSearchFiles && (allIgnoredFiles.data?.truncated || fileQuery.length > 0) ? (
432 // Native search inputs clear on Escape even during IME composition.
433 <Input
434 size="sm"
435 type="text"
436 role="searchbox"
437 enterKeyHint="search"
438 aria-label={gt`Search ignored files`}
439 placeholder={gt`Search ignored files`}
440 value={fileQuery}
441 maxLength={256}
442 onChange={(event) => setFileQuery(event.target.value)}
443 onKeyDown={(event) => {
444 // Enter would otherwise submit the clone.
445 if (event.key === "Enter") event.preventDefault();
446 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
447 if (event.key === "Escape" && (fileQuery || event.repeat)) {
448 event.preventDefault();
449 event.stopPropagation();
450 setFileQuery("");
451 }
452 }}
453 spellCheck={false}
454 autoComplete="off"
455 />
456 ) : null}
457 {ignoredFiles.error ? (
458 <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
459 ) : files.length === 0 ? (
460 <p className="text-muted-foreground text-xs">
461 {!ignoredFiles.isSuccess
462 ? gt`Finding ignored files…`
463 : searching
464 ? gt`No ignored files match.`
465 : gt`No ignored files to copy.`}
466 </p>
467 ) : (
468 <div className="max-h-52 overflow-y-auto rounded-md border">
469 {files.map((file) => (
470 <IgnoredFileRow
471 key={file.path}
472 file={file}
473 checked={selectedFiles.has(file.path)}
474 disabled={atSelectionLimit && !selectedFiles.has(file.path)}
475 onCheckedChange={(checked) => toggleFile(file, checked)}
476 />
477 ))}
478 </div>
479 )}
480 {ignoredFiles.data?.truncated ? (
481 <p className="text-muted-foreground text-xs">
482 {canSearchFiles
483 ? gt`${plural(
484 { count: files.length },
485 {
486 one: part`Showing the first ${{ count: files.length }} files. Search to find the rest.`,
487 other: part`Showing the first ${{ count: files.length }} files. Search to find the rest.`,
488 },
489 )}`
490 : gt`${plural(
491 { count: files.length },
492 {
493 one: part`Showing the first ${{ count: files.length }} files.`,
494 other: part`Showing the first ${{ count: files.length }} files.`,
495 },
496 )}`}
497 </p>
498 ) : null}
499 <p className="text-muted-foreground text-xs">
500 <T>
501 Files are copied after the clone finishes. Folders git ignores whole, like
502 node_modules, are left out.
503 </T>
504 </p>
505 </div>
506 ) : null}
507​
508 {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
509 </DialogPanel>
510 <DialogFooter>
511 <Button type="button" variant="outline" onClick={close}>
512 <T>Cancel</T>
513 </Button>
514 <Button type="submit" disabled={unavailable || submitting}>
515 {submitting
516 ? gt`Starting…`
517 : target
518 ? gt`Clone to ${{ machine: target.label }}`
519 : gt`Clone to machine`}
520 </Button>
521 </DialogFooter>
522 </form>
523 </DialogPopup>
524 </Dialog>
525 );
527​
528/**
529 * A project can be rooted below its repository's top folder. The clone lands
530 * at the top, so copied files keep the same path below it.
531 */
532function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
533 if (!repositoryRoot) return "";
534 const prefix = repositoryRoot.replace(/[\\/]+$/, "");
535 const rest = workspaceRoot.slice(prefix.length);
536 return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
537 ? rest.slice(1).replaceAll("\\", "/")
538 : "";
540​
541function defaultSelection(
542 files: readonly ProjectIgnoredFile[],
543): ReadonlyMap<string, ProjectIgnoredFile> {
544 return new Map(
545 files
546 .filter(
547 (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
548 )
549 .map((file) => [file.path, file]),
550 );
552​
553function IgnoredFileRow({
554 file,
555 checked,
556 disabled,
557 onCheckedChange,
558}: {
559 file: ProjectIgnoredFile;
560 checked: boolean;
561 disabled: boolean;
562 onCheckedChange: (checked: boolean) => void;
563}) {
564 const gt = useGT();
565 const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
566 return (
567 <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">
568 <Checkbox
569 checked={checked}
570 disabled={tooLarge || disabled}
571 onCheckedChange={onCheckedChange}
572 />
573 <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
574 <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
575 {tooLarge ? gt`Over 1 MB` : formatBytes(file.byteLength)}
576 </span>
577 </label>
578 );