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

ProjectRepositoriesSettings.tsx

382 lines14.1 KB

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