resonare 0.1.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +329 -270
  2. package/dist/index.d.ts +220 -102
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/lite-react.d.ts +41 -0
  7. package/dist/lite-react.d.ts.map +1 -0
  8. package/dist/lite-react.js +2 -0
  9. package/dist/lite-react.js.map +1 -0
  10. package/dist/lite-solid.d.ts +42 -0
  11. package/dist/lite-solid.d.ts.map +1 -0
  12. package/dist/lite-solid.js +2 -0
  13. package/dist/lite-solid.js.map +1 -0
  14. package/dist/lite-svelte.d.ts +41 -0
  15. package/dist/lite-svelte.d.ts.map +1 -0
  16. package/dist/lite-svelte.js +2 -0
  17. package/dist/lite-svelte.js.map +1 -0
  18. package/dist/lite-vue.d.ts +49 -0
  19. package/dist/lite-vue.d.ts.map +1 -0
  20. package/dist/lite-vue.js +2 -0
  21. package/dist/lite-vue.js.map +1 -0
  22. package/dist/lite.d.ts +124 -0
  23. package/dist/lite.d.ts.map +1 -0
  24. package/dist/lite.js +2 -0
  25. package/dist/lite.js.map +1 -0
  26. package/dist/react.d.ts +39 -30
  27. package/dist/react.d.ts.map +1 -1
  28. package/dist/react.js +1 -1
  29. package/dist/react.js.map +1 -1
  30. package/dist/solid.d.ts +84 -0
  31. package/dist/solid.d.ts.map +1 -0
  32. package/dist/solid.js +2 -0
  33. package/dist/solid.js.map +1 -0
  34. package/dist/storage-BqWA8jeP.js +2 -0
  35. package/dist/storage-BqWA8jeP.js.map +1 -0
  36. package/dist/storage-CsXjZKyt.d.ts +65 -0
  37. package/dist/storage-CsXjZKyt.d.ts.map +1 -0
  38. package/dist/svelte.d.ts +86 -0
  39. package/dist/svelte.d.ts.map +1 -0
  40. package/dist/svelte.js +2 -0
  41. package/dist/svelte.js.map +1 -0
  42. package/dist/vue.d.ts +82 -0
  43. package/dist/vue.d.ts.map +1 -0
  44. package/dist/vue.js +2 -0
  45. package/dist/vue.js.map +1 -0
  46. package/package.json +75 -32
package/dist/index.d.ts CHANGED
@@ -1,152 +1,270 @@
1
- //#region src/storage.d.ts
2
- /**
3
- * Pluggable persistence for `createThemeStore`.
4
- */
5
- type StorageAdapter = {
6
- get: () => object | null;
7
- set: (value: object) => void; /** Optional: notify other tabs/contexts after local `set` operation. */
8
- broadcast?: (value: object) => void; /** Optional: subscribes to other tabs/contexts' updates, returns `unsubscribe` function. */
9
- watch?: (cb: (value: object) => void) => () => void;
10
- };
11
- type StorageAdapterCreate = ({
12
- abortController
13
- }: {
14
- abortController: AbortController;
15
- }) => StorageAdapter;
16
- type StorageAdapterCreator<Options> = (options: Options) => StorageAdapterCreate;
17
- /**
18
- * Persists theme store in `localStorage` or `sessionStorage`.
19
- * @example
20
- * ```ts
21
- * import { createThemeStore, localStorageAdapter } from 'resonare'
22
- *
23
- * const store = createThemeStore(
24
- * { colorMode: { options: ['light', 'dark'] },
25
- * { storage: localStorageAdapter({ key: 'app', type: 'localStorage' }) },
26
- * )
27
- * ```
28
- */
29
- declare const localStorageAdapter: StorageAdapterCreator<{
30
- key: string;
31
- type?: 'localStorage' | 'sessionStorage';
32
- }>;
33
- /**
34
- * In-memory persistence and sync via `BroadcastChannel`.
35
- * Useful with server-side persistence.
36
- * @example
37
- * ```ts
38
- * import { createThemeStore, memoryStorageAdapter } from 'resonare'
39
- *
40
- * const store = createThemeStore(
41
- * { colorMode: { options: ['light', 'dark'] },
42
- * { storage: memoryStorageAdapter({ key: 'app' }) },
43
- * )
44
- * ```
45
- */
46
- declare const memoryStorageAdapter: StorageAdapterCreator<{
47
- key: string;
48
- }>;
49
- //#endregion
50
- //#region src/index.d.ts
1
+ import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-CsXjZKyt.js";
51
2
  type ThemeValue = string | number | boolean;
52
3
  type ThemeOption<T extends ThemeValue = string> = {
53
4
  value: T;
54
- media?: [string, T, T];
5
+ media?: readonly [string, T, T];
55
6
  };
56
7
  type ThemeConfig<T extends ThemeValue = string> = {
57
8
  options: ReadonlyArray<T | ThemeOption<T>>;
58
- initialValue?: T;
9
+ defaultValue?: T;
59
10
  } | {
60
- initialValue: T;
11
+ defaultValue: T;
61
12
  options?: never;
62
13
  };
63
- type ThemeStoreConfig = Record<string, ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>>;
64
- type Themes<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
14
+ /**
15
+ * Config for `createThemeStore`. Each key is a theme setting (`colorMode`,
16
+ * `contrast`, …) with either:
17
+ *
18
+ * - `options`: the allowed values, plus an optional `defaultValue` (otherwise the
19
+ * first option). One option may be a `{ value, media }` object: when it is
20
+ * selected, the setting follows a media query, using `media[1]` while the
21
+ * query matches and `media[2]` while it doesn't.
22
+ * - `defaultValue` alone: a free value of that type, such as a number.
23
+ *
24
+ * @example
25
+ * const config = {
26
+ * colorMode: {
27
+ * options: [
28
+ * 'light',
29
+ * 'dark',
30
+ * {
31
+ * value: 'system',
32
+ * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
33
+ * },
34
+ * ],
35
+ * defaultValue: 'system',
36
+ * },
37
+ * contrast: {
38
+ * options: ['normal', 'more'],
39
+ * },
40
+ * sidebarWidth: {
41
+ * defaultValue: 240,
42
+ * },
43
+ * } as const satisfies ThemeStoreConfig
44
+ */
45
+ export type ThemeStoreConfig = Record<string, ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>>;
46
+ /**
47
+ * The selected value of each setting, as passed to `setThemes` (e.g.
48
+ * `colorMode: 'system'`). Inferred from your `ThemeStoreConfig`.
49
+ */
50
+ export type Themes<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
65
51
  options: ReadonlyArray<infer U>;
66
52
  } ? U extends ThemeOption ? U['value'] : U : T[K] extends {
67
- initialValue: infer U;
68
- } ? U extends string ? string : U extends number ? number : boolean : never };
53
+ defaultValue: infer U;
54
+ } ? U extends string ? string : U extends number ? number : boolean : never; };
69
55
  type ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
70
56
  options: ReadonlyArray<infer U>;
71
57
  } ? U extends {
72
58
  media: ReadonlyArray<unknown>;
73
- } ? K : never : never }[keyof T];
59
+ } ? K : never : never; }[keyof T];
74
60
  type NonSystemOptionValues<T extends ThemeStoreConfig, K extends keyof T> = T[K] extends {
75
61
  options: ReadonlyArray<infer U>;
76
62
  } ? U extends ThemeValue ? U : U extends ThemeOption ? U extends {
77
- media: [string, string, string];
63
+ media: ReadonlyArray<unknown>;
78
64
  } ? never : U['value'] : never : never;
79
- type ResolvedSystemThemes<T extends ThemeStoreConfig> = { [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K> };
80
- type Listener<T extends ThemeStoreConfig, O extends boolean = false> = (value: O extends true ? {
81
- themes: Themes<T>;
82
- resolvedThemes: Themes<T>;
83
- } : {
65
+ /**
66
+ * For each setting with a `media` option, the value that option currently
67
+ * resolves to, whether or not it is selected.
68
+ */
69
+ type ResolvedSystemThemes<T extends ThemeStoreConfig> = { [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>; };
70
+ type Snapshot<T extends ThemeStoreConfig> = {
84
71
  themes: Themes<T>;
85
72
  resolvedThemes: Themes<T>;
86
73
  resolvedSystemThemes: ResolvedSystemThemes<T>;
87
- }) => void;
74
+ };
75
+ type Listener<T extends ThemeStoreConfig> = (value: Snapshot<T>) => void;
88
76
  type PersistedSystemOptionPairs = Record<string, [string, string]>;
89
77
  type PersistedState<T extends ThemeStoreConfig> = {
90
78
  themes: Partial<Themes<T>>;
91
79
  systemOptions: PersistedSystemOptionPairs;
92
80
  };
93
81
  type ThemeStoreOptions<T extends ThemeStoreConfig> = {
94
- initialState?: Partial<PersistedState<T>>;
82
+ persisted?: Partial<PersistedState<T>>;
95
83
  storage?: StorageAdapterCreate | null;
96
84
  };
97
85
  type ThemeAndOptions<T extends ThemeStoreConfig> = Array<{ [K in keyof T]: [K, Array<T[K] extends {
98
86
  options: ReadonlyArray<infer U>;
99
- } ? U extends ThemeOption ? U['value'] : U : never>] }[keyof T]>;
100
- declare function getThemesAndOptions<T extends ThemeStoreConfig>(config: T): ThemeAndOptions<T>;
101
- declare function getDefaultThemes<T extends ThemeStoreConfig>(config: T): Themes<T>;
102
- declare class ThemeStore<T extends ThemeStoreConfig> {
103
- #private;
104
- constructor(config: T, {
105
- initialState,
106
- storage
107
- }?: ThemeStoreOptions<T>);
108
- getThemes: () => Themes<T>;
109
- getResolvedThemes: () => Themes<T>;
110
- getResolvedSystemThemes: () => ResolvedSystemThemes<T>;
87
+ } ? U extends ThemeOption ? U['value'] : U : never>]; }[keyof T]>;
88
+ /**
89
+ * Lists each setting with its option values (`{ value, media }` options become
90
+ * their `value`). Useful for rendering a picker for every setting.
91
+ *
92
+ * @example
93
+ * import { getThemesAndOptions } from 'resonare'
94
+ *
95
+ * getThemesAndOptions({
96
+ * colorMode: {
97
+ * options: [
98
+ * 'light',
99
+ * 'dark',
100
+ * {
101
+ * value: 'system',
102
+ * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
103
+ * },
104
+ * ],
105
+ * },
106
+ * })
107
+ * // [['colorMode', ['light', 'dark', 'system']]]
108
+ */
109
+ export declare function getThemesAndOptions<T extends ThemeStoreConfig>(config: T): ThemeAndOptions<T>;
110
+ /**
111
+ * Returns each setting's default: its `defaultValue`, or else its first
112
+ * option.
113
+ *
114
+ * @example
115
+ * import { getDefaultThemes } from 'resonare'
116
+ *
117
+ * getDefaultThemes({
118
+ * colorMode: { options: ['light', 'dark'], defaultValue: 'dark' },
119
+ * }) // { colorMode: 'dark' }
120
+ */
121
+ export declare function getDefaultThemes<T extends ThemeStoreConfig>(config: T): Themes<T>;
122
+ /**
123
+ * Creates a store for the settings in `config`. It saves changes through
124
+ * `storage` (`localStorage` under the key `'resonare'` by default; `null`
125
+ * disables saving), resolves `media` options in the browser, and notifies
126
+ * subscribers.
127
+ *
128
+ * Read state with `getSnapshot()` or `subscribe`.
129
+ *
130
+ * @example
131
+ * import { createThemeStore, localStorageAdapter } from 'resonare'
132
+ *
133
+ * const store = createThemeStore(
134
+ * {
135
+ * colorMode: {
136
+ * options: [
137
+ * 'light',
138
+ * 'dark',
139
+ * {
140
+ * value: 'system',
141
+ * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
142
+ * },
143
+ * ],
144
+ * defaultValue: 'system',
145
+ * },
146
+ * },
147
+ * { storage: localStorageAdapter({ key: 'my-app' }) }
148
+ * )
149
+ *
150
+ * // In the browser: load the saved choice and follow other tabs.
151
+ * store.restore()
152
+ * store.sync()
153
+ *
154
+ * store.subscribe(({ resolvedThemes }) => {
155
+ * document.documentElement.dataset.colorMode = resolvedThemes.colorMode
156
+ * })
157
+ *
158
+ * store.setThemes({ colorMode: 'dark' })
159
+ */
160
+ export declare function createThemeStore<T extends ThemeStoreConfig>(config: T, { persisted, storage: createStorage }?: ThemeStoreOptions<T>): {
161
+ /**
162
+ * Current state:
163
+ *
164
+ * - `themes`: the selected value of each setting (e.g. `'system'`).
165
+ * - `resolvedThemes`: the same with `media` options resolved (e.g. `'dark'`).
166
+ * - `resolvedSystemThemes`: what each `media` option resolves to, even when
167
+ * it isn't selected.
168
+ *
169
+ * Returns the same object until the next change.
170
+ */
171
+ getSnapshot: () => Snapshot<T>;
172
+ /**
173
+ * The state as rendered on the server: defaults plus `persisted`, with
174
+ * `media` options resolved to their "not matched" value. It never changes,
175
+ * so hydration can match the server HTML even after `restore()`.
176
+ */
177
+ getServerSnapshot: () => Snapshot<T>;
178
+ /**
179
+ * Updates the given settings (others keep their value), saves to storage,
180
+ * and notifies subscribers.
181
+ *
182
+ * @example
183
+ * store.setThemes({ colorMode: 'dark' })
184
+ *
185
+ * store.setThemes((current) => ({
186
+ * colorMode: current.colorMode === 'dark' ? 'light' : 'dark',
187
+ * }))
188
+ */
111
189
  setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
190
+ /**
191
+ * Changes which values a `media` option resolves to: `[whenMatched,
192
+ * whenNotMatched]`, replacing `media[1]` and `media[2]` from the config.
193
+ * Saved like `setThemes`.
194
+ *
195
+ * @example
196
+ * // system now picks 'dark-dimmed' when the OS prefers dark
197
+ * store.updateSystemOption('colorMode', ['dark-dimmed', 'light'])
198
+ */
112
199
  updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(themeKey: K, pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]) => void;
200
+ /**
201
+ * The state to save, e.g. to a database: pass it back as `persisted` when
202
+ * creating the store.
203
+ */
113
204
  toPersist: () => PersistedState<T>;
205
+ /**
206
+ * Loads the saved state from storage. Does nothing when nothing is saved.
207
+ * Call it in the browser, e.g. after hydration.
208
+ */
114
209
  restore: () => void;
210
+ /**
211
+ * Calls `callback` with the new state (see `getSnapshot`) after every
212
+ * change, including OS preference changes. Returns an unsubscribe
213
+ * function.
214
+ */
115
215
  subscribe: (callback: Listener<T>) => (() => void);
216
+ /**
217
+ * Applies changes saved by other tabs (if the storage adapter supports
218
+ * it); when another tab clears the saved state, resets to the config
219
+ * defaults. Returns a function that stops syncing, or `undefined` when the
220
+ * adapter can't sync.
221
+ */
116
222
  sync: () => (() => void) | undefined;
117
- /** Clears subscribers and aborts media-query listeners tied to this store instance. */
223
+ /**
224
+ * Removes all subscribers and stops listening to media queries and
225
+ * storage. The store doesn't update after this.
226
+ */
118
227
  destroy: () => void;
119
- }
120
- declare function createThemeStore<T extends ThemeStoreConfig>(config: T, options?: ThemeStoreOptions<T>): ThemeStore<T>;
121
- type ThemeScriptParameter = {
122
- /** `localStorage` key; defaults to the 'resonare'. */key?: string;
228
+ };
229
+ export type ThemeStore<T extends ThemeStoreConfig> = ReturnType<typeof createThemeStore<T>>;
230
+ /** One store for `createInlineThemeScript`. */
231
+ export type ThemeScriptParameter = {
232
+ /** The store's `localStorage` key; defaults to `'resonare'`. */
233
+ key?: string;
234
+ /** The same config passed to `createThemeStore`. */
123
235
  config: ThemeStoreConfig;
124
- handler: Listener<any, true>;
236
+ /**
237
+ * Applies the state to the page; receives the same value as `subscribe`.
238
+ * It is copied into the script as source code, so it can't use variables
239
+ * from outside the function.
240
+ */
241
+ handler: Listener<any>;
125
242
  };
126
243
  /**
127
- * Creates an IIFE script string that reads persisted themes from `localStorage` and runs your handlers immediately.
244
+ * Returns the source of a small script that reads the saved state from
245
+ * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in
246
+ * the `<head>` so the page has the right theme before first paint. Pass an
247
+ * array to set up several stores.
248
+ *
249
+ * Use the same handler with `store.subscribe` to keep the page updated after
250
+ * that.
128
251
  *
129
- * Useful for avoiding flash of incorrect styles.
130
252
  * @example
131
- * ```tsx
132
- * import { createInlineThemeScript } from 'resonare'
253
+ * import { createInlineThemeScript } from 'resonare'
133
254
  *
134
- * const inlineScript = createInlineThemeScript([
135
- * {
255
+ * // config: the same object passed to createThemeStore
256
+ * const themeScript = createInlineThemeScript({
136
257
  * key: 'my-app',
137
- * config: {
138
- * colorMode: { options: ['light', 'dark'] },
139
- * },
258
+ * config,
140
259
  * handler: ({ resolvedThemes }) => {
141
- * document.documentElement.dataset.colorMode = String(
142
- * resolvedThemes.colorMode,
143
- * )
260
+ * const root = document.documentElement
261
+ * root.dataset.colorMode = resolvedThemes.colorMode
144
262
  * },
145
- * },
146
- * ])
147
- * ```
263
+ * })
264
+ *
265
+ * // In <head>:
266
+ * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />
148
267
  */
149
- declare function createInlineThemeScript(themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>): string;
150
- //#endregion
151
- export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, ThemeScriptParameter, type ThemeStore, ThemeStoreConfig, Themes, createInlineThemeScript, createThemeStore, getDefaultThemes, getThemesAndOptions, localStorageAdapter, memoryStorageAdapter };
268
+ export declare function createInlineThemeScript(themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>): string;
269
+ export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, localStorageAdapter, memoryStorageAdapter };
152
270
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/storage.ts","../src/index.ts"],"mappings":";;AAKA;;KAAY,cAAA;EACX,GAAA;EACA,GAAA,GAAM,KAAA,mBAAN;EAEA,SAAA,IAAa,KAAA,mBAAb;EAEA,KAAA,IAAS,EAAA,GAAK,KAAA;AAAA;AAAA,KAGH,oBAAA;EACX;AAAA;EAEA,eAAA,EAAiB,eAAA;AAAA,MACZ,cAAA;AAAA,KAEM,qBAAA,aACX,OAAA,EAAS,OAAA,KACL,oBAAoB;AARzB;;;;;;;;;;;;AAAA,cAsBa,mBAAA,EAAqB,qBAAqB;EACtD,GAAA;EACA,IAAA;AAAA;;;;;;;;;AAhBwB;AAczB;;;;cAuDa,oBAAA,EAAsB,qBAAqB;EACvD,GAAG;AAAA;;;KCnFC,UAAA;AAAA,KAEA,WAAA,WAAsB,UAAA;EAC1B,KAAA,EAAO,CAAA;EACP,KAAA,YAAiB,CAAA,EAAG,CAAA;AAAA;AAAA,KAGhB,WAAA,WAAsB,UAAA;EAExB,OAAA,EAAS,aAAA,CAAc,CAAA,GAAI,WAAA,CAAY,CAAA;EACvC,YAAA,GAAe,CAAA;AAAA;EAEb,YAAA,EAAc,CAAA;EAAG,OAAA;AAAA;AAAA,KAEV,gBAAA,GAAmB,MAAA,SAE9B,WAAA,WAAsB,WAAA,WAAsB,WAAA;AAAA,KAGjC,MAAA,WAAiB,gBAAA,kBAChB,CAAA,GAAI,CAAA,CAAE,CAAA;EAAa,OAAA,EAAS,aAAA;AAAA,IACrC,CAAA,SAAU,WAAA,GACT,CAAA,YACA,CAAA,GACD,CAAA,CAAE,CAAA;EAAa,YAAA;AAAA,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F,mBAAA,SAAS;;;;;;EASH,yBAAA,SAAS;;;;;;;;;;;;EApC5B,YAAA,QAAA,QAAQ,OAAO,QACb,eAAe,OAAO,OAAO,QAAQ,OAAO;;;;;;;;;;EA6D7B,qBAAA,UAAU,0BAA0B,IAAE,UAC/C,GAAC,OACJ,sBAAsB,GAAG,IAAI,sBAAsB,GAAG;;;;;EA5E3C,iBAAA,eAAe;;;;;EA6FtB;;;;;;EASS,YAAA,UAAA,SAAS;;;;;;;EAcrB;;;;;EAqBG;;YAQL,WAAW,UAAU,oBAAoB,kBAC5C,iBAAiB;;YA+Dd;;EAEV;;EAEA,QAAQ;;;;;;EAMR,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA4BK,wBACd,uBAAuB,uBAAuB,MAAM"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var e=`resonare`;const t=({key:e,type:t=`localStorage`})=>({abortController:n})=>({get:()=>JSON.parse(window[t].getItem(e)||`null`),set:n=>{window[t].setItem(e,JSON.stringify(n))},watch:r=>{let i=new AbortController;return window.addEventListener(`storage`,n=>{n.storageArea===window[t]&&n.key===e&&r(JSON.parse(n.newValue))},{signal:AbortSignal.any([n.signal,i.signal])}),()=>{i.abort()}}}),n=({key:t})=>({abortController:n})=>{let r=new Map,i=new BroadcastChannel(e);return{get:()=>r.get(t)||null,set:e=>{r.set(t,e)},broadcast:e=>{i.postMessage({key:t,value:e})},watch:e=>{let r=new AbortController;return i.addEventListener(`message`,n=>{n.data.key===t&&e(n.data.value)},{signal:AbortSignal.any([n.signal,r.signal])}),()=>{r.abort()}}}};function r(e){return Object.entries(e).map(([e,t])=>[e,(t.options||[]).map(e=>typeof e==`object`?e.value:e)])}function i(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.initialValue??(typeof t.options[0]==`object`?t.options[0].value:t.options[0])]))}var a=class{#e;#t;#n={};#r;#i={};#a=new Set;#o=new AbortController;constructor(n,{initialState:r={},storage:a=t({key:e})}={}){this.#e=i(n),this.#t={...this.#e,...r.themes},this.#n=Object.fromEntries(Object.entries(n).flatMap(([e,t])=>{let n=(t.options||[]).find(e=>typeof e==`object`&&!!e.media);if(!n)return[];let{value:i,media:[a,o,s]}=n;return[[e,{value:i,mediaQuery:a,pair:r.systemOptions?.[e]??[o,s]}]]})),this.#r=a?.({abortController:this.#o})??null}getThemes=()=>this.#t;getResolvedThemes=()=>Object.fromEntries(Object.entries(this.#t).map(([e,t])=>{let n=this.#n[e];return[e,n&&t===n.value?this.#l(e):t]}));getResolvedSystemThemes=()=>Object.fromEntries(Object.keys(this.#n).map(e=>[e,this.#l(e)]));setThemes=e=>{let t=typeof e==`function`?e(this.#t):e;this.#c({...this.#t,...t});let n=this.toPersist();this.#r&&(this.#r.set(n),this.#r.broadcast?.(n))};updateSystemOption=(e,t)=>{this.#n[e].pair=t,this.setThemes({...this.#t})};toPersist=()=>({themes:this.#t,systemOptions:Object.fromEntries(Object.entries(this.#n).map(([e,{pair:t}])=>[e,t]))});restore=()=>{let e=this.#r?.get();if(!e){this.#c({...this.#e});return}this.#s(e.systemOptions),this.#c({...this.#e,...e.themes})};subscribe=e=>(this.#a.add(e),()=>this.#a.delete(e));sync=()=>{if(this.#r?.watch)return this.#r.watch(e=>{this.#s(e.systemOptions),this.#c(e.themes)})};destroy=()=>{this.#a.clear(),this.#o.abort()};#s=(e={})=>{Object.entries(e).forEach(([e,t])=>{!t||!this.#n[e]||(this.#n[e].pair=t)})};#c=e=>{this.#t=e;for(let e of this.#a)e({themes:this.#t,resolvedThemes:this.getResolvedThemes(),resolvedSystemThemes:this.getResolvedSystemThemes()})};#l=e=>{let{value:t,mediaQuery:n,pair:r}=this.#n[e];return typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0?(this.#i[n]||(this.#i[n]=window.matchMedia(n),this.#i[n].addEventListener(`change`,()=>{this.#c({...this.#t})},{signal:this.#o.signal})),this.#i[n].matches?r[0]:r[1]):t}};function o(e,t={}){return new a(e,t)}const s=e=>{e.forEach(([e,t,n])=>{let r=JSON.parse(localStorage.getItem(e)||`{}`);n(t.reduce((e,[t,n,i,a,o,s])=>{let c=r.themes?.[t]??n;if(e.resolvedThemes[t]=e.themes[t]=c,c===i){let n=r.systemOptions?.[t]??[o,s];e.resolvedThemes[t]=matchMedia(a).matches?n[0]:n[1]}return e},{themes:{},resolvedThemes:{}}))})};function c(t){return`(${s})([${(Array.isArray(t)?t:[t]).map(({key:t=e,config:n,handler:r})=>{let i=Object.entries(n).map(([e,{options:t,initialValue:n}])=>{let r=t?.[0],i=n??(typeof r==`object`?r.value:r),a=t?.find(e=>typeof e==`object`&&!!e.media);if(a){let{value:t,media:n}=a;return[e,i,t,...n]}return[e,i]});return`['${t}',${JSON.stringify(i)},${r}]`})}])`}export{c as createInlineThemeScript,o as createThemeStore,i as getDefaultThemes,r as getThemesAndOptions,t as localStorageAdapter,n as memoryStorageAdapter};
1
+ import{a as e,i as t,n,r,t as i}from"./storage-BqWA8jeP.js";function a(e){return Object.entries(e).map(([e,t])=>[e,(t.options||[]).map(e=>typeof e==`object`?e.value:e)])}function o(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.defaultValue??(typeof t.options[0]==`object`?t.options[0].value:t.options[0])]))}function s(t,{persisted:n={},storage:r=i({key:e})}={}){let a=o(t),s={...a,...n.themes},c={};for(let e in t){let r=(t[e].options||[]).find(e=>typeof e==`object`&&!!e.media);if(r){let{value:t,media:[i,a,o]}=r,s=[a,o];c[e]={value:t,mediaQuery:i,pair:[...n.systemOptions?.[e]??s],defaultPair:s}}}let l={},u=/* @__PURE__ */ new Set,d=new AbortController,f=r?.({abortController:d}),p=(e,t)=>{let{mediaQuery:n,pair:r}=c[e];if(t||typeof matchMedia>`u`)return r[1];let i=l[n];return i||(i=l[n]=matchMedia(n),i.addEventListener(`change`,()=>{_()},d)),r[+!i.matches]},m=e=>{let t={},n={...s};for(let r in c)t[r]=p(r,e),n[r]===c[r].value&&(n[r]=t[r]);return{themes:s,resolvedThemes:n,resolvedSystemThemes:t}},h=m(!0),g=m(),_=e=>{s={...s,...e},g=m();for(let e of u)e(g)},v=e=>{let t;try{t=e?JSON.parse(e):void 0}catch{}if(t?.themes&&typeof t.themes==`object`){for(let e in t.systemOptions){let n=t.systemOptions[e];n&&c[e]&&(c[e].pair=n)}_(t.themes)}},y=()=>{let e={};for(let t in c)e[t]=[...c[t].pair];return{themes:{...s},systemOptions:e}},b=e=>{if(_(typeof e==`function`?e(s):e),f){let e=JSON.stringify(y());f.set(e),f.broadcast?.(e)}};return{getSnapshot:()=>g,getServerSnapshot:()=>h,setThemes:b,updateSystemOption:(e,t)=>{c[e].pair=[...t],b({})},toPersist:y,restore:()=>{v(f?.get())},subscribe:e=>(u.add(e),()=>{u.delete(e)}),sync:()=>f?.watch?.(e=>{if(e===null){for(let e in c){let t=c[e];t.pair=t.defaultPair}_(a)}else v(e)}),destroy:()=>{u.clear(),d.abort()}}}const c=e=>{e.forEach(([e,t,n])=>{let r;try{r=JSON.parse(localStorage.getItem(e))}catch{}n(t.reduce((e,[t,n,i,a,o,s])=>{let c=r?.themes?.[t]??n;if(e.resolvedThemes[t]=e.themes[t]=c,a!=null){let n=r?.systemOptions?.[t]??[o,s],l=matchMedia(a).matches?n[0]:n[1];e.resolvedSystemThemes[t]=l,c===i&&(e.resolvedThemes[t]=l)}return e},{themes:{},resolvedThemes:{},resolvedSystemThemes:{}}))})};function l(n){let i=(Array.isArray(n)?n:[n]).map(({key:n=e,config:i,handler:a})=>{let o=Object.entries(i).map(([e,{options:t,defaultValue:n}])=>{let r=t?.[0],i=n??(typeof r==`object`?r.value:r),a=t?.find(e=>typeof e==`object`&&!!e.media);if(a){let{value:t,media:n}=a;return[e,i,t,...n]}return[e,i]});return`[${t(n)},${t(o)},${r(a)}]`});return`(${c})([${i}])`}export{l as createInlineThemeScript,s as createThemeStore,o as getDefaultThemes,a as getThemesAndOptions,i as localStorageAdapter,n as memoryStorageAdapter};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["name","PACKAGE_NAME","type","StorageAdapter","get","set","value","broadcast","watch","cb","StorageAdapterCreate","abortController","AbortController","StorageAdapterCreator","options","Options","localStorageAdapter","key","JSON","parse","window","getItem","setItem","stringify","controller","addEventListener","e","storageArea","newValue","signal","AbortSignal","any","abort","memoryStorageAdapter","storage","Map","channel","BroadcastChannel","postMessage","data","name","PACKAGE_NAME","type","localStorageAdapter","StorageAdapter","StorageAdapterCreate","ThemeValue","ThemeOption","value","T","media","ThemeConfig","options","ReadonlyArray","initialValue","ThemeStoreConfig","Record","Themes","K","U","ThemeKeysWithSystemOption","NonSystemOptionValues","ResolvedSystemThemes","SystemOptions","mediaQuery","pair","Listener","O","themes","resolvedThemes","resolvedSystemThemes","PersistedSystemOptionPairs","PersistedState","Partial","systemOptions","ThemeStoreOptions","initialState","storage","ThemeAndOptions","Array","getThemesAndOptions","config","Object","entries","map","themeKey","themeConfig","option","getDefaultThemes","fromEntries","ThemeStore","defaultThemes","currentThemes","mediaQueryCache","MediaQueryList","listeners","Set","abortController","AbortController","constructor","key","flatMap","systemOption","find","Required","optionWhenMatched","optionWhenNotMatched","getThemes","getResolvedThemes","optionKey","resolveSystemOption","getResolvedSystemThemes","keys","setThemes","updatedThemes","setThemesAndNotify","stateToPersist","toPersist","set","broadcast","updateSystemOption","restore","persistedState","get","applyPersistedSystemOptions","subscribe","callback","add","delete","sync","watch","destroy","clear","abort","#applyPersistedSystemOptions","forEach","#setThemesAndNotify","listener","#resolveSystemOption","window","document","createElement","matchMedia","addEventListener","signal","matches","createThemeStore","restoreScript","params","flattenedConfig","handler","persisted","JSON","parse","localStorage","getItem","reduce","acc","initial","systemOptionValue","currentValue","ThemeScriptParameter","createInlineThemeScript","themeScriptParameters","serializedArgs","isArray","firstOption","resolvedInitialValue","stringify"],"sources":["../package.json","../src/storage.ts","../src/index.ts"],"sourcesContent":["","import { name as PACKAGE_NAME } from '../package.json' with { type: 'json' }\n\n/**\n * Pluggable persistence for `createThemeStore`.\n */\nexport type StorageAdapter = {\n\tget: () => object | null\n\tset: (value: object) => void\n\t/** Optional: notify other tabs/contexts after local `set` operation. */\n\tbroadcast?: (value: object) => void\n\t/** Optional: subscribes to other tabs/contexts' updates, returns `unsubscribe` function. */\n\twatch?: (cb: (value: object) => void) => () => void\n}\n\nexport type StorageAdapterCreate = ({\n\tabortController,\n}: {\n\tabortController: AbortController\n}) => StorageAdapter\n\nexport type StorageAdapterCreator<Options> = (\n\toptions: Options,\n) => StorageAdapterCreate\n\n/**\n * Persists theme store in `localStorage` or `sessionStorage`.\n * @example\n * ```ts\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] },\n * { storage: localStorageAdapter({ key: 'app', type: 'localStorage' }) },\n * )\n * ```\n */\nexport const localStorageAdapter: StorageAdapterCreator<{\n\tkey: string\n\ttype?: 'localStorage' | 'sessionStorage'\n}> = ({ key, type = 'localStorage' }) => {\n\treturn ({ abortController }) => {\n\t\treturn {\n\t\t\tget: () => {\n\t\t\t\treturn JSON.parse(window[type].getItem(key) || 'null')\n\t\t\t},\n\n\t\t\tset: (value: object) => {\n\t\t\t\twindow[type].setItem(key, JSON.stringify(value))\n\t\t\t},\n\n\t\t\twatch: (cb) => {\n\t\t\t\tconst controller = new AbortController()\n\n\t\t\t\twindow.addEventListener(\n\t\t\t\t\t'storage',\n\t\t\t\t\t(e) => {\n\t\t\t\t\t\tif (e.storageArea !== window[type]) return\n\n\t\t\t\t\t\tif (e.key !== key) return\n\n\t\t\t\t\t\tcb(JSON.parse(e.newValue!))\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal: AbortSignal.any([\n\t\t\t\t\t\t\tabortController.signal,\n\t\t\t\t\t\t\tcontroller.signal,\n\t\t\t\t\t\t]),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn () => {\n\t\t\t\t\tcontroller.abort()\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n}\n\n/**\n * In-memory persistence and sync via `BroadcastChannel`.\n * Useful with server-side persistence.\n * @example\n * ```ts\n * import { createThemeStore, memoryStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] },\n * { storage: memoryStorageAdapter({ key: 'app' }) },\n * )\n * ```\n */\nexport const memoryStorageAdapter: StorageAdapterCreator<{\n\tkey: string\n}> = ({ key }) => {\n\treturn ({ abortController }) => {\n\t\tconst storage = new Map<string, object>()\n\t\tconst channel = new BroadcastChannel(PACKAGE_NAME)\n\n\t\treturn {\n\t\t\tget: () => {\n\t\t\t\treturn storage.get(key) || null\n\t\t\t},\n\n\t\t\tset: (value: object) => {\n\t\t\t\tstorage.set(key, value)\n\t\t\t},\n\n\t\t\tbroadcast: (value: object) => {\n\t\t\t\tchannel.postMessage({ key, value })\n\t\t\t},\n\n\t\t\twatch: (cb) => {\n\t\t\t\tconst controller = new AbortController()\n\n\t\t\t\tchannel.addEventListener(\n\t\t\t\t\t'message',\n\t\t\t\t\t(e) => {\n\t\t\t\t\t\tif (e.data.key !== key) return\n\n\t\t\t\t\t\tcb(e.data.value)\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal: AbortSignal.any([\n\t\t\t\t\t\t\tabortController.signal,\n\t\t\t\t\t\t\tcontroller.signal,\n\t\t\t\t\t\t]),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn () => {\n\t\t\t\t\tcontroller.abort()\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t}\n}\n","import { name as PACKAGE_NAME } from '../package.json' with { type: 'json' }\nimport {\n\tlocalStorageAdapter,\n\ttype StorageAdapter,\n\ttype StorageAdapterCreate,\n} from './storage'\n\nexport * from './storage'\n\ntype ThemeValue = string | number | boolean\n\ntype ThemeOption<T extends ThemeValue = string> = {\n\tvalue: T\n\tmedia?: [string, T, T]\n}\n\ntype ThemeConfig<T extends ThemeValue = string> =\n\t| {\n\t\t\toptions: ReadonlyArray<T | ThemeOption<T>>\n\t\t\tinitialValue?: T\n\t }\n\t| { initialValue: T; options?: never }\n\nexport type ThemeStoreConfig = Record<\n\tstring,\n\tThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>\n>\n\nexport type Themes<T extends ThemeStoreConfig> = {\n\t[K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n\t\t? U extends ThemeOption\n\t\t\t? U['value']\n\t\t\t: U\n\t\t: T[K] extends { initialValue: infer U }\n\t\t\t? U extends string\n\t\t\t\t? string\n\t\t\t\t: U extends number\n\t\t\t\t\t? number\n\t\t\t\t\t: boolean\n\t\t\t: never\n}\n\ntype ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = {\n\t[K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n\t\t? U extends { media: ReadonlyArray<unknown> }\n\t\t\t? K\n\t\t\t: never\n\t\t: never\n}[keyof T]\n\ntype NonSystemOptionValues<\n\tT extends ThemeStoreConfig,\n\tK extends keyof T,\n> = T[K] extends { options: ReadonlyArray<infer U> }\n\t? U extends ThemeValue\n\t\t? U\n\t\t: U extends ThemeOption\n\t\t\t? U extends { media: [string, string, string] }\n\t\t\t\t? never\n\t\t\t\t: U['value']\n\t\t\t: never\n\t: never\n\ntype ResolvedSystemThemes<T extends ThemeStoreConfig> = {\n\t[K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>\n}\n\ntype SystemOptions = Record<\n\tstring,\n\t{\n\t\tvalue: string\n\t\tmediaQuery: string\n\t\tpair: [string, string]\n\t}\n>\n\ntype Listener<T extends ThemeStoreConfig, O extends boolean = false> = (\n\tvalue: O extends true\n\t\t? {\n\t\t\t\tthemes: Themes<T>\n\t\t\t\tresolvedThemes: Themes<T>\n\t\t\t}\n\t\t: {\n\t\t\t\tthemes: Themes<T>\n\t\t\t\tresolvedThemes: Themes<T>\n\t\t\t\tresolvedSystemThemes: ResolvedSystemThemes<T>\n\t\t\t},\n) => void\n\ntype PersistedSystemOptionPairs = Record<string, [string, string]>\n\ntype PersistedState<T extends ThemeStoreConfig> = {\n\tthemes: Partial<Themes<T>>\n\tsystemOptions: PersistedSystemOptionPairs\n}\n\ntype ThemeStoreOptions<T extends ThemeStoreConfig> = {\n\tinitialState?: Partial<PersistedState<T>>\n\tstorage?: StorageAdapterCreate | null\n}\n\ntype ThemeAndOptions<T extends ThemeStoreConfig> = Array<\n\t{\n\t\t[K in keyof T]: [\n\t\t\tK,\n\t\t\tArray<\n\t\t\t\tT[K] extends { options: ReadonlyArray<infer U> }\n\t\t\t\t\t? U extends ThemeOption\n\t\t\t\t\t\t? U['value']\n\t\t\t\t\t\t: U\n\t\t\t\t\t: never\n\t\t\t>,\n\t\t]\n\t}[keyof T]\n>\n\nexport function getThemesAndOptions<T extends ThemeStoreConfig>(config: T) {\n\treturn Object.entries(config).map(([themeKey, themeConfig]) => {\n\t\treturn [\n\t\t\tthemeKey,\n\t\t\t(themeConfig.options || []).map((option) =>\n\t\t\t\ttypeof option === 'object' ? option.value : option,\n\t\t\t),\n\t\t]\n\t}) as ThemeAndOptions<T>\n}\n\nexport function getDefaultThemes<T extends ThemeStoreConfig>(config: T) {\n\treturn Object.fromEntries(\n\t\tObject.entries(config).map(([themeKey, themeConfig]) => {\n\t\t\treturn [\n\t\t\t\tthemeKey,\n\t\t\t\tthemeConfig.initialValue ??\n\t\t\t\t\t(typeof themeConfig.options[0] === 'object'\n\t\t\t\t\t\t? themeConfig.options[0].value\n\t\t\t\t\t\t: themeConfig.options[0]),\n\t\t\t]\n\t\t}),\n\t) as Themes<T>\n}\n\nclass ThemeStore<T extends ThemeStoreConfig> {\n\t#defaultThemes: Themes<T>\n\n\t#currentThemes: Themes<T>\n\n\t#systemOptions: SystemOptions = {}\n\n\t#storage: StorageAdapter | null\n\n\t#mediaQueryCache: Record<string, MediaQueryList> = {}\n\n\t#listeners: Set<Listener<T>> = new Set<Listener<T>>()\n\n\t#abortController = new AbortController()\n\n\tconstructor(\n\t\tconfig: T,\n\t\t{\n\t\t\tinitialState = {},\n\t\t\tstorage = localStorageAdapter({ key: PACKAGE_NAME }),\n\t\t}: ThemeStoreOptions<T> = {},\n\t) {\n\t\tthis.#defaultThemes = getDefaultThemes(config)\n\n\t\tthis.#currentThemes = { ...this.#defaultThemes, ...initialState.themes }\n\n\t\tthis.#systemOptions = Object.fromEntries(\n\t\t\tObject.entries(config).flatMap(([themeKey, themeConfig]) => {\n\t\t\t\tconst systemOption = (themeConfig.options || []).find(\n\t\t\t\t\t(option): option is Required<ThemeOption> =>\n\t\t\t\t\t\ttypeof option === 'object' && !!option.media,\n\t\t\t\t)\n\n\t\t\t\tif (!systemOption) return []\n\n\t\t\t\tconst {\n\t\t\t\t\tvalue,\n\t\t\t\t\tmedia: [mediaQuery, optionWhenMatched, optionWhenNotMatched],\n\t\t\t\t} = systemOption\n\n\t\t\t\treturn [\n\t\t\t\t\t[\n\t\t\t\t\t\tthemeKey,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\tmediaQuery,\n\t\t\t\t\t\t\tpair: initialState.systemOptions?.[themeKey] ?? [\n\t\t\t\t\t\t\t\toptionWhenMatched,\n\t\t\t\t\t\t\t\toptionWhenNotMatched,\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t]\n\t\t\t}),\n\t\t)\n\n\t\tthis.#storage =\n\t\t\tstorage?.({\n\t\t\t\tabortController: this.#abortController,\n\t\t\t}) ?? null\n\t}\n\n\tgetThemes = (): Themes<T> => {\n\t\treturn this.#currentThemes\n\t}\n\n\tgetResolvedThemes = (): Themes<T> => {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(this.#currentThemes).map(([themeKey, optionKey]) => {\n\t\t\t\tconst systemOption = this.#systemOptions[themeKey]\n\n\t\t\t\treturn [\n\t\t\t\t\tthemeKey,\n\t\t\t\t\tsystemOption && optionKey === systemOption.value\n\t\t\t\t\t\t? this.#resolveSystemOption(themeKey)\n\t\t\t\t\t\t: optionKey,\n\t\t\t\t]\n\t\t\t}),\n\t\t) as Themes<T>\n\t}\n\n\tgetResolvedSystemThemes = (): ResolvedSystemThemes<T> => {\n\t\treturn Object.fromEntries(\n\t\t\tObject.keys(this.#systemOptions).map((themeKey) => [\n\t\t\t\tthemeKey,\n\t\t\t\tthis.#resolveSystemOption(themeKey),\n\t\t\t]),\n\t\t) as ResolvedSystemThemes<T>\n\t}\n\n\tsetThemes = (\n\t\tthemes:\n\t\t\t| Partial<Themes<T>>\n\t\t\t| ((currentThemes: Themes<T>) => Partial<Themes<T>>),\n\t): void => {\n\t\tconst updatedThemes =\n\t\t\ttypeof themes === 'function' ? themes(this.#currentThemes) : themes\n\n\t\tthis.#setThemesAndNotify({ ...this.#currentThemes, ...updatedThemes })\n\n\t\tconst stateToPersist = this.toPersist()\n\n\t\tif (this.#storage) {\n\t\t\tthis.#storage.set(stateToPersist)\n\t\t\tthis.#storage.broadcast?.(stateToPersist)\n\t\t}\n\t}\n\n\tupdateSystemOption = <K extends ThemeKeysWithSystemOption<T>>(\n\t\tthemeKey: K,\n\t\tpair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>],\n\t): void => {\n\t\tthis.#systemOptions[themeKey]!.pair = pair\n\n\t\tthis.setThemes({ ...this.#currentThemes })\n\t}\n\n\ttoPersist = (): PersistedState<T> => {\n\t\treturn {\n\t\t\tthemes: this.#currentThemes,\n\t\t\tsystemOptions: Object.fromEntries(\n\t\t\t\tObject.entries(this.#systemOptions).map(([themeKey, { pair }]) => [\n\t\t\t\t\tthemeKey,\n\t\t\t\t\tpair,\n\t\t\t\t]),\n\t\t\t),\n\t\t}\n\t}\n\n\trestore = (): void => {\n\t\tconst persistedState = this.#storage?.get()\n\n\t\tif (!persistedState) {\n\t\t\tthis.#setThemesAndNotify({ ...this.#defaultThemes })\n\t\t\treturn\n\t\t}\n\n\t\tthis.#applyPersistedSystemOptions(persistedState.systemOptions)\n\n\t\tthis.#setThemesAndNotify({\n\t\t\t...this.#defaultThemes,\n\t\t\t...persistedState.themes,\n\t\t})\n\t}\n\n\tsubscribe = (callback: Listener<T>): (() => void) => {\n\t\tthis.#listeners.add(callback)\n\n\t\treturn () => this.#listeners.delete(callback)\n\t}\n\n\tsync = (): (() => void) | undefined => {\n\t\tif (!this.#storage?.watch) return\n\n\t\treturn this.#storage.watch((persistedState) => {\n\t\t\tthis.#applyPersistedSystemOptions(\n\t\t\t\t(persistedState as PersistedState<T>).systemOptions,\n\t\t\t)\n\n\t\t\tthis.#setThemesAndNotify((persistedState as PersistedState<T>).themes)\n\t\t})\n\t}\n\n\t/** Clears subscribers and aborts media-query listeners tied to this store instance. */\n\tdestroy = (): void => {\n\t\tthis.#listeners.clear()\n\t\tthis.#abortController.abort()\n\t}\n\n\t#applyPersistedSystemOptions = (\n\t\tsystemOptions: PersistedSystemOptionPairs = {},\n\t): void => {\n\t\tObject.entries(systemOptions).forEach(([themeKey, pair]) => {\n\t\t\tif (!pair || !this.#systemOptions[themeKey]) return\n\n\t\t\tthis.#systemOptions[themeKey].pair = pair\n\t\t})\n\t}\n\n\t#setThemesAndNotify = (themes: Themes<T>): void => {\n\t\tthis.#currentThemes = themes\n\n\t\tfor (const listener of this.#listeners) {\n\t\t\tlistener({\n\t\t\t\tthemes: this.#currentThemes,\n\t\t\t\tresolvedThemes: this.getResolvedThemes(),\n\t\t\t\tresolvedSystemThemes: this.getResolvedSystemThemes(),\n\t\t\t})\n\t\t}\n\t}\n\n\t#resolveSystemOption = (themeKey: string): string => {\n\t\tconst { value, mediaQuery, pair } = this.#systemOptions[themeKey]!\n\n\t\tif (\n\t\t\t!(\n\t\t\t\ttypeof window !== 'undefined' &&\n\t\t\t\ttypeof window.document !== 'undefined' &&\n\t\t\t\ttypeof window.document.createElement !== 'undefined'\n\t\t\t)\n\t\t) {\n\t\t\treturn value\n\t\t}\n\n\t\tif (!this.#mediaQueryCache[mediaQuery]) {\n\t\t\tthis.#mediaQueryCache[mediaQuery] = window.matchMedia(mediaQuery)\n\n\t\t\tthis.#mediaQueryCache[mediaQuery].addEventListener(\n\t\t\t\t'change',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#setThemesAndNotify({ ...this.#currentThemes })\n\t\t\t\t},\n\t\t\t\t{ signal: this.#abortController.signal },\n\t\t\t)\n\t\t}\n\n\t\treturn this.#mediaQueryCache[mediaQuery].matches ? pair[0] : pair[1]\n\t}\n}\n\nexport type { ThemeStore }\n\nexport function createThemeStore<T extends ThemeStoreConfig>(\n\tconfig: T,\n\toptions: ThemeStoreOptions<T> = {},\n): ThemeStore<T> {\n\treturn new ThemeStore<T>(config, options)\n}\n\nconst restoreScript = <T extends ThemeValue>(\n\tparams: Array<\n\t\t[\n\t\t\tstring,\n\t\t\tArray<[string, T] | [string, T, T, string, T, T]>,\n\t\t\tListener<any, true>,\n\t\t]\n\t>,\n) => {\n\tparams.forEach(([key, flattenedConfig, handler]) => {\n\t\tconst persisted = JSON.parse(localStorage.getItem(key) || '{}')\n\n\t\thandler(\n\t\t\tflattenedConfig.reduce<{\n\t\t\t\tthemes: Record<string, ThemeValue>\n\t\t\t\tresolvedThemes: Record<string, ThemeValue>\n\t\t\t}>(\n\t\t\t\t(\n\t\t\t\t\tacc,\n\t\t\t\t\t[\n\t\t\t\t\t\tthemeKey,\n\t\t\t\t\t\tinitial,\n\t\t\t\t\t\tsystemOptionValue,\n\t\t\t\t\t\tmediaQuery,\n\t\t\t\t\t\toptionWhenMatched,\n\t\t\t\t\t\toptionWhenNotMatched,\n\t\t\t\t\t],\n\t\t\t\t) => {\n\t\t\t\t\tconst currentValue = persisted.themes?.[themeKey] ?? initial\n\n\t\t\t\t\tacc.resolvedThemes[themeKey] = acc.themes[themeKey] = currentValue\n\n\t\t\t\t\tif (currentValue === systemOptionValue) {\n\t\t\t\t\t\tconst pair = persisted.systemOptions?.[themeKey] ?? [\n\t\t\t\t\t\t\toptionWhenMatched,\n\t\t\t\t\t\t\toptionWhenNotMatched,\n\t\t\t\t\t\t]\n\n\t\t\t\t\t\tacc.resolvedThemes[themeKey] = matchMedia(mediaQuery!).matches\n\t\t\t\t\t\t\t? pair[0]\n\t\t\t\t\t\t\t: pair[1]\n\t\t\t\t\t}\n\n\t\t\t\t\treturn acc\n\t\t\t\t},\n\t\t\t\t{ themes: {}, resolvedThemes: {} },\n\t\t\t),\n\t\t)\n\t})\n}\n\nexport type ThemeScriptParameter = {\n\t/** `localStorage` key; defaults to the 'resonare'. */\n\tkey?: string\n\tconfig: ThemeStoreConfig\n\thandler: Listener<any, true>\n}\n\n/**\n * Creates an IIFE script string that reads persisted themes from `localStorage` and runs your handlers immediately.\n *\n * Useful for avoiding flash of incorrect styles.\n * @example\n * ```tsx\n * import { createInlineThemeScript } from 'resonare'\n *\n * const inlineScript = createInlineThemeScript([\n * {\n * key: 'my-app',\n * config: {\n * colorMode: { options: ['light', 'dark'] },\n * },\n * handler: ({ resolvedThemes }) => {\n * document.documentElement.dataset.colorMode = String(\n * resolvedThemes.colorMode,\n * )\n * },\n * },\n * ])\n * ```\n */\nexport function createInlineThemeScript(\n\tthemeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>,\n) {\n\tconst serializedArgs = (\n\t\tArray.isArray(themeScriptParameters)\n\t\t\t? themeScriptParameters\n\t\t\t: [themeScriptParameters]\n\t).map(({ key = PACKAGE_NAME, config, handler }) => {\n\t\tconst flattenedConfig = Object.entries(config).map(\n\t\t\t([themeKey, { options, initialValue }]) => {\n\t\t\t\tconst firstOption = options?.[0]\n\n\t\t\t\tconst resolvedInitialValue =\n\t\t\t\t\tinitialValue ??\n\t\t\t\t\t(typeof firstOption === 'object' ? firstOption.value : firstOption!)\n\n\t\t\t\tconst systemOption = options?.find(\n\t\t\t\t\t(option): option is Required<ThemeOption> =>\n\t\t\t\t\t\ttypeof option === 'object' && !!option.media,\n\t\t\t\t)\n\n\t\t\t\tif (systemOption) {\n\t\t\t\t\tconst { value, media } = systemOption\n\n\t\t\t\t\treturn [themeKey, resolvedInitialValue, value, ...media]\n\t\t\t\t}\n\n\t\t\t\treturn [themeKey, resolvedInitialValue]\n\t\t\t},\n\t\t)\n\n\t\treturn `['${key}',${JSON.stringify(flattenedConfig)},${handler}]`\n\t})\n\n\treturn `(${restoreScript})([${serializedArgs}])`\n}\n"],"mappings":"iBCoCA,MAAagB,GAGP,CAAEC,MAAKf,OAAO,mBACX,CAAES,sBACF,CACNP,QACQc,KAAKC,MAAMC,OAAOlB,EAAK,CAACmB,QAAQJ,CAAG,GAAK,MAAM,EAGtDZ,IAAMC,GAAkB,CACvBc,OAAOlB,EAAK,CAACoB,QAAQL,EAAKC,KAAKK,UAAUjB,CAAK,CAAC,CAChD,EAEAE,MAAQC,GAAO,CACd,IAAMe,EAAa,IAAIZ,gBAmBvB,OAjBAQ,OAAOK,iBACN,UACCC,GAAM,CACFA,EAAEC,cAAgBP,OAAOlB,IAEzBwB,EAAET,MAAQA,GAEdR,EAAGS,KAAKC,MAAMO,EAAEE,QAAS,CAAC,CAC3B,EACA,CACCC,OAAQC,YAAYC,IAAI,CACvBpB,EAAgBkB,OAChBL,EAAWK,MAAM,CACjB,CACF,CACD,MAEa,CACZL,EAAWQ,MAAM,CAClB,CACD,CACD,GAiBWC,GAEP,CAAEhB,UACC,CAAEN,qBAAsB,CAC/B,IAAMuB,EAAU,IAAIC,IACdC,EAAU,IAAIC,iBAAiBpC,CAAY,EAEjD,MAAO,CACNG,QACQ8B,EAAQ9B,IAAIa,CAAG,GAAK,KAG5BZ,IAAMC,GAAkB,CACvB4B,EAAQ7B,IAAIY,EAAKX,CAAK,CACvB,EAEAC,UAAYD,GAAkB,CAC7B8B,EAAQE,YAAY,CAAErB,MAAKX,OAAM,CAAC,CACnC,EAEAE,MAAQC,GAAO,CACd,IAAMe,EAAa,IAAIZ,gBAiBvB,OAfAwB,EAAQX,iBACP,UACCC,GAAM,CACFA,EAAEa,KAAKtB,MAAQA,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jH,IACC,OAAOgH,GAAgB,SAAWA,EAAYtH,MAAQsH,GAElDhE,EAAelD,GAASmD,KAC5BhB,GACA,OAAOA,GAAW,UAAY,CAAC,CAACA,EAAOrC,KACzC,EAEA,GAAIoD,EAAc,CACjB,GAAM,CAAEtD,QAAOE,SAAUoD,EAEzB,MAAO,CAACjB,EAAUkF,EAAsBvH,EAAO,GAAGE,CAAK,CACxD,CAEA,MAAO,CAACmC,EAAUkF,CAAoB,CACvC,CACD,EAEA,MAAO,KAAKnE,EAAG,IAAKoD,KAAKgB,UAAUnB,CAAe,EAAC,GAAIC,EAAO,EAC/D,CAE8Bc,EAAc,GAC7C"}
1
+ {"version":3,"file":"index.js","names":["DEFAULT_KEY","toScriptJson","localStorageAdapter","getThemesAndOptions","config","themeKey","themeConfig","option","getDefaultThemes","createThemeStore","createStorage","defaultThemes","currentThemes","persisted","systemOptions","systemOption","mediaQuery","optionWhenMatched","optionWhenNotMatched","defaultPair","mediaQueryLists","listeners","abortController","storage","resolveSystemOption","server","pair","mqList","setThemesAndNotify","createSnapshot","resolvedSystemThemes","resolvedThemes","serverSnapshot","snapshot","themes","listener","applyStored","parsed","stored","toPersist","pairs","setThemes","callback","restoreScript","params","key","flattenedConfig","handler","initial","systemOptionValue","currentValue","systemTheme","acc","createInlineThemeScript","serializedArgs","themeScriptParameters","firstOption","options","resolvedInitialValue","defaultValue","value","media","toScriptFunction","memoryStorageAdapter"],"sources":["../src/index.ts"],"sourcesContent":["import { DEFAULT_KEY } from './constants'\nimport { toScriptFunction, toScriptJson } from './script'\nimport { type StorageAdapterCreate, localStorageAdapter } from './storage'\n\nexport * from './storage'\n\ntype ThemeValue = string | number | boolean\n\ntype ThemeOption<T extends ThemeValue = string> = {\n value: T\n media?: readonly [string, T, T]\n}\n\ntype ThemeConfig<T extends ThemeValue = string> =\n | {\n options: ReadonlyArray<T | ThemeOption<T>>\n defaultValue?: T\n }\n | { defaultValue: T; options?: never }\n\n/**\n * Config for `createThemeStore`. Each key is a theme setting (`colorMode`,\n * `contrast`, …) with either:\n *\n * - `options`: the allowed values, plus an optional `defaultValue` (otherwise the\n * first option). One option may be a `{ value, media }` object: when it is\n * selected, the setting follows a media query, using `media[1]` while the\n * query matches and `media[2]` while it doesn't.\n * - `defaultValue` alone: a free value of that type, such as a number.\n *\n * @example\n * const config = {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * contrast: {\n * options: ['normal', 'more'],\n * },\n * sidebarWidth: {\n * defaultValue: 240,\n * },\n * } as const satisfies ThemeStoreConfig\n */\nexport type ThemeStoreConfig = Record<\n string,\n ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>\n>\n\n/**\n * The selected value of each setting, as passed to `setThemes` (e.g.\n * `colorMode: 'system'`). Inferred from your `ThemeStoreConfig`.\n */\nexport type Themes<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : T[K] extends { defaultValue: infer U }\n ? U extends string\n ? string\n : U extends number\n ? number\n : boolean\n : never\n}\n\ntype ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends { media: ReadonlyArray<unknown> }\n ? K\n : never\n : never\n}[keyof T]\n\ntype NonSystemOptionValues<\n T extends ThemeStoreConfig,\n K extends keyof T,\n> = T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeValue\n ? U\n : U extends ThemeOption\n ? U extends { media: ReadonlyArray<unknown> }\n ? never\n : U['value']\n : never\n : never\n\n/**\n * For each setting with a `media` option, the value that option currently\n * resolves to, whether or not it is selected.\n */\ntype ResolvedSystemThemes<T extends ThemeStoreConfig> = {\n [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>\n}\n\n/** Runtime state for each dimension that defines a `media` option. */\ntype SystemOptions = Record<\n string,\n {\n value: string\n mediaQuery: string\n pair: [string, string]\n defaultPair: [string, string]\n }\n>\n\ntype Snapshot<T extends ThemeStoreConfig> = {\n themes: Themes<T>\n resolvedThemes: Themes<T>\n resolvedSystemThemes: ResolvedSystemThemes<T>\n}\n\ntype Listener<T extends ThemeStoreConfig> = (value: Snapshot<T>) => void\n\ntype PersistedSystemOptionPairs = Record<string, [string, string]>\n\ntype PersistedState<T extends ThemeStoreConfig> = {\n themes: Partial<Themes<T>>\n systemOptions: PersistedSystemOptionPairs\n}\n\ntype ThemeStoreOptions<T extends ThemeStoreConfig> = {\n persisted?: Partial<PersistedState<T>>\n storage?: StorageAdapterCreate | null\n}\n\ntype ThemeAndOptions<T extends ThemeStoreConfig> = Array<\n {\n [K in keyof T]: [\n K,\n Array<\n T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : never\n >,\n ]\n }[keyof T]\n>\n\n/**\n * Lists each setting with its option values (`{ value, media }` options become\n * their `value`). Useful for rendering a picker for every setting.\n *\n * @example\n * import { getThemesAndOptions } from 'resonare'\n *\n * getThemesAndOptions({\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * },\n * })\n * // [['colorMode', ['light', 'dark', 'system']]]\n */\nexport function getThemesAndOptions<T extends ThemeStoreConfig>(config: T) {\n return Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n (themeConfig.options || []).map((option) => {\n return typeof option === 'object' ? option.value : option\n }),\n ]\n }) as ThemeAndOptions<T>\n}\n\n/**\n * Returns each setting's default: its `defaultValue`, or else its first\n * option.\n *\n * @example\n * import { getDefaultThemes } from 'resonare'\n *\n * getDefaultThemes({\n * colorMode: { options: ['light', 'dark'], defaultValue: 'dark' },\n * }) // { colorMode: 'dark' }\n */\nexport function getDefaultThemes<T extends ThemeStoreConfig>(config: T) {\n return Object.fromEntries(\n Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n themeConfig.defaultValue ??\n (typeof themeConfig.options[0] === 'object'\n ? themeConfig.options[0].value\n : themeConfig.options[0]),\n ]\n })\n ) as Themes<T>\n}\n\n/**\n * Creates a store for the settings in `config`. It saves changes through\n * `storage` (`localStorage` under the key `'resonare'` by default; `null`\n * disables saving), resolves `media` options in the browser, and notifies\n * subscribers.\n *\n * Read state with `getSnapshot()` or `subscribe`.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * },\n * { storage: localStorageAdapter({ key: 'my-app' }) }\n * )\n *\n * // In the browser: load the saved choice and follow other tabs.\n * store.restore()\n * store.sync()\n *\n * store.subscribe(({ resolvedThemes }) => {\n * document.documentElement.dataset.colorMode = resolvedThemes.colorMode\n * })\n *\n * store.setThemes({ colorMode: 'dark' })\n */\nexport function createThemeStore<T extends ThemeStoreConfig>(\n config: T,\n {\n persisted = {},\n storage: createStorage = localStorageAdapter({ key: DEFAULT_KEY }),\n }: ThemeStoreOptions<T> = {}\n) {\n const defaultThemes = getDefaultThemes(config)\n\n let currentThemes: Themes<T> = { ...defaultThemes, ...persisted.themes }\n\n const systemOptions: SystemOptions = {}\n\n for (const themeKey in config) {\n const systemOption = (config[themeKey]!.options || []).find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const {\n value,\n media: [mediaQuery, optionWhenMatched, optionWhenNotMatched],\n } = systemOption\n\n const defaultPair: [string, string] = [\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n\n systemOptions[themeKey] = {\n value,\n mediaQuery,\n pair: [...(persisted.systemOptions?.[themeKey] ?? defaultPair)],\n defaultPair,\n }\n }\n }\n\n const mediaQueryLists: Record<string, MediaQueryList> = {}\n\n const listeners = new Set<Listener<T>>()\n\n const abortController = new AbortController()\n\n const storage = createStorage?.({ abortController })\n\n const resolveSystemOption = (themeKey: string, server?: boolean): string => {\n const { mediaQuery, pair } = systemOptions[themeKey]!\n\n // No media support (e.g. on the server): use the \"not matched\" value.\n if (server || typeof matchMedia === 'undefined') {\n return pair[1]\n }\n\n let mqList = mediaQueryLists[mediaQuery]\n\n if (!mqList) {\n mqList = mediaQueryLists[mediaQuery] = matchMedia(mediaQuery)\n\n mqList.addEventListener(\n 'change',\n () => {\n setThemesAndNotify()\n },\n abortController\n )\n }\n\n return pair[mqList.matches ? 0 : 1]\n }\n\n const createSnapshot = (server?: boolean): Snapshot<T> => {\n const resolvedSystemThemes: Record<string, string> = {}\n\n const resolvedThemes = { ...currentThemes } as Record<string, ThemeValue>\n\n for (const themeKey in systemOptions) {\n resolvedSystemThemes[themeKey] = resolveSystemOption(themeKey, server)\n\n if (resolvedThemes[themeKey] === systemOptions[themeKey]!.value) {\n resolvedThemes[themeKey] = resolvedSystemThemes[themeKey]\n }\n }\n\n return {\n themes: currentThemes,\n resolvedThemes: resolvedThemes as Themes<T>,\n resolvedSystemThemes: resolvedSystemThemes as ResolvedSystemThemes<T>,\n }\n }\n\n const serverSnapshot = createSnapshot(true)\n\n let snapshot = createSnapshot()\n\n const setThemesAndNotify = (themes?: Partial<Themes<T>>): void => {\n currentThemes = { ...currentThemes, ...themes }\n\n snapshot = createSnapshot()\n\n for (const listener of listeners) {\n listener(snapshot)\n }\n }\n\n /** Applies saved state; ignores empty or malformed input. */\n const applyStored = (stored: string | null | undefined): void => {\n let parsed: PersistedState<T> | undefined\n\n try {\n parsed = stored ? JSON.parse(stored) : undefined\n } catch {}\n\n if (!parsed?.themes || typeof parsed.themes !== 'object') {\n return\n }\n\n for (const themeKey in parsed.systemOptions) {\n const pair = parsed.systemOptions[themeKey]\n\n if (pair && systemOptions[themeKey]) {\n systemOptions[themeKey].pair = pair\n }\n }\n\n setThemesAndNotify(parsed.themes)\n }\n\n const toPersist = (): PersistedState<T> => {\n const pairs: PersistedSystemOptionPairs = {}\n\n for (const themeKey in systemOptions) {\n pairs[themeKey] = [...systemOptions[themeKey]!.pair]\n }\n\n return { themes: { ...currentThemes }, systemOptions: pairs }\n }\n\n const setThemes = (\n themes:\n | Partial<Themes<T>>\n | ((currentThemes: Themes<T>) => Partial<Themes<T>>)\n ): void => {\n setThemesAndNotify(\n typeof themes === 'function' ? themes(currentThemes) : themes\n )\n\n if (storage) {\n const stored = JSON.stringify(toPersist())\n\n storage.set(stored)\n\n storage.broadcast?.(stored)\n }\n }\n\n return {\n /**\n * Current state:\n *\n * - `themes`: the selected value of each setting (e.g. `'system'`).\n * - `resolvedThemes`: the same with `media` options resolved (e.g. `'dark'`).\n * - `resolvedSystemThemes`: what each `media` option resolves to, even when\n * it isn't selected.\n *\n * Returns the same object until the next change.\n */\n getSnapshot: (): Snapshot<T> => {\n return snapshot\n },\n\n /**\n * The state as rendered on the server: defaults plus `persisted`, with\n * `media` options resolved to their \"not matched\" value. It never changes,\n * so hydration can match the server HTML even after `restore()`.\n */\n getServerSnapshot: (): Snapshot<T> => {\n return serverSnapshot\n },\n\n /**\n * Updates the given settings (others keep their value), saves to storage,\n * and notifies subscribers.\n *\n * @example\n * store.setThemes({ colorMode: 'dark' })\n *\n * store.setThemes((current) => ({\n * colorMode: current.colorMode === 'dark' ? 'light' : 'dark',\n * }))\n */\n setThemes,\n\n /**\n * Changes which values a `media` option resolves to: `[whenMatched,\n * whenNotMatched]`, replacing `media[1]` and `media[2]` from the config.\n * Saved like `setThemes`.\n *\n * @example\n * // system now picks 'dark-dimmed' when the OS prefers dark\n * store.updateSystemOption('colorMode', ['dark-dimmed', 'light'])\n */\n updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(\n themeKey: K,\n pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]\n ): void => {\n systemOptions[themeKey as string]!.pair = [...pair]\n\n setThemes({})\n },\n\n /**\n * The state to save, e.g. to a database: pass it back as `persisted` when\n * creating the store.\n */\n toPersist,\n\n /**\n * Loads the saved state from storage. Does nothing when nothing is saved.\n * Call it in the browser, e.g. after hydration.\n */\n restore: (): void => {\n applyStored(storage?.get())\n },\n\n /**\n * Calls `callback` with the new state (see `getSnapshot`) after every\n * change, including OS preference changes. Returns an unsubscribe\n * function.\n */\n subscribe: (callback: Listener<T>): (() => void) => {\n listeners.add(callback)\n\n return () => {\n listeners.delete(callback)\n }\n },\n\n /**\n * Applies changes saved by other tabs (if the storage adapter supports\n * it); when another tab clears the saved state, resets to the config\n * defaults. Returns a function that stops syncing, or `undefined` when the\n * adapter can't sync.\n */\n sync: (): (() => void) | undefined => {\n return storage?.watch?.((stored) => {\n // `null` means another tab cleared the stored preferences.\n if (stored === null) {\n for (const themeKey in systemOptions) {\n const systemOption = systemOptions[themeKey]!\n\n systemOption.pair = systemOption.defaultPair\n }\n\n setThemesAndNotify(defaultThemes)\n } else {\n applyStored(stored)\n }\n })\n },\n\n /**\n * Removes all subscribers and stops listening to media queries and\n * storage. The store doesn't update after this.\n */\n destroy: (): void => {\n listeners.clear()\n\n abortController.abort()\n },\n }\n}\n\nexport type ThemeStore<T extends ThemeStoreConfig> = ReturnType<\n typeof createThemeStore<T>\n>\n\nconst restoreScript = <T extends ThemeValue>(\n params: Array<\n [string, Array<[string, T] | [string, T, T, string, T, T]>, Listener<any>]\n >\n) => {\n params.forEach(([key, flattenedConfig, handler]) => {\n let persisted: any\n\n // Blocked storage or bad JSON must not stop the handler from running.\n try {\n persisted = JSON.parse(localStorage.getItem(key)!)\n } catch {}\n\n handler(\n flattenedConfig.reduce<{\n themes: Record<string, ThemeValue>\n resolvedThemes: Record<string, ThemeValue>\n resolvedSystemThemes: Record<string, ThemeValue>\n }>(\n (\n acc,\n [\n themeKey,\n initial,\n systemOptionValue,\n mediaQuery,\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n ) => {\n const currentValue = persisted?.themes?.[themeKey] ?? initial\n\n acc.resolvedThemes[themeKey] = acc.themes[themeKey] = currentValue\n\n if (mediaQuery != null) {\n const pair = persisted?.systemOptions?.[themeKey] ?? [\n optionWhenMatched!,\n optionWhenNotMatched!,\n ]\n\n const systemTheme = matchMedia(mediaQuery).matches\n ? pair[0]\n : pair[1]\n\n acc.resolvedSystemThemes[themeKey] = systemTheme\n\n if (currentValue === systemOptionValue) {\n acc.resolvedThemes[themeKey] = systemTheme\n }\n }\n\n return acc\n },\n { themes: {}, resolvedThemes: {}, resolvedSystemThemes: {} }\n )\n )\n })\n}\n\n/** One store for `createInlineThemeScript`. */\nexport type ThemeScriptParameter = {\n /** The store's `localStorage` key; defaults to `'resonare'`. */\n key?: string\n /** The same config passed to `createThemeStore`. */\n config: ThemeStoreConfig\n /**\n * Applies the state to the page; receives the same value as `subscribe`.\n * It is copied into the script as source code, so it can't use variables\n * from outside the function.\n */\n handler: Listener<any>\n}\n\n/**\n * Returns the source of a small script that reads the saved state from\n * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in\n * the `<head>` so the page has the right theme before first paint. Pass an\n * array to set up several stores.\n *\n * Use the same handler with `store.subscribe` to keep the page updated after\n * that.\n *\n * @example\n * import { createInlineThemeScript } from 'resonare'\n *\n * // config: the same object passed to createThemeStore\n * const themeScript = createInlineThemeScript({\n * key: 'my-app',\n * config,\n * handler: ({ resolvedThemes }) => {\n * const root = document.documentElement\n * root.dataset.colorMode = resolvedThemes.colorMode\n * },\n * })\n *\n * // In <head>:\n * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />\n */\nexport function createInlineThemeScript(\n themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>\n) {\n const serializedArgs = (\n Array.isArray(themeScriptParameters)\n ? themeScriptParameters\n : [themeScriptParameters]\n ).map(({ key = DEFAULT_KEY, config, handler }) => {\n const flattenedConfig = Object.entries(config).map(\n ([themeKey, { options, defaultValue }]) => {\n const firstOption = options?.[0]\n\n const resolvedInitialValue =\n defaultValue ??\n (typeof firstOption === 'object' ? firstOption.value : firstOption!)\n\n const systemOption = options?.find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const { value, media } = systemOption\n\n return [themeKey, resolvedInitialValue, value, ...media]\n }\n\n return [themeKey, resolvedInitialValue]\n }\n )\n\n return `[${toScriptJson(key)},${toScriptJson(flattenedConfig)},${toScriptFunction(handler)}]`\n })\n\n return `(${restoreScript})([${serializedArgs}])`\n}\n"],"mappings":"A,4DA0KA,SAAgBG,EAAgD,EAAW,CACzE,OAAO,OAAO,QAAQC,CAAM,CAAC,CAAC,KAAK,CAACC,EAAUC,KACrC,CACLD,GACCC,EAAY,SAAW,CAAC,EAAA,CAAG,IAAK,GACxB,OAAOC,GAAW,SAAWA,EAAO,MAAQA,CACpD,CACH,CACD,CACH,CAaA,SAAgBC,EAA6C,EAAW,CACtE,OAAO,OAAO,YACZ,OAAO,QAAQJ,CAAM,CAAC,CAAC,KAAK,CAACC,EAAUC,KAC9B,CACLD,EACAC,EAAY,eACT,OAAOA,EAAY,QAAQ,IAAO,SAC/BA,EAAY,QAAQ,EAAE,CAAC,MACvBA,EAAY,QAAQ,GAC5B,CACD,CACH,CACF,CAwCA,SAAgBG,EACd,EACA,CACE,YAAY,CAAC,EACb,QAASC,EAAgBR,EAAoB,CAAE,IAAKF,CAAY,CAAC,GACzC,CAAC,EAC3B,CACA,IAAMW,EAAgBH,EAAiBJ,CAAM,EAEzCQ,EAA2B,CAAE,GAAGD,EAAe,GAAGE,EAAU,MAAO,EAEjEC,EAA+B,CAAC,EAEtC,IAAK,IAAMT,KAAYD,EAAQ,CAC7B,IAAMW,GAAgBX,EAAOC,EAAS,CAAE,SAAW,CAAC,EAAA,CAAG,KACpD,GACQ,OAAOE,GAAW,UAAY,CAAC,CAACA,EAAO,KAElD,EAEA,GAAIQ,EAAc,CAChB,GAAM,CACJ,QACA,MAAO,CAACC,EAAYC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EAAE,EAC7F,CAAC,EAED,MAAO,IAAIJ,EAAc,KAAKW,EAAe,GAC/C,C"}
@@ -0,0 +1,41 @@
1
+ import { ThemeStore } from "./lite.js";
2
+ /**
3
+ * Returns the store's current state (see `store.getSnapshot()`) and its
4
+ * methods, and re-renders the component when the state changes. Server
5
+ * rendering and hydration are handled automatically.
6
+ *
7
+ * @example
8
+ * import { createThemeStore } from 'resonare/lite'
9
+ * import { useResonare } from 'resonare/lite/react'
10
+ *
11
+ * const store = createThemeStore()
12
+ *
13
+ * function ThemeToggle() {
14
+ * const { resolvedTheme, setTheme } = useResonare(store)
15
+ *
16
+ * return (
17
+ * <button
18
+ * onClick={() => {
19
+ * setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')
20
+ * }}
21
+ * >
22
+ * {resolvedTheme}
23
+ * </button>
24
+ * )
25
+ * }
26
+ */
27
+ export declare function useResonare(store: ThemeStore): {
28
+ theme: "dark" | "light" | "system";
29
+ resolvedTheme: "dark" | "light";
30
+ systemTheme: "dark" | "light";
31
+ destroy: () => void;
32
+ restore: () => void;
33
+ setTheme: (next: ("dark" | "light" | "system") | ((current: "dark" | "light" | "system") => "dark" | "light" | "system")) => void;
34
+ subscribe: (callback: (value: {
35
+ theme: "dark" | "light" | "system";
36
+ resolvedTheme: "dark" | "light";
37
+ systemTheme: "dark" | "light";
38
+ }) => void) => (() => void);
39
+ sync: () => (() => void) | undefined;
40
+ };
41
+ //# sourceMappingURL=lite-react.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-react.d.ts","names":[],"sources":["../src/lite-react.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;wBA6BgB,YAAY,OAAO"}
@@ -0,0 +1,2 @@
1
+ import{c as e}from"react/compiler-runtime";import*as t from"react";function n(n){let r=e(7),{destroy:i,getServerSnapshot:a,getSnapshot:o,restore:s,setTheme:c,subscribe:l,sync:u}=n,d=t.useSyncExternalStore(l,o,a),f;return r[0]!==i||r[1]!==s||r[2]!==c||r[3]!==d||r[4]!==l||r[5]!==u?(f={...d,destroy:i,restore:s,setTheme:c,subscribe:l,sync:u},r[0]=i,r[1]=s,r[2]=c,r[3]=d,r[4]=l,r[5]=u,r[6]=f):f=r[6],f}export{n as useResonare};
2
+ //# sourceMappingURL=lite-react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-react.js","names":["{ ...snapshot, destroy, restore, setTheme, subscribe, sync }","_c","React","useResonare","$","c","store","snapshot","subscribe","getSnapshot","getServerSnapshot","t0","destroy","restore","setTheme","sync"],"sources":["../src/lite-react.ts"],"sourcesContent":["import * as React from 'react'\n\nimport type { ThemeStore } from './lite'\n\n/**\n * Returns the store's current state (see `store.getSnapshot()`) and its\n * methods, and re-renders the component when the state changes. Server\n * rendering and hydration are handled automatically.\n *\n * @example\n * import { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/react'\n *\n * const store = createThemeStore()\n *\n * function ThemeToggle() {\n * const { resolvedTheme, setTheme } = useResonare(store)\n *\n * return (\n * <button\n * onClick={() => {\n * setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')\n * }}\n * >\n * {resolvedTheme}\n * </button>\n * )\n * }\n */\nexport function useResonare(store: ThemeStore) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setTheme,\n subscribe,\n sync,\n } = store\n\n const snapshot = React.useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n )\n\n return { ...snapshot, destroy, restore, setTheme, subscribe, sync }\n}\n"],"mappings":"A,mEA6BA,SAAgBG,EAAY,EAAmB,C,WACvC,CACJ,UACA,oBACA,cACA,UACA,WACA,YACA,QACEG,EAEEC,EAAWL,EAAM,qBACrBM,EACAC,EACAC,CACF,EAEOV,EAAP,OAAsBI,EAAA,KAAAQ,GAAAR,EAAA,KAASS,GAAAT,EAAA,KAASU,GAAAV,EAAA,KAA5BG,GAAAH,EAAA,KAAsCI,GAAAJ,EAAA,KAAWW,GAAtD,EAAA,CAAE,GAAGR,EAAU,UAAS,UAAS,WAAU,YAAW,MAAK,EAA5C,EAAA,GAAAK,EAAS,EAAA,GAAAC,EAAS,EAAA,GAAAC,EAA5B,EAAA,GAAAP,EAAsC,EAAA,GAAAC,EAAW,EAAA,GAAAO,E,eAAtDf,CACT,C"}