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

useSettings.ts

480 lines16.3 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 {
29 findSharedSettingsMismatches,
30 pickSharedServerSettings,
31 splitSharedServerPatch,
32 supportsSharedSettingsSync,
33} from "@t3tools/client-runtime/state/shared-settings";
34import { ensureLocalApi } from "~/localApi";
35import {
36 getThemeDefinition,
37 getThemePreviewSidebarArtwork,
38 resolveThemeHalf,
39 subscribeToThemePreview,
40 themeAllowsSidebarArtwork,
41} from "~/themePalette";
42import * as Struct from "effect/Struct";
43import { toastManager } from "~/components/ui/toast";
44import { isHostedStaticApp } from "~/hostedPairing";
45import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
46import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";
47import { useAtomCommand } from "~/state/use-atom-command";
48import { useTheme } from "./useTheme";
49​
50const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
51​
52type UnifiedSettingsPatch = ServerSettingsPatch & ClientSettingsPatch;
53​
54const clientSettingsListeners = new Set<() => void>();
55const clientSettingsHydrationListeners = new Set<() => void>();
56let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
57let clientSettingsHydrated = false;
58let clientSettingsHydrationPromise: Promise<void> | null = null;
59let clientSettingsHydrationGeneration = 0;
60​
61function emitClientSettingsChange() {
62 for (const listener of clientSettingsListeners) {
63 listener();
64 }
66​
67function emitClientSettingsHydrationChange() {
68 for (const listener of clientSettingsHydrationListeners) {
69 listener();
70 }
72​
73function getClientSettingsSnapshot(): ClientSettings {
74 return clientSettingsSnapshot;
76​
77function replaceClientSettingsSnapshot(settings: ClientSettings): void {
78 clientSettingsSnapshot = settings;
79 emitClientSettingsChange();
81​
82function setClientSettingsHydrated(nextHydrated: boolean): void {
83 if (clientSettingsHydrated === nextHydrated) {
84 return;
85 }
86 clientSettingsHydrated = nextHydrated;
87 emitClientSettingsHydrationChange();
89​
90function subscribeClientSettings(listener: () => void): () => void {
91 clientSettingsListeners.add(listener);
92 void hydrateClientSettings();
93 return () => {
94 clientSettingsListeners.delete(listener);
95 };
97​
98function getClientSettingsHydratedSnapshot(): boolean {
99 return clientSettingsHydrated;
101​
102function subscribeClientSettingsHydration(listener: () => void): () => void {
103 clientSettingsHydrationListeners.add(listener);
104 void hydrateClientSettings();
105 return () => {
106 clientSettingsHydrationListeners.delete(listener);
107 };
109​
110async function hydrateClientSettings(): Promise<void> {
111 if (clientSettingsHydrated) {
112 return;
113 }
114 if (clientSettingsHydrationPromise) {
115 return clientSettingsHydrationPromise;
116 }
117​
118 const hydrationGeneration = clientSettingsHydrationGeneration;
119 const nextHydration = (async () => {
120 try {
121 const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
122 if (hydrationGeneration !== clientSettingsHydrationGeneration) {
123 return;
124 }
125 if (persistedSettings) {
126 replaceClientSettingsSnapshot({ ...DEFAULT_CLIENT_SETTINGS, ...persistedSettings });
127 }
128 } catch (error) {
129 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, {
130 operation: "hydrate",
131 ...safeErrorLogAttributes(error),
132 });
133 } finally {
134 if (hydrationGeneration === clientSettingsHydrationGeneration) {
135 setClientSettingsHydrated(true);
136 }
137 }
138 })();
139​
140 const hydrationPromise = nextHydration.finally(() => {
141 if (clientSettingsHydrationPromise === hydrationPromise) {
142 clientSettingsHydrationPromise = null;
143 }
144 });
145 clientSettingsHydrationPromise = hydrationPromise;
146​
147 return clientSettingsHydrationPromise;
149​
150function persistClientSettings(settings: ClientSettings): void {
151 replaceClientSettingsSnapshot(settings);
152 void ensureLocalApi()
153 .persistence.setClientSettings(settings)
154 .catch((error) => {
155 console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, {
156 operation: "persist",
157 ...safeErrorLogAttributes(error),
158 });
159 });
161​
162// ── Key sets for routing patches ─────────────────────────────────────
163​
164const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
165​
166function splitPatch(patch: UnifiedSettingsPatch): {
167 serverPatch: ServerSettingsPatch;
168 clientPatch: ClientSettingsPatch;
169} {
170 const serverPatch: Record<string, unknown> = {};
171 const clientPatch: Record<string, unknown> = {};
172 for (const [key, value] of Object.entries(patch)) {
173 if (SERVER_SETTINGS_KEYS.has(key)) {
174 serverPatch[key] = value;
175 } else {
176 clientPatch[key] = value;
177 }
178 }
179 return {
180 serverPatch: serverPatch as ServerSettingsPatch,
181 clientPatch: clientPatch as ClientSettingsPatch,
182 };
184​
185// ── Hooks ────────────────────────────────────────────────────────────
186​
187/**
188 * Non-hook accessor for the current merged client settings snapshot.
189 * Used by non-React code paths (e.g. runtime services) that need the latest
190 * settings without subscribing.
191 */
192export function getClientSettings(): ClientSettings {
193 return getClientSettingsSnapshot();
195​
196/**
197 * Resolves once client settings have been read from disk.
198 *
199 * The pre-hydration snapshot is just the schema defaults, so imperative paths
200 * that open a preview must await this or they bake the built-in viewport, zoom
201 * and appearance into a tab that never picks up the user's saved values.
202 */
203export function ensureClientSettingsHydrated(): Promise<void> {
204 return hydrateClientSettings();
206​
207export function useClientSettingsHydrated(): boolean {
208 return useSyncExternalStore(
209 subscribeClientSettingsHydration,
210 getClientSettingsHydratedSnapshot,
211 () => false,
212 );
214​
215function useClientSettingsValue(): ClientSettings {
216 return useSyncExternalStore(
217 subscribeClientSettings,
218 getClientSettingsSnapshot,
219 () => DEFAULT_CLIENT_SETTINGS,
220 );
222​
223export function mergeEnvironmentSettings(
224 serverSettings: ServerSettings,
225 clientSettings: ClientSettings,
226): UnifiedSettings {
227 // Decode drops retired client keys, but older untyped persistence adapters
228 // can still return them. Server-owned values must always win.
229 return { ...clientSettings, ...serverSettings };
231​
232function useMergedSettings<T>(
233 serverSettings: ServerSettings,
234 selector: ((settings: UnifiedSettings) => T) | undefined,
235): T {
236 const clientSettings = useClientSettingsValue();
237​
238 const merged = useMemo<UnifiedSettings>(
239 () => mergeEnvironmentSettings(serverSettings, clientSettings),
240 [clientSettings, serverSettings],
241 );
242​
243 return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
245​
246export function useClientSettings<T = ClientSettings>(
247 selector?: (settings: ClientSettings) => T,
248): T {
249 const settings = useClientSettingsValue();
250 return useMemo(() => (selector ? selector(settings) : (settings as T)), [selector, settings]);
252​
253export function resolveEnvironmentIdentificationMode(input: {
254 mode: EnvironmentIdentificationMode;
255 settingsHydrated: boolean;
256 paletteThemeActive?: boolean;
257 paletteThemeAllowsArtwork?: boolean;
258}): EnvironmentIdentificationMode {
259 // Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
260 if (!input.settingsHydrated) return "none";
261 // Artwork palettes are maintained for built-ins only. Keep an explicit
262 // "none", but use the theme-aware pill for user-controlled palettes.
263 return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
264 ? "pill"
265 : input.mode;
267​
268export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
269 const settingsHydrated = useClientSettingsHydrated();
270 const mode = useClientSettingsValue().environmentIdentificationMode;
271 const { resolvedTheme, theme, themeHalves } = useTheme();
272 const previewSidebarArtwork = useSyncExternalStore(
273 subscribeToThemePreview,
274 getThemePreviewSidebarArtwork,
275 () => null,
276 );
277 const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
278 const activeThemeDefinition = getThemeDefinition(activeTheme);
279 return resolveEnvironmentIdentificationMode({
280 mode,
281 settingsHydrated,
282 paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
283 paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
284 });
286​
287/**
288 * Whether the legacy sidebar (Settings → General → Legacy features) replaces
289 * the default one.
290 *
291 * Held at the default sidebar until client settings hydrate: the pre-hydration
292 * snapshot is just the schema defaults, so resolving against it could mount one
293 * sidebar and then swap it out once persisted settings land — remounting the
294 * whole tree for everyone instead of only for legacy opt-ins.
295 */
296export function useLegacySidebarEnabled(): boolean {
297 const settingsHydrated = useClientSettingsHydrated();
298 const legacySidebarEnabled = useClientSettingsValue().legacySidebarEnabled;
299 return settingsHydrated && legacySidebarEnabled;
301​
302/** Read current settings for one environment, merged with client-local preferences. */
303export function useEnvironmentSettings<T = UnifiedSettings>(
304 environmentId: EnvironmentId,
305 selector?: (settings: UnifiedSettings) => T,
306): T {
307 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
308 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
310​
311/** Primary-only settings access for the settings UI and other explicitly global surfaces. */
312export function usePrimarySettings<T = UnifiedSettings>(
313 selector?: (settings: UnifiedSettings) => T,
314): T {
315 return useMergedSettings(useAtomValue(primaryServerSettingsAtom), selector);
317​
318export const PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE =
319 "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.";
320​
321/**
322 * Whether primary-scoped server settings have a server to live on. The
323 * hosted app connects to every environment as a remote, so it has no primary:
324 * `usePrimarySettings` reads schema defaults there and writes have nowhere
325 * to go. Desktop and server-served web always have one.
326 */
327export function usePrimarySettingsAvailable(): boolean {
328 const primaryEnvironment = usePrimaryEnvironment();
329 return primaryEnvironment !== null || !isHostedStaticApp();
331​
332/** Environments that can receive a shared settings write right now. */
333function useSharedSettingsSyncTargetIds(): ReadonlyArray<EnvironmentId> {
334 const { environments } = useEnvironments();
335 return useMemo(
336 () =>
337 environments
338 .filter(supportsSharedSettingsSync)
339 .map((environment) => environment.environmentId),
340 [environments],
341 );
343​
344/**
345 * Returns an updater that routes each key to the correct backing store.
346 *
347 * Server keys are optimistically patched in atom-backed server state, then
348 * persisted via RPC. Shared server keys (see `SHARED_SERVER_SETTING_KEYS`)
349 * are written to every eligible sync target, not only the selected target, so
350 * a user preference does not silently drift between machines. Client keys go
351 * through client persistence.
352 */
353function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
354 const persistServerSettings = useAtomCommand(
355 serverEnvironment.updateSettings,
356 "server settings update",
357 );
358 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds();
359 const updateSettings = useCallback(
360 (patch: UnifiedSettingsPatch) => {
361 const { serverPatch, clientPatch } = splitPatch(patch);
362​
363 if (Object.keys(serverPatch).length > 0) {
364 const { sharedPatch, localPatch } = splitSharedServerPatch(serverPatch);
365 // Dropping the write silently leaves the control looking saved.
366 const warnUnsaved = () =>
367 toastManager.add({
368 type: "warning",
369 title: "Setting not saved",
370 description: PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
371 });
372 if (Object.keys(localPatch).length > 0) {
373 if (environmentId) {
374 void persistServerSettings({
375 environmentId,
376 input: { patch: localPatch },
377 });
378 } else {
379 warnUnsaved();
380 }
381 }
382 if (Object.keys(sharedPatch).length > 0) {
383 const targets = new Set(sharedSettingsSyncTargetIds);
384 if (environmentId) {
385 targets.add(environmentId);
386 }
387 if (targets.size === 0) {
388 warnUnsaved();
389 }
390 for (const targetId of targets) {
391 void persistServerSettings({
392 environmentId: targetId,
393 input: { patch: sharedPatch },
394 });
395 }
396 }
397 }
398 if (Object.keys(clientPatch).length > 0) {
399 persistClientSettings({
400 ...getClientSettingsSnapshot(),
401 ...clientPatch,
402 });
403 }
404 },
405 [environmentId, persistServerSettings, sharedSettingsSyncTargetIds],
406 );
407​
408 return updateSettings;
410​
411/**
412 * Shared-settings sync targets whose values differ from the primary's,
413 * plus an action that writes the primary's values to all of them. Drift
414 * happens when an environment was offline during an edit or was changed by
415 * an older client.
416 */
417export function useSharedSettingsSync() {
418 const primaryEnvironment = usePrimaryEnvironment();
419 const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
420 // Read the loaded config, not `primaryServerSettingsAtom`: that atom falls
421 // back to defaults while the primary is disconnected, and "apply to all"
422 // must never push defaults over real values. Same for a primary too old to
423 // hold the shared keys: its decoded defaults are not a source of truth.
424 const primarySettings =
425 primaryEnvironment !== null && supportsSharedSettingsSync(primaryEnvironment)
426 ? (primaryEnvironment.serverConfig?.settings ?? null)
427 : null;
428 const { environments } = useEnvironments();
429 const persistServerSettings = useAtomCommand(
430 serverEnvironment.updateSettings,
431 "server settings update",
432 );
433​
434 const mismatches = useMemo(
435 () =>
436 findSharedSettingsMismatches({
437 primaryEnvironmentId,
438 primarySettings,
439 environments: environments.map((environment) => ({
440 environmentId: environment.environmentId,
441 label: environment.label,
442 syncEligible: supportsSharedSettingsSync(environment),
443 settings: environment.serverConfig?.settings ?? null,
444 })),
445 }),
446 [environments, primaryEnvironmentId, primarySettings],
447 );
448​
449 const applyToAll = useCallback(() => {
450 if (primarySettings === null) {
451 return;
452 }
453 const patch = pickSharedServerSettings(primarySettings);
454 for (const mismatch of mismatches) {
455 void persistServerSettings({
456 environmentId: mismatch.environmentId,
457 input: { patch },
458 });
459 }
460 }, [mismatches, persistServerSettings, primarySettings]);
461​
462 return { mismatches, applyToAll };
464​
465export function useUpdateEnvironmentSettings(environmentId: EnvironmentId) {
466 return useUpdateSettingsTarget(environmentId);
468​
469export function useUpdatePrimarySettings() {
470 return useUpdateSettingsTarget(usePrimaryEnvironment()?.environmentId ?? null);
472​
473export function useUpdateClientSettings() {
474 return useCallback((patch: ClientSettingsPatch) => {
475 persistClientSettings({
476 ...getClientSettingsSnapshot(),
477 ...patch,
478 });
479 }, []);