Open History to see the last commit
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 getCloneDestinationForPickedFolder,
8 getCloneDestinationPath,
9 getCloneDirectoryLeafName,
10 getCloneDirectoryPath,
11} from "@t3tools/client-runtime/operations/projects";
12import {
13 filterFilesystemBrowseEntries,
14 getFilesystemBrowsePath,
15} from "@t3tools/client-runtime/state/filesystem";
16import {
17 ensureBrowseDirectoryPath,
18 getBrowseParentPath,
19 isExplicitRelativeProjectPath,
20} from "@t3tools/client-runtime/state/projects";
21import { isAbsolutePath, resolvePastedPath } from "@t3tools/shared/path";
22import {
23 type EnvironmentId,
24 type ProjectIgnoredFile,
25 type ScopedProjectRef,
26 resolveEnvironmentMachineKind,
27} from "@t3tools/contracts";
28import {
29 type CloneProtocol,
30 cloneUrlForProtocol,
31 cloneUrlProtocol,
32 withoutRemoteUrlCredentials,
33} from "@t3tools/shared/cloneUrl";
34import { ArrowRightIcon, FolderIcon, FolderOpenIcon } from "lucide-react";
35import { useId, useRef, useState } from "react";
36import { T, useGT, Var } from "gt-react";
37import { create } from "zustand";
38
39import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
40import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
41import { useNewThreadHandler } from "../hooks/useHandleNewThread";
42import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
43import {
44 COPIED_FILES_MAX_COUNT,
45 COPYABLE_FILE_MAX_BYTES,
46 addProjectToMachine,
47 isDefaultCopiedFile,
48} from "../lib/addProjectToMachine";
49import { formatBytes } from "../lib/formatBytes";
50import { seedDraftModelSelection } from "../lib/seedDraftModelSelection";
51import { isWindowsPlatform, newProjectId } from "../lib/utils";
52import { readProject, subscribeProject, useProject } from "../state/entities";
53import { useEnvironments } from "../state/environments";
54import { filesystemEnvironment, useFilesystemReadAccess } from "../state/filesystem";
55import { holdProjectCloneToasts, silenceProjectCloneToasts } from "../state/projectClones";
56import { projectEnvironment } from "../state/projects";
57import { useDebouncedValue } from "../state/queries";
58import { useEnvironmentQuery } from "../state/query";
59import { getEnvironmentBrowsePlatform } from "./CommandPalette.logic";
60import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
61import { Button } from "./ui/button";
62import { Checkbox } from "./ui/checkbox";
63import {
64 Dialog,
65 DialogDescription,
66 DialogFooter,
67 DialogHeader,
68 DialogPanel,
69 DialogPopup,
70 DialogTitle,
71} from "./ui/dialog";
72import { Input } from "./ui/input";
73import { Label } from "./ui/label";
74import { MiddleTruncate } from "./ui/middle-truncate";
75import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
76import { Toggle, ToggleGroup } from "./ui/toggle-group";
77
78interface AddProjectToMachineRequest {
79 readonly projectRef: ScopedProjectRef;
80 readonly targetEnvironmentId: EnvironmentId | null;
81}
82
83const FOLDER_LIST_LIMIT = 100;
84
85const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
86 request: null,
87 session: 0,
88}));
89
90let endRequestWithProject: (() => void) | null = null;
91
92/** Opens the dialog that clones a project onto another connected machine. */
93export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
94 if (readProject(request.projectRef) === null) return;
95 endRequestWithProject?.();
96 // The request ends when its project goes away, so a project that comes back
97 // later cannot reopen a dialog nobody asked for.
98 endRequestWithProject = subscribeProject(request.projectRef, (project) => {
99 if (project === null) close();
100 });
101 useRequest.setState((state) => ({ request, session: state.session + 1 }));
102}
103
104function close() {
105 endRequestWithProject?.();
106 endRequestWithProject = null;
107 useRequest.setState({ request: null });
108}
109
110export function AddProjectToMachineDialogHost() {
111 const request = useRequest((state) => state.request);
112 const session = useRequest((state) => state.session);
113 return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
114}
115
116function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
117 const gt = useGT();
118 const id = useId();
119 const project = useProject(request.projectRef);
120 const handleNewThread = useNewThreadHandler();
121 const { draftId: routeDraftId } = useParams({ strict: false });
122 const { environments } = useEnvironments();
123 const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
124 const [targetId, setTargetId] = useState(request.targetEnvironmentId);
125 const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
126 const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
127 // An environment on an older version reports the remote URL as configured, login included.
128 const sourceUrl = withoutRemoteUrlCredentials(
129 project?.repositoryIdentity?.origin?.remoteUrl ??
130 project?.repositoryIdentity?.locator.remoteUrl ??
131 "",
132 );
133 const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
134 const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
135 const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
136 const remoteUrl =
137 (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
138
139 const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
140 const platform = getEnvironmentBrowsePlatform(
141 targetEnvironment?.serverConfig?.environment.platform.os,
142 );
143 const ghqCloneLayout = targetEnvironment?.serverConfig?.settings.ghqCloneLayout === true;
144 const defaultPath = getCloneDestinationPath(
145 getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
146 getCloneDirectoryPath(sourceUrl, ghqCloneLayout),
147 );
148 const [pathByTarget, setPathByTarget] = useState<Partial<Record<EnvironmentId, string>>>({});
149 const [browseTargetId, setBrowseTargetId] = useState<EnvironmentId | null>(null);
150 const browseButton = useRef<HTMLButtonElement>(null);
151 const browsing = target !== null && target.environmentId === browseTargetId;
152 const destinationPath = (target && pathByTarget[target.environmentId]) ?? defaultPath;
153 const setDestinationPath = (path: string) => {
154 if (target) setPathByTarget((paths) => ({ ...paths, [target.environmentId]: path }));
155 };
156 const closeFolderPicker = () => {
157 setBrowseTargetId(null);
158 browseButton.current?.focus();
159 };
160
161 const capabilities = source?.serverConfig?.environment.capabilities;
162 const canListFiles = capabilities?.ignoredFileListing === true;
163 const canSearchFiles = canListFiles && capabilities?.ignoredFileSearch === true;
164 const allIgnoredFiles = useEnvironmentQuery(
165 project && canListFiles
166 ? projectEnvironment.listIgnoredFiles({
167 environmentId: project.environmentId,
168 input: { cwd: project.workspaceRoot },
169 })
170 : null,
171 );
172 const [fileQuery, setFileQuery] = useState("");
173 const sentFileQuery = useDebouncedValue(fileQuery.trim(), 120);
174 const searching = canSearchFiles && sentFileQuery.length > 0;
175 const searchedFiles = useEnvironmentQuery(
176 project && searching
177 ? projectEnvironment.listIgnoredFiles({
178 environmentId: project.environmentId,
179 input: { cwd: project.workspaceRoot, query: sentFileQuery },
180 })
181 : null,
182 );
183 const ignoredFiles = searching ? searchedFiles : allIgnoredFiles;
184 const files = ignoredFiles.data?.files ?? [];
185 // Keyed by path with the file kept, so picks made under one search survive the next.
186 const [selected, setSelected] = useState<ReadonlyMap<string, ProjectIgnoredFile> | null>(null);
187 const selectedFiles = selected ?? defaultSelection(allIgnoredFiles.data?.files ?? []);
188 const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
189 const allCopyableSelected = copyable.every((file) => selectedFiles.has(file.path));
190 const atSelectionLimit = selectedFiles.size >= COPIED_FILES_MAX_COUNT;
191 const selectedBytes = [...selectedFiles.values()].reduce(
192 (total, file) => total + file.byteLength,
193 0,
194 );
195
196 const [submitting, setSubmitting] = useState(false);
197 const [error, setError] = useState<string | null>(null);
198
199 // The project or every target can vanish while the dialog is open. Submitting
200 // before the file list loads would silently skip the default .env copies.
201 const unavailable =
202 project === null ||
203 target === null ||
204 (canListFiles && allIgnoredFiles.data === null && allIgnoredFiles.error === null);
205 const toggleFile = (file: ProjectIgnoredFile, checked: boolean) => {
206 const next = new Map(selectedFiles);
207 if (!checked) next.delete(file.path);
208 else if (!atSelectionLimit) next.set(file.path, file);
209 setSelected(next);
210 };
211 const toggleShownFiles = () => {
212 const next = new Map(selectedFiles);
213 for (const file of copyable) {
214 if (allCopyableSelected) next.delete(file.path);
215 else if (next.size < COPIED_FILES_MAX_COUNT) next.set(file.path, file);
216 }
217 setSelected(next);
218 };
219
220 // Lands the user on the new machine right away; its composer shows the clone
221 // and holds sends until it finishes. A draft open on the source project moves
222 // over with whatever was typed in it.
223 const openClonedProject = (targetRef: ScopedProjectRef) => {
224 const drafts = useComposerDraftStore.getState();
225 const draftId = routeDraftId as DraftId | undefined;
226 const draft = draftId ? drafts.getDraftSession(draftId) : null;
227 if (
228 draftId &&
229 draft &&
230 !draft.promotedTo &&
231 draft.environmentId === request.projectRef.environmentId &&
232 draft.projectId === request.projectRef.projectId
233 ) {
234 drafts.setDraftThreadContext(draftId, {
235 projectRef: targetRef,
236 environmentSelection: "manual",
237 loadBalancedEnvironmentId: null,
238 });
239 seedDraftModelSelection(draftId, targetRef);
240 return;
241 }
242 void handleNewThread(targetRef);
243 };
244
245 const submit = async () => {
246 if (!project || !target || submitting || browsing) return;
247 if (destinationPath.trim().length === 0) {
248 setError(gt("Choose a folder on the other machine."));
249 return;
250 }
251 setSubmitting(true);
252 setError(null);
253 const requestedId = newProjectId();
254 // The clone list can arrive before the start reply.
255 const releaseToastHold = holdProjectCloneToasts(
256 scopeProjectRef(target.environmentId, requestedId),
257 );
258 try {
259 const projectId = await addProjectToMachine({
260 source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
261 subdirectory: projectSubdirectory(
262 project.repositoryIdentity?.rootPath,
263 project.workspaceRoot,
264 ),
265 target: { environmentId: target.environmentId, label: target.label },
266 projectId: requestedId,
267 title: project.title,
268 remoteUrl,
269 destinationPath: destinationPath.trim(),
270 files: [...selectedFiles.keys()],
271 });
272 if (useRequest.getState().request === request) {
273 const targetRef = scopeProjectRef(target.environmentId, projectId);
274 silenceProjectCloneToasts(targetRef);
275 close();
276 openClonedProject(targetRef);
277 }
278 } catch (cause) {
279 setError(thrownErrorMessage(cause, m) ?? gt("Could not start the clone."));
280 setSubmitting(false);
281 }
282 releaseToastHold();
283 };
284
285 return (
286 <Dialog
287 open
288 onOpenChange={(open, eventDetails) => {
289 if (open) return;
290 if (eventDetails.reason === "escape-key" && (browsing || eventDetails.event.repeat)) {
291 eventDetails.cancel();
292 if (browsing) closeFolderPicker();
293 return;
294 }
295 close();
296 }}
297 >
298 <DialogPopup className="sm:max-w-xl">
299 <form
300 className="flex min-h-0 flex-col"
301 onSubmit={(event) => {
302 event.preventDefault();
303 void submit();
304 }}
305 >
306 <DialogHeader>
307 <DialogTitle>
308 <T>Add to another machine</T>
309 </DialogTitle>
310 <DialogDescription>
311 <T>
312 Clone <Var>{project?.repositoryIdentity?.displayName ?? project?.title}</Var> and
313 bring the local files git does not track.
314 </T>
315 </DialogDescription>
316 </DialogHeader>
317 <DialogPanel>
318 <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
319 <div className="flex min-w-0 flex-col gap-1">
320 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
321 <EnvironmentMachineIcon
322 kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
323 className="size-3.5 shrink-0"
324 />
325 <span className="truncate">{source?.label ?? gt("This machine")}</span>
326 </span>
327 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
328 <MiddleTruncate value={project?.workspaceRoot ?? ""} />
329 </span>
330 </div>
331 <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
332 {/* oxlint-disable-next-line t3code/no-untranslated-copy -- git command name */}
333 <span>git clone</span>
334 <span className="flex w-full items-center">
335 <span className="h-px flex-1 bg-border" />
336 <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
337 </span>
338 <span>
339 {selectedFiles.size === 0
340 ? gt("no files")
341 : gt("{count, plural, one {+ {count} file} other {+ {count} files}}", {
342 count: selectedFiles.size,
343 })}
344 </span>
345 </div>
346 <div className="flex min-w-0 flex-col gap-1">
347 {targets.length > 1 ? (
348 <Select
349 value={target?.environmentId ?? null}
350 onValueChange={(value) => {
351 if (value) {
352 setTargetId(value);
353 setBrowseTargetId(null);
354 }
355 }}
356 items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
357 >
358 <SelectTrigger size="sm" aria-label={gt("Machine to add the project to")}>
359 {target ? (
360 <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
361 ) : null}
362 <SelectValue />
363 </SelectTrigger>
364 <SelectPopup>
365 {targets.map((t) => (
366 <SelectItem key={t.environmentId} value={t.environmentId}>
367 <span className="inline-flex items-center gap-1.5">
368 <EnvironmentMachineIcon kind={t.machine} className="size-3" />
369 {t.label}
370 </span>
371 </SelectItem>
372 ))}
373 </SelectPopup>
374 </Select>
375 ) : (
376 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
377 {target ? (
378 <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
379 ) : null}
380 <span className="truncate">{target?.label ?? gt("No machine available")}</span>
381 </span>
382 )}
383 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
384 <MiddleTruncate value={destinationPath} />
385 </span>
386 </div>
387 </div>
388
389 <div className="flex flex-col gap-1.5">
390 <Label>
391 <T>Clone over</T>
392 </Label>
393 {sshUrl && httpsUrl ? (
394 <ToggleGroup
395 aria-label={gt("Clone protocol")}
396 value={protocol ? [protocol] : []}
397 onValueChange={(next) => {
398 const value = next[0];
399 if (value === "ssh" || value === "https") setProtocol(value);
400 }}
401 >
402 <Toggle value="ssh">SSH</Toggle>
403 <Toggle value="https">HTTPS</Toggle>
404 </ToggleGroup>
405 ) : null}
406 <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
407 </div>
408
409 <div className="flex flex-col gap-1.5">
410 <Label htmlFor={`${id}-path`}>
411 {target
412 ? gt("Folder on {machine}", { machine: target.label })
413 : gt("Folder on the other machine")}
414 </Label>
415 <div className="flex gap-2">
416 <Input
417 id={`${id}-path`}
418 value={destinationPath}
419 onChange={(event) =>
420 setDestinationPath(resolvePastedPath(destinationPath, event.target.value))
421 }
422 disabled={!target || submitting}
423 spellCheck={false}
424 autoComplete="off"
425 />
426 {target ? (
427 <Button
428 ref={browseButton}
429 type="button"
430 variant="outline"
431 disabled={submitting}
432 aria-expanded={browsing}
433 aria-controls={browsing ? `${id}-picker` : undefined}
434 onClick={() => setBrowseTargetId(browsing ? null : target.environmentId)}
435 >
436 <FolderOpenIcon />
437 <T>Browse</T>
438 </Button>
439 ) : null}
440 </div>
441 {browsing ? (
442 <CloneFolderPicker
443 key={target.environmentId}
444 id={`${id}-picker`}
445 environmentId={target.environmentId}
446 platform={platform}
447 destinationPath={destinationPath}
448 onClose={closeFolderPicker}
449 onChoose={(pickedPath) => {
450 setDestinationPath(
451 getCloneDestinationForPickedFolder({
452 pickedPath,
453 cloneDirectoryName: getCloneDirectoryLeafName(sourceUrl, ghqCloneLayout),
454 caseSensitive: !isWindowsPlatform(platform),
455 }),
456 );
457 closeFolderPicker();
458 }}
459 />
460 ) : null}
461 </div>
462
463 {canListFiles ? (
464 <div className="flex flex-col gap-1.5">
465 <div className="flex items-center gap-2">
466 <Label className="flex-1">
467 <T>Copy ignored files</T>
468 </Label>
469 {copyable.length > 0 ? (
470 <>
471 <span className="text-muted-foreground text-xs">
472 {gt("{selected} of {total}", {
473 selected: selectedFiles.size,
474 total: allIgnoredFiles.data?.files.length ?? 0,
475 })}
476 {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
477 </span>
478 <Button type="button" variant="ghost" size="xs" onClick={toggleShownFiles}>
479 {allCopyableSelected
480 ? gt("None", { $context: "select no files" })
481 : gt("All", { $context: "select all files" })}
482 </Button>
483 </>
484 ) : null}
485 </div>
486 {canSearchFiles && (allIgnoredFiles.data?.truncated || fileQuery.length > 0) ? (
487 // Native search inputs clear on Escape even during IME composition.
488 <Input
489 size="sm"
490 type="text"
491 role="searchbox"
492 enterKeyHint="search"
493 aria-label={gt("Search ignored files")}
494 placeholder={gt("Search ignored files")}
495 value={fileQuery}
496 maxLength={256}
497 onChange={(event) => setFileQuery(event.target.value)}
498 onKeyDown={(event) => {
499 // Enter would otherwise submit the clone.
500 if (event.key === "Enter") event.preventDefault();
501 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
502 if (event.key === "Escape" && (fileQuery || event.repeat)) {
503 event.preventDefault();
504 event.stopPropagation();
505 setFileQuery("");
506 }
507 }}
508 spellCheck={false}
509 autoComplete="off"
510 />
511 ) : null}
512 {ignoredFiles.error ? (
513 <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
514 ) : files.length === 0 ? (
515 <p className="text-muted-foreground text-xs">
516 {!ignoredFiles.isSuccess
517 ? gt("Finding ignored files…")
518 : searching
519 ? gt("No ignored files match.")
520 : gt("No ignored files to copy.")}
521 </p>
522 ) : (
523 <div className="max-h-52 overflow-y-auto rounded-md border">
524 {files.map((file) => (
525 <IgnoredFileRow
526 key={file.path}
527 file={file}
528 checked={selectedFiles.has(file.path)}
529 disabled={atSelectionLimit && !selectedFiles.has(file.path)}
530 onCheckedChange={(checked) => toggleFile(file, checked)}
531 />
532 ))}
533 </div>
534 )}
535 {ignoredFiles.data?.truncated ? (
536 <p className="text-muted-foreground text-xs">
537 {canSearchFiles
538 ? gt(
539 "{count, plural, one {Showing the first {count} files. Search to find the rest.} other {Showing the first {count} files. Search to find the rest.}}",
540 {
541 count: files.length,
542 },
543 )
544 : gt(
545 "{count, plural, one {Showing the first {count} files.} other {Showing the first {count} files.}}",
546 { count: files.length },
547 )}
548 </p>
549 ) : null}
550 <p className="text-muted-foreground text-xs">
551 <T>
552 Files are copied after the clone finishes. Folders git ignores whole, like
553 node_modules, are left out.
554 </T>
555 </p>
556 </div>
557 ) : null}
558
559 {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
560 </DialogPanel>
561 <DialogFooter>
562 <Button type="button" variant="outline" onClick={close}>
563 <T>Cancel</T>
564 </Button>
565 <Button type="submit" disabled={unavailable || submitting || browsing}>
566 {submitting
567 ? gt("Starting…")
568 : target
569 ? gt("Clone to {machine}", { machine: target.label })
570 : gt("Clone to machine")}
571 </Button>
572 </DialogFooter>
573 </form>
574 </DialogPopup>
575 </Dialog>
576 );
577}
578
579function CloneFolderPicker(props: {
580 readonly id: string;
581 readonly environmentId: EnvironmentId;
582 readonly platform: string;
583 readonly destinationPath: string;
584 readonly onClose: () => void;
585 readonly onChoose: (directory: string) => void;
586}) {
587 const gt = useGT();
588 const [query, setQuery] = useState(() => {
589 const path = props.destinationPath.trim();
590 const directory = getBrowseParentPath(path) ?? (isAbsolutePath(path) ? path : "~/");
591 return isExplicitRelativeProjectPath(directory) ? "~/" : ensureBrowseDirectoryPath(directory);
592 });
593 const access = useFilesystemReadAccess(props.environmentId);
594 const browsePath = getFilesystemBrowsePath(query, props.platform, access.canReadFiles);
595 const listing = useEnvironmentQuery(
596 browsePath.isBrowsing &&
597 browsePath.directoryPath &&
598 !isExplicitRelativeProjectPath(browsePath.directoryPath)
599 ? filesystemEnvironment.browse({
600 environmentId: props.environmentId,
601 input: { partialPath: browsePath.directoryPath },
602 })
603 : null,
604 );
605 const directory = listing.data?.parentPath ?? null;
606 const parent = directory && getBrowseParentPath(directory);
607 const { visibleEntries, exactEntry } = filterFilesystemBrowseEntries(
608 listing.data?.entries ?? [],
609 browsePath.filterQuery,
610 );
611 const selected = browsePath.filterQuery ? exactEntry?.fullPath : directory;
612 const error = access.error ?? listing.error;
613 const pending = access.isPending || listing.isPending;
614
615 return (
616 <section
617 id={props.id}
618 aria-label={gt("Choose clone location")}
619 className="flex flex-col gap-2 rounded-md border p-3"
620 >
621 <div className="flex flex-col gap-2">
622 <Label htmlFor={`${props.id}-path`}>
623 <T>Folder path</T>
624 </Label>
625 <Input
626 id={`${props.id}-path`}
627 font="mono"
628 value={query}
629 onChange={(event) => setQuery(event.currentTarget.value)}
630 disabled={!access.canReadFiles}
631 autoComplete="off"
632 spellCheck={false}
633 />
634 </div>
635 <div className="flex max-h-40 min-h-16 flex-col overflow-y-auto">
636 {parent ? (
637 <FolderBrowseRow label={gt("Parent folder")} onClick={() => setQuery(parent)} />
638 ) : null}
639 {visibleEntries.slice(0, FOLDER_LIST_LIMIT).map((entry) => (
640 <FolderBrowseRow
641 key={entry.fullPath}
642 label={entry.name}
643 onClick={() => setQuery(ensureBrowseDirectoryPath(entry.fullPath))}
644 />
645 ))}
646 {error ? (
647 <p role="alert" className="text-destructive-foreground text-sm">
648 {error}
649 </p>
650 ) : pending ? (
651 <p role="status" className="text-muted-foreground text-sm">
652 <T>Loading folders…</T>
653 </p>
654 ) : !access.canReadFiles ? (
655 <p className="text-muted-foreground text-sm">
656 {gt("This connection cannot browse host folders.")}
657 </p>
658 ) : visibleEntries.length > FOLDER_LIST_LIMIT ? (
659 <p className="text-muted-foreground text-sm">
660 <T>
661 <Var>{visibleEntries.length - FOLDER_LIST_LIMIT}</Var> more. Keep typing to narrow the
662 list.
663 </T>
664 </p>
665 ) : directory && visibleEntries.length === 0 ? (
666 <p className="text-muted-foreground text-sm">
667 <T>No folders found.</T>
668 </p>
669 ) : null}
670 </div>
671 <div className="flex flex-wrap items-center justify-end gap-2">
672 <Button type="button" size="sm" variant="outline" onClick={props.onClose}>
673 <T>Cancel</T>
674 </Button>
675 <Button
676 type="button"
677 size="sm"
678 disabled={!selected || !!error || pending}
679 onClick={() => selected && props.onChoose(selected)}
680 >
681 <T>Set clone location</T>
682 </Button>
683 </div>
684 </section>
685 );
686}
687
688function FolderBrowseRow({ label, onClick }: { label: string; onClick: () => void }) {
689 return (
690 <button
691 type="button"
692 className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-start text-sm outline-none hover:bg-muted/50 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"
693 onClick={onClick}
694 >
695 <FolderIcon className="size-4 shrink-0 text-muted-foreground" />
696 <span className="min-w-0 truncate">{label}</span>
697 </button>
698 );
699}
700
701/**
702 * A project can be rooted below its repository's top folder. The clone lands
703 * at the top, so copied files keep the same path below it.
704 */
705function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
706 if (!repositoryRoot) return "";
707 const prefix = repositoryRoot.replace(/[\\/]+$/, "");
708 const rest = workspaceRoot.slice(prefix.length);
709 return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
710 ? rest.slice(1).replaceAll("\\", "/")
711 : "";
712}
713
714function defaultSelection(
715 files: readonly ProjectIgnoredFile[],
716): ReadonlyMap<string, ProjectIgnoredFile> {
717 return new Map(
718 files
719 .filter(
720 (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
721 )
722 .map((file) => [file.path, file]),
723 );
724}
725
726function IgnoredFileRow({
727 file,
728 checked,
729 disabled,
730 onCheckedChange,
731}: {
732 file: ProjectIgnoredFile;
733 checked: boolean;
734 disabled: boolean;
735 onCheckedChange: (checked: boolean) => void;
736}) {
737 const gt = useGT();
738 const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
739 return (
740 <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">
741 <Checkbox
742 checked={checked}
743 disabled={tooLarge || disabled}
744 onCheckedChange={onCheckedChange}
745 />
746 <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
747 <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
748 {tooLarge ? gt("Over 1 MB") : formatBytes(file.byteLength)}
749 </span>
750 </label>
751 );
752}