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