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

useScopedSettings.ts

132 lines4.5 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 { serverEnvironment } from "../../state/server";
19import { useAtomCommand } from "../../state/use-atom-command";
20import { toastManager } from "../ui/toast";
21import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
22import {
23 persistScopedSettingsPatch,
24 planProjectOverridesClear,
25 planScopedSettingsClear,
26 planScopedSettingsPatch,
27 scopedSettingsAreMixed,
28 scopedSettingsSource,
29 type ProjectOverrideEntry,
30 type ScopedSettingsPatch,
31} from "./scopedSettings";
32​
33export function useScopedSettings<T = UnifiedSettings>(
34 selector?: (settings: UnifiedSettings) => T,
35): T {
36 const { target } = useSettingsScope();
37 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
39​
40export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
41 const { targets } = useSettingsScope();
42 return scopedSettingsAreMixed(targets, keys);
44​
45export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
46 const { targets } = useSettingsScope();
47 return scopedSettingsSource(targets, keys);
49​
50function useRunScopedPlan() {
51 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
52 return (plan: ReturnType<typeof planScopedSettingsPatch>) => {
53 if (plan.unavailableReason) {
54 toastManager.add({
55 type: "warning",
56 title: "Setting not saved",
57 description: plan.unavailableReason,
58 });
59 return;
60 }
61 void persistScopedSettingsPatch(
62 plan,
63 async (request) => {
64 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
65 (scope) => !readEnvironmentScope(request.environmentId, scope),
66 );
67 if (missing)
68 return AsyncResult.failure(
69 Cause.fail(
70 new EnvironmentAuthorizationError({
71 requiredScope: missing,
72 message: "This connection lacks permission to change these settings.",
73 }),
74 ),
75 );
76 return persistServer(request);
77 },
78 persistClientSettingsPatch,
79 ).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
80 if (failedEnvironments.length === 0) return;
81 toastManager.add({
82 type: "error",
83 title:
84 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
85 description: [
86 ...failedEnvironments.map(
87 ({ label, message }) => `Could not save on ${label}: ${message}`,
88 ),
89 ...(savedEnvironmentCount > 0
90 ? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
91 : []),
92 ].join("\n"),
93 });
94 });
95 };
97​
98export function useUpdateScopedSettings() {
99 const { scope, environments } = useSettingsScope();
100 const run = useRunScopedPlan();
101 return (patch: ScopedSettingsPatch) => run(planScopedSettingsPatch(scope, environments, patch));
103​
104export function useClearScopedSettings() {
105 const context = useOptionalSettingsScope();
106 const run = useRunScopedPlan();
107 return (keys: readonly ProjectScopedServerSettingKey[]) => {
108 if (context === null) return;
109 run(planScopedSettingsClear(context.scope, context.environments, keys));
110 };
112​
113export function useClearProjectOverrides() {
114 const context = useOptionalSettingsScope();
115 const run = useRunScopedPlan();
116 return (
117 entries: readonly ProjectOverrideEntry[],
118 keys: readonly ProjectScopedServerSettingKey[],
119 ) => {
120 if (context === null) return;
121 run(planProjectOverridesClear(context.environments, entries, keys));
122 };
124​
125export function useScopedSettingsWriteAllowed() {
126 const { connectedEnvironments } = useSettingsScope();
127 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
128 return (
129 connectedEnvironments.length > 0 &&
130 connectedEnvironments.every((target) => writable.has(target.environmentId))
131 );