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

useProjectScriptSettings.ts

202 lines7.5 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 {
23 decodeProjectScriptKeybindingRule,
24 keybindingValueForCommand,
25} from "../../lib/projectScriptKeybindings";
26import {
27 buildProjectScript,
28 commandForProjectScript,
29 nextProjectScriptId,
30 releaseClaimedRoles,
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​
50export function useProjectScriptSettings(
51 targets: readonly {
52 environmentId: EnvironmentId;
53 settings: ServerSettings;
54 keybindings: ResolvedKeybindingsConfig;
55 project?: { id: ProjectId; scripts: readonly ProjectScript[] };
56 }[],
57) {
58 const projects = useProjects();
59 const [saving, setSaving] = useState(false);
60 const savingRef = useRef(false);
61 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, "project actions update");
62 const upsertKeybinding = useAtomCommand(
63 serverEnvironment.upsertKeybinding,
64 "action shortcut update",
65 );
66 const removeKeybinding = useAtomCommand(
67 serverEnvironment.removeKeybinding,
68 "action shortcut removal",
69 );
70​
71 async function persist(
72 transform: (current: readonly ProjectScript[]) => readonly ProjectScript[] | null,
73 scriptId?: string,
74 keybinding?: string | null,
75 ): Promise<AtomCommandResult<void, unknown>> {
76 if (savingRef.current || targets.length === 0) {
77 const message = "No available machine, or another action change is saving.";
78 toastManager.add({ type: "error", title: "Actions not saved", description: message });
79 return AsyncResult.failure(Cause.fail(new Error(message)));
80 }
81 if (
82 targets.some(
83 ({ environmentId }) => !readEnvironmentScope(environmentId, AuthSettingsWriteScope),
84 )
85 ) {
86 return reportScriptFailure(
87 AsyncResult.failure(
88 Cause.fail(
89 new EnvironmentAuthorizationError({
90 requiredScope: AuthSettingsWriteScope,
91 message: "This connection cannot change environment settings.",
92 }),
93 ),
94 ),
95 );
96 }
97 savingRef.current = true;
98 setSaving(true);
99 try {
100 for (const { environmentId, settings, keybindings, project } of targets) {
101 const current = project
102 ? resolveProjectScripts(settings, project)
103 : settings.defaultProjectScripts;
104 const nextScripts = transform(current);
105 const effectiveScripts = nextScripts ?? settings.defaultProjectScripts;
106 const result = await updateSettings({
107 environmentId,
108 input: {
109 patch: project
110 ? {
111 projectSettingsOverrides: {
112 [project.id]:
113 nextScripts === null
114 ? clearProjectSettingsOverrides(settings, project.id, [
115 "defaultProjectScripts",
116 ])
117 : {
118 ...settings.projectSettingsOverrides[project.id],
119 defaultProjectScripts: nextScripts,
120 },
121 },
122 }
123 : { defaultProjectScripts: nextScripts ?? [] },
124 },
125 });
126 if (result._tag === "Failure") return reportScriptFailure(result);
127 const changedIds = scriptId
128 ? [scriptId]
129 : current
130 .filter((script) => !effectiveScripts.some((next) => next.id === script.id))
131 .map((script) => script.id);
132 for (const id of changedIds) {
133 const command = commandForProjectScript(id);
134 const previousValue = keybindingValueForCommand(keybindings, command);
135 const previous = previousValue
136 ? decodeProjectScriptKeybindingRule({ keybinding: previousValue, command })
137 : null;
138 const next = decodeProjectScriptKeybindingRule({ keybinding, command });
139 const retainedElsewhere =
140 !nextScripts?.some((script) => script.id === id) &&
141 ((project && settings.defaultProjectScripts.some((script) => script.id === id)) ||
142 Object.entries(settings.projectSettingsOverrides).some(
143 ([projectId, entry]) =>
144 projectId !== project?.id &&
145 entry.defaultProjectScripts?.some((script) => script.id === id),
146 ) ||
147 projects.some(
148 (other) =>
149 other.environmentId === environmentId &&
150 other.id !== project?.id &&
151 (project ? resolveProjectScripts(settings, other) : other.scripts).some(
152 (script) => script.id === id,
153 ),
154 ));
155 const bindingResult = next
156 ? await upsertKeybinding({
157 environmentId,
158 input:
159 previous && previous.key !== next.key ? { ...next, replace: previous } : next,
160 })
161 : previous && !retainedElsewhere
162 ? await removeKeybinding({ environmentId, input: previous })
163 : null;
164 if (bindingResult?._tag === "Failure") return reportScriptFailure(bindingResult);
165 }
166 }
167 return AsyncResult.success(undefined);
168 } finally {
169 savingRef.current = false;
170 setSaving(false);
171 }
172 }
173​
174 function submit(scriptId: string | null, input: NewProjectScriptInput) {
175 const existingIds = [
176 ...projects.flatMap((project) => project.scripts.map((script) => script.id)),
177 ...targets.flatMap(({ settings, project }) =>
178 [
179 ...settings.defaultProjectScripts,
180 ...Object.values(settings.projectSettingsOverrides).flatMap(
181 (entry) => entry.defaultProjectScripts ?? [],
182 ),
183 ...(project?.scripts ?? []),
184 ].map((script) => script.id),
185 ),
186 ];
187 const id = scriptId ?? nextProjectScriptId(input.name, existingIds);
188 const next = buildProjectScript(id, input);
189 return persist(
190 (current) => {
191 const updated = current.map((script) =>
192 script.id === id ? next : releaseClaimedRoles(script, input),
193 );
194 return scriptId === null ? [...updated, next] : updated;
195 },
196 id,
197 input.keybinding,
198 );
199 }
200​
201 return { saving, persist, submit };