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

useScopedSettings.ts

153 lines5.4 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";
16import { useCallback, useMemo } from "react";
17​
18import {
19 mergeEnvironmentSettings,
20 persistClientSettingsPatch,
21 useClientSettings,
22} from "../../hooks/useSettings";
23import { serverEnvironment } from "../../state/server";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { toastManager } from "../ui/toast";
26import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext";
27import {
28 persistScopedSettingsPatch,
29 planProjectOverridesClear,
30 planScopedSettingsClear,
31 planScopedSettingsPatch,
32 scopedSettingsAreMixed,
33 scopedSettingsSource,
34 type ProjectOverrideEntry,
35 type ScopedSettingsPatch,
36} from "./scopedSettings";
37​
38/** Effective settings for the representative target: project overrides applied on top of its environment. */
39export function useScopedSettings<T = UnifiedSettings>(
40 selector?: (settings: UnifiedSettings) => T,
41): T {
42 const { target } = useSettingsScope();
43 const clientSettings = useClientSettings();
44 const serverSettings = target?.settings ?? DEFAULT_SERVER_SETTINGS;
45 const settings = useMemo(
46 () => mergeEnvironmentSettings(serverSettings, clientSettings),
47 [clientSettings, serverSettings],
48 );
49 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
51​
52export function useScopedSettingsMixed(keys: readonly (keyof ServerSettings)[]): boolean {
53 const { targets } = useSettingsScope();
54 return scopedSettingsAreMixed(targets, keys);
56​
57/** Where the keys' effective values come from across the selected targets. */
58export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[]) {
59 const { targets } = useSettingsScope();
60 return scopedSettingsSource(targets, keys);
62​
63function useRunScopedPlan() {
64 const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
65 return useCallback(
66 (plan: ReturnType<typeof planScopedSettingsPatch>) => {
67 if (plan.unavailableReason) {
68 toastManager.add({
69 type: "warning",
70 title: "Setting not saved",
71 description: plan.unavailableReason,
72 });
73 return;
74 }
75 void persistScopedSettingsPatch(
76 plan,
77 async (request) => {
78 const missing = requiredScopesForServerSettingsPatch(request.input.patch).find(
79 (scope) => !readEnvironmentScope(request.environmentId, scope),
80 );
81 if (missing)
82 return AsyncResult.failure(
83 Cause.fail(
84 new EnvironmentAuthorizationError({
85 requiredScope: missing,
86 message: "This connection cannot change these settings.",
87 }),
88 ),
89 );
90 return persistServer(request);
91 },
92 persistClientSettingsPatch,
93 ).then(({ failedEnvironments, savedEnvironmentCount }) => {
94 if (failedEnvironments.length === 0) return;
95 toastManager.add({
96 type: "error",
97 title:
98 savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
99 description: `Could not update ${failedEnvironments.map((environment) => environment.label).join(", ")}.${savedEnvironmentCount > 0 ? " The other selected environments saved the change." : ""}`,
100 });
101 });
102 },
103 [persistServer],
104 );
106​
107export function useUpdateScopedSettings() {
108 const { scope, environments } = useSettingsScope();
109 const run = useRunScopedPlan();
110 return useCallback(
111 (patch: ScopedSettingsPatch) => run(planScopedSettingsPatch(scope, environments, patch)),
112 [environments, run, scope],
113 );
115​
116/**
117 * Drop the project overrides for `keys` so the selected checkouts inherit
118 * again. Rows also render outside the settings layout (provider cards,
119 * dialogs), where there is no scope and nothing to clear.
120 */
121export function useClearScopedSettings() {
122 const context = useOptionalSettingsScope();
123 const run = useRunScopedPlan();
124 return useCallback(
125 (keys: readonly ProjectScopedServerSettingKey[]) => {
126 if (context === null) return;
127 run(planScopedSettingsClear(context.scope, context.environments, keys));
128 },
129 [context, run],
130 );
132​
133/** Clear `keys` on specific project entries, from an environment scope's chain popover. */
134export function useClearProjectOverrides() {
135 const context = useOptionalSettingsScope();
136 const run = useRunScopedPlan();
137 return useCallback(
138 (entries: readonly ProjectOverrideEntry[], keys: readonly ProjectScopedServerSettingKey[]) => {
139 if (context === null) return;
140 run(planProjectOverridesClear(context.environments, entries, keys));
141 },
142 [context, run],
143 );
145​
146export function useScopedSettingsWriteAllowed() {
147 const { connectedEnvironments } = useSettingsScope();
148 const writable = useEnvironmentsWithScope(connectedEnvironments, AuthSettingsWriteScope);
149 return (
150 connectedEnvironments.length > 0 &&
151 connectedEnvironments.every((target) => writable.has(target.environmentId))
152 );