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

ThreadRepositorySections.tsx

374 lines13.5 KB

1import {
2 addableTaskFolderRepositories,
3 pinnableThreadRepositories,
4 repositorySectionSummary,
5 THREAD_REPOSITORY_SECTIONS_VISIBLE,
6 threadChangedRepositories,
7 threadRepositorySections,
8 type ThreadRepositorySection,
9 type ThreadRepositorySections as RepositorySections,
10} from "@t3tools/client-runtime/state/thread-repositories";
11import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import type {
17 EnvironmentId,
18 ProjectId,
19 ScopedThreadRef,
20 TaskFolder,
21 ThreadId,
22} from "@t3tools/contracts";
23import { useAtomValue } from "@effect/atom-react";
24import {
25 ChevronDownIcon,
26 ChevronRightIcon,
27 FolderGitIcon,
28 PinOffIcon,
29 PlusIcon,
30} from "lucide-react";
31import { msg, T, useGT } from "gt-react";
32import { memo, useState } from "react";
33​
34import { m } from "~/i18n/messages";
35import { cn } from "~/lib/utils";
36import { useQuietThreadProjection } from "~/state/entities";
37import { filesystemEnvironment, useFilesystemReadAccess } from "~/state/filesystem";
38import { useEnvironmentQuery } from "~/state/query";
39import { useAtomCommand } from "~/state/use-atom-command";
40import { vcsEnvironment } from "~/state/vcs";
41import { useThreadRepositoryPins, useThreadRepositoryPinsStore } from "~/threadRepositoryPinsStore";
42​
43import { GitActionsControl } from "../GitActionsControl";
44import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuTrigger } from "../ui/menu";
45import { stackedThreadToast, toastManager } from "../ui/toast";
46import { ThreadDetailsControl } from "./ThreadDetailsControl";
47import {
48 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
49 THREAD_DETAILS_PANEL_ICON_CLASS,
50 THREAD_DETAILS_PANEL_LABEL_CLASS,
51} from "./threadDetailsPanelStyles";
52​
53interface ThreadRepositorySectionsProps {
54 environmentId: EnvironmentId;
55 threadId: ThreadId;
56 projectId: ProjectId;
57 isServerThread: boolean;
58 /** The thread's own folder, which has its own Git controls when it is a repository. */
59 threadCwd: string | null;
60 /**
61 * The thread's task folder. Its repositories are then the only ones listed, each bound to the
62 * thread's own worktree of it, and adding one creates that worktree.
63 */
64 taskFolder: TaskFolder | null;
65 /** False when the thread reaches no tracked repository: it lists only what it changed. */
66 reachesTracked: boolean;
67 onTaskFolderChange: () => void;
68 /** Says so when no repository is listed, instead of leaving the section blank. */
69 explainsEmpty: boolean;
70 showActions: boolean;
72​
73const RepositorySection = memo(function RepositorySection(props: {
74 threadRef: ScopedThreadRef;
75 sectionKey: string;
76 name: string;
77 cwd: string;
78 removable: boolean;
79 expanded: boolean;
80 overflow: boolean;
81 owner: { readonly threadId?: ThreadId; readonly projectId?: ProjectId };
82 showActions: boolean;
83 onToggle: (key: string) => void;
84 onRemove: (key: string) => void;
85}) {
86 // Local status only: a remote read for every listed repository would fetch on a timer. The
87 // expanded section's actions hold the full subscription, and its remote updates land here too.
88 const status = useEnvironmentQuery(
89 vcsEnvironment.status({
90 environmentId: props.threadRef.environmentId,
91 input: { cwd: props.cwd, includeRemote: false },
92 }),
93 );
94 const summary = repositorySectionSummary(status.data);
95 const Chevron = props.expanded ? ChevronDownIcon : ChevronRightIcon;
96 const bodyId = `thread-repository-${props.sectionKey}`;
97 const gt = useGT();
98​
99 return (
100 <div
101 role="group"
102 aria-label={gt("Repository {name}", { name: props.name })}
103 data-thread-details-repository-overflow={props.overflow || undefined}
104 className="flex flex-col"
105 >
106 <ThreadDetailsControl
107 size="sm"
108 variant="ghost"
109 part="row"
110 aria-expanded={props.expanded}
111 aria-controls={props.expanded ? bodyId : undefined}
112 onClick={() => props.onToggle(props.sectionKey)}
113 >
114 <Chevron className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} aria-hidden />
115 <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
116 <span className="max-w-2/3 shrink-0 truncate">{props.name}</span>
117 <span className="min-w-0 truncate font-normal text-muted-foreground">
118 {summary === null
119 ? (status.error ?? "")
120 : !summary.isRepository
121 ? gt("Not a Git repository")
122 : (summary.branch ?? gt("Detached HEAD"))}
123 </span>
124 {summary?.isRepository ? (
125 <span className="ml-auto flex shrink-0 items-baseline gap-2 ps-2 font-mono tabular-nums">
126 {summary.pullRequest ? (
127 <span className="font-sans font-normal text-muted-foreground">
128 #{summary.pullRequest.number}
129 </span>
130 ) : null}
131 {summary.changedFiles > 0 ? (
132 <>
133 <span className="text-diff-addition-foreground">
134 +{formatDiffCount(summary.insertions)}
135 </span>
136 <span className="text-diff-deletion-foreground">
137 -{formatDiffCount(summary.deletions)}
138 </span>
139 </>
140 ) : null}
141 </span>
142 ) : null}
143 </span>
144 </ThreadDetailsControl>
145 {props.expanded ? (
146 <div id={bodyId} className="flex flex-col ps-4">
147 <GitActionsControl
148 target={{ key: props.sectionKey, cwd: props.cwd, name: props.name }}
149 threadRef={props.threadRef}
150 owner={props.owner}
151 showActions={props.showActions}
152 showChanges={false}
153 />
154 {props.removable ? (
155 <ThreadDetailsControl
156 size="sm"
157 variant="ghost"
158 part="row"
159 tone="muted"
160 onClick={() => props.onRemove(props.sectionKey)}
161 >
162 <PinOffIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
163 <span className={THREAD_DETAILS_PANEL_LABEL_CLASS}>
164 <T>Remove from this thread</T>
165 </span>
166 </ThreadDetailsControl>
167 ) : null}
168 </div>
169 ) : null}
170 </div>
171 );
172});
173​
174/** Mounted while the menu is open, so the folder list is read only when someone asks for it. */
175function OtherRepositoryItems(props: {
176 environmentId: EnvironmentId;
177 projectId: ProjectId;
178 threadCwd: string | null;
179 taskFolder: TaskFolder | null;
180 sections: RepositorySections;
181 onPick: (repository: { repositoryPath: string; name: string }) => void;
182}) {
183 const folders = useEnvironmentQuery(
184 filesystemEnvironment.listFolders({
185 environmentId: props.environmentId,
186 input: { projectId: props.projectId },
187 }),
188 );
189 const gt = useGT();
190 if (folders.data === null) {
191 return (
192 <MenuItem disabled>
193 <MenuItemLabel>{folders.error ?? gt("Loading repositories...")}</MenuItemLabel>
194 </MenuItem>
195 );
196 }
197 const repositories =
198 props.taskFolder === null
199 ? pinnableThreadRepositories({
200 folders: folders.data.folders,
201 sections: props.sections,
202 threadCwd: props.threadCwd,
203 })
204 : addableTaskFolderRepositories({
205 folders: folders.data.folders,
206 taskFolder: props.taskFolder,
207 });
208 if (repositories.length === 0) {
209 return (
210 <MenuItem disabled>
211 <MenuItemLabel>
212 <T>No other repositories</T>
213 </MenuItemLabel>
214 </MenuItem>
215 );
216 }
217 return repositories.map((repository) => (
218 <MenuItem key={repository.repositoryPath} onClick={() => props.onPick(repository)}>
219 <FolderGitIcon />
220 <MenuItemLabel>{repository.name}</MenuItemLabel>
221 </MenuItem>
222 ));
224​
225/**
226 * Git state and actions for the tracked repositories a thread changed or the user added, or for
227 * the worktrees in its task folder. Folded sections are not rendered, so they hold no subscription.
228 */
229export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) {
230 const threadRef: ScopedThreadRef = {
231 environmentId: props.environmentId,
232 threadId: props.threadId,
233 };
234 const structure = useQuietThreadProjection(props.isServerThread ? threadRef : null);
235 const pinned = useThreadRepositoryPins(threadRef);
236 const pin = useThreadRepositoryPinsStore((state) => state.pin);
237 const unpin = useThreadRepositoryPinsStore((state) => state.unpin);
238 const { canReadFiles } = useFilesystemReadAccess(props.environmentId);
239 const [showAll, setShowAll] = useState(false);
240 const [expandedKey, setExpandedKey] = useState<string | null>(null);
241 const [isPickerOpen, setIsPickerOpen] = useState(false);
242 const canAddWorktree = useAtomValue(
243 filesystemEnvironment.addTaskFolderRepository.permissionAtom(props.environmentId),
244 );
245 const addTaskFolderRepository = useAtomCommand(filesystemEnvironment.addTaskFolderRepository, {
246 label: "task folder add repository",
247 reportFailure: false,
248 });
249 const [addingName, setAddingName] = useState<string | null>(null);
250 const gt = useGT();
251​
252 const { taskFolder } = props;
253 const sections = threadRepositorySections({
254 changed: structure === null ? [] : threadChangedRepositories(structure.projection),
255 pinned,
256 threadCwd: props.threadCwd,
257 showAll,
258 taskFolder,
259 reachesTracked: props.reachesTracked,
260 });
261 const addWorktree = async (repository: { repositoryPath: string; name: string }) => {
262 if (addingName !== null) return;
263 setAddingName(repository.name);
264 const result = await addTaskFolderRepository({
265 environmentId: props.environmentId,
266 input: { threadId: props.threadId, repositoryPath: repository.repositoryPath },
267 });
268 setAddingName(null);
269 if (result._tag === "Failure") {
270 if (isAtomCommandInterrupted(result)) return;
271 const error = squashAtomCommandFailure(result);
272 toastManager.add(
273 stackedThreadToast({
274 type: "error",
275 title: m(msg("Could not add {name}", { name: repository.name })),
276 description: error instanceof Error ? error.message : String(error),
277 }),
278 );
279 return;
280 }
281 props.onTaskFolderChange();
282 setShowAll(true);
283 setExpandedKey(repository.repositoryPath);
284 };
285 const owner = props.isServerThread
286 ? { threadId: props.threadId }
287 : { projectId: props.projectId };
288 const toggle = (key: string) => setExpandedKey((current) => (current === key ? null : key));
289 const remove = (key: string) => unpin(threadRef, key);
290 const renderSection = (section: ThreadRepositorySection, index: number) => (
291 <RepositorySection
292 key={section.key}
293 threadRef={threadRef}
294 sectionKey={section.key}
295 name={section.name}
296 cwd={section.cwd}
297 removable={section.origin === "pinned"}
298 expanded={expandedKey === section.key}
299 overflow={index >= THREAD_REPOSITORY_SECTIONS_VISIBLE}
300 owner={owner}
301 showActions={props.showActions}
302 onToggle={toggle}
303 onRemove={remove}
304 />
305 );
306​
307 return (
308 <>
309 {sections.visible.length === 0 && props.explainsEmpty && props.reachesTracked ? (
310 <p className="px-2.5 py-1.5 text-xs text-muted-foreground">
311 {taskFolder === null
312 ? gt("Repositories appear here once this thread changes them.")
313 : gt("This thread has no repository worktrees yet.")}
314 </p>
315 ) : null}
316 {sections.visible.map(renderSection)}
317 {sections.hidden.length > 0 ||
318 (showAll && sections.visible.length > THREAD_REPOSITORY_SECTIONS_VISIBLE) ? (
319 <ThreadDetailsControl
320 size="sm"
321 variant="ghost"
322 part="row"
323 tone="muted"
324 aria-expanded={showAll}
325 onClick={() => setShowAll((current) => !current)}
326 >
327 <span className={cn("ms-6.5", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
328 {showAll
329 ? gt("Show fewer")
330 : gt("Show {count} more", { count: sections.hidden.length })}
331 </span>
332 </ThreadDetailsControl>
333 ) : null}
334 {props.reachesTracked &&
335 canReadFiles &&
336 (taskFolder === null || (props.isServerThread && canAddWorktree)) ? (
337 <Menu open={isPickerOpen} onOpenChange={setIsPickerOpen}>
338 <MenuTrigger
339 render={<ThreadDetailsControl size="sm" variant="ghost" part="row" tone="muted" />}
340 disabled={addingName !== null}
341 >
342 <PlusIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
343 <span className={THREAD_DETAILS_PANEL_LABEL_CLASS}>
344 {addingName === null
345 ? gt("Other repositories...")
346 : gt("Adding a worktree of {name}...", { name: addingName })}
347 </span>
348 </MenuTrigger>
349 <MenuPopup align="start">
350 {isPickerOpen ? (
351 <OtherRepositoryItems
352 environmentId={props.environmentId}
353 projectId={props.projectId}
354 threadCwd={props.threadCwd}
355 taskFolder={taskFolder}
356 sections={sections}
357 onPick={(repository) => {
358 if (taskFolder !== null) {
359 void addWorktree(repository);
360 return;
361 }
362 pin(threadRef, repository);
363 // Pins beyond the visible few would land folded away, out of sight.
364 if (pinned.length >= THREAD_REPOSITORY_SECTIONS_VISIBLE) setShowAll(true);
365 setExpandedKey(repository.repositoryPath);
366 }}
367 />
368 ) : null}
369 </MenuPopup>
370 </Menu>
371 ) : null}
372 </>
373 );