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

useSettings.ts

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