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

useSettings.ts

196 lines6.2 KB

1/**
2 * Unified settings hook.
3 *
4 * Abstracts the split between server-authoritative settings (persisted in
5 * `settings.json` on the server, fetched via `server.getConfig`) and
6 * client-only settings (persisted in localStorage).
7 *
8 * Consumers use `useSettings(selector)` to read, and `useUpdateSettings()` to
9 * write. The hook transparently routes reads/writes to the correct backing
10 * store.
11 */
12import { useCallback, useMemo, useSyncExternalStore } from "react";
13import { ServerSettings, type ServerSettingsPatch } from "@t3tools/contracts";
14import {
15 type ClientSettingsPatch,
16 type ClientSettings,
17 DEFAULT_CLIENT_SETTINGS,
18 DEFAULT_UNIFIED_SETTINGS,
19 UnifiedSettings,
20} from "@t3tools/contracts/settings";
21import { ensureLocalApi } from "~/localApi";
22import { Struct } from "effect";
23import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
24import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
25​
26const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
27​
28const clientSettingsListeners = new Set<() => void>();
29let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
30let clientSettingsHydrated = false;
31let clientSettingsHydrationPromise: Promise<void> | null = null;
32​
33function emitClientSettingsChange() {
34 for (const listener of clientSettingsListeners) {
35 listener();
36 }
38​
39function getClientSettingsSnapshot(): ClientSettings {
40 return clientSettingsSnapshot;
42​
43function replaceClientSettingsSnapshot(settings: ClientSettings): void {
44 clientSettingsSnapshot = settings;
45 emitClientSettingsChange();
47​
48function subscribeClientSettings(listener: () => void): () => void {
49 clientSettingsListeners.add(listener);
50 void hydrateClientSettings();
51 return () => {
52 clientSettingsListeners.delete(listener);
53 };
55​
56async function hydrateClientSettings(): Promise<void> {
57 if (clientSettingsHydrated) {
58 return;
59 }
60 if (clientSettingsHydrationPromise) {
61 return clientSettingsHydrationPromise;
62 }
63​
64 const nextHydration = (async () => {
65 try {
66 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
67 if (persistedSettings) {
68 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
69 }
70 } catch (error) {
71 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
72 } finally {
73 clientSettingsHydrated = true;
74 }
75 })();
76​
77 const hydrationPromise = nextHydration.finally(() => {
78 if (clientSettingsHydrationPromise === hydrationPromise) {
79 clientSettingsHydrationPromise = null;
80 }
81 });
82 clientSettingsHydrationPromise = hydrationPromise;
83​
84 return clientSettingsHydrationPromise;
86​
87function persistClientSettings(settings: ClientSettings): void {
88 replaceClientSettingsSnapshot(settings);
89 void ensureLocalApi()
90 .persistence.setClientSettings(settings)
91 .catch((error) => {
92 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
93 });
95​
96// ── Key sets for routing patches ─────────────────────────────────────
97​
98const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
99​
100function splitPatch(patch: Partial<UnifiedSettings>): {
101 serverPatch: ServerSettingsPatch;
102 clientPatch: ClientSettingsPatch;
103} {
104 const serverPatch: Record<string, unknown> = {};
105 const clientPatch: Record<string, unknown> = {};
106 for (const [key, value] of Object.entries(patch)) {
107 if (SERVER_SETTINGS_KEYS.has(key)) {
108 serverPatch[key] = value;
109 } else {
110 clientPatch[key] = value;
111 }
112 }
113 return {
114 serverPatch: serverPatch as ServerSettingsPatch,
115 clientPatch: clientPatch as ClientSettingsPatch,
116 };
118​
119// ── Hooks ────────────────────────────────────────────────────────────
120​
121/**
122 * Read merged settings. Selector narrows the subscription so components
123 * only re-render when the slice they care about changes.
124 */
125​
126/**
127 * Non-hook accessor for the current merged client settings snapshot.
128 * Used by non-React code paths (e.g. runtime services) that need the latest
129 * settings without subscribing.
130 */
131export function getClientSettings(): ClientSettings {
132 return getClientSettingsSnapshot();
134​
135export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
136 const serverSettings = useServerSettings();
137 const clientSettings = useSyncExternalStore(
138 subscribeClientSettings,
139 getClientSettingsSnapshot,
140 () => DEFAULT_CLIENT_SETTINGS,
141 );
142​
143 const merged = useMemo<UnifiedSettings>(
144 () => ({
145 ...serverSettings,
146 ...clientSettings,
147 }),
148 [clientSettings, serverSettings],
149 );
150​
151 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
153​
154/**
155 * Returns an updater that routes each key to the correct backing store.
156 *
157 * Server keys are optimistically patched in atom-backed server state, then
158 * persisted via RPC. Client keys go through client persistence.
159 */
160export function useUpdateSettings() {
161 const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
162 const { serverPatch, clientPatch } = splitPatch(patch);
163​
164 if (Object.keys(serverPatch).length > 0) {
165 const currentServerConfig = getServerConfig();
166 if (currentServerConfig) {
167 applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
168 }
169 // Fire-and-forget RPC — push will reconcile on success
170 void ensureLocalApi().server.updateSettings(serverPatch);
171 }
172​
173 if (Object.keys(clientPatch).length > 0) {
174 persistClientSettings({
175 ...getClientSettingsSnapshot(),
176 ...clientPatch,
177 });
178 }
179 }, []);
180​
181 const resetSettings = useCallback(() => {
182 updateSettings(DEFAULT_UNIFIED_SETTINGS);
183 }, [updateSettings]);
184​
185 return {
186 updateSettings,
187 resetSettings,
188 };
190​
191export function __resetClientSettingsPersistenceForTests(): void {
192 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
193 clientSettingsHydrated = false;
194 clientSettingsHydrationPromise = null;
195 clientSettingsListeners.clear();