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

useSettings.ts

232 lines7.1 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 * as Struct from "effect/Struct";
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>();
29const clientSettingsHydrationListeners = new Set<() => void>();
30let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
31let clientSettingsHydrated = false;
32let clientSettingsHydrationPromise: Promise<void> | null = null;
33​
34function emitClientSettingsChange() {
35 for (const listener of clientSettingsListeners) {
36 listener();
37 }
39​
40function emitClientSettingsHydrationChange() {
41 for (const listener of clientSettingsHydrationListeners) {
42 listener();
43 }
45​
46function getClientSettingsSnapshot(): ClientSettings {
47 return clientSettingsSnapshot;
49​
50function replaceClientSettingsSnapshot(settings: ClientSettings): void {
51 clientSettingsSnapshot = settings;
52 emitClientSettingsChange();
54​
55function setClientSettingsHydrated(nextHydrated: boolean): void {
56 if (clientSettingsHydrated === nextHydrated) {
57 return;
58 }
59 clientSettingsHydrated = nextHydrated;
60 emitClientSettingsHydrationChange();
62​
63function subscribeClientSettings(listener: () => void): () => void {
64 clientSettingsListeners.add(listener);
65 void hydrateClientSettings();
66 return () => {
67 clientSettingsListeners.delete(listener);
68 };
70​
71function getClientSettingsHydratedSnapshot(): boolean {
72 return clientSettingsHydrated;
74​
75function subscribeClientSettingsHydration(listener: () => void): () => void {
76 clientSettingsHydrationListeners.add(listener);
77 void hydrateClientSettings();
78 return () => {
79 clientSettingsHydrationListeners.delete(listener);
80 };
82​
83async function hydrateClientSettings(): Promise<void> {
84 if (clientSettingsHydrated) {
85 return;
86 }
87 if (clientSettingsHydrationPromise) {
88 return clientSettingsHydrationPromise;
89 }
90​
91 const nextHydration = (async () => {
92 try {
93 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
94 if (persistedSettings) {
95 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
96 }
97 } catch (error) {
98 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
99 } finally {
100 setClientSettingsHydrated(true);
101 }
102 })();
103​
104 const hydrationPromise = nextHydration.finally(() => {
105 if (clientSettingsHydrationPromise === hydrationPromise) {
106 clientSettingsHydrationPromise = null;
107 }
108 });
109 clientSettingsHydrationPromise = hydrationPromise;
110​
111 return clientSettingsHydrationPromise;
113​
114function persistClientSettings(settings: ClientSettings): void {
115 replaceClientSettingsSnapshot(settings);
116 void ensureLocalApi()
117 .persistence.setClientSettings(settings)
118 .catch((error) => {
119 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
120 });
122​
123// ── Key sets for routing patches ─────────────────────────────────────
124​
125const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
126​
127function splitPatch(patch: Partial<UnifiedSettings>): {
128 serverPatch: ServerSettingsPatch;
129 clientPatch: ClientSettingsPatch;
130} {
131 const serverPatch: Record<string, unknown> = {};
132 const clientPatch: Record<string, unknown> = {};
133 for (const [key, value] of Object.entries(patch)) {
134 if (SERVER_SETTINGS_KEYS.has(key)) {
135 serverPatch[key] = value;
136 } else {
137 clientPatch[key] = value;
138 }
139 }
140 return {
141 serverPatch: serverPatch as ServerSettingsPatch,
142 clientPatch: clientPatch as ClientSettingsPatch,
143 };
145​
146// ── Hooks ────────────────────────────────────────────────────────────
147​
148/**
149 * Read merged settings. Selector narrows the subscription so components
150 * only re-render when the slice they care about changes.
151 */
152​
153/**
154 * Non-hook accessor for the current merged client settings snapshot.
155 * Used by non-React code paths (e.g. runtime services) that need the latest
156 * settings without subscribing.
157 */
158export function getClientSettings(): ClientSettings {
159 return getClientSettingsSnapshot();
161​
162export function useClientSettingsHydrated(): boolean {
163 return useSyncExternalStore(
164 subscribeClientSettingsHydration,
165 getClientSettingsHydratedSnapshot,
166 () => false,
167 );
169​
170export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
171 const serverSettings = useServerSettings();
172 const clientSettings = useSyncExternalStore(
173 subscribeClientSettings,
174 getClientSettingsSnapshot,
175 () => DEFAULT_CLIENT_SETTINGS,
176 );
177​
178 const merged = useMemo<UnifiedSettings>(
179 () => ({
180 ...serverSettings,
181 ...clientSettings,
182 }),
183 [clientSettings, serverSettings],
184 );
185​
186 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
188​
189/**
190 * Returns an updater that routes each key to the correct backing store.
191 *
192 * Server keys are optimistically patched in atom-backed server state, then
193 * persisted via RPC. Client keys go through client persistence.
194 */
195export function useUpdateSettings() {
196 const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
197 const { serverPatch, clientPatch } = splitPatch(patch);
198​
199 if (Object.keys(serverPatch).length > 0) {
200 const currentServerConfig = getServerConfig();
201 if (currentServerConfig) {
202 applySettingsUpdated(applyServerSettingsPatch(currentServerConfig.settings, serverPatch));
203 }
204 // Fire-and-forget RPC — push will reconcile on success
205 void ensureLocalApi().server.updateSettings(serverPatch);
206 }
207​
208 if (Object.keys(clientPatch).length > 0) {
209 persistClientSettings({
210 ...getClientSettingsSnapshot(),
211 ...clientPatch,
212 });
213 }
214 }, []);
215​
216 const resetSettings = useCallback(() => {
217 updateSettings(DEFAULT_UNIFIED_SETTINGS);
218 }, [updateSettings]);
219​
220 return {
221 updateSettings,
222 resetSettings,
223 };
225​
226export function __resetClientSettingsPersistenceForTests(): void {
227 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
228 clientSettingsHydrated = false;
229 clientSettingsHydrationPromise = null;
230 clientSettingsListeners.clear();
231 clientSettingsHydrationListeners.clear();