Open History to see the last commit
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 {
29 filterSharedServerPatch,
30 splitSharedServerPatch,
31 supportsSharedSettingsSync,
32} from "@t3tools/client-runtime/state/shared-settings";
33import { ensureLocalApi } from "~/localApi";
34import {
35 getThemeDefinition,
36 getThemePreviewSidebarArtwork,
37 resolveThemeHalf,
38 subscribeToThemePreview,
39 themeAllowsSidebarArtwork,
40} from "~/themePalette";
41import * as Struct from "effect/Struct";
42import { toastManager } from "~/components/ui/toast";
43import { isHostedStaticApp } from "~/hostedPairing";
44import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
45import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
46import { useAtomCommand } from "~/state/use-atom-command";
47import { useTheme } from "./useTheme";
48
49const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
50
51type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
52
53const clientSettingsListeners = new Set<() => void>();
54const clientSettingsHydrationListeners = new Set<() => void>();
55type ClientSettingsHydrationStatus = "pending" | "ready" | "failed" | "retrying";
56let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
57let clientSettingsHydrationStatus: ClientSettingsHydrationStatus = "pending";
58let clientSettingsHydrationPromise: Promise<void> | null = null;
59let clientSettingsHydrationGeneration = 0;
60let clientSettingsPersistenceQueue: Promise<void> = Promise.resolve();
61let deferredClientSettingsPatchCount = 0;
62
63function emitClientSettingsChange() {
64 for (const listener of clientSettingsListeners) {
65 listener();
66 }
67}
68
69function emitClientSettingsHydrationChange() {
70 for (const listener of clientSettingsHydrationListeners) {
71 listener();
72 }
73}
74
75function getClientSettingsSnapshot(): ClientSettings {
76 return clientSettingsSnapshot;
77}
78
79function replaceClientSettingsSnapshot(settings: ClientSettings): void {
80 clientSettingsSnapshot = settings;
81 emitClientSettingsChange();
82}
83
84function setClientSettingsHydrationStatus(nextStatus: ClientSettingsHydrationStatus): void {
85 if (clientSettingsHydrationStatus === nextStatus) {
86 return;
87 }
88 clientSettingsHydrationStatus = nextStatus;
89 emitClientSettingsHydrationChange();
90}
91
92function subscribeClientSettings(listener: () => void): () => void {
93 clientSettingsListeners.add(listener);
94 void hydrateClientSettings().catch(() => undefined);
95 return () => {
96 clientSettingsListeners.delete(listener);
97 };
98}
99
100function getClientSettingsHydratedSnapshot(): boolean {
101 return clientSettingsHydrationStatus === "ready";
102}
103
104function getClientSettingsHydrationStatusSnapshot(): ClientSettingsHydrationStatus {
105 return clientSettingsHydrationStatus;
106}
107
108function subscribeClientSettingsHydration(listener: () => void): () => void {
109 clientSettingsHydrationListeners.add(listener);
110 void hydrateClientSettings().catch(() => undefined);
111 return () => {
112 clientSettingsHydrationListeners.delete(listener);
113 };
114}
115
116async function hydrateClientSettings(): Promise<void> {
117 if (clientSettingsHydrationStatus === "ready") {
118 return;
119 }
120 if (clientSettingsHydrationPromise) {
121 return clientSettingsHydrationPromise;
122 }
123
124 const hydrationGeneration = clientSettingsHydrationGeneration;
125 setClientSettingsHydrationStatus(
126 clientSettingsHydrationStatus === "failed" || clientSettingsHydrationStatus === "retrying"
127 ? "retrying"
128 : "pending",
129 );
130 const nextHydration = (async () => {
131 try {
132 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
133 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
134 return;
135 }
136 if (persistedSettings) {
137 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
138 }
139 setClientSettingsHydrationStatus("ready");
140 } catch (error) {
141 if (hydrationGeneration === clientSettingsHydrationGeneration) {
142 setClientSettingsHydrationStatus("failed");
143 }
144 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
145 operation: "hydrate",
146 ...safeErrorLogAttributes(error),
147 });
148 throw error;
149 }
150 })();
151
152 const hydrationPromise = nextHydration.finally(() => {
153 if (clientSettingsHydrationPromise === hydrationPromise) {
154 clientSettingsHydrationPromise = null;
155 }
156 });
157 clientSettingsHydrationPromise = hydrationPromise;
158
159 return clientSettingsHydrationPromise;
160}
161
162const defaultClientSettingsPersistence = (settings: ClientSettings): Promise<void> =>
163 ensureLocalApi().persistence.setClientSettings(settings);
164
165function enqueueClientSettingsPersistence<A>(work: () => Promise<A>): Promise<A> {
166 const result = clientSettingsPersistenceQueue.then(work);
167 clientSettingsPersistenceQueue = result.then(
168 () => undefined,
169 () => undefined,
170 );
171 return result;
172}
173
174export function persistClientSettingsPatch(
175 patch: ClientSettingsPatch,
176 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
177): Promise<void> {
178 // Patches queued before hydration must publish before newer optimistic patches.
179 const deferPatch =
180 clientSettingsHydrationStatus !== "ready" || deferredClientSettingsPatchCount > 0;
181 if (deferPatch) {
182 deferredClientSettingsPatchCount += 1;
183 } else {
184 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
185 }
186 return enqueueClientSettingsPersistence(async () => {
187 if (deferPatch) {
188 try {
189 if (clientSettingsHydrationStatus !== "ready") {
190 await hydrateClientSettings();
191 }
192 replaceClientSettingsSnapshot({ ...getClientSettingsSnapshot(), ...patch });
193 } finally {
194 deferredClientSettingsPatchCount -= 1;
195 }
196 }
197 await persist(getClientSettingsSnapshot());
198 }).catch((error) => {
199 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
200 operation: "persist",
201 ...safeErrorLogAttributes(error),
202 });
203 });
204}
205
206/**
207 * Persists a client-settings update before publishing it to the in-memory
208 * snapshot. If another settings write lands while persistence is pending, the
209 * updater is reapplied to that newer snapshot and persisted again so neither
210 * change is lost.
211 */
212export async function persistClientSettingsUpdate(
213 update: (current: ClientSettings) => ClientSettings,
214 persist: (settings: ClientSettings) => Promise<void> = defaultClientSettingsPersistence,
215): Promise<ClientSettings> {
216 return enqueueClientSettingsPersistence(async () => {
217 if (clientSettingsHydrationStatus !== "ready") {
218 await hydrateClientSettings();
219 }
220 for (;;) {
221 const current = getClientSettingsSnapshot();
222 const next = update(current);
223 await persist(next);
224 if (getClientSettingsSnapshot() === current) {
225 replaceClientSettingsSnapshot(next);
226 return next;
227 }
228 }
229 });
230}
231
232// ── Key sets for routing patches ─────────────────────────────────────
233
234const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
235
236function splitPatch(patch: UnifiedSettingsPatch): {
237 serverPatch: ServerSettingsPatch;
238 clientPatch: ClientSettingsPatch;
239} {
240 const serverPatch: Record<string, unknown> = {};
241 const clientPatch: Record<string, unknown> = {};
242 for (const [key, value] of Object.entries(patch)) {
243 if (SERVER_SETTINGS_KEYS.has(key)) {
244 serverPatch[key] = value;
245 } else {
246 clientPatch[key] = value;
247 }
248 }
249 return {
250 serverPatch: serverPatch as ServerSettingsPatch,
251 clientPatch: clientPatch as ClientSettingsPatch,
252 };
253}
254
255// ── Hooks ────────────────────────────────────────────────────────────
256
257/**
258 * Non-hook accessor for the current merged client settings snapshot.
259 * Used by non-React code paths (e.g. runtime services) that need the latest
260 * settings without subscribing.
261 */
262export function getClientSettings(): ClientSettings {
263 return getClientSettingsSnapshot();
264}
265
266/**
267 * Resolves after settings load or storage confirms no saved settings exist.
268 * Failed reads reject and remain retryable. They must not allow defaults to
269 * overwrite saved preferences.
270 *
271 * The pre-hydration snapshot is just the schema defaults, so imperative paths
272 * that open a preview must await this or they bake the built-in viewport, zoom
273 * and appearance into a tab that never picks up the user's saved values.
274 */
275export function ensureClientSettingsHydrated(): Promise<void> {
276 return hydrateClientSettings();
277}
278
279export function useClientSettingsHydrated(): boolean {
280 return useSyncExternalStore(
281 subscribeClientSettingsHydration,
282 getClientSettingsHydratedSnapshot,
283 () => false,
284 );
285}
286
287export function useClientSettingsHydrationStatus(): ClientSettingsHydrationStatus {
288 return useSyncExternalStore(
289 subscribeClientSettingsHydration,
290 getClientSettingsHydrationStatusSnapshot,
291 () => "pending",
292 );
293}
294
295function useClientSettingsValue(): ClientSettings {
296 return useSyncExternalStore(
297 subscribeClientSettings,
298 getClientSettingsSnapshot,
299 () => DEFAULT_CLIENT_SETTINGS,
300 );
301}
302
303export function mergeEnvironmentSettings(
304 serverSettings: ServerSettings,
305 clientSettings: ClientSettings,
306): UnifiedSettings {
307 // Decode drops retired client keys, but older untyped persistence adapters
308 // can still return them. Server-owned values must always win.
309 return { ...clientSettings, ...serverSettings };
310}
311
312function useMergedSettings<T>(
313 serverSettings: ServerSettings,
314 selector: ((settings: UnifiedSettings) => T) | undefined,
315): T {
316 const clientSettings = useClientSettingsValue();
317
318 const merged = useMemo<UnifiedSettings>(
319 () => mergeEnvironmentSettings(serverSettings, clientSettings),
320 [clientSettings, serverSettings],
321 );
322
323 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
324}
325
326export function useClientSettings<T = ClientSettings>(
327 selector?: (settings: ClientSettings) => T,
328): T {
329 const settings = useClientSettingsValue();
330 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
331}
332
333export function resolveEnvironmentIdentificationMode(input: {
334 mode: EnvironmentIdentificationMode;
335 settingsHydrated: boolean;
336 paletteThemeActive?: boolean;
337 paletteThemeAllowsArtwork?: boolean;
338}): EnvironmentIdentificationMode {
339 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
340 if (!input.settingsHydrated) return "none";
341 // Artwork palettes are maintained for built-ins only. Keep an explicit
342 // "none", but use the theme-aware pill for user-controlled palettes.
343 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
344 ? "pill"
345 : input.mode;
346}
347
348export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
349 const settingsHydrated = useClientSettingsHydrated();
350 const mode = useClientSettingsValue().environmentIdentificationMode;
351 const { resolvedTheme, theme, themeHalves } = useTheme();
352 const previewSidebarArtwork = useSyncExternalStore(
353 subscribeToThemePreview,
354 getThemePreviewSidebarArtwork,
355 () => null,
356 );
357 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
358 const activeThemeDefinition = getThemeDefinition(activeTheme);
359 return resolveEnvironmentIdentificationMode({
360 mode,
361 settingsHydrated,
362 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
363 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
364 });
365}
366
367/**
368 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
369 * the default one.
370 *
371 * Held at the default sidebar until client settings hydrate: the pre-hydration
372 * snapshot is just the schema defaults, so resolving against it could mount one
373 * sidebar and then swap it out once persisted settings land — remounting the
374 * whole tree for everyone instead of only for legacy opt-ins.
375 */
376export function useLegacySidebarEnabled(): boolean {
377 const settingsHydrated = useClientSettingsHydrated();
378 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
379 return settingsHydrated && legacySidebarEnabled;
380}
381
382/** Keep the default collapsed sidebar until persisted client settings hydrate. */
383export function useCompactSidebarEnabled(): boolean {
384 const settingsHydrated = useClientSettingsHydrated();
385 const compactSidebarEnabled = useClientSettingsValue().compactSidebarEnabled;
386 return settingsHydrated && compactSidebarEnabled;
387}
388
389/** Read current settings for one environment, merged with client-local preferences. */
390export function useEnvironmentSettings<T = UnifiedSettings>(
391 environmentId: EnvironmentId,
392 selector?: (settings: UnifiedSettings) => T,
393): T {
394 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
395 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
396}
397
398/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
399export function usePrimarySettings<T = UnifiedSettings>(
400 selector?: (settings: UnifiedSettings) => T,
401): T {
402 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
403}
404
405export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
406 "This setting is saved on a server, and the hosted app is not anchored to one. Change it from the desktop app or from the server's own address.";
407
408/**
409 * Whether primary-scoped server settings have a server to live on. The
410 * hosted app connects to every environment as a remote, so it has no primary:
411 * `usePrimarySettings` reads schema defaults there and writes have nowhere
412 * to go. Desktop and server-served web always have one.
413 */
414export function usePrimarySettingsAvailable(): boolean {
415 const primaryEnvironment = usePrimaryEnvironment();
416 return primaryEnvironment !== null || !isHostedStaticApp();
417}
418
419/**
420 * Returns an updater that routes each key to the correct backing store.
421 *
422 * Server keys are optimistically patched in atom-backed server state, then
423 * persisted via RPC. Shared server keys (see `SHARED_SERVER_SETTING_KEYS`)
424 * are written to every eligible sync target, not only the selected target, so
425 * a user preference does not silently drift between machines. Client keys go
426 * through client persistence.
427 */
428function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
429 const persistServerSettings = useAtomCommand(
430 serverEnvironment.updateSettings,
431 "server settings update",
432 );
433 const { environments } = useEnvironments();
434 const updateSettings = useCallback(
435 (patch: UnifiedSettingsPatch) => {
436 const { serverPatch, clientPatch } = splitPatch(patch);
437
438 if (Object.keys(serverPatch).length > 0) {
439 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
440 // Dropping the write silently leaves the control looking saved.
441 const warnUnsaved = (description = PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE) =>
442 toastManager.add({
443 type: "warning",
444 title: "Setting not saved",
445 description,
446 });
447 if (Object.keys(localPatch).length > 0) {
448 if (environmentId) {
449 void persistServerSettings({
450 environmentId,
451 input: { patch: localPatch },
452 });
453 } else {
454 warnUnsaved();
455 }
456 }
457 if (Object.keys(sharedPatch).length > 0) {
458 const sourceSettings = environments.find(
459 (target) => target.environmentId === environmentId,
460 )?.serverConfig?.settings;
461 const targets = new Set(
462 environments.filter(supportsSharedSettingsSync).map((target) => target.environmentId),
463 );
464 if (environmentId) {
465 targets.add(environmentId);
466 }
467 let wroteToTarget = false;
468 for (const targetId of targets) {
469 const target = environments.find((candidate) => candidate.environmentId === targetId);
470 const targetPatch = filterSharedServerPatch(
471 sharedPatch,
472 target?.serverConfig?.environment.capabilities,
473 target?.serverConfig?.settings,
474 sourceSettings,
475 targetId === environmentId,
476 );
477 if (Object.keys(targetPatch).length === 0) continue;
478 wroteToTarget = true;
479 void persistServerSettings({
480 environmentId: targetId,
481 input: { patch: targetPatch },
482 });
483 }
484 if (!wroteToTarget) {
485 warnUnsaved(
486 targets.size > 0 ? "Update older servers to save this setting." : undefined,
487 );
488 }
489 }
490 }
491 if (Object.keys(clientPatch).length > 0) {
492 void persistClientSettingsPatch(clientPatch);
493 }
494 },
495 [environmentId, environments, persistServerSettings],
496 );
497
498 return updateSettings;
499}
500
501export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
502 return useUpdateSettingsTarget(environmentId);
503}
504
505export function useUpdatePrimarySettings() {
506 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
507}
508
509export function useUpdateClientSettings() {
510 return useCallback((patch: ClientSettingsPatch) => {
511 return persistClientSettingsPatch(patch);
512 }, []);
513}
514
515export function __resetClientSettingsPersistenceForTests(): void {
516 clientSettingsHydrationGeneration += 1;
517 clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
518 clientSettingsHydrationStatus = "pending";
519 clientSettingsHydrationPromise = null;
520 clientSettingsPersistenceQueue = Promise.resolve();
521 deferredClientSettingsPatchCount = 0;
522 clientSettingsListeners.clear();
523 clientSettingsHydrationListeners.clear();
524}
525
526export function __setClientSettingsForTests(settings: ClientSettings): void {
527 clientSettingsHydrationGeneration += 1;
528 clientSettingsSnapshot = settings;
529 clientSettingsHydrationStatus = "ready";
530 clientSettingsHydrationPromise = null;
531}