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

useScopedSettings.ts

182 lines6.3 KB

1import { AuthSettingsWriteScope } from "@t3tools/contracts";
2import { useEnvironmentsWithScope } from "../../state/session";
3import {
4 requiredScopesForServerSettingsPatch,
5 EnvironmentAuthorizationError,
6} from "@t3tools/contracts";
7import { readEnvironmentScope } from "../../state/session";
8import * as Cause from "effect/Cause";
9import { AsyncResult } from "effect/reactivity";
10import { msg } from "gt-react";
11import {
12 DEFAULT_SERVER_SETTINGS,
13 type EnvironmentId,
14 type ProjectScopedServerSettingKey,
15 type ServerSettings,
16 type UnifiedSettings,
17} from "@t3tools/contracts";
18​
19import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
20import { m } from "../../i18n/messages";
21import { appAtomRegistry } from "../../rpc/atomRegistry";
22import { readEnvironment } from "../../state/environments";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { toastManager } from "../ui/toast";
26import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
27import {
28 createScopedSettingsWriter,
29 pendingScopedWritesAtom,
30 planProjectOverridesClear,
31 planScopedSettingsClear,
32 planScopedSettingsPatch,
33 scopedSettingsAreMixed,
34 scopedSettingsSource,
35 settlePendingScopedWrites,
36 type ProjectOverrideEntry,
37 type ScopedSettingsPatch,
38} from "./scopedSettings";
39​
40const readSettings = (environmentId: EnvironmentId) =>
41 readEnvironment(environmentId)?.serverConfig?.settings ?? null;
42const writeScopedSettings = createScopedSettingsWriter(readSettings);
43​
44export function useScopedSettings<T = UnifiedSettings>(
45 selector?: (settings: UnifiedSettings) => T,
46): T {
47 const { target } = useSettingsScope();
48 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
50​
51export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
52 const { targets } = useSettingsScope();
53 return scopedSettingsAreMixed(targets, keys);
55​
56export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
57 const { targets } = useSettingsScope();
58 return scopedSettingsSource(targets, keys);
60​
61function useRunScopedPlan() {
62 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
63 return (
64 environments: Parameters<typeof writeScopedSettings>[0],
65 planner: Parameters<typeof writeScopedSettings>[1],
66 onFailed?: () => void,
67 ) => {
68 const plan = planner(environments);
69 if (plan.unavailableReason) {
70 toastManager.add({
71 type: "warning",
72 title: m(msg("Setting not saved")),
73 description: plan.unavailableReason,
74 });
75 onFailed?.();
76 return;
77 }
78 const save = {};
79 const settle = (environmentId: EnvironmentId, saved?: ServerSettings) =>
80 appAtomRegistry.update(pendingScopedWritesAtom, (writes) =>
81 settlePendingScopedWrites(
82 writes,
83 { save, environmentId },
84 (id) => readSettings(id) ?? undefined,
85 saved,
86 ),
87 );
88 appAtomRegistry.update(pendingScopedWritesAtom, (writes) => [
89 ...writes,
90 ...plan.serverWrites.map(({ environmentId, patch }) => ({ save, environmentId, patch })),
91 ]);
92 void writeScopedSettings(
93 environments,
94 planner,
95 async (request) => {
96 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
97 (scope) => !readEnvironmentScope(request.environmentId, scope),
98 );
99 const result = missing
100 ? AsyncResult.failure(
101 Cause.fail(
102 new EnvironmentAuthorizationError({
103 requiredScope: missing,
104 message: m(msg("This connection lacks permission to change these settings.")),
105 }),
106 ),
107 )
108 : await persistServer(request).catch((error: unknown) => {
109 settle(request.environmentId);
110 throw error;
111 });
112 settle(request.environmentId, result._tag === "Success" ? result.value : undefined);
113 return result;
114 },
115 persistClientSettingsPatch,
116 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
117 if (failedEnvironments.length === 0) return;
118 onFailed?.();
119 toastManager.add({
120 type: "error",
121 title:
122 savedEnvironmentCount > 0
123 ? m(msg("Setting saved on some environments"))
124 : m(msg("Setting not saved")),
125 description: [
126 ...failedEnvironments.map(({ label, message }) =>
127 m(msg`Could not save on ${{ label }}: ${{ message }}`),
128 ),
129 ...(savedEnvironmentCount > 0
130 ? [
131 m(
132 msg`Saved on ${{ environments: savedEnvironments.map(({ label }) => label).join(", ") }}.`,
133 ),
134 ]
135 : []),
136 ].join("\n"),
137 });
138 });
139 };
141​
142export function useUpdateScopedSettings() {
143 const { scope, environments, deviceOnly } = useSettingsScope();
144 const run = useRunScopedPlan();
145 /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
146 return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
147 run(
148 environments,
149 (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }),
150 options?.onFailed,
151 );
153​
154export function useClearScopedSettings() {
155 const context = useOptionalSettingsScope();
156 const run = useRunScopedPlan();
157 return (keys: readonly ProjectScopedServerSettingKey[]) => {
158 if (context === null) return;
159 run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys));
160 };
162​
163export function useClearProjectOverrides() {
164 const context = useOptionalSettingsScope();
165 const run = useRunScopedPlan();
166 return (
167 entries: readonly ProjectOverrideEntry[],
168 keys: readonly ProjectScopedServerSettingKey[],
169 ) => {
170 if (context === null) return;
171 run(context.environments, (current) => planProjectOverridesClear(current, entries, keys));
172 };
174​
175export function useScopedSettingsWriteAllowed() {
176 const { connectedEnvironments } = useSettingsScope();
177 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
178 return (
179 connectedEnvironments.length > 0 &&
180 connectedEnvironments.every((target) => writable.has(target.environmentId))
181 );