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

ProjectRepositoriesSettings.tsx

397 lines14.2 KB

1import {
2 filterFilesystemBrowseEntries,
3 getFilesystemBrowsePath,
4} from "@t3tools/client-runtime/state/filesystem";
5import {
6 appendBrowsePathSegment,
7 ensureBrowseDirectoryPath,
8 getBrowseParentPath,
9} from "@t3tools/client-runtime/state/projects";
10import {
11 AuthOrchestrationOperateScope,
12 PROJECT_TRACKED_FOLDERS_MAX,
13 type EnvironmentId,
14 type ProjectTrackedFolder,
15 type WorkspaceFolderState,
16 type WorkspaceScanFoldersResult,
17 type WorkspaceScannedFolder,
18} from "@t3tools/contracts";
19import { FolderIcon, PlusIcon } from "lucide-react";
20import { useId, useState } from "react";
21​
22import { checkProjectAccess, reportProjectFailure } from "../../hooks/useProjectGroupUpdate";
23import type { SidebarProjectGroupMember } from "../../sidebarProjectGrouping";
24import { useEnvironments } from "../../state/environments";
25import { filesystemEnvironment, useFilesystemReadAccess } from "../../state/filesystem";
26import { projectEnvironment } from "../../state/projects";
27import { useEnvironmentQuery } from "../../state/query";
28import { useEnvironmentScope } from "../../state/session";
29import { useAtomQueryRunner } from "../../state/use-atom-query-runner";
30import { useOrchestrationCommand } from "../../state/use-orchestration-command";
31import { getEnvironmentBrowsePlatform } from "../CommandPalette.logic";
32import { TrackedFoldersDialog } from "../TrackedFoldersDialog";
33import {
34 mergeScannedTrackedFolders,
35 resolveTrackedFolderInput,
36 trackedFolderDisplayPath,
37 untrackedScannedPaths,
38} from "../TrackedFoldersDialog.logic";
39import { Badge } from "../ui/badge";
40import { Button } from "../ui/button";
41import {
42 Dialog,
43 DialogDescription,
44 DialogFooter,
45 DialogHeader,
46 DialogPanel,
47 DialogPopup,
48 DialogTitle,
49} from "../ui/dialog";
50import { Input } from "../ui/input";
51import { Label } from "../ui/label";
52import { stackedThreadToast, toastManager } from "../ui/toast";
53import { SettingsRow, SettingsSection } from "./settingsLayout";
54​
55const NO_TRACKED_FOLDERS: ReadonlyArray<ProjectTrackedFolder> = [];
56const BROWSE_SUGGESTION_LIMIT = 100;
57​
58const FOLDER_STATE_LABELS: Record<WorkspaceFolderState, string> = {
59 git: "Git repository",
60 plain: "Folder",
61 missing: "Missing",
62};
63​
64/** Tracked folder paths belong to one checkout's machine, so each checkout has its own list. */
65export function ProjectRepositoriesSettings({
66 members,
67}: {
68 members: ReadonlyArray<SidebarProjectGroupMember>;
69}) {
70 const checkouts = members.filter((member) => !member.isScratch);
71 if (checkouts.length === 0) return null;
72 return (
73 <SettingsSection id="project-repositories" title="Repositories">
74 {checkouts.map((member) => (
75 <CheckoutRepositories key={member.physicalProjectKey} member={member} />
76 ))}
77 </SettingsSection>
78 );
80​
81function CheckoutRepositories({ member }: { member: SidebarProjectGroupMember }) {
82 const environmentId = member.environmentId;
83 const { environments } = useEnvironments();
84 const environment = environments.find((entry) => entry.environmentId === environmentId);
85 const isConnected = environment?.connection.phase === "connected";
86 const canEdit = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
87 const access = useFilesystemReadAccess(environmentId);
88 const tracked = member.trackedFolders ?? NO_TRACKED_FOLDERS;
89 // The project carries the list; this query only says what each folder is on disk right now.
90 const listQuery = useEnvironmentQuery(
91 access.canReadFiles && tracked.length > 0
92 ? filesystemEnvironment.listFolders({ environmentId, input: { projectId: member.id } })
93 : null,
94 );
95 const stateByPath = new Map(
96 (listQuery.data?.folders ?? []).map((folder) => [folder.path, folder.state]),
97 );
98 const updateProject = useOrchestrationCommand(projectEnvironment.update, {
99 reportFailure: false,
100 });
101 const scanFolders = useAtomQueryRunner(filesystemEnvironment.scanFolders, {
102 reportFailure: false,
103 reportDefect: false,
104 refresh: true,
105 });
106 const [isSaving, setIsSaving] = useState(false);
107 const [isScanning, setIsScanning] = useState(false);
108 const [rescan, setRescan] = useState<WorkspaceScanFoldersResult | null>(null);
109 const [isAddingFolder, setIsAddingFolder] = useState(false);
110 const disabled = !canEdit || !isConnected || isSaving;
111​
112 const save = async (next: ReadonlyArray<ProjectTrackedFolder>, failureTitle: string) => {
113 if (checkProjectAccess([member], failureTitle)) return false;
114 setIsSaving(true);
115 const result = await updateProject({
116 environmentId,
117 input: { projectId: member.id, trackedFolders: next },
118 });
119 setIsSaving(false);
120 if (result._tag === "Failure") {
121 reportProjectFailure(failureTitle, result);
122 return false;
123 }
124 listQuery.refresh();
125 return true;
126 };
127​
128 const runRescan = async () => {
129 setIsScanning(true);
130 const result = await scanFolders({
131 environmentId,
132 input: { workspaceRoot: member.workspaceRoot },
133 });
134 setIsScanning(false);
135 if (result._tag === "Failure") {
136 reportProjectFailure("Failed to scan for repositories", result);
137 return;
138 }
139 if (result.value.folders.length === 0) {
140 toastManager.add(
141 stackedThreadToast({
142 type: "info",
143 title: "No repositories found",
144 description: `Nothing to track inside ${member.workspaceRoot}.`,
145 }),
146 );
147 return;
148 }
149 setRescan(result.value);
150 };
151​
152 const saveRescan = async (
153 scan: WorkspaceScanFoldersResult,
154 checked: ReadonlyArray<WorkspaceScannedFolder>,
155 ) => {
156 const next = mergeScannedTrackedFolders({ tracked, scanned: scan.folders, checked });
157 if (await save(next, "Failed to save repositories")) setRescan(null);
158 };
159​
160 const addFolder = async (folder: ProjectTrackedFolder) => {
161 if (await save([...tracked, folder], "Failed to add folder")) setIsAddingFolder(false);
162 };
163​
164 const scannedButUntracked = rescan ? untrackedScannedPaths(tracked, rescan.folders) : null;
165​
166 return (
167 <>
168 <SettingsRow
169 title={member.environmentLabel ?? "Environment"}
170 description={member.workspaceRoot}
171 control={
172 <div className="flex flex-wrap items-center gap-1.5">
173 <Button
174 size="xs"
175 variant="ghost"
176 disabled={disabled || isScanning || !access.canReadFiles}
177 onClick={() => void runRescan()}
178 >
179 {isScanning ? "Scanning…" : "Rescan"}
180 </Button>
181 <Button
182 size="xs"
183 variant="outline"
184 disabled={disabled || tracked.length >= PROJECT_TRACKED_FOLDERS_MAX}
185 onClick={() => setIsAddingFolder(true)}
186 >
187 <PlusIcon className="size-3.5" />
188 Add folder
189 </Button>
190 </div>
191 }
192 />
193 {tracked.length === 0 ? (
194 <p className="px-3 py-2 text-base text-muted-foreground sm:px-4 sm:text-sm">
195 Track a repository to give it its own changes and review, and to let agents work across it
196 and this folder.
197 </p>
198 ) : (
199 tracked.map((folder) => {
200 const state = stateByPath.get(folder.path);
201 return (
202 <SettingsRow
203 key={folder.path}
204 className="py-2"
205 title={
206 <span className="flex min-w-0 items-center gap-2">
207 <span className="min-w-0 truncate">{folder.name}</span>
208 {state ? (
209 <Badge size="sm" variant={state === "missing" ? "warning" : "outline"}>
210 {FOLDER_STATE_LABELS[state]}
211 </Badge>
212 ) : null}
213 </span>
214 }
215 description={
216 <code className="block max-w-full truncate font-mono">
217 {trackedFolderDisplayPath(folder.path, member.workspaceRoot)}
218 </code>
219 }
220 control={
221 <Button
222 size="xs"
223 variant="ghost"
224 disabled={disabled}
225 aria-label={`Stop tracking ${folder.name}`}
226 onClick={() =>
227 void save(
228 tracked.filter((candidate) => candidate.path !== folder.path),
229 "Failed to remove repository",
230 )
231 }
232 >
233 Remove
234 </Button>
235 }
236 />
237 );
238 })
239 )}
240 {listQuery.error ? (
241 <p role="alert" className="px-3 py-2 text-xs text-warning-foreground sm:px-4">
242 {listQuery.error}
243 </p>
244 ) : null}
245 {rescan && scannedButUntracked ? (
246 <TrackedFoldersDialog
247 mode="edit"
248 scan={rescan}
249 maxChecked={
250 PROJECT_TRACKED_FOLDERS_MAX -
251 (tracked.length - (rescan.folders.length - scannedButUntracked.size))
252 }
253 newPaths={scannedButUntracked}
254 busy={isSaving}
255 onConfirm={(checked) => void saveRescan(rescan, checked)}
256 onClose={() => setRescan(null)}
257 />
258 ) : null}
259 {isAddingFolder ? (
260 <AddTrackedFolderDialog
261 environmentId={environmentId}
262 workspaceRoot={member.workspaceRoot}
263 platform={getEnvironmentBrowsePlatform(
264 environment?.serverConfig?.environment.platform.os,
265 )}
266 canBrowse={access.canReadFiles}
267 busy={isSaving}
268 onAdd={(folder) => void addFolder(folder)}
269 onClose={() => setIsAddingFolder(false)}
270 />
271 ) : null}
272 </>
273 );
275​
276function AddTrackedFolderDialog(props: {
277 readonly environmentId: EnvironmentId;
278 readonly workspaceRoot: string;
279 readonly platform: string;
280 readonly canBrowse: boolean;
281 readonly busy: boolean;
282 readonly onAdd: (folder: ProjectTrackedFolder) => void;
283 readonly onClose: () => void;
284}) {
285 const inputId = useId();
286 // Repositories next to the project folder are the common case, so the listing starts there.
287 const [query, setQuery] = useState(
288 () =>
289 getBrowseParentPath(props.workspaceRoot) ?? ensureBrowseDirectoryPath(props.workspaceRoot),
290 );
291 const browsePath = getFilesystemBrowsePath(query, props.platform, props.canBrowse);
292 const browseQuery = useEnvironmentQuery(
293 browsePath.isBrowsing && browsePath.directoryPath.length > 0
294 ? filesystemEnvironment.browse({
295 environmentId: props.environmentId,
296 input: { partialPath: browsePath.directoryPath, cwd: props.workspaceRoot },
297 })
298 : null,
299 );
300 const { visibleEntries, exactEntry } = filterFilesystemBrowseEntries(
301 browseQuery.data?.entries ?? [],
302 browsePath.filterQuery,
303 );
304 const folder = resolveTrackedFolderInput({
305 query,
306 listedDirectoryPath: browseQuery.data?.parentPath ?? null,
307 exactEntryPath: exactEntry?.fullPath ?? null,
308 });
309 const parentPath = browsePath.canBrowseUp ? browsePath.parentPath : null;
310 const hiddenCount = Math.max(0, visibleEntries.length - BROWSE_SUGGESTION_LIMIT);
311 const rowClassName =
312 "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";
313​
314 return (
315 <Dialog
316 open
317 onOpenChange={(open) => {
318 if (!open) props.onClose();
319 }}
320 >
321 <DialogPopup>
322 <form
323 className="flex min-h-0 flex-col"
324 onSubmit={(event) => {
325 event.preventDefault();
326 if (folder && !props.busy) props.onAdd(folder);
327 }}
328 >
329 <DialogHeader>
330 <DialogTitle>Add folder</DialogTitle>
331 <DialogDescription>
332 Track a repository or folder anywhere on this project's machine.
333 </DialogDescription>
334 <div className="flex flex-col gap-2 pt-1">
335 <Label htmlFor={inputId}>Folder path</Label>
336 <Input
337 id={inputId}
338 font="mono"
339 autoComplete="off"
340 spellCheck={false}
341 placeholder="/path/to/repository"
342 value={query}
343 onChange={(event) => setQuery(event.currentTarget.value)}
344 />
345 </div>
346 </DialogHeader>
347 <DialogPanel>
348 <div className="-mx-2 flex min-h-40 flex-col">
349 {parentPath !== null ? (
350 <button type="button" className={rowClassName} onClick={() => setQuery(parentPath)}>
351 <FolderIcon className="size-4 shrink-0 text-muted-foreground" />
352 ..
353 </button>
354 ) : null}
355 {visibleEntries.slice(0, BROWSE_SUGGESTION_LIMIT).map((entry) => (
356 <button
357 key={entry.fullPath}
358 type="button"
359 className={rowClassName}
360 onClick={() => setQuery(appendBrowsePathSegment(query, entry.name))}
361 >
362 <FolderIcon className="size-4 shrink-0 text-muted-foreground" />
363 <span className="min-w-0 truncate">{entry.name}</span>
364 </button>
365 ))}
366 {browseQuery.error ? (
367 <p role="alert" className="px-2 py-1.5 text-sm text-muted-foreground">
368 {browseQuery.error}
369 </p>
370 ) : browseQuery.isPending && browseQuery.data === null ? (
371 <p role="status" className="px-2 py-1.5 text-sm text-muted-foreground">
372 Loading folders…
373 </p>
374 ) : hiddenCount > 0 ? (
375 <p className="px-2 py-1.5 text-xs text-muted-foreground">
376 {hiddenCount} more. Keep typing to narrow the list.
377 </p>
378 ) : !props.canBrowse ? (
379 <p className="px-2 py-1.5 text-sm text-muted-foreground">
380 This connection cannot browse folders. Enter an absolute path.
381 </p>
382 ) : null}
383 </div>
384 </DialogPanel>
385 <DialogFooter>
386 <Button type="button" variant="outline" onClick={props.onClose}>
387 Cancel
388 </Button>
389 <Button type="submit" disabled={folder === null || props.busy}>
390 Add folder
391 </Button>
392 </DialogFooter>
393 </form>
394 </DialogPopup>
395 </Dialog>
396 );