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

useSettings.ts

377 lines12.4 KB

1/**
2 * Environment-scoped settings hooks.
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 * Live server settings always require an environment id. Primary-environment
9 * access is intentionally named as such so environment-sensitive consumers
10 * cannot silently read the wrong server's settings.
11 */
12import { useCallback, useMemo, useSyncExternalStore } from "react";
13import { useAtomValue } from "@effect/atom-react";
14import {
15 DEFAULT_SERVER_SETTINGS,
16 type EnvironmentId,
17 ServerSettings,
18 type ServerSettingsPatch,
19} from "@t3tools/contracts";
20import {
21 type ClientSettingsPatch,
22 type ClientSettings,
23 DEFAULT_CLIENT_SETTINGS,
24 type EnvironmentIdentificationMode,
25 type UnifiedSettings,
26} from "@t3tools/contracts/settings";
27import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
28import { ensureLocalApi } from "~/localApi";
29import {
30 getThemeDefinition,
31 getThemePreviewSidebarArtwork,
32 resolveThemeHalf,
33 subscribeToThemePreview,
34 themeAllowsSidebarArtwork,
35} from "~/themePalette";
36import * as Struct from "effect/Struct";
37import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
38import { usePrimaryEnvironment } from "~/state/environments";
39import { useAtomCommand } from "~/state/use-atom-command";
40import { useTheme } from "./useTheme";
41​
42const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
43​
44type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
45​
46const clientSettingsListeners = new Set<() => void>();
47const clientSettingsHydrationListeners = new Set<() => void>();
48let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
49let clientSettingsHydrated = false;
50let clientSettingsHydrationPromise: Promise<void> | null = null;
51let clientSettingsHydrationGeneration = 0;
52​
53function emitClientSettingsChange() {
54 for (const listener of clientSettingsListeners) {
55 listener();
56 }
58​
59function emitClientSettingsHydrationChange() {
60 for (const listener of clientSettingsHydrationListeners) {
61 listener();
62 }
64​
65function getClientSettingsSnapshot(): ClientSettings {
66 return clientSettingsSnapshot;
68​
69function replaceClientSettingsSnapshot(settings: ClientSettings): void {
70 clientSettingsSnapshot = settings;
71 emitClientSettingsChange();
73​
74function setClientSettingsHydrated(nextHydrated: boolean): void {
75 if (clientSettingsHydrated === nextHydrated) {
76 return;
77 }
78 clientSettingsHydrated = nextHydrated;
79 emitClientSettingsHydrationChange();
81​
82function subscribeClientSettings(listener: () => void): () => void {
83 clientSettingsListeners.add(listener);
84 void hydrateClientSettings();
85 return () => {
86 clientSettingsListeners.delete(listener);
87 };
89​
90function getClientSettingsHydratedSnapshot(): boolean {
91 return clientSettingsHydrated;
93​
94function subscribeClientSettingsHydration(listener: () => void): () => void {
95 clientSettingsHydrationListeners.add(listener);
96 void hydrateClientSettings();
97 return () => {
98 clientSettingsHydrationListeners.delete(listener);
99 };
101​
102async function hydrateClientSettings(): Promise<void> {
103 if (clientSettingsHydrated) {
104 return;
105 }
106 if (clientSettingsHydrationPromise) {
107 return clientSettingsHydrationPromise;
108 }
109​
110 const hydrationGeneration = clientSettingsHydrationGeneration;
111 const nextHydration = (async () => {
112 try {
113 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
114 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
115 return;
116 }
117 if (persistedSettings) {
118 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
119 }
120 } catch (error) {
121 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
122 operation: "hydrate",
123 ...safeErrorLogAttributes(error),
124 });
125 } finally {
126 if (hydrationGeneration === clientSettingsHydrationGeneration) {
127 setClientSettingsHydrated(true);
128 }
129 }
130 })();
131​
132 const hydrationPromise = nextHydration.finally(() => {
133 if (clientSettingsHydrationPromise === hydrationPromise) {
134 clientSettingsHydrationPromise = null;
135 }
136 });
137 clientSettingsHydrationPromise = hydrationPromise;
138​
139 return clientSettingsHydrationPromise;
141​
142function persistClientSettings(settings: ClientSettings): void {
143 replaceClientSettingsSnapshot(settings);
144 void ensureLocalApi()
145 .persistence.setClientSettings(settings)
146 .catch((error) => {
147 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
148 operation: "persist",
149 ...safeErrorLogAttributes(error),
150 });
151 });
153​
154// ── Key sets for routing patches ─────────────────────────────────────
155​
156const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
157​
158function splitPatch(patch: UnifiedSettingsPatch): {
159 serverPatch: ServerSettingsPatch;
160 clientPatch: ClientSettingsPatch;
161} {
162 const serverPatch: Record<string, unknown> = {};
163 const clientPatch: Record<string, unknown> = {};
164 for (const [key, value] of Object.entries(patch)) {
165 if (SERVER_SETTINGS_KEYS.has(key)) {
166 serverPatch[key] = value;
167 } else {
168 clientPatch[key] = value;
169 }
170 }
171 return {
172 serverPatch: serverPatch as ServerSettingsPatch,
173 clientPatch: clientPatch as ClientSettingsPatch,
174 };
176​
177// ── Hooks ────────────────────────────────────────────────────────────
178​
179/**
180 * Non-hook accessor for the current merged client settings snapshot.
181 * Used by non-React code paths (e.g. runtime services) that need the latest
182 * settings without subscribing.
183 */
184export function getClientSettings(): ClientSettings {
185 return getClientSettingsSnapshot();
187​
188/**
189 * Resolves once client settings have been read from disk.
190 *
191 * The pre-hydration snapshot is just the schema defaults, so imperative paths
192 * that open a preview must await this or they bake the built-in viewport, zoom
193 * and appearance into a tab that never picks up the user's saved values.
194 */
195export function ensureClientSettingsHydrated(): Promise<void> {
196 return hydrateClientSettings();
198​
199export function useClientSettingsHydrated(): boolean {
200 return useSyncExternalStore(
201 subscribeClientSettingsHydration,
202 getClientSettingsHydratedSnapshot,
203 () => false,
204 );
206​
207function useClientSettingsValue(): ClientSettings {
208 return useSyncExternalStore(
209 subscribeClientSettings,
210 getClientSettingsSnapshot,
211 () => DEFAULT_CLIENT_SETTINGS,
212 );
214​
215export function mergeEnvironmentSettings(
216 serverSettings: ServerSettings,
217 clientSettings: ClientSettings,
218): UnifiedSettings {
219 // Decode drops retired client keys, but older untyped persistence adapters
220 // can still return them. Server-owned values must always win.
221 return { ...clientSettings, ...serverSettings };
223​
224function useMergedSettings<T>(
225 serverSettings: ServerSettings,
226 selector: ((settings: UnifiedSettings) => T) | undefined,
227): T {
228 const clientSettings = useClientSettingsValue();
229​
230 const merged = useMemo<UnifiedSettings>(
231 () => mergeEnvironmentSettings(serverSettings, clientSettings),
232 [clientSettings, serverSettings],
233 );
234​
235 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
237​
238export function useClientSettings<T = ClientSettings>(
239 selector?: (settings: ClientSettings) => T,
240): T {
241 const settings = useClientSettingsValue();
242 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
244​
245export function resolveEnvironmentIdentificationMode(input: {
246 mode: EnvironmentIdentificationMode;
247 settingsHydrated: boolean;
248 paletteThemeActive?: boolean;
249 paletteThemeAllowsArtwork?: boolean;
250}): EnvironmentIdentificationMode {
251 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
252 if (!input.settingsHydrated) return "none";
253 // Artwork palettes are maintained for built-ins only. Keep an explicit
254 // "none", but use the theme-aware pill for user-controlled palettes.
255 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
256 ? "pill"
257 : input.mode;
259​
260export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
261 const settingsHydrated = useClientSettingsHydrated();
262 const mode = useClientSettingsValue().environmentIdentificationMode;
263 const { resolvedTheme, theme, themeHalves } = useTheme();
264 const previewSidebarArtwork = useSyncExternalStore(
265 subscribeToThemePreview,
266 getThemePreviewSidebarArtwork,
267 () => null,
268 );
269 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
270 const activeThemeDefinition = getThemeDefinition(activeTheme);
271 return resolveEnvironmentIdentificationMode({
272 mode,
273 settingsHydrated,
274 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
275 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
276 });
278​
279/**
280 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
281 * the default one.
282 *
283 * Held at the default sidebar until client settings hydrate: the pre-hydration
284 * snapshot is just the schema defaults, so resolving against it could mount one
285 * sidebar and then swap it out once persisted settings land — remounting the
286 * whole tree for everyone instead of only for legacy opt-ins.
287 */
288export function useLegacySidebarEnabled(): boolean {
289 const settingsHydrated = useClientSettingsHydrated();
290 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
291 return settingsHydrated && legacySidebarEnabled;
293​
294/** Read current settings for one environment, merged with client-local preferences. */
295export function useEnvironmentSettings<T = UnifiedSettings>(
296 environmentId: EnvironmentId,
297 selector?: (settings: UnifiedSettings) => T,
298): T {
299 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
300 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
302​
303/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
304export function usePrimarySettings<T = UnifiedSettings>(
305 selector?: (settings: UnifiedSettings) => T,
306): T {
307 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
309​
310/**
311 * Returns an updater that routes each key to the correct backing store.
312 *
313 * Server keys are optimistically patched in atom-backed server state, then
314 * persisted via RPC. Client keys go through client persistence.
315 */
316function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
317 const persistServerSettings = useAtomCommand(
318 serverEnvironment.updateSettings,
319 "server settings update",
320 );
321 const updateSettings = useCallback(
322 (patch: UnifiedSettingsPatch) => {
323 const { serverPatch, clientPatch } = splitPatch(patch);
324​
325 if (Object.keys(serverPatch).length > 0) {
326 if (environmentId) {
327 void persistServerSettings({
328 environmentId,
329 input: { patch: serverPatch },
330 });
331 }
332 }
333 if (Object.keys(clientPatch).length > 0) {
334 persistClientSettings({
335 ...getClientSettingsSnapshot(),
336 ...clientPatch,
337 });
338 }
339 },
340 [environmentId, persistServerSettings],
341 );
342​
343 return updateSettings;
345​
346export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
347 return useUpdateSettingsTarget(environmentId);
349​
350export function useUpdatePrimarySettings() {
351 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
353​
354export function useUpdateClientSettings() {
355 return useCallback((patch: ClientSettingsPatch) => {
356 persistClientSettings({
357 ...getClientSettingsSnapshot(),
358 ...patch,
359 });
360 }, []);
362​
363export function __resetClientSettingsPersistenceForTests(): void {
364 clientSettingsHydrationGeneration += 1;
365 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
366 clientSettingsHydrated = false;
367 clientSettingsHydrationPromise = null;
368 clientSettingsListeners.clear();
369 clientSettingsHydrationListeners.clear();
371​
372export function __setClientSettingsForTests(settings: ClientSettings): void {
373 clientSettingsHydrationGeneration += 1;
374 clientSettingsSnapshot = settings;
375 clientSettingsHydrated = true;
376 clientSettingsHydrationPromise = null;