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

useProjectScriptSettings.ts

211 lines7.8 KB

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