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

ProjectActionsSettings.tsx

219 lines8.4 KB

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