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

useScopedSettings.ts

151 lines5.2 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 {
11 DEFAULT_SERVER_SETTINGS,
12 type ProjectScopedServerSettingKey,
13 type ServerSettings,
14 type UnifiedSettings,
15} from "@t3tools/contracts";
16​
17import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
18import { readEnvironment } from "../../state/environments";
19import { serverEnvironment } from "../../state/server";
20import { useAtomCommand } from "../../state/use-atom-command";
21import { toastManager } from "../ui/toast";
22import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
23import {
24 createScopedSettingsWriter,
25 planProjectOverridesClear,
26 planScopedSettingsClear,
27 planScopedSettingsPatch,
28 scopedSettingsAreMixed,
29 scopedSettingsSource,
30 type ProjectOverrideEntry,
31 type ScopedSettingsPatch,
32} from "./scopedSettings";
33​
34const writeScopedSettings = createScopedSettingsWriter(
35 (environmentId) => readEnvironment(environmentId)?.serverConfig?.settings ?? null,
36);
37​
38export function useScopedSettings<T = UnifiedSettings>(
39 selector?: (settings: UnifiedSettings) => T,
40): T {
41 const { target } = useSettingsScope();
42 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
44​
45export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
46 const { targets } = useSettingsScope();
47 return scopedSettingsAreMixed(targets, keys);
49​
50export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
51 const { targets } = useSettingsScope();
52 return scopedSettingsSource(targets, keys);
54​
55function useRunScopedPlan() {
56 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
57 return (
58 environments: Parameters<typeof writeScopedSettings>[0],
59 planner: Parameters<typeof writeScopedSettings>[1],
60 onFailed?: () => void,
61 ) => {
62 const plan = planner(environments);
63 if (plan.unavailableReason) {
64 toastManager.add({
65 type: "warning",
66 title: "Setting not saved",
67 description: plan.unavailableReason,
68 });
69 onFailed?.();
70 return;
71 }
72 void writeScopedSettings(
73 environments,
74 planner,
75 async (request) => {
76 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
77 (scope) => !readEnvironmentScope(request.environmentId, scope),
78 );
79 if (missing)
80 return AsyncResult.failure(
81 Cause.fail(
82 new EnvironmentAuthorizationError({
83 requiredScope: missing,
84 message: "This connection lacks permission to change these settings.",
85 }),
86 ),
87 );
88 return persistServer(request);
89 },
90 persistClientSettingsPatch,
91 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
92 if (failedEnvironments.length === 0) return;
93 onFailed?.();
94 toastManager.add({
95 type: "error",
96 title:
97 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
98 description: [
99 ...failedEnvironments.map(
100 ({ label, message }) => `Could not save on ${label}: ${message}`,
101 ),
102 ...(savedEnvironmentCount > 0
103 ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
104 : []),
105 ].join("\n"),
106 });
107 });
108 };
110​
111export function useUpdateScopedSettings() {
112 const { scope, environments, deviceOnly } = useSettingsScope();
113 const run = useRunScopedPlan();
114 /** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
115 return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
116 run(
117 environments,
118 (current) => planScopedSettingsPatch(scope, current, patch, { deviceOnly }),
119 options?.onFailed,
120 );
122​
123export function useClearScopedSettings() {
124 const context = useOptionalSettingsScope();
125 const run = useRunScopedPlan();
126 return (keys: readonly ProjectScopedServerSettingKey[]) => {
127 if (context === null) return;
128 run(context.environments, (current) => planScopedSettingsClear(context.scope, current, keys));
129 };
131​
132export function useClearProjectOverrides() {
133 const context = useOptionalSettingsScope();
134 const run = useRunScopedPlan();
135 return (
136 entries: readonly ProjectOverrideEntry[],
137 keys: readonly ProjectScopedServerSettingKey[],
138 ) => {
139 if (context === null) return;
140 run(context.environments, (current) => planProjectOverridesClear(current, entries, keys));
141 };
143​
144export function useScopedSettingsWriteAllowed() {
145 const { connectedEnvironments } = useSettingsScope();
146 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
147 return (
148 connectedEnvironments.length > 0 &&
149 connectedEnvironments.every((target) => writable.has(target.environmentId))
150 );