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