Open History to see the last commit
1import {
2 isAtomCommandInterrupted,
3 mapAtomCommandResult,
4 squashAtomCommandFailure,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import {
8 type EnvironmentId,
9 type ProjectId,
10 type ProjectScript,
11 type ResolvedKeybindingsConfig,
12 type ServerSettings,
13} from "@t3tools/contracts";
14import { resolveProjectScripts } from "@t3tools/shared/projectScripts";
15import { clearProjectSettingsOverrides } from "@t3tools/shared/projectSettings";
16import * as Cause from "effect/Cause";
17import { AsyncResult } from "effect/reactivity";
18import { useRef, useState } from "react";
19
20import { isElectron } from "../../env";
21import {
22 decodeProjectScriptKeybindingRule,
23 keybindingValueForCommand,
24} from "../../lib/projectScriptKeybindings";
25import {
26 buildProjectScript,
27 commandForProjectScript,
28 nextProjectScriptId,
29} from "../../projectScripts";
30import { useProjects } from "../../state/entities";
31import { serverEnvironment } from "../../state/server";
32import { useAtomCommand } from "../../state/use-atom-command";
33import type { NewProjectScriptInput } from "../projectScriptEditor";
34import { toastManager } from "../ui/toast";
35
36function reportScriptFailure(result: AtomCommandResult<unknown, unknown>) {
37 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
38 const error = squashAtomCommandFailure(result);
39 toastManager.add({
40 type: "error",
41 title: "Failed to save project actions",
42 description: error instanceof Error ? error.message : "An error occurred.",
43 });
44 }
45 return mapAtomCommandResult(result, () => undefined);
46}
47
48/**
49 * Edits the action list on every target: the environment default when there is
50 * no project, else that project's override entry. Shortcuts follow on desktop.
51 */
52export function useProjectScriptSettings(
53 targets: readonly {
54 environmentId: EnvironmentId;
55 settings: ServerSettings;
56 keybindings: ResolvedKeybindingsConfig;
57 project?: { id: ProjectId; scripts: readonly ProjectScript[] };
58 }[],
59) {
60 const projects = useProjects();
61 const [saving, setSaving] = useState(false);
62 const savingRef = useRef(false);
63 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
64 const upsertKeybinding = useAtomCommand(
65 serverEnvironment.upsertKeybinding,
66 "action shortcut update",
67 );
68 const removeKeybinding = useAtomCommand(
69 serverEnvironment.removeKeybinding,
70 "action shortcut removal",
71 );
72
73 async function persist(
74 transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
75 scriptId?: string,
76 keybinding?: string | null,
77 ): Promise<AtomCommandResult<void, unknown>> {
78 if (savingRef.current || targets.length === 0) {
79 const message = "No available machine, or another action change is saving.";
80 toastManager.add({ type: "error", title: "Actions not saved", description: message });
81 return AsyncResult.failure(Cause.fail(new Error(message)));
82 }
83 savingRef.current = true;
84 setSaving(true);
85 try {
86 for (const { environmentId, settings, keybindings, project } of targets) {
87 const current = project
88 ? resolveProjectScripts(settings, project)
89 : settings.defaultProjectScripts;
90 const nextScripts = transform(current);
91 const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
92 const result = await updateSettings({
93 environmentId,
94 input: {
95 patch: project
96 ? {
97 projectSettingsOverrides: {
98 [project.id]:
99 nextScripts === null
100 ? clearProjectSettingsOverrides(settings, project.id, [
101 "defaultProjectScripts",
102 ])
103 : {
104 ...settings.projectSettingsOverrides[project.id],
105 defaultProjectScripts: nextScripts,
106 },
107 },
108 }
109 : { defaultProjectScripts: nextScripts ?? [] },
110 },
111 });
112 if (result._tag === "Failure") return reportScriptFailure(result);
113 if (!isElectron) continue;
114 const changedIds = scriptId
115 ? [scriptId]
116 : current
117 .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
118 .map((script) => script.id);
119 for (const id of changedIds) {
120 const command = commandForProjectScript(id);
121 const previousValue = keybindingValueForCommand(keybindings, command);
122 const previous = previousValue
123 ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
124 : null;
125 const next = decodeProjectScriptKeybindingRule({ keybinding, command });
126 const retainedElsewhere =
127 !nextScripts?.some((script) => script.id === id) &&
128 ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
129 Object.entries(settings.projectSettingsOverrides).some(
130 ([projectId, entry]) =>
131 projectId !== project?.id &&
132 entry.defaultProjectScripts?.some((script) => script.id === id),
133 ) ||
134 projects.some(
135 (other) =>
136 other.environmentId === environmentId &&
137 other.id !== project?.id &&
138 (project ? resolveProjectScripts(settings, other) : other.scripts).some(
139 (script) => script.id === id,
140 ),
141 ));
142 const bindingResult = next
143 ? await upsertKeybinding({
144 environmentId,
145 input:
146 previous && previous.key !== next.key ? { ...next, replace: previous } : next,
147 })
148 : previous && !retainedElsewhere
149 ? await removeKeybinding({ environmentId, input: previous })
150 : null;
151 if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
152 }
153 }
154 return AsyncResult.success(undefined);
155 } finally {
156 savingRef.current = false;
157 setSaving(false);
158 }
159 }
160
161 function submit(scriptId: string | null, input: NewProjectScriptInput) {
162 const existingIds = [
163 ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
164 ...targets.flatMap(({ settings, project }) =>
165 [
166 ...settings.defaultProjectScripts,
167 ...Object.values(settings.projectSettingsOverrides).flatMap(
168 (entry) => entry.defaultProjectScripts ?? [],
169 ),
170 ...(project?.scripts ?? []),
171 ].map((script) => script.id),
172 ),
173 ];
174 const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
175 const next = buildProjectScript(id, input);
176 return persist(
177 (current) => {
178 const updated = current.map((script) =>
179 script.id === id
180 ? next
181 : input.runOnWorktreeCreate
182 ? { ...script, runOnWorktreeCreate: false }
183 : script,
184 );
185 return scriptId === null ? [...updated, next] : updated;
186 },
187 id,
188 input.keybinding,
189 );
190 }
191
192 return { saving, persist, submit };
193}