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

ProjectActionsSettings.tsx

216 lines8.3 KB

1import { useScopedSettingsWriteAllowed } from "./useScopedSettings";
2import { AuthSettingsWriteScope } from "@t3tools/contracts";
3import { EnvironmentId, type T3ProjectFileScript } from "@t3tools/contracts";
4import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7} from "@t3tools/client-runtime/state/runtime";
8import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
9import { ChevronDownIcon, PlusIcon } from "lucide-react";
10import { useState } from "react";
11import { useT3ProjectFileState } from "../../hooks/useT3ProjectFileScripts";
12import { useEnvironments } from "../../state/environments";
13import {
14 EMPTY_PROJECT_SCRIPT_INPUT,
15 editorRequestForScript,
16 ProjectScriptEditorDialog,
17 ScriptIcon,
18 type NewProjectScriptInput,
19 type ProjectScriptEditorRequest,
20} from "../projectScriptEditor";
21import { Button } from "../ui/button";
22import {
23 Menu,
24 MenuGroup,
25 MenuGroupLabel,
26 MenuItem,
27 MenuPopup,
28 MenuSeparator,
29 MenuTrigger,
30} from "../ui/menu";
31import { ProjectActionsList } from "./ProjectActionsList";
32import { useProjectScriptSettings } from "./useProjectScriptSettings";
33import { SettingsRow, SettingsSection } from "./settingsLayout";
34import { useSettingsScope } from "./SettingsScopeContext";
35​
36export function ProjectActionsSettings() {
37 const { scope, targets, target } = useSettingsScope();
38 const { environments } = useEnvironments();
39 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
40 const representativeConfig = target
41 ? environments.find((environment) => environment.environmentId === target.environmentId)
42 ?.serverConfig
43 : undefined;
44 const scripts = target?.settings.defaultProjectScripts ?? [];
45 const keybindings = representativeConfig?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS;
46 const mixed = targets.some(
47 (candidate) =>
48 JSON.stringify(candidate.settings.defaultProjectScripts) !== JSON.stringify(scripts),
49 );
50 const canWriteSettings = useScopedSettingsWriteAllowed();
51 const [request, setRequest] = useState<ProjectScriptEditorRequest | null>(null);
52 const memberById = new Map(
53 isProjectScope ? scope.members.map((member) => [member.id, member]) : [],
54 );
55 const { saving, persist, submit } = useProjectScriptSettings(
56 targets.flatMap((candidate) => {
57 const environment = environments.find(
58 (entry) => entry.environmentId === candidate.environmentId,
59 );
60 if (!environment?.serverConfig) return [];
61 const member = candidate.projectId ? memberById.get(candidate.projectId) : undefined;
62 // Older servers ignore override records; exclude them from edits and retain their legacy per-project
63 // map.
64 if (
65 member &&
66 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
67 ) {
68 return [];
69 }
70 return [
71 {
72 environmentId: candidate.environmentId,
73 settings: environment.serverConfig.settings,
74 keybindings: environment.serverConfig.keybindings,
75 ...(member ? { project: member } : {}),
76 },
77 ];
78 }),
79 );
80​
81 const representativeMember = target?.projectId ? memberById.get(target.projectId) : undefined;
82 const t3File = useT3ProjectFileState(
83 representativeMember?.environmentId ?? EnvironmentId.make("none"),
84 representativeMember?.workspaceRoot ?? null,
85 );
86 const importableScripts = t3File.scripts.filter(
87 (fileScript) =>
88 !scripts.some(
89 (script) =>
90 script.command === fileScript.command ||
91 script.name.toLowerCase() === fileScript.name.toLowerCase(),
92 ),
93 );
94 const importFileScript = async (fileScript: T3ProjectFileScript) => {
95 const payload: NewProjectScriptInput = {
96 name: fileScript.name,
97 command: fileScript.command,
98 icon: fileScript.icon ?? "play",
99 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
100 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
101 runOnSettle: fileScript.runOnSettle ?? false,
102 keybinding: null,
103 previewUrl: fileScript.previewUrl ?? null,
104 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
105 };
106 const result = await submit(null, payload);
107 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
108 const error = squashAtomCommandFailure(result);
109 setRequest({
110 scriptId: null,
111 initial: payload,
112 error: error instanceof Error ? error.message : "Failed to import action.",
113 });
114 }
115 };
116​
117 return (
118 <SettingsSection id="project-actions" title="Actions">
119 <SettingsRow
120 serverScoped
121 settingKeys={["defaultProjectScripts"]}
122 mixed={mixed}
123 title="Actions"
124 description="Commands that run in this project's checkout or its worktree, with optional shortcuts."
125 onResetOverride={() => void persist(() => null)}
126 control={
127 <div className="flex flex-wrap items-center gap-1.5">
128 {importableScripts.length > 0 ? (
129 <Menu>
130 <MenuTrigger
131 render={
132 <Button
133 id="import-scripts"
134 size="xs"
135 variant="ghost"
136 disabled={saving || !canWriteSettings}
137 type="button"
138 />
139 }
140 >
141 Import scripts
142 <ChevronDownIcon className="size-3.5" />
143 </MenuTrigger>
144 <MenuPopup align="end">
145 <MenuGroup>
146 <MenuGroupLabel>Import from t3.json</MenuGroupLabel>
147 <p className="px-2 pb-2 text-pretty text-sm text-muted-foreground">
148 Add actions declared by this checkout without editing them first.
149 </p>
150 </MenuGroup>
151 <MenuSeparator />
152 {importableScripts.map((fileScript) => (
153 <MenuItem
154 key={`${fileScript.name} ${fileScript.command}`}
155 onClick={() => void importFileScript(fileScript)}
156 >
157 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4 shrink-0" />
158 <div className="min-w-0 flex-1">
159 <div className="truncate font-medium">{fileScript.name}</div>
160 <div className="truncate font-mono text-muted-foreground">
161 {fileScript.command}
162 </div>
163 </div>
164 </MenuItem>
165 ))}
166 </MenuPopup>
167 </Menu>
168 ) : null}
169 <Button
170 size="xs"
171 variant="outline"
172 disabled={saving || !canWriteSettings || targets.length === 0}
173 onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
174 >
175 <PlusIcon className="size-3.5" />
176 Add action
177 </Button>
178 </div>
179 }
180 />
181 {mixed ? (
182 <SettingsRow
183 title="Different actions across environments"
184 description="Choose one environment to edit its list. Adding an action here adds it on every selected environment."
185 />
186 ) : (
187 <ProjectActionsList
188 scripts={scripts}
189 keybindings={keybindings}
190 disabled={saving || !canWriteSettings}
191 onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
192 />
193 )}
194 {t3File.status === "invalid" ? (
195 <SettingsRow
196 title="t3.json is invalid"
197 description="A t3.json exists in this checkout but fails to parse, so every action and icon it declares is ignored. Check the JSON syntax and icon values."
198 className="text-warning"
199 />
200 ) : null}
201 {target && (
202 <ProjectScriptEditorDialog
203 environmentId={target.environmentId}
204 editScope={AuthSettingsWriteScope}
205 request={request}
206 scripts={scripts}
207 onSubmit={submit}
208 onDelete={(id) =>
209 void persist((current) => current.filter((script) => script.id !== id), id, null)
210 }
211 onClose={() => setRequest(null)}
212 />
213 )}
214 </SettingsSection>
215 );