@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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