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