Open History to see the last commit
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 // An older server ignores the override record, so a project edit there
63 // would report success and vanish; such environments are left out and
64 // the legacy per-project map keeps serving them.
65 if (
66 member &&
67 environment.serverConfig.environment?.capabilities.projectSettingsOverrides !== true
68 ) {
69 return [];
70 }
71 return [
72 {
73 environmentId: candidate.environmentId,
74 settings: environment.serverConfig.settings,
75 keybindings: environment.serverConfig.keybindings,
76 ...(member ? { project: member } : {}),
77 },
78 ];
79 }),
80 );
81
82 const representativeMember = target?.projectId ? memberById.get(target.projectId) : undefined;
83 const t3File = useT3ProjectFileState(
84 representativeMember?.environmentId ?? EnvironmentId.make("none"),
85 representativeMember?.workspaceRoot ?? null,
86 );
87 const importableScripts = t3File.scripts.filter(
88 (fileScript) =>
89 !scripts.some(
90 (script) =>
91 script.command === fileScript.command ||
92 script.name.toLowerCase() === fileScript.name.toLowerCase(),
93 ),
94 );
95 const importFileScript = async (fileScript: T3ProjectFileScript) => {
96 const payload: NewProjectScriptInput = {
97 name: fileScript.name,
98 command: fileScript.command,
99 icon: fileScript.icon ?? "play",
100 runOnWorktreeCreate: fileScript.runOnWorktreeCreate ?? false,
101 waitForSetup: fileScript.runOnWorktreeCreate === true && fileScript.async === false,
102 runOnSettle: fileScript.runOnSettle ?? false,
103 keybinding: null,
104 previewUrl: fileScript.previewUrl ?? null,
105 autoOpenPreview: fileScript.previewUrl ? (fileScript.autoOpenPreview ?? false) : false,
106 };
107 const result = await submit(null, payload);
108 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
109 const error = squashAtomCommandFailure(result);
110 setRequest({
111 scriptId: null,
112 initial: payload,
113 error: error instanceof Error ? error.message : "Failed to import action.",
114 });
115 }
116 };
117
118 return (
119 <SettingsSection id="project-actions" title="Actions">
120 <SettingsRow
121 serverScoped
122 settingKeys={["defaultProjectScripts"]}
123 mixed={mixed}
124 title="Actions"
125 description="Commands that run in this project's checkout or its worktree, with optional shortcuts."
126 onResetOverride={() => void persist(() => null)}
127 control={
128 <div className="flex flex-wrap items-center gap-1.5">
129 {importableScripts.length > 0 ? (
130 <Menu>
131 <MenuTrigger
132 render={
133 <Button
134 id="import-scripts"
135 size="xs"
136 variant="ghost"
137 disabled={saving || !canWriteSettings}
138 type="button"
139 />
140 }
141 >
142 Import scripts
143 <ChevronDownIcon className="size-3.5" />
144 </MenuTrigger>
145 <MenuPopup align="end">
146 <MenuGroup>
147 <MenuGroupLabel>Import from t3.json</MenuGroupLabel>
148 <p className="px-2 pb-2 text-pretty text-sm text-muted-foreground">
149 Add actions declared by this checkout without editing them first.
150 </p>
151 </MenuGroup>
152 <MenuSeparator />
153 {importableScripts.map((fileScript) => (
154 <MenuItem
155 key={`${fileScript.name} ${fileScript.command}`}
156 onClick={() => void importFileScript(fileScript)}
157 >
158 <ScriptIcon icon={fileScript.icon ?? "play"} className="size-4 shrink-0" />
159 <div className="min-w-0 flex-1">
160 <div className="truncate font-medium">{fileScript.name}</div>
161 <div className="truncate font-mono text-muted-foreground">
162 {fileScript.command}
163 </div>
164 </div>
165 </MenuItem>
166 ))}
167 </MenuPopup>
168 </Menu>
169 ) : null}
170 <Button
171 size="xs"
172 variant="outline"
173 disabled={saving || !canWriteSettings || targets.length === 0}
174 onClick={() => setRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT })}
175 >
176 <PlusIcon className="size-3.5" />
177 Add action
178 </Button>
179 </div>
180 }
181 />
182 {mixed ? (
183 <SettingsRow
184 title="Different actions across environments"
185 description="Choose one environment to edit its list. Adding an action here adds it on every selected environment."
186 />
187 ) : (
188 <ProjectActionsList
189 scripts={scripts}
190 keybindings={keybindings}
191 disabled={saving || !canWriteSettings}
192 onEdit={(script) => setRequest(editorRequestForScript(script, keybindings))}
193 />
194 )}
195 {t3File.status === "invalid" ? (
196 <SettingsRow
197 title="t3.json is invalid"
198 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."
199 className="text-warning"
200 />
201 ) : null}
202 {target && (
203 <ProjectScriptEditorDialog
204 environmentId={target.environmentId}
205 editScope={AuthSettingsWriteScope}
206 request={request}
207 scripts={scripts}
208 onSubmit={submit}
209 onDelete={(id) =>
210 void persist((current) => current.filter((script) => script.id !== id), id, null)
211 }
212 onClose={() => setRequest(null)}
213 />
214 )}
215 </SettingsSection>
216 );
217}