Open History to see the last commit
1import { ClientSettingsSchema, type ClientSettings } from "@t3tools/contracts";
2
3import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
4
5const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
6
7function hasWindow(): boolean {
8 return typeof window !== "undefined";
9}
10
11export function readBrowserClientSettings(): ClientSettings | null {
12 if (!hasWindow()) {
13 return null;
14 }
15
16 return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
17}
18
19export function writeBrowserClientSettings(settings: ClientSettings): void {
20 if (!hasWindow()) {
21 return;
22 }
23
24 setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema);
25}
26
27/** Storage events fire only for other tabs' writes; a null key means storage was cleared. */
28export function subscribeBrowserClientSettingsWrites(onChange: () => void): () => void {
29 if (!hasWindow()) {
30 return () => undefined;
31 }
32 const handleStorage = (event: StorageEvent) => {
33 if (event.key === CLIENT_SETTINGS_STORAGE_KEY || event.key === null) {
34 onChange();
35 }
36 };
37 const target = window;
38 target.addEventListener("storage", handleStorage);
39 return () => target.removeEventListener("storage", handleStorage);
40}