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

ProjectSettingsPanel.tsx

544 lines19.5 KB

1import {
2 isAtomCommandInterrupted,
3 mapAtomCommandResult,
4 settlePromise,
5 squashAtomCommandFailure,
6 type AtomCommandResult,
7} from "@t3tools/client-runtime/state/runtime";
8import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
9import { AsyncResult } from "effect/unstable/reactivity";
10import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
11import { useLocation, useNavigate } from "@tanstack/react-router";
12import * as Cause from "effect/Cause";
13import { Trash2Icon } from "lucide-react";
14import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
15​
16import { useComposerDraftStore } from "../../composerDraftStore";
17import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
18import { readLocalApi } from "../../localApi";
19import {
20 type SidebarProjectGroupMember,
21 type SidebarProjectSnapshot,
22} from "../../sidebarProjectGrouping";
23import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
24import { useThreadShells } from "../../state/entities";
25import { projectEnvironment } from "../../state/projects";
26import { useAtomCommand } from "../../state/use-atom-command";
27import { ProjectFavicon } from "../ProjectFavicon";
28import { Button } from "../ui/button";
29import { Input } from "../ui/input";
30import { stackedThreadToast, toastManager } from "../ui/toast";
31import {
32 SettingResetButton,
33 SettingsPageContainer,
34 SettingsRow,
35 SettingsSection,
36} from "./settingsLayout";
37import {
38 canPickExternalProjectFavicon,
39 ProjectFaviconPickerDialog,
40} from "./ProjectFaviconPickerDialog";
41import { ProjectActionsSettings } from "./ProjectActionsSettings";
42import { projectGroupTitleNeedsUpdate } from "./ProjectSettingsPanel.logic";
43import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
44​
45const ProjectIconPickerDialog = lazy(() =>
46 import("./ProjectIconPickerDialog").then((module) => ({
47 default: module.ProjectIconPickerDialog,
48 })),
49);
50​
51function memberKey(member: { environmentId: string; id: string }): string {
52 return `${member.environmentId}:${member.id}`;
54​
55export type ProjectSettingsCategory = "general" | "integrations" | "source-control";
56​
57export function ProjectSettingsPanel({
58 projectKey,
59 environmentId = null,
60 checkoutKey = null,
61}: {
62 projectKey: string;
63 environmentId?: EnvironmentId | null;
64 checkoutKey?: string | null;
65}) {
66 const groups = useSettingsProjectGroups();
67 const navigate = useNavigate({ from: "/settings" });
68 const pathname = useLocation({ select: (location) => location.pathname });
69​
70 const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
71 const members = useMemo(
72 () =>
73 selected?.memberProjects.filter(
74 (member) =>
75 (environmentId === null || member.environmentId === environmentId) &&
76 (checkoutKey === null || member.physicalProjectKey === checkoutKey),
77 ) ?? [],
78 [selected, environmentId, checkoutKey],
79 );
80​
81 // Remember the members of the last rendered group so a grouping-rule change
82 // (which changes the group key) can follow the project to its new group.
83 const lastSelectionRef = useRef<{
84 key: string;
85 environmentId: EnvironmentId | null;
86 checkoutKey: string | null;
87 memberKeys: string[];
88 } | null>(null);
89 useEffect(() => {
90 if (!selected || members.length === 0) return;
91 lastSelectionRef.current = {
92 key: selected.projectKey,
93 environmentId,
94 checkoutKey,
95 memberKeys: members.map((member) => member.physicalProjectKey),
96 };
97 }, [selected, members, environmentId, checkoutKey]);
98​
99 // A grouping-rule change replaces the group key mid-visit; follow the
100 // project to its new key instead of parking on the not-found state.
101 useEffect(() => {
102 if (members.length > 0) return;
103 const last = lastSelectionRef.current;
104 if (
105 last?.key !== projectKey ||
106 last.environmentId !== environmentId ||
107 last.checkoutKey !== checkoutKey
108 )
109 return;
110 const successor = groups.find((group) =>
111 group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),
112 );
113 if (successor) {
114 void navigate({
115 to: pathname,
116 search: () => ({
117 project: successor.projectKey,
118 machine: environmentId ?? undefined,
119 checkout: checkoutKey ?? undefined,
120 }),
121 replace: true,
122 hashScrollIntoView: false,
123 });
124 }
125 }, [groups, navigate, pathname, projectKey, members.length, environmentId, checkoutKey]);
126​
127 if (!selected) {
128 return (
129 <div className="flex flex-1 items-center justify-center p-8 text-sm text-muted-foreground">
130 {groups.length === 0
131 ? "Add a project from the sidebar to configure it here."
132 : "This project is no longer available."}
133 </div>
134 );
135 }
136 if (members.length === 0)
137 return (
138 <p className="p-8 text-sm text-muted-foreground">
139 This checkout is no longer available in the selected project and environment.
140 </p>
141 );
142 const scopedGroup = {
143 ...selected,
144 memberProjects: members,
145 environmentId: members[0]!.environmentId,
146 id: members[0]!.id,
147 };
148 return (
149 <ProjectDetail
150 key={`${selected.projectKey}:${environmentId ?? "all"}:${checkoutKey ?? "all"}`}
151 group={scopedGroup}
152 hasOtherMembers={members.length < selected.memberProjects.length}
153 />
154 );
156​
157function ProjectDetail({
158 group,
159 hasOtherMembers,
160}: {
161 group: SidebarProjectSnapshot;
162 hasOtherMembers: boolean;
163}) {
164 const navigate = useNavigate({ from: "/settings" });
165 const primaryEnvironmentId = usePrimaryEnvironmentId();
166 const { environments } = useEnvironments();
167 const environmentById = useMemo(
168 () => new Map(environments.map((environment) => [environment.environmentId, environment])),
169 [environments],
170 );
171 const representative =
172 group.memberProjects.find(
173 (member) => environmentById.get(member.environmentId)?.serverConfig != null,
174 ) ?? group.memberProjects[0]!;
175 const threads = useThreadShells();
176 const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
177 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
178 const projectNameEditedRef = useRef(false);
179​
180 const faviconPath = representative.faviconPath ?? null;
181 const projectIcon = representative.projectIcon ?? null;
182 const pickProjectFavicon =
183 typeof window !== "undefined" &&
184 group.memberProjects.every(
185 (member) =>
186 member.environmentId === primaryEnvironmentId &&
187 canPickExternalProjectFavicon(member.workspaceRoot, navigator.platform),
188 )
189 ? window.desktopBridge?.pickProjectFavicon
190 : undefined;
191​
192 const reportFailure = useCallback((title: string, result: AtomCommandResult<void, unknown>) => {
193 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
194 const error = squashAtomCommandFailure(result);
195 toastManager.add(
196 stackedThreadToast({
197 type: "error",
198 title,
199 description: error instanceof Error ? error.message : "An error occurred.",
200 }),
201 );
202 }, []);
203​
204 // Group-shared fields live on each physical project record, so a
205 // group-level edit fans out to every member.
206 const updateAllMembers = useCallback(
207 async (
208 input: Partial<{
209 title: string;
210 faviconPath: string | null;
211 projectIcon: ProjectIconOverride | null;
212 }>,
213 failureTitle: string,
214 ): Promise<AtomCommandResult<void, unknown>> => {
215 const unavailable = group.memberProjects.find((member) => {
216 const environment = environmentById.get(member.environmentId);
217 return environment?.connection.phase !== "connected" || !environment.serverConfig;
218 });
219 if (unavailable) {
220 const error = new Error(
221 `Connect ${unavailable.environmentLabel ?? "the selected environment"} and try again.`,
222 );
223 const result: AtomCommandResult<void, unknown> = AsyncResult.failure(Cause.fail(error));
224 reportFailure(failureTitle, result);
225 return result;
226 }
227 for (const member of group.memberProjects) {
228 const result = mapAtomCommandResult(
229 await updateProject({
230 environmentId: member.environmentId,
231 input: { projectId: member.id, ...input },
232 }),
233 () => undefined,
234 );
235 if (result._tag === "Failure") {
236 // A partial fan-out is possible: earlier members already took the
237 // write. Name the environment so the user knows where it stopped.
238 reportFailure(
239 group.memberProjects.length > 1
240 ? `${failureTitle} on ${member.environmentLabel ?? "the current environment"}`
241 : failureTitle,
242 result,
243 );
244 return result;
245 }
246 }
247 return AsyncResult.success(undefined);
248 },
249 [environmentById, group.memberProjects, reportFailure, updateProject],
250 );
251​
252 const renameGroup = useCallback(
253 async (nextTitle: string, wasEdited: boolean) => {
254 const title = nextTitle.trim();
255 if (!title) {
256 toastManager.add({ type: "warning", title: "Project title cannot be empty" });
257 return;
258 }
259 if (
260 !projectGroupTitleNeedsUpdate(
261 group.memberProjects.map((member) => member.title),
262 title,
263 wasEdited,
264 )
265 ) {
266 return;
267 }
268 await updateAllMembers({ title }, "Failed to rename project");
269 },
270 [group.memberProjects, updateAllMembers],
271 );
272​
273 // ----- project icon -----
274 const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
275 const [iconPickerOpen, setIconPickerOpen] = useState(false);
276 const [isSavingFavicon, setIsSavingFavicon] = useState(false);
277 const savingFaviconRef = useRef(false);
278 const setProjectIcon = useCallback(
279 async (input: { faviconPath: string | null; projectIcon: ProjectIconOverride | null }) => {
280 if (savingFaviconRef.current) return;
281 savingFaviconRef.current = true;
282 setIsSavingFavicon(true);
283 try {
284 await updateAllMembers(input, "Failed to update project icon");
285 } finally {
286 savingFaviconRef.current = false;
287 setIsSavingFavicon(false);
288 }
289 },
290 [updateAllMembers],
291 );
292​
293 const hasMultipleCheckouts = group.memberProjects.length > 1;
294​
295 const removeMembers = useCallback(
296 async (members: ReadonlyArray<SidebarProjectGroupMember>) => {
297 const api = readLocalApi();
298 if (!api) return;
299​
300 const memberKeys = new Set(members.map(memberKey));
301 const projectThreads = threads.filter((thread) =>
302 memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
303 );
304 const isWholeGroup = members.length === group.memberProjects.length;
305 const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project";
306 const singleMember = members.length === 1 ? members[0]! : null;
307 const targetLabel = singleMember?.title ?? group.displayName;
308 const confirmed = await settlePromise(() =>
309 api.dialogs.confirm(
310 [
311 projectThreads.length > 0
312 ? `Remove ${targetKind} "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
313 : `Remove ${targetKind} "${targetLabel}"?`,
314 ...(singleMember
315 ? [
316 `Path: ${singleMember.workspaceRoot}`,
317 ...(singleMember.environmentLabel
318 ? [`Environment: ${singleMember.environmentLabel}`]
319 : []),
320 ]
321 : [`This removes ${members.length} grouped project entries.`]),
322 ...(projectThreads.length > 0
323 ? [
324 "This permanently clears conversation history for those threads and any archived threads.",
325 ]
326 : ["This permanently clears any archived conversation history."]),
327 isWholeGroup && !hasOtherMembers
328 ? "This removes only the project entries, not the files on disk."
329 : "Other entries in this grouped project are unaffected.",
330 "This action cannot be undone.",
331 ].join("\n"),
332 { variant: "destructive" },
333 ),
334 );
335 if (confirmed._tag === "Failure" || !confirmed.value) return;
336​
337 const draftStore = useComposerDraftStore.getState();
338 for (const member of members) {
339 const memberThreads = projectThreads.filter(
340 (thread) =>
341 thread.environmentId === member.environmentId && thread.projectId === member.id,
342 );
343 const result = mapAtomCommandResult(
344 await deleteProject({
345 environmentId: member.environmentId,
346 input: {
347 projectId: member.id,
348 force: true,
349 },
350 }),
351 () => undefined,
352 );
353 if (result._tag === "Failure") {
354 reportFailure(`Failed to remove "${member.title}"`, result);
355 return;
356 }
357 const projectRef = scopeProjectRef(member.environmentId, member.id);
358 releaseProjectDraftUploads(
359 projectRef,
360 memberThreads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
361 );
362 const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef);
363 if (projectDraftThread) {
364 draftStore.clearDraftThread(projectDraftThread.draftId);
365 }
366 draftStore.clearProjectDraftThreadId(projectRef);
367 }
368​
369 if (isWholeGroup && !hasOtherMembers) {
370 void navigate({ to: "/", replace: true });
371 }
372 },
373 [
374 deleteProject,
375 group.displayName,
376 group.memberProjects.length,
377 hasOtherMembers,
378 navigate,
379 reportFailure,
380 threads,
381 ],
382 );
383​
384 const checkoutChoices = (
385 <SettingsSection title="Checkouts">
386 {group.memberProjects.map((member) => (
387 <SettingsRow
388 key={member.physicalProjectKey}
389 title={member.environmentLabel ?? "Environment"}
390 description={member.workspaceRoot}
391 control={
392 <Button
393 size="sm"
394 variant="outline"
395 onClick={() => void removeMembers([member])}
396 aria-label={`Remove checkout ${member.workspaceRoot}`}
397 >
398 Remove
399 </Button>
400 }
401 />
402 ))}
403 </SettingsSection>
404 );
405​
406 return (
407 <>
408 <SettingsPageContainer className="gap-6">
409 <SettingsSection id="project-overview" title="Project" hideTitle>
410 <SettingsRow
411 title="Name"
412 description="The shared name for this project group in the sidebar and thread lists."
413 control={
414 <Input
415 key={`${group.projectKey}:${group.displayName}`}
416 size="sm"
417 className="w-full sm:w-64"
418 aria-label="Project name"
419 defaultValue={group.displayName}
420 onChange={() => {
421 projectNameEditedRef.current = true;
422 }}
423 onBlur={(event) => {
424 const wasEdited = projectNameEditedRef.current;
425 projectNameEditedRef.current = false;
426 void renameGroup(event.currentTarget.value, wasEdited);
427 }}
428 onKeyDown={(event) => {
429 if (event.key === "Enter") event.currentTarget.blur();
430 }}
431 />
432 }
433 />
434 <SettingsRow
435 title="Project icon"
436 description={
437 projectIcon?.kind === "lucide"
438 ? `${projectIcon.name} · ${projectIcon.color}`
439 : projectIcon?.kind === "monogram"
440 ? `${projectIcon.text} · ${projectIcon.color}`
441 : projectIcon?.kind === "emoji"
442 ? projectIcon.emoji
443 : (faviconPath ?? "Automatic")
444 }
445 resetAction={
446 group.memberProjects.some(
447 (member) => member.faviconPath != null || member.projectIcon != null,
448 ) ? (
449 <SettingResetButton
450 label="project icon"
451 disabled={isSavingFavicon}
452 onClick={() => void setProjectIcon({ faviconPath: null, projectIcon: null })}
453 />
454 ) : null
455 }
456 control={
457 <div className="flex items-center gap-2">
458 <ProjectFavicon project={representative} className="size-6" />
459 <Button
460 size="sm"
461 variant="outline"
462 type="button"
463 aria-label="Choose a project icon"
464 disabled={isSavingFavicon}
465 onClick={() => setIconPickerOpen(true)}
466 >
467 Choose icon
468 </Button>
469 <Button
470 size="sm"
471 variant="outline"
472 type="button"
473 aria-label="Choose a project icon file"
474 disabled={isSavingFavicon}
475 onClick={() => setFaviconPickerOpen(true)}
476 >
477 Choose file
478 </Button>
479 </div>
480 }
481 />
482 </SettingsSection>
483 <ProjectActionsSettings />
484 {hasMultipleCheckouts ? checkoutChoices : null}
485 <SettingsSection title="Danger">
486 <SettingsRow
487 title={
488 hasOtherMembers
489 ? "Remove checkout"
490 : group.memberProjects.length > 1
491 ? "Remove this project everywhere"
492 : "Remove project"
493 }
494 description={
495 hasOtherMembers
496 ? "Deletes the selected machine's checkout entries and their threads. Other machines and files on disk are not touched."
497 : group.memberProjects.length > 1
498 ? `Deletes all ${group.memberProjects.length} checkout entries and their threads on every machine. Files on disk are not touched.`
499 : "Deletes the project entry and its threads. Files on disk are not touched."
500 }
501 control={
502 <Button
503 size="sm"
504 variant="destructive-outline"
505 onClick={() => void removeMembers(group.memberProjects)}
506 >
507 <Trash2Icon />
508 {hasOtherMembers
509 ? "Remove checkout"
510 : group.memberProjects.length > 1
511 ? "Remove all entries"
512 : "Remove project"}
513 </Button>
514 }
515 />
516 </SettingsSection>
517 </SettingsPageContainer>
518​
519 <ProjectFaviconPickerDialog
520 key={`${representative.environmentId}:${representative.workspaceRoot}:${faviconPickerOpen}`}
521 cwd={representative.workspaceRoot}
522 environmentId={representative.environmentId}
523 onOpenChange={setFaviconPickerOpen}
524 {...(pickProjectFavicon
525 ? { onPickExternal: () => pickProjectFavicon(representative.workspaceRoot) }
526 : {})}
527 onSelect={(path) => void setProjectIcon({ faviconPath: path, projectIcon: null })}
528 open={faviconPickerOpen}
529 projectName={group.displayName}
530 />
531 {iconPickerOpen ? (
532 <Suspense fallback={null}>
533 <ProjectIconPickerDialog
534 current={projectIcon}
535 projectName={representative.title}
536 open
537 onOpenChange={setIconPickerOpen}
538 onSelect={(icon) => void setProjectIcon({ faviconPath: null, projectIcon: icon })}
539 />
540 </Suspense>
541 ) : null}
542 </>
543 );