resonare 0.2.0 → 0.4.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 (64) hide show
  1. package/README.md +398 -270
  2. package/dist/effects-core-CuoeZrRP.js +2 -0
  3. package/dist/effects-core-CuoeZrRP.js.map +1 -0
  4. package/dist/effects-core-DPJyVK-w.d.ts +14 -0
  5. package/dist/effects-core-DPJyVK-w.d.ts.map +1 -0
  6. package/dist/effects.d.ts +105 -0
  7. package/dist/effects.d.ts.map +1 -0
  8. package/dist/effects.js +2 -0
  9. package/dist/effects.js.map +1 -0
  10. package/dist/index.d.ts +233 -30
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/lite-effects.d.ts +65 -0
  15. package/dist/lite-effects.d.ts.map +1 -0
  16. package/dist/lite-effects.js +2 -0
  17. package/dist/lite-effects.js.map +1 -0
  18. package/dist/lite-react.d.ts +31 -22
  19. package/dist/lite-react.d.ts.map +1 -1
  20. package/dist/lite-react.js +1 -1
  21. package/dist/lite-react.js.map +1 -1
  22. package/dist/lite-solid.d.ts +46 -0
  23. package/dist/lite-solid.d.ts.map +1 -0
  24. package/dist/lite-solid.js +2 -0
  25. package/dist/lite-solid.js.map +1 -0
  26. package/dist/lite-svelte.d.ts +45 -0
  27. package/dist/lite-svelte.d.ts.map +1 -0
  28. package/dist/lite-svelte.js +2 -0
  29. package/dist/lite-svelte.js.map +1 -0
  30. package/dist/lite-vue.d.ts +53 -0
  31. package/dist/lite-vue.d.ts.map +1 -0
  32. package/dist/lite-vue.js +2 -0
  33. package/dist/lite-vue.js.map +1 -0
  34. package/dist/lite.d.ts +110 -23
  35. package/dist/lite.d.ts.map +1 -1
  36. package/dist/lite.js +1 -1
  37. package/dist/lite.js.map +1 -1
  38. package/dist/react.d.ts +62 -38
  39. package/dist/react.d.ts.map +1 -1
  40. package/dist/react.js +1 -1
  41. package/dist/react.js.map +1 -1
  42. package/dist/solid.d.ts +99 -0
  43. package/dist/solid.d.ts.map +1 -0
  44. package/dist/solid.js +2 -0
  45. package/dist/solid.js.map +1 -0
  46. package/dist/storage-CsXjZKyt.d.ts +65 -0
  47. package/dist/storage-CsXjZKyt.d.ts.map +1 -0
  48. package/dist/storage-fOH2xeQ1.js +2 -0
  49. package/dist/storage-fOH2xeQ1.js.map +1 -0
  50. package/dist/svelte.d.ts +101 -0
  51. package/dist/svelte.d.ts.map +1 -0
  52. package/dist/svelte.js +2 -0
  53. package/dist/svelte.js.map +1 -0
  54. package/dist/utils-CWI4hy3w.js +2 -0
  55. package/dist/utils-CWI4hy3w.js.map +1 -0
  56. package/dist/vue.d.ts +97 -0
  57. package/dist/vue.d.ts.map +1 -0
  58. package/dist/vue.js +2 -0
  59. package/dist/vue.js.map +1 -0
  60. package/package.json +75 -32
  61. package/dist/storage-B5xjLRee.js +0 -2
  62. package/dist/storage-B5xjLRee.js.map +0 -1
  63. package/dist/storage-DGYV332J.d.ts +0 -23
  64. package/dist/storage-DGYV332J.d.ts.map +0 -1
package/dist/lite.d.ts CHANGED
@@ -1,6 +1,4 @@
1
- import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-DGYV332J.js";
2
-
3
- //#region src/lite.d.ts
1
+ import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-CsXjZKyt.js";
4
2
  type Theme = 'system' | 'light' | 'dark';
5
3
  type ResolvedTheme = 'light' | 'dark';
6
4
  type Snapshot = {
@@ -8,36 +6,125 @@ type Snapshot = {
8
6
  resolvedTheme: ResolvedTheme;
9
7
  systemTheme: ResolvedTheme;
10
8
  };
11
- type Listener = (value: Snapshot) => void;
9
+ /** The state passed to listeners; see `getSnapshot`. */
10
+ export type ThemeSnapshot = Snapshot;
11
+ /**
12
+ * Receives the new state and, except in the inline script (first paint), the
13
+ * state before the change.
14
+ */
15
+ type Listener = (value: Snapshot, prev?: Snapshot) => void;
12
16
  type ThemeStoreOptions = {
13
17
  persisted?: Theme;
14
18
  storage?: StorageAdapterCreate | null;
15
19
  };
16
- declare class ThemeStore {
17
- #private;
18
- constructor({
19
- persisted,
20
- storage
21
- }?: ThemeStoreOptions);
22
- getTheme: () => Theme;
23
- getResolvedTheme: () => ResolvedTheme;
24
- getSystemTheme: () => ResolvedTheme;
20
+ /**
21
+ * Creates a store for a single light / dark / system preference. It saves
22
+ * changes through `storage` (`localStorage` under the key `'resonare/lite'` by
23
+ * default; `null` disables saving), follows `prefers-color-scheme` while the
24
+ * preference is `system`, and notifies subscribers.
25
+ *
26
+ * Read state with `getSnapshot()` or `subscribe`.
27
+ *
28
+ * @example
29
+ * import { createThemeStore, localStorageAdapter } from 'resonare/lite'
30
+ *
31
+ * const store = createThemeStore({
32
+ * storage: localStorageAdapter({ key: 'my-app' }),
33
+ * })
34
+ *
35
+ * // In the browser: load the saved choice and follow other tabs.
36
+ * store.restore()
37
+ * store.sync()
38
+ *
39
+ * store.subscribe(({ resolvedTheme }) => {
40
+ * document.documentElement.dataset.theme = resolvedTheme
41
+ * })
42
+ *
43
+ * store.setTheme('dark')
44
+ */
45
+ export declare function createThemeStore({ persisted, storage: createStorage }?: ThemeStoreOptions): {
46
+ /**
47
+ * Current state:
48
+ *
49
+ * - `theme`: the selected preference (`'system'`, `'light'` or `'dark'`).
50
+ * - `resolvedTheme`: `'light'` or `'dark'`, with `system` resolved.
51
+ * - `systemTheme`: the OS preference, even when `system` isn't selected.
52
+ *
53
+ * Returns the same object until the next change.
54
+ */
25
55
  getSnapshot: () => Snapshot;
26
- setTheme: (theme: Theme | ((current: Theme) => Theme)) => void;
56
+ /**
57
+ * The state as rendered on the server: `persisted` (or `system`), with the
58
+ * OS preference taken as `light`. It never changes, so hydration can match
59
+ * the server HTML even after `restore()`.
60
+ */
61
+ getServerSnapshot: () => Snapshot;
62
+ /**
63
+ * Sets the preference, saves it to storage, and notifies subscribers.
64
+ *
65
+ * @example
66
+ * store.setTheme('dark')
67
+ * store.setTheme((current) => (current === 'dark' ? 'light' : 'dark'))
68
+ */
69
+ setTheme: (next: Theme | ((current: Theme) => Theme)) => void;
70
+ /**
71
+ * Loads the saved preference from storage. Does nothing when nothing is
72
+ * saved. Call it in the browser, e.g. after hydration.
73
+ */
27
74
  restore: () => void;
75
+ /**
76
+ * Calls `callback` with the new state (see `getSnapshot`) and the state
77
+ * before it after every change, including OS preference changes. Returns
78
+ * an unsubscribe function.
79
+ */
28
80
  subscribe: (callback: Listener) => (() => void);
81
+ /**
82
+ * Applies changes saved by other tabs (if the storage adapter supports
83
+ * it); when another tab clears the saved value, resets to `system`.
84
+ * Returns a function that stops syncing, or `undefined` when the adapter
85
+ * can't sync.
86
+ */
29
87
  sync: () => (() => void) | undefined;
88
+ /**
89
+ * Removes all subscribers and stops listening to the OS preference and
90
+ * storage. The store doesn't update after this.
91
+ */
30
92
  destroy: () => void;
31
- }
32
- declare function createThemeStore(options?: ThemeStoreOptions): ThemeStore;
33
- type ThemeScriptParameter = {
93
+ };
94
+ export type ThemeStore = ReturnType<typeof createThemeStore>;
95
+ /** Options for `createInlineThemeScript`. */
96
+ export type ThemeScriptParameter = {
97
+ /** The store's `localStorage` key; defaults to `'resonare/lite'`. */
34
98
  key?: string;
99
+ /**
100
+ * Applies the state to the page; receives the same value as `subscribe`.
101
+ * It is copied into the script as source code, so it can't use variables
102
+ * from outside the function.
103
+ */
35
104
  handler: Listener;
36
105
  };
37
- declare function createInlineThemeScript({
38
- key,
39
- handler
40
- }: ThemeScriptParameter): string;
41
- //#endregion
42
- export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, ThemeScriptParameter, type ThemeStore, createInlineThemeScript, createThemeStore, localStorageAdapter, memoryStorageAdapter };
106
+ /**
107
+ * Returns the source of a small script that reads the saved preference from
108
+ * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in
109
+ * the `<head>` so the page has the right theme before first paint.
110
+ *
111
+ * Use the same handler with `store.subscribe` to keep the page updated after
112
+ * that.
113
+ *
114
+ * @example
115
+ * import { createInlineThemeScript, createThemeStore } from 'resonare/lite'
116
+ *
117
+ * const handler = ({ resolvedTheme }) => {
118
+ * document.documentElement.dataset.theme = resolvedTheme
119
+ * }
120
+ *
121
+ * const themeScript = createInlineThemeScript({ key: 'my-app', handler })
122
+ * // In <head>:
123
+ * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />
124
+ *
125
+ * const store = createThemeStore()
126
+ * store.subscribe(handler)
127
+ */
128
+ export declare function createInlineThemeScript({ key, handler }: ThemeScriptParameter): string;
129
+ export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, localStorageAdapter, memoryStorageAdapter };
43
130
  //# sourceMappingURL=lite.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lite.d.ts","names":[],"sources":["../src/lite.ts"],"mappings":";;;KASK,KAAA;AAAA,KAEA,aAAA;AAAA,KAEA,QAAA;EACJ,KAAA,EAAO,KAAA;EACP,aAAA,EAAe,aAAA;EACf,WAAA,EAAa,aAAA;AAAA;AAAA,KAGT,QAAA,IAAY,KAAe,EAAR,QAAQ;AAAA,KAE3B,iBAAA;EACJ,SAAA,GAAY,KAAA;EACZ,OAAA,GAAU,oBAAoB;AAAA;AAAA,cAGzB,UAAA;EAAA;;IAcJ,SAAA;IACA;EAAA,IACE,iBAAA;EAWH,QAAA,QAAe,KAAA;EAIf,gBAAA,QAAuB,aAAA;EAIvB,cAAA,QAAqB,aAAA;EAIrB,WAAA,QAAkB,QAAA;EAIlB,QAAA,GAAY,KAAA,EAAO,KAAA,KAAU,OAAA,EAAS,KAAA,KAAU,KAAA;EAWhD,OAAA;EAIA,SAAA,GAAa,QAAA,EAAU,QAAA;EAQvB,IAAA;EAQA,OAAA;AAAA;AAAA,iBAyCe,gBAAA,CAAiB,OAAA,GAAS,iBAAA,GAAyB,UAAU;AAAA,KAcjE,oBAAA;EACX,GAAA;EACA,OAAA,EAAS,QAAQ;AAAA;AAAA,iBAGF,uBAAA;EACf,GAAA;EACA;AAAA,GACE,oBAAA"}
1
+ {"version":3,"file":"lite.d.ts","names":[],"sources":["../src/lite.ts"],"mappings":";KAKK;KAEA;KAEA;EACH,OAAO;EACP,eAAe;EACf,aAAa;;;YAIH,gBAAgB;;;;;KAMvB,YAAY,OAAO,UAAU,OAAO;KAEpC;EACH,YAAY;EACZ,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA4BI,mBACd,WACA,SAAS,kBACR;;;;;;;;;;EAoEC,mBAAiB;;;;;;EASjB,yBAAuB;;;;;;;;EAWvB,WAAQ,MAAS,UAAU,SAAS,UAAU;;;;;EAY9C;;;;;;EAaA,YAAS,UAAa;;;;;;;EActB;;;;;EAUA;;YAQQ,aAAa,kBAAkB;;YAoB/B;;EAEV;;;;;;EAMA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;wBAyBK,0BACd,KACA,WACC"}
package/dist/lite.js CHANGED
@@ -1,2 +1,2 @@
1
- import{i as e,n as t,t as n}from"./storage-B5xjLRee.js";var r=class{#e;#t;#n;#r;#i=new Set;#a=new AbortController;constructor({persisted:t,storage:r=n({key:e})}={}){this.#e=t??`system`,this.#n=r?.({abortController:this.#a})??null,this.#t=this.#o()}getTheme=()=>this.#e;getResolvedTheme=()=>this.#e===`system`?this.#c():this.#e;getSystemTheme=()=>this.#c();getSnapshot=()=>this.#t;setTheme=e=>{this.#s(typeof e==`function`?e(this.#e):e),this.#n&&(this.#n.set(this.#e),this.#n.broadcast?.(this.#e))};restore=()=>{this.#s(this.#n?.get()??`system`)};subscribe=e=>(this.#i.add(e),()=>{this.#i.delete(e)});sync=()=>{if(this.#n?.watch)return this.#n.watch(e=>{this.#s(e??`system`)})};destroy=()=>{this.#i.clear(),this.#a.abort()};#o=()=>({theme:this.#e,resolvedTheme:this.getResolvedTheme(),systemTheme:this.getSystemTheme()});#s=e=>{this.#e=e,this.#t=this.#o();for(let e of this.#i)e(this.#t)};#c=()=>typeof matchMedia>`u`?`light`:(this.#r||(this.#r=window.matchMedia(`(prefers-color-scheme: dark)`),this.#r.addEventListener(`change`,()=>{this.#s(this.#e)},{signal:this.#a.signal})),this.#r.matches?`dark`:`light`)};function i(e={}){return new r(e)}const a=(e,t)=>{let n=localStorage.getItem(e)??`system`,r=matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;t({theme:n,resolvedTheme:n===`system`?r:n,systemTheme:r})};function o({key:t=e,handler:n}){return`(${a})('${t}',${n})`}export{o as createInlineThemeScript,i as createThemeStore,n as localStorageAdapter,t as memoryStorageAdapter};
1
+ import{i as e,n as t,r as n}from"./utils-CWI4hy3w.js";import{n as r,t as i}from"./storage-fOH2xeQ1.js";function a({persisted:e,storage:n=i({key:t})}={}){let r=e??`system`,a,o=/* @__PURE__ */ new Set,s=new AbortController,c=n?.({abortController:s}),l=e=>e||typeof matchMedia>`u`?`light`:(a||(a=matchMedia(`(prefers-color-scheme: dark)`),a.addEventListener(`change`,()=>{p(r)},s)),a.matches?`dark`:`light`),u=e=>{let t=l(e);return{theme:r,resolvedTheme:r===`system`?t:r,systemTheme:t}},d=u(!0),f=u(),p=e=>{r=e;let t=f;f=u();for(let e of o)e(f,t)};return{getSnapshot:()=>f,getServerSnapshot:()=>d,setTheme:e=>{p(typeof e==`function`?e(r):e),c?.set(r),c?.broadcast?.(r)},restore:()=>{let e=c?.get();e&&p(e)},subscribe:e=>(o.add(e),()=>{o.delete(e)}),sync:()=>c?.watch?.(e=>{p(e??`system`)}),destroy:()=>{o.clear(),s.abort()}}}const o=(e,t)=>{let n=`system`;try{n=localStorage.getItem(e)??n}catch{}let r=matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;t({theme:n,resolvedTheme:n===`system`?r:n,systemTheme:r})};function s({key:r=t,handler:i}){return`(${o})(${e(r)},${n(i)})`}export{s as createInlineThemeScript,a as createThemeStore,i as localStorageAdapter,r as memoryStorageAdapter};
2
2
  //# sourceMappingURL=lite.js.map
package/dist/lite.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lite.js","names":["DEFAULT_LITE_KEY","localStorageAdapter","StorageAdapter","StorageAdapterCreate","Theme","ResolvedTheme","Snapshot","theme","resolvedTheme","systemTheme","Listener","value","ThemeStoreOptions","persisted","storage","ThemeStore","snapshot","mediaQuery","MediaQueryList","listeners","Set","abortController","AbortController","constructor","key","createSnapshot","getTheme","getResolvedTheme","resolveSystemTheme","getSystemTheme","getSnapshot","setTheme","current","setThemeAndNotify","set","broadcast","restore","get","subscribe","callback","add","delete","sync","watch","destroy","clear","abort","#createSnapshot","#setThemeAndNotify","listener","#resolveSystemTheme","matchMedia","window","addEventListener","signal","matches","createThemeStore","options","restoreScript","handler","localStorage","getItem","ThemeScriptParameter","createInlineThemeScript"],"sources":["../src/lite.ts"],"sourcesContent":["import { DEFAULT_LITE_KEY } from './constants'\nimport {\n\tlocalStorageAdapter,\n\ttype StorageAdapter,\n\ttype StorageAdapterCreate,\n} from './storage'\n\nexport * from './storage'\n\ntype Theme = 'system' | 'light' | 'dark'\n\ntype ResolvedTheme = 'light' | 'dark'\n\ntype Snapshot = {\n\ttheme: Theme\n\tresolvedTheme: ResolvedTheme\n\tsystemTheme: ResolvedTheme\n}\n\ntype Listener = (value: Snapshot) => void\n\ntype ThemeStoreOptions = {\n\tpersisted?: Theme\n\tstorage?: StorageAdapterCreate | null\n}\n\nclass ThemeStore {\n\t#theme: Theme\n\n\t#snapshot: Snapshot\n\n\t#storage: StorageAdapter | null\n\n\t#mediaQuery: MediaQueryList | undefined\n\n\t#listeners = new Set<Listener>()\n\n\t#abortController = new AbortController()\n\n\tconstructor({\n\t\tpersisted,\n\t\tstorage = localStorageAdapter({ key: DEFAULT_LITE_KEY }),\n\t}: ThemeStoreOptions = {}) {\n\t\tthis.#theme = persisted ?? 'system'\n\n\t\tthis.#storage =\n\t\t\tstorage?.({\n\t\t\t\tabortController: this.#abortController,\n\t\t\t}) ?? null\n\n\t\tthis.#snapshot = this.#createSnapshot()\n\t}\n\n\tgetTheme = (): Theme => {\n\t\treturn this.#theme\n\t}\n\n\tgetResolvedTheme = (): ResolvedTheme => {\n\t\treturn this.#theme === 'system' ? this.#resolveSystemTheme() : this.#theme\n\t}\n\n\tgetSystemTheme = (): ResolvedTheme => {\n\t\treturn this.#resolveSystemTheme()\n\t}\n\n\tgetSnapshot = (): Snapshot => {\n\t\treturn this.#snapshot\n\t}\n\n\tsetTheme = (theme: Theme | ((current: Theme) => Theme)): void => {\n\t\tthis.#setThemeAndNotify(\n\t\t\ttypeof theme === 'function' ? theme(this.#theme) : theme,\n\t\t)\n\n\t\tif (this.#storage) {\n\t\t\tthis.#storage.set(this.#theme)\n\t\t\tthis.#storage.broadcast?.(this.#theme)\n\t\t}\n\t}\n\n\trestore = (): void => {\n\t\tthis.#setThemeAndNotify((this.#storage?.get() ?? 'system') as Theme)\n\t}\n\n\tsubscribe = (callback: Listener): (() => void) => {\n\t\tthis.#listeners.add(callback)\n\n\t\treturn () => {\n\t\t\tthis.#listeners.delete(callback)\n\t\t}\n\t}\n\n\tsync = (): (() => void) | undefined => {\n\t\tif (!this.#storage?.watch) return\n\n\t\treturn this.#storage.watch((theme) => {\n\t\t\tthis.#setThemeAndNotify((theme ?? 'system') as Theme)\n\t\t})\n\t}\n\n\tdestroy = (): void => {\n\t\tthis.#listeners.clear()\n\t\tthis.#abortController.abort()\n\t}\n\n\t#createSnapshot = (): Snapshot => ({\n\t\ttheme: this.#theme,\n\t\tresolvedTheme: this.getResolvedTheme(),\n\t\tsystemTheme: this.getSystemTheme(),\n\t})\n\n\t#setThemeAndNotify = (theme: Theme): void => {\n\t\tthis.#theme = theme\n\t\tthis.#snapshot = this.#createSnapshot()\n\n\t\tfor (const listener of this.#listeners) {\n\t\t\tlistener(this.#snapshot)\n\t\t}\n\t}\n\n\t#resolveSystemTheme = (): ResolvedTheme => {\n\t\tif (typeof matchMedia === 'undefined') return 'light'\n\n\t\tif (!this.#mediaQuery) {\n\t\t\tthis.#mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')\n\n\t\t\tthis.#mediaQuery.addEventListener(\n\t\t\t\t'change',\n\t\t\t\t() => {\n\t\t\t\t\tthis.#setThemeAndNotify(this.#theme)\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.#mediaQuery.matches ? 'dark' : 'light'\n\t}\n}\n\nexport type { ThemeStore }\n\nexport function createThemeStore(options: ThemeStoreOptions = {}): ThemeStore {\n\treturn new ThemeStore(options)\n}\n\nconst restoreScript = (key: string, handler: Listener) => {\n\tconst theme = (localStorage.getItem(key) ?? 'system') as Theme\n\tconst systemTheme = matchMedia('(prefers-color-scheme: dark)').matches\n\t\t? 'dark'\n\t\t: 'light'\n\tconst resolvedTheme = theme === 'system' ? systemTheme : theme\n\n\thandler({ theme, resolvedTheme, systemTheme })\n}\n\nexport type ThemeScriptParameter = {\n\tkey?: string\n\thandler: Listener\n}\n\nexport function createInlineThemeScript({\n\tkey = DEFAULT_LITE_KEY,\n\thandler,\n}: ThemeScriptParameter) {\n\treturn `(${restoreScript})('${key}',${handler})`\n}\n"],"mappings":"wDA0BA,IAAMe,EAAN,KAAiB,CAChB,GAEA,GAEA,GAEA,GAEA,GAAa,IAAIK,IAEjB,GAAmB,IAAIE,gBAEvBC,YAAY,CACXV,YACAC,UAAUb,EAAoB,CAAEuB,IAAKxB,CAAiB,CAAC,GACjC,CAAC,EAAG,CAC1B,KAAK,GAASa,GAAa,SAE3B,KAAK,GACJC,IAAU,CACTO,gBAAiB,KAAK,EACvB,CAAC,GAAK,KAEP,KAAK,GAAY,KAAK,GAAgB,CACvC,CAEAK,aACQ,KAAK,GAGbC,qBACQ,KAAK,KAAW,SAAW,KAAK,GAAoB,EAAI,KAAK,GAGrEE,mBACQ,KAAK,GAAoB,EAGjCC,gBACQ,KAAK,GAGbC,SAAYxB,GAAqD,CAChE,KAAK,GACJ,OAAOA,GAAU,WAAaA,EAAM,KAAK,EAAM,EAAIA,CACpD,EAEI,KAAK,KACR,KAAK,GAAS2B,IAAI,KAAK,EAAM,EAC7B,KAAK,GAASC,YAAY,KAAK,EAAM,EAEvC,EAEAC,YAAsB,CACrB,KAAK,GAAoB,KAAK,IAAUC,IAAI,GAAK,QAAkB,CACpE,EAEAC,UAAaC,IACZ,KAAK,GAAWC,IAAID,CAAQ,MAEf,CACZ,KAAK,GAAWE,OAAOF,CAAQ,CAChC,GAGDG,SAAuC,CACjC,QAAK,IAAUC,MAEpB,OAAO,KAAK,GAASA,MAAOpC,GAAU,CACrC,KAAK,GAAoBA,GAAS,QAAkB,CACrD,CAAC,CACF,EAEAqC,YAAsB,CACrB,KAAK,GAAWC,MAAM,EACtB,KAAK,GAAiBC,MAAM,CAC7B,EAEA,QAAmC,CAClCvC,MAAO,KAAK,GACZC,cAAe,KAAKmB,iBAAiB,EACrClB,YAAa,KAAKoB,eAAe,CAClC,GAEA,GAAsBtB,GAAuB,CAC5C,KAAK,GAASA,EACd,KAAK,GAAY,KAAK,GAAgB,EAEtC,IAAK,IAAM0C,KAAY,KAAK,GAC3BA,EAAS,KAAK,EAAS,CAEzB,EAEA,OACK,OAAOE,WAAe,IAAoB,SAEzC,KAAK,KACT,KAAK,GAAcC,OAAOD,WAAW,8BAA8B,EAEnE,KAAK,GAAYE,iBAChB,aACM,CACL,KAAK,GAAmB,KAAK,EAAM,CACpC,EACA,CAAEC,OAAQ,KAAK,GAAiBA,MAAO,CACxC,GAGM,KAAK,GAAYC,QAAU,OAAS,QAE7C,EAIA,SAAgBC,EAAiBC,EAA6B,CAAC,EAAe,CAC7E,OAAO,IAAI1C,EAAW0C,CAAO,CAC9B,CAEA,MAAMC,GAAiBlC,EAAamC,IAAsB,CACzD,IAAMpD,EAASqD,aAAaC,QAAQrC,CAAG,GAAK,SACtCf,EAAc0C,WAAW,8BAA8B,CAAC,CAACI,QAC5D,OACA,QAGHI,EAAQ,CAAEpD,QAAOC,cAFKD,IAAU,SAAWE,EAAcF,EAEzBE,aAAY,CAAC,CAC9C,EAOA,SAAgBsD,EAAwB,CACvCvC,MAAMxB,EACN2D,WACwB,CACxB,MAAO,IAAID,EAAa,KAAMlC,EAAG,IAAKmC,EAAO,EAC9C"}
1
+ {"version":3,"file":"lite.js","names":["toScriptJson","DEFAULT_LITE_KEY","toScriptFunction","memoryStorageAdapter","localStorageAdapter","createThemeStore","createStorage","theme","persisted","mediaQuery","listeners","abortController","storage","resolveSystemTheme","server","setThemeAndNotify","createSnapshot","systemTheme","serverSnapshot","snapshot","next","prev","listener","stored","callback","restoreScript","key","handler","createInlineThemeScript"],"sources":["../src/lite.ts"],"sourcesContent":["import { type StorageAdapterCreate, localStorageAdapter } from './storage'\nimport { DEFAULT_LITE_KEY, toScriptFunction, toScriptJson } from './utils'\n\nexport * from './storage'\n\ntype Theme = 'system' | 'light' | 'dark'\n\ntype ResolvedTheme = 'light' | 'dark'\n\ntype Snapshot = {\n theme: Theme\n resolvedTheme: ResolvedTheme\n systemTheme: ResolvedTheme\n}\n\n/** The state passed to listeners; see `getSnapshot`. */\nexport type ThemeSnapshot = Snapshot\n\n/**\n * Receives the new state and, except in the inline script (first paint), the\n * state before the change.\n */\ntype Listener = (value: Snapshot, prev?: Snapshot) => void\n\ntype ThemeStoreOptions = {\n persisted?: Theme\n storage?: StorageAdapterCreate | null\n}\n\n/**\n * Creates a store for a single light / dark / system preference. It saves\n * changes through `storage` (`localStorage` under the key `'resonare/lite'` by\n * default; `null` disables saving), follows `prefers-color-scheme` while the\n * preference is `system`, and notifies subscribers.\n *\n * Read state with `getSnapshot()` or `subscribe`.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare/lite'\n *\n * const store = createThemeStore({\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(({ resolvedTheme }) => {\n * document.documentElement.dataset.theme = resolvedTheme\n * })\n *\n * store.setTheme('dark')\n */\nexport function createThemeStore({\n persisted,\n storage: createStorage = localStorageAdapter({ key: DEFAULT_LITE_KEY }),\n}: ThemeStoreOptions = {}) {\n let theme: Theme = persisted ?? 'system'\n\n let mediaQuery: MediaQueryList | undefined\n\n const listeners = new Set<Listener>()\n\n const abortController = new AbortController()\n\n const storage = createStorage?.({ abortController })\n\n // No media support (e.g. on the server): `system` is `light`.\n const resolveSystemTheme = (server?: boolean): ResolvedTheme => {\n if (server || typeof matchMedia === 'undefined') {\n return 'light'\n }\n\n if (!mediaQuery) {\n mediaQuery = matchMedia('(prefers-color-scheme: dark)')\n\n mediaQuery.addEventListener(\n 'change',\n () => {\n setThemeAndNotify(theme)\n },\n abortController\n )\n }\n\n return mediaQuery.matches ? 'dark' : 'light'\n }\n\n const createSnapshot = (server?: boolean): Snapshot => {\n const systemTheme = resolveSystemTheme(server)\n\n return {\n theme,\n resolvedTheme: theme === 'system' ? systemTheme : theme,\n systemTheme,\n }\n }\n\n const serverSnapshot = createSnapshot(true)\n\n let snapshot = createSnapshot()\n\n const setThemeAndNotify = (next: Theme): void => {\n theme = next\n\n const prev = snapshot\n\n snapshot = createSnapshot()\n\n for (const listener of listeners) {\n listener(snapshot, prev)\n }\n }\n\n return {\n /**\n * Current state:\n *\n * - `theme`: the selected preference (`'system'`, `'light'` or `'dark'`).\n * - `resolvedTheme`: `'light'` or `'dark'`, with `system` resolved.\n * - `systemTheme`: the OS preference, even when `system` isn't selected.\n *\n * Returns the same object until the next change.\n */\n getSnapshot: (): Snapshot => {\n return snapshot\n },\n\n /**\n * The state as rendered on the server: `persisted` (or `system`), with the\n * OS preference taken as `light`. It never changes, so hydration can match\n * the server HTML even after `restore()`.\n */\n getServerSnapshot: (): Snapshot => {\n return serverSnapshot\n },\n\n /**\n * Sets the preference, saves it to storage, and notifies subscribers.\n *\n * @example\n * store.setTheme('dark')\n * store.setTheme((current) => (current === 'dark' ? 'light' : 'dark'))\n */\n setTheme: (next: Theme | ((current: Theme) => Theme)): void => {\n setThemeAndNotify(typeof next === 'function' ? next(theme) : next)\n\n storage?.set(theme)\n\n storage?.broadcast?.(theme)\n },\n\n /**\n * Loads the saved preference from storage. Does nothing when nothing is\n * saved. Call it in the browser, e.g. after hydration.\n */\n restore: (): void => {\n const stored = storage?.get() as Theme | null | undefined\n\n if (stored) {\n setThemeAndNotify(stored)\n }\n },\n\n /**\n * Calls `callback` with the new state (see `getSnapshot`) and the state\n * before it after every change, including OS preference changes. Returns\n * an unsubscribe function.\n */\n subscribe: (callback: Listener): (() => 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 value, resets to `system`.\n * Returns a function that stops syncing, or `undefined` when the adapter\n * can't sync.\n */\n sync: (): (() => void) | undefined => {\n return storage?.watch?.((stored) => {\n setThemeAndNotify((stored ?? 'system') as Theme)\n })\n },\n\n /**\n * Removes all subscribers and stops listening to the OS preference 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 = ReturnType<typeof createThemeStore>\n\nconst restoreScript = (key: string, handler: Listener) => {\n let theme: Theme = 'system'\n\n // Blocked storage must not stop the handler from running.\n try {\n theme = (localStorage.getItem(key) ?? theme) as Theme\n } catch {}\n\n const systemTheme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n\n const resolvedTheme = theme === 'system' ? systemTheme : theme\n\n handler({ theme, resolvedTheme, systemTheme })\n}\n\n/** Options for `createInlineThemeScript`. */\nexport type ThemeScriptParameter = {\n /** The store's `localStorage` key; defaults to `'resonare/lite'`. */\n key?: string\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\n}\n\n/**\n * Returns the source of a small script that reads the saved preference 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.\n *\n * Use the same handler with `store.subscribe` to keep the page updated after\n * that.\n *\n * @example\n * import { createInlineThemeScript, createThemeStore } from 'resonare/lite'\n *\n * const handler = ({ resolvedTheme }) => {\n * document.documentElement.dataset.theme = resolvedTheme\n * }\n *\n * const themeScript = createInlineThemeScript({ key: 'my-app', handler })\n * // In <head>:\n * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />\n *\n * const store = createThemeStore()\n * store.subscribe(handler)\n */\nexport function createInlineThemeScript({\n key = DEFAULT_LITE_KEY,\n handler,\n}: ThemeScriptParameter) {\n return `(${restoreScript})(${toScriptJson(key)},${toScriptFunction(handler)})`\n}\n"],"mappings":"A,uGAsDA,SAAgBK,EAAiB,CAC/B,YACA,QAASC,EAAgBF,EAAoB,CAAE,IAAKH,CAAiB,CAAC,GACjD,CAAC,EAAG,CACzB,IAAIM,EAAeC,GAAa,SAE5BC,EAEEC,kBAAY,IAAI,IAEhBC,EAAkB,IAAI,gBAEtBC,EAAUN,IAAgB,CAAE,iBAAgB,CAAC,EAG7CO,EAAsB,GACtBC,GAAU,OAAO,WAAe,IAC3B,SAGJL,IACH,EAAa,WAAW,8BAA8B,EAEtDA,EAAW,iBACT,aACM,CACJM,EAAkBR,CAAK,CACzB,EACAI,CACF,GAGKF,EAAW,QAAU,OAAS,SAGjCO,EAAkB,GAA+B,CACrD,IAAMC,EAAcJ,EAAmBC,CAAM,EAE7C,MAAO,CACL,QACA,cAAeP,IAAU,SAAWU,EAAcV,EAClD,aACF,CACF,EAEMW,EAAiBF,EAAe,EAAI,EAEtCG,EAAWH,EAAe,EAExBD,EAAqB,GAAsB,CAC/C,EAAQK,EAER,IAAMC,EAAOF,EAEb,EAAWH,EAAe,EAE1B,IAAK,IAAMM,KAAYZ,EACrBY,EAASH,EAAUE,CAAI,CAE3B,EAEA,MAAO,CAUL,gBACSF,EAQT,sBACSD,EAUT,SAAW,GAAoD,CAC7DH,EAAkB,OAAOK,GAAS,WAAaA,EAAKb,CAAK,EAAIa,CAAI,EAEjER,GAAS,IAAIL,CAAK,EAElBK,GAAS,YAAYL,CAAK,CAC5B,EAMA,YAAqB,CACnB,IAAMgB,EAASX,GAAS,IAAI,EAExBW,GACFR,EAAkBQ,CAAM,CAE5B,EAOA,UAAY,IACVb,EAAU,IAAIc,CAAQ,MAET,CACXd,EAAU,OAAOc,CAAQ,CAC3B,GASF,SACSZ,GAAS,QAAS,GAAW,CAClCG,EAAmBQ,GAAU,QAAkB,CACjD,CAAC,EAOH,YAAqB,CACnBb,EAAU,MAAM,EAEhBC,EAAgB,MAAM,CACxB,CACF,CACF,CAIA,MAAMc,GAAiB,EAAa,IAAsB,CACxD,IAAIlB,EAAe,SAGnB,GAAI,CACF,EAAS,aAAa,QAAQmB,CAAG,GAAKnB,CACxC,MAAQ,CAAC,CAET,IAAMU,EAAc,WAAW,8BAA8B,CAAC,CAAC,QAC3D,OACA,QAIJU,EAAQ,CAAE,QAAO,cAFKpB,IAAU,SAAWU,EAAcV,EAEzB,aAAY,CAAC,CAC/C,EAoCA,SAAgBqB,EAAwB,CACtC,MAAM3B,EACN,WACuB,CACvB,MAAO,IAAIwB,EAAc,IAAIzB,EAAa0B,CAAG,EAAE,GAAGxB,EAAiByB,CAAO,EAAE,EAC9E,C"}
package/dist/react.d.ts CHANGED
@@ -1,37 +1,77 @@
1
1
  import { ThemeStore, ThemeStoreConfig, Themes } from "./index.js";
2
-
3
- //#region src/react.d.ts
4
2
  /**
5
- * Subscribes a React component to a theme store.
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
+ *
6
7
  * @example
7
- * ```tsx
8
- * export function ThemeToggle() {
9
- * const { themes, resolvedThemes, resolvedSystemThemes, setThemes } = useResonare(store)
8
+ * import { useResonare } from 'resonare/react'
9
+ *
10
+ * function ColorModeToggle() {
11
+ * const { themes, setThemes } = useResonare(store)
12
+ *
13
+ * const next = themes.colorMode === 'dark' ? 'light' : 'dark'
10
14
  *
11
- * // ...
12
- * }
13
- * ```
15
+ * return (
16
+ * <button
17
+ * onClick={() => {
18
+ * setThemes({ colorMode: next })
19
+ * }}
20
+ * >
21
+ * {themes.colorMode}
22
+ * </button>
23
+ * )
24
+ * }
14
25
  */
15
- declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>): {
26
+ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>): {
27
+ themes: Themes<T>;
28
+ resolvedThemes: Themes<T>;
29
+ resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
30
+ options: ReadonlyArray<infer U>;
31
+ } ? U extends {
32
+ media: ReadonlyArray<unknown>;
33
+ } ? K : never : never; }[keyof T]]: T[K] extends {
34
+ options: ReadonlyArray<infer U>;
35
+ } ? U extends string | number | boolean ? U : U extends {
36
+ value: string;
37
+ media?: readonly [string, string, string] | undefined;
38
+ } ? U extends {
39
+ media: ReadonlyArray<unknown>;
40
+ } ? never : U["value"] : never : never; };
16
41
  destroy: () => void;
17
42
  restore: () => void;
18
43
  setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
19
44
  subscribe: (callback: (value: {
20
45
  themes: Themes<T>;
21
46
  resolvedThemes: Themes<T>;
22
- resolvedSystemThemes: { [K_1 in { [K in keyof T]: T[K] extends {
47
+ resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
23
48
  options: ReadonlyArray<infer U>;
24
49
  } ? U extends {
25
50
  media: ReadonlyArray<unknown>;
26
- } ? K : never : never }[keyof T]]: T[K_1] extends {
51
+ } ? K : never : never; }[keyof T]]: T[K] extends {
27
52
  options: ReadonlyArray<infer U>;
28
53
  } ? U extends string | number | boolean ? U : U extends {
29
54
  value: string;
30
- media?: [string, string, string];
55
+ media?: readonly [string, string, string] | undefined;
56
+ } ? U extends {
57
+ media: ReadonlyArray<unknown>;
58
+ } ? never : U["value"] : never : never; };
59
+ }, prev?: {
60
+ themes: Themes<T>;
61
+ resolvedThemes: Themes<T>;
62
+ resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
63
+ options: ReadonlyArray<infer U>;
31
64
  } ? U extends {
32
- media: [string, string, string];
33
- } ? never : U["value"] : never : never };
34
- }) => void) => (() => void);
65
+ media: ReadonlyArray<unknown>;
66
+ } ? K : never : never; }[keyof T]]: T[K] extends {
67
+ options: ReadonlyArray<infer U>;
68
+ } ? U extends string | number | boolean ? U : U extends {
69
+ value: string;
70
+ media?: readonly [string, string, string] | undefined;
71
+ } ? U extends {
72
+ media: ReadonlyArray<unknown>;
73
+ } ? never : U["value"] : never : never; };
74
+ } | undefined) => void) => () => void;
35
75
  sync: () => (() => void) | undefined;
36
76
  toPersist: () => {
37
77
  themes: Partial<Themes<T>>;
@@ -39,40 +79,24 @@ declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>):
39
79
  [x: string]: [string, string];
40
80
  };
41
81
  };
42
- updateSystemOption: <K extends { [K_1 in keyof T]: T[K_1] extends {
82
+ updateSystemOption: <K extends { [K in keyof T]: T[K] extends {
43
83
  options: ReadonlyArray<infer U>;
44
84
  } ? U extends {
45
85
  media: ReadonlyArray<unknown>;
46
- } ? K_1 : never : never }[keyof T]>(themeKey: K, pair: [T[K] extends {
86
+ } ? K : never : never; }[keyof T]>(themeKey: K, pair: [T[K] extends {
47
87
  options: ReadonlyArray<infer U>;
48
88
  } ? U extends string | number | boolean ? U : U extends {
49
89
  value: string;
50
- media?: [string, string, string];
90
+ media?: readonly [string, string, string] | undefined;
51
91
  } ? U extends {
52
- media: [string, string, string];
92
+ media: ReadonlyArray<unknown>;
53
93
  } ? never : U["value"] : never : never, T[K] extends {
54
94
  options: ReadonlyArray<infer U>;
55
95
  } ? U extends string | number | boolean ? U : U extends {
56
96
  value: string;
57
- media?: [string, string, string];
58
- } ? U extends {
59
- media: [string, string, string];
60
- } ? never : U["value"] : never : never]) => void;
61
- themes: Themes<T>;
62
- resolvedThemes: Themes<T>;
63
- resolvedSystemThemes: { [K_1 in { [K in keyof T]: T[K] extends {
64
- options: ReadonlyArray<infer U>;
97
+ media?: readonly [string, string, string] | undefined;
65
98
  } ? U extends {
66
99
  media: ReadonlyArray<unknown>;
67
- } ? K : never : never }[keyof T]]: T[K_1] extends {
68
- options: ReadonlyArray<infer U>;
69
- } ? U extends string | number | boolean ? U : U extends {
70
- value: string;
71
- media?: [string, string, string];
72
- } ? U extends {
73
- media: [string, string, string];
74
- } ? never : U["value"] : never : never };
100
+ } ? never : U["value"] : never : never]) => void;
75
101
  };
76
- //#endregion
77
- export { useResonare };
78
102
  //# sourceMappingURL=react.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.ts","names":[],"sources":["../src/react.ts"],"mappings":";;;;;AAcA;;;;;;;;;iBAAgB,WAAA,WAAsB,gBAAA,EAAkB,KAAA,EAAO,UAAA,CAAW,CAAA"}
1
+ {"version":3,"file":"react.d.ts","names":["_$_0.Themes"],"sources":["../src/react.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;wBA4BgB,YAAY,UAAU,kBAAkB,OAAO,WAAW"}
package/dist/react.js CHANGED
@@ -1,2 +1,2 @@
1
- import{c as e}from"react-compiler-runtime";import*as t from"react";function n(n){let r=e(9),{destroy:i,getSnapshot:a,restore:o,setThemes:s,subscribe:c,sync:l,toPersist:u,updateSystemOption:d}=n,f=t.useSyncExternalStore(c,a,a),p;return r[0]!==i||r[1]!==o||r[2]!==s||r[3]!==f||r[4]!==c||r[5]!==l||r[6]!==u||r[7]!==d?(p={...f,destroy:i,restore:o,setThemes:s,subscribe:c,sync:l,toPersist:u,updateSystemOption:d},r[0]=i,r[1]=o,r[2]=s,r[3]=f,r[4]=c,r[5]=l,r[6]=u,r[7]=d,r[8]=p):p=r[8],p}export{n as useResonare};
1
+ import{c as e}from"react/compiler-runtime";import*as t from"react";function n(n){let r=e(9),{destroy:i,getServerSnapshot:a,getSnapshot:o,restore:s,setThemes:c,subscribe:l,sync:u,toPersist:d,updateSystemOption:f}=n,p=t.useSyncExternalStore(l,o,a),m;return r[0]!==i||r[1]!==s||r[2]!==c||r[3]!==p||r[4]!==l||r[5]!==u||r[6]!==d||r[7]!==f?(m={...p,destroy:i,restore:s,setThemes:c,subscribe:l,sync:u,toPersist:d,updateSystemOption:f},r[0]=i,r[1]=s,r[2]=c,r[3]=p,r[4]=l,r[5]=u,r[6]=d,r[7]=f,r[8]=m):m=r[8],m}export{n as useResonare};
2
2
  //# sourceMappingURL=react.js.map
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":["React","ThemeStore","ThemeStoreConfig","useResonare","store","$","_c","destroy","getSnapshot","restore","setThemes","subscribe","sync","toPersist","updateSystemOption","snapshot","useSyncExternalStore","t0"],"sources":["../src/react.ts"],"sourcesContent":["import * as React from 'react'\nimport type { ThemeStore, ThemeStoreConfig } from '.'\n\n/**\n * Subscribes a React component to a theme store.\n * @example\n * ```tsx\n * export function ThemeToggle() {\n * const { themes, resolvedThemes, resolvedSystemThemes, setThemes } = useResonare(store)\n *\n * // ...\n * }\n * ```\n */\nexport function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>) {\n\tconst {\n\t\tdestroy,\n\t\tgetSnapshot,\n\t\trestore,\n\t\tsetThemes,\n\t\tsubscribe,\n\t\tsync,\n\t\ttoPersist,\n\t\tupdateSystemOption,\n\t} = store\n\n\tconst snapshot = React.useSyncExternalStore(\n\t\tsubscribe,\n\t\tgetSnapshot,\n\t\tgetSnapshot,\n\t)\n\n\treturn {\n\t\t...snapshot,\n\t\tdestroy,\n\t\trestore,\n\t\tsetThemes,\n\t\tsubscribe,\n\t\tsync,\n\t\ttoPersist,\n\t\tupdateSystemOption,\n\t}\n}\n"],"mappings":"mEAcA,SAAOG,EAAAC,EAAA,CAAA,IAAAC,EAAAC,EAAA,CAAA,EACN,CAAAC,UAAAC,cAAAC,UAAAC,YAAAC,YAAAC,OAAAC,YAAAC,sBASIV,EAEJW,EAAiBf,EAAKgB,qBACrBL,EACAH,EACAA,CACD,EAACS,EAWA,OAXAZ,EAAA,KAAAE,GAAAF,EAAA,KAAAI,GAAAJ,EAAA,KAAAK,GAAAL,EAAA,KAAAU,GAAAV,EAAA,KAAAM,GAAAN,EAAA,KAAAO,GAAAP,EAAA,KAAAQ,GAAAR,EAAA,KAAAS,GAEMG,EAAA,CAAA,GACHF,EAAQR,UAAAE,UAAAC,YAAAC,YAAAC,OAAAC,YAAAC,oBAQZ,EAACT,EAAA,GAAAE,EAAAF,EAAA,GAAAI,EAAAJ,EAAA,GAAAK,EAAAL,EAAA,GAAAU,EAAAV,EAAA,GAAAM,EAAAN,EAAA,GAAAO,EAAAP,EAAA,GAAAQ,EAAAR,EAAA,GAAAS,EAAAT,EAAA,GAAAY,GAAAA,EAAAZ,EAAA,GATMY,CASN"}
1
+ {"version":3,"file":"react.js","names":["{\n ...snapshot,\n destroy,\n restore,\n setThemes,\n subscribe,\n sync,\n toPersist,\n updateSystemOption,\n }","_c","React","useResonare","$","c","store","snapshot","subscribe","getSnapshot","getServerSnapshot","t0","destroy","restore","setThemes","sync","toPersist","updateSystemOption"],"sources":["../src/react.ts"],"sourcesContent":["import * as React from 'react'\n\nimport type { ThemeStore, ThemeStoreConfig } from '.'\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 { useResonare } from 'resonare/react'\n *\n * function ColorModeToggle() {\n * const { themes, setThemes } = useResonare(store)\n *\n * const next = themes.colorMode === 'dark' ? 'light' : 'dark'\n *\n * return (\n * <button\n * onClick={() => {\n * setThemes({ colorMode: next })\n * }}\n * >\n * {themes.colorMode}\n * </button>\n * )\n * }\n */\nexport function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setThemes,\n subscribe,\n sync,\n toPersist,\n updateSystemOption,\n } = store\n\n const snapshot = React.useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n )\n\n return {\n ...snapshot,\n destroy,\n restore,\n setThemes,\n subscribe,\n sync,\n toPersist,\n updateSystemOption,\n }\n}\n"],"mappings":"A,mEA4BA,SAAgBG,EAAwC,EAAsB,C,WACtE,CACJ,UACA,oBACA,cACA,UACA,YACA,YACA,OACA,YACA,sBACEG,EAEEC,EAAWL,EAAM,qBACrBM,EACAC,EACAC,CACF,EAEOV,EAAP,OAEEI,EAAA,KAAAQ,GAAAR,EAAA,KACAS,GAAAT,EAAA,KACAU,GAAAV,EAAA,KAHGG,GAAAH,EAAA,KAIHI,GAAAJ,EAAA,KACAW,GAAAX,EAAA,KACAY,GAAAZ,EAAA,KACAa,GARK,EAAA,CACL,GAAGV,EACH,UACA,UACA,YACA,YACA,OACA,YACA,oBACF,EAPE,EAAA,GAAAK,EACA,EAAA,GAAAC,EACA,EAAA,GAAAC,EAHG,EAAA,GAAAP,EAIH,EAAA,GAAAC,EACA,EAAA,GAAAO,EACA,EAAA,GAAAC,EACA,EAAA,GAAAC,E,eARKjB,CAUT,C"}
@@ -0,0 +1,99 @@
1
+ import { ThemeStore, ThemeStoreConfig, Themes } from "./index.js";
2
+ /**
3
+ * Returns the store's state as signals (`themes()`, `resolvedThemes()`,
4
+ * `resolvedSystemThemes()`) and its methods. Call it inside a component (or
5
+ * `createRoot`); the subscription ends when that owner is cleaned up. Server
6
+ * rendering and hydration are handled automatically.
7
+ *
8
+ * @example
9
+ * import { useResonare } from 'resonare/solid'
10
+ *
11
+ * function ColorModeToggle() {
12
+ * const { themes, setThemes } = useResonare(store)
13
+ *
14
+ * const toggle = () => {
15
+ * const isDark = themes().colorMode === 'dark'
16
+ *
17
+ * setThemes({ colorMode: isDark ? 'light' : 'dark' })
18
+ * }
19
+ *
20
+ * return <button onClick={toggle}>{themes().colorMode}</button>
21
+ * }
22
+ */
23
+ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>): {
24
+ themes: () => Themes<T>;
25
+ resolvedThemes: () => Themes<T>;
26
+ resolvedSystemThemes: () => { [K in { [K in keyof T]: T[K] extends {
27
+ options: ReadonlyArray<infer U>;
28
+ } ? U extends {
29
+ media: ReadonlyArray<unknown>;
30
+ } ? K : never : never; }[keyof T]]: T[K] extends {
31
+ options: ReadonlyArray<infer U>;
32
+ } ? U extends string | number | boolean ? U : U extends {
33
+ value: string;
34
+ media?: readonly [string, string, string] | undefined;
35
+ } ? U extends {
36
+ media: ReadonlyArray<unknown>;
37
+ } ? never : U["value"] : never : never; };
38
+ destroy: () => void;
39
+ restore: () => void;
40
+ setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
41
+ subscribe: (callback: (value: {
42
+ themes: Themes<T>;
43
+ resolvedThemes: Themes<T>;
44
+ resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
45
+ options: ReadonlyArray<infer U>;
46
+ } ? U extends {
47
+ media: ReadonlyArray<unknown>;
48
+ } ? K : never : never; }[keyof T]]: T[K] extends {
49
+ options: ReadonlyArray<infer U>;
50
+ } ? U extends string | number | boolean ? U : U extends {
51
+ value: string;
52
+ media?: readonly [string, string, string] | undefined;
53
+ } ? U extends {
54
+ media: ReadonlyArray<unknown>;
55
+ } ? never : U["value"] : never : never; };
56
+ }, prev?: {
57
+ themes: Themes<T>;
58
+ resolvedThemes: Themes<T>;
59
+ resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
60
+ options: ReadonlyArray<infer U>;
61
+ } ? U extends {
62
+ media: ReadonlyArray<unknown>;
63
+ } ? K : never : never; }[keyof T]]: T[K] extends {
64
+ options: ReadonlyArray<infer U>;
65
+ } ? U extends string | number | boolean ? U : U extends {
66
+ value: string;
67
+ media?: readonly [string, string, string] | undefined;
68
+ } ? U extends {
69
+ media: ReadonlyArray<unknown>;
70
+ } ? never : U["value"] : never : never; };
71
+ } | undefined) => void) => () => void;
72
+ sync: () => (() => void) | undefined;
73
+ toPersist: () => {
74
+ themes: Partial<Themes<T>>;
75
+ systemOptions: {
76
+ [x: string]: [string, string];
77
+ };
78
+ };
79
+ updateSystemOption: <K extends { [K in keyof T]: T[K] extends {
80
+ options: ReadonlyArray<infer U>;
81
+ } ? U extends {
82
+ media: ReadonlyArray<unknown>;
83
+ } ? K : never : never; }[keyof T]>(themeKey: K, pair: [T[K] extends {
84
+ options: ReadonlyArray<infer U>;
85
+ } ? U extends string | number | boolean ? U : U extends {
86
+ value: string;
87
+ media?: readonly [string, string, string] | undefined;
88
+ } ? U extends {
89
+ media: ReadonlyArray<unknown>;
90
+ } ? never : U["value"] : never : never, T[K] extends {
91
+ options: ReadonlyArray<infer U>;
92
+ } ? U extends string | number | boolean ? U : U extends {
93
+ value: string;
94
+ media?: readonly [string, string, string] | undefined;
95
+ } ? U extends {
96
+ media: ReadonlyArray<unknown>;
97
+ } ? never : U["value"] : never : never]) => void;
98
+ };
99
+ //# sourceMappingURL=solid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solid.d.ts","names":["_$_0.Themes"],"sources":["../src/solid.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;wBAyBgB,YAAY,UAAU,kBAAkB,OAAO,WAAW"}
package/dist/solid.js ADDED
@@ -0,0 +1,2 @@
1
+ import{createSignal as e,onCleanup as t,onMount as n,sharedConfig as r}from"solid-js";function i(i){let{destroy:a,getServerSnapshot:o,getSnapshot:s,restore:c,setThemes:l,subscribe:u,sync:d,toPersist:f,updateSystemOption:p}=i,m=!!r.context,[h,g]=e(m?o():s()),_=u(e=>{g(()=>e)});return t(_),m&&n(()=>{g(()=>s())}),{themes:()=>h().themes,resolvedThemes:()=>h().resolvedThemes,resolvedSystemThemes:()=>h().resolvedSystemThemes,destroy:a,restore:c,setThemes:l,subscribe:u,sync:d,toPersist:f,updateSystemOption:p}}export{i as useResonare};
2
+ //# sourceMappingURL=solid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solid.js","names":["useResonare","store","hydrating","sharedConfig","snapshot","setSnapshot","createSignal","getServerSnapshot","getSnapshot","unsubscribe","subscribe","value","onCleanup","onMount"],"sources":["../src/solid.ts"],"sourcesContent":["import { createSignal, onCleanup, onMount, sharedConfig } from 'solid-js'\n\nimport type { ThemeStore, ThemeStoreConfig } from '.'\n\n/**\n * Returns the store's state as signals (`themes()`, `resolvedThemes()`,\n * `resolvedSystemThemes()`) and its methods. Call it inside a component (or\n * `createRoot`); the subscription ends when that owner is cleaned up. Server\n * rendering and hydration are handled automatically.\n *\n * @example\n * import { useResonare } from 'resonare/solid'\n *\n * function ColorModeToggle() {\n * const { themes, setThemes } = useResonare(store)\n *\n * const toggle = () => {\n * const isDark = themes().colorMode === 'dark'\n *\n * setThemes({ colorMode: isDark ? 'light' : 'dark' })\n * }\n *\n * return <button onClick={toggle}>{themes().colorMode}</button>\n * }\n */\nexport function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setThemes,\n subscribe,\n sync,\n toPersist,\n updateSystemOption,\n } = store\n\n // Match the server HTML while rendering on the server or hydrating, then\n // switch to the live snapshot once mounted.\n const hydrating = !!sharedConfig.context\n\n const [snapshot, setSnapshot] = createSignal(\n hydrating ? getServerSnapshot() : getSnapshot()\n )\n\n const unsubscribe = subscribe((value) => {\n setSnapshot(() => {\n return value\n })\n })\n\n onCleanup(unsubscribe)\n\n if (hydrating) {\n onMount(() => {\n setSnapshot(() => {\n return getSnapshot()\n })\n })\n }\n\n return {\n themes: () => {\n return snapshot().themes\n },\n resolvedThemes: () => {\n return snapshot().resolvedThemes\n },\n resolvedSystemThemes: () => {\n return snapshot().resolvedSystemThemes\n },\n destroy,\n restore,\n setThemes,\n subscribe,\n sync,\n toPersist,\n updateSystemOption,\n }\n}\n"],"mappings":"A,sFAyBA,SAAgBA,EAAwC,EAAsB,CAC5E,GAAM,CACJ,UACA,oBACA,cACA,UACA,YACA,YACA,OACA,YACA,sBACEC,EAIEC,EAAY,CAAC,CAACC,EAAa,QAE3B,CAACC,EAAUC,GAAeC,EAC9BJ,EAAYK,EAAkB,EAAIC,EAAY,CAChD,EAEMC,EAAcC,EAAW,GAAU,CACvCL,MACSM,CACR,CACH,CAAC,EAYD,OAVAC,EAAUH,CAAW,EAEjBP,GACFW,MAAc,CACZR,MACSG,EAAY,CACpB,CACH,CAAC,EAGI,CACL,WACSJ,EAAS,CAAC,CAAC,OAEpB,mBACSA,EAAS,CAAC,CAAC,eAEpB,yBACSA,EAAS,CAAC,CAAC,qBAEpB,UACA,UACA,YACA,YACA,OACA,YACA,oBACF,CACF,C"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Where a store saves its state. Values are strings: the full store saves
3
+ * JSON, the lite store saves the theme name.
4
+ */
5
+ type StorageAdapter = {
6
+ /** Returns the saved value, or `null` when nothing is saved. */
7
+ get: () => string | null;
8
+ /** Saves a value. */
9
+ set: (value: string) => void;
10
+ /** Optional: tells other tabs about a value just saved with `set`. */
11
+ broadcast?: (value: string) => void;
12
+ /**
13
+ * Optional: calls `cb` when another tab saves a value (`null` when it clears
14
+ * it). Returns a function that stops watching. Used by `store.sync()`.
15
+ */
16
+ watch?: (cb: (value: string | null) => void) => () => void;
17
+ };
18
+ /**
19
+ * What a store's `storage` option takes: a function that creates the adapter.
20
+ * `abortController` is aborted when the store is destroyed; use it to remove
21
+ * listeners.
22
+ */
23
+ type StorageAdapterCreate = ({ abortController }: {
24
+ abortController: AbortController;
25
+ }) => StorageAdapter;
26
+ /**
27
+ * Shape of the built-in adapters such as `localStorageAdapter`: takes options
28
+ * (like the key) and returns a {@link StorageAdapterCreate}.
29
+ */
30
+ type StorageAdapterCreator<Options> = (options: Options) => StorageAdapterCreate;
31
+ /**
32
+ * Saves the store in `localStorage` (default) or `sessionStorage` under `key`,
33
+ * and supports `store.sync()` across tabs. If storage is blocked or full,
34
+ * reads return nothing and writes are skipped.
35
+ *
36
+ * @example
37
+ * import { createThemeStore, localStorageAdapter } from 'resonare'
38
+ *
39
+ * const store = createThemeStore(
40
+ * { colorMode: { options: ['light', 'dark'] } },
41
+ * { storage: localStorageAdapter({ key: 'app', type: 'localStorage' }) }
42
+ * )
43
+ */
44
+ declare const localStorageAdapter: StorageAdapterCreator<{
45
+ key: string;
46
+ type?: 'localStorage' | 'sessionStorage';
47
+ }>;
48
+ /**
49
+ * Keeps the store in memory only, and supports `store.sync()` across tabs
50
+ * through `BroadcastChannel`. Use it when you save the state yourself (e.g.
51
+ * `toPersist()` to a database) and don't want it in `localStorage`.
52
+ *
53
+ * @example
54
+ * import { createThemeStore, memoryStorageAdapter } from 'resonare'
55
+ *
56
+ * const store = createThemeStore(
57
+ * { colorMode: { options: ['light', 'dark'] } },
58
+ * { storage: memoryStorageAdapter({ key: 'app' }) }
59
+ * )
60
+ */
61
+ declare const memoryStorageAdapter: StorageAdapterCreator<{
62
+ key: string;
63
+ }>;
64
+ export { memoryStorageAdapter as a, localStorageAdapter as i, StorageAdapterCreate as n, StorageAdapterCreator as r, StorageAdapter as t };
65
+ //# sourceMappingURL=storage-CsXjZKyt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-CsXjZKyt.d.ts","names":[],"sources":["../src/storage.ts"],"mappings":";;;;KAMY;;EAEV;;EAEA,MAAM;;EAEN,aAAa;;;;;EAKb,SAAS,KAAK;;;;;;;KAQJ,0BACV;EAEA,iBAAiB;MACb;;;;;KAMM,sBAAsB,YAChC,SAAS,YACN;;;;;;;;;;;;;;cAeQ,qBAAqB;EAChC;EACA;;;;;;;;;;;;;;;cAoDW,sBAAsB;EACjC"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./utils-CWI4hy3w.js";const t=({key:e,type:t=`localStorage`})=>({abortController:n})=>({get:()=>{try{return window[t].getItem(e)}catch{return null}},set:n=>{try{window[t].setItem(e,n)}catch{}},watch:r=>{let i=n=>{n.storageArea===window[t]&&n.key===e&&r(n.newValue)};return addEventListener(`storage`,i,n),()=>{removeEventListener(`storage`,i)}}}),n=({key:t})=>({abortController:n})=>{let r=/* @__PURE__ */ new Map,i=new BroadcastChannel(e);return n.signal.addEventListener(`abort`,()=>{i.close()}),{get:()=>r.get(t)??null,set:e=>{r.set(t,e)},broadcast:e=>{i.postMessage({key:t,value:e})},watch:e=>{let n=n=>{n.data.key===t&&(r.set(t,n.data.value),e(n.data.value))};return i.addEventListener(`message`,n),()=>{i.removeEventListener(`message`,n)}}}};export{n,t};
2
+ //# sourceMappingURL=storage-fOH2xeQ1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-fOH2xeQ1.js","names":["DEFAULT_KEY","localStorageAdapter","type","key","value","listener","e","cb","abortController","memoryStorageAdapter","storage","channel"],"sources":["../src/storage.ts"],"sourcesContent":["import { DEFAULT_KEY } from './utils'\n\n/**\n * Where a store saves its state. Values are strings: the full store saves\n * JSON, the lite store saves the theme name.\n */\nexport type StorageAdapter = {\n /** Returns the saved value, or `null` when nothing is saved. */\n get: () => string | null\n /** Saves a value. */\n set: (value: string) => void\n /** Optional: tells other tabs about a value just saved with `set`. */\n broadcast?: (value: string) => void\n /**\n * Optional: calls `cb` when another tab saves a value (`null` when it clears\n * it). Returns a function that stops watching. Used by `store.sync()`.\n */\n watch?: (cb: (value: string | null) => void) => () => void\n}\n\n/**\n * What a store's `storage` option takes: a function that creates the adapter.\n * `abortController` is aborted when the store is destroyed; use it to remove\n * listeners.\n */\nexport type StorageAdapterCreate = ({\n abortController,\n}: {\n abortController: AbortController\n}) => StorageAdapter\n\n/**\n * Shape of the built-in adapters such as `localStorageAdapter`: takes options\n * (like the key) and returns a {@link StorageAdapterCreate}.\n */\nexport type StorageAdapterCreator<Options> = (\n options: Options\n) => StorageAdapterCreate\n\n/**\n * Saves the store in `localStorage` (default) or `sessionStorage` under `key`,\n * and supports `store.sync()` across tabs. If storage is blocked or full,\n * reads return nothing and writes are skipped.\n *\n * @example\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 */\nexport const localStorageAdapter: StorageAdapterCreator<{\n key: string\n type?: 'localStorage' | 'sessionStorage'\n}> = ({ key, type = 'localStorage' }) => {\n return ({ abortController }) => {\n return {\n // Storage access throws when it is blocked (e.g. cookies disabled,\n // sandboxed iframes) or full.\n get: () => {\n try {\n return window[type].getItem(key)\n } catch {\n return null\n }\n },\n\n set: (value) => {\n try {\n window[type].setItem(key, value)\n } catch {}\n },\n\n watch: (cb) => {\n const listener = (e: StorageEvent) => {\n if (e.storageArea === window[type] && e.key === key) {\n cb(e.newValue)\n }\n }\n\n // Passing the controller as options (it has `signal`) removes the\n // listener when the store is destroyed.\n addEventListener('storage', listener, abortController)\n\n return () => {\n removeEventListener('storage', listener)\n }\n },\n }\n }\n}\n\n/**\n * Keeps the store in memory only, and supports `store.sync()` across tabs\n * through `BroadcastChannel`. Use it when you save the state yourself (e.g.\n * `toPersist()` to a database) and don't want it in `localStorage`.\n *\n * @example\n * import { createThemeStore, memoryStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] } },\n * { storage: memoryStorageAdapter({ key: 'app' }) }\n * )\n */\nexport const memoryStorageAdapter: StorageAdapterCreator<{\n key: string\n}> = ({ key }) => {\n return ({ abortController }) => {\n const storage = new Map<string, string>()\n\n const channel = new BroadcastChannel(DEFAULT_KEY)\n\n // An open channel keeps a Node process alive.\n abortController.signal.addEventListener('abort', () => {\n channel.close()\n })\n\n return {\n get: () => {\n return storage.get(key) ?? null\n },\n\n set: (value) => {\n storage.set(key, value)\n },\n\n broadcast: (value) => {\n channel.postMessage({ key, value })\n },\n\n watch: (cb) => {\n const listener = (e: MessageEvent) => {\n if (e.data.key === key) {\n storage.set(key, e.data.value)\n\n cb(e.data.value)\n }\n }\n\n channel.addEventListener('message', listener)\n\n return () => {\n channel.removeEventListener('message', listener)\n }\n },\n }\n }\n}\n"],"mappings":"A,wCAoDA,MAAaC,GAGP,CAAE,MAAK,OAAO,mBACV,CAAE,sBACD,CAGL,QAAW,CACT,GAAI,CACF,OAAO,OAAOC,EAAK,CAAC,QAAQC,CAAG,CACjC,MAAQ,CACN,OAAO,IACT,CACF,EAEA,IAAM,GAAU,CACd,GAAI,CACF,OAAOD,EAAK,CAAC,QAAQC,EAAKC,CAAK,CACjC,MAAQ,CAAC,CACX,EAEA,MAAQ,GAAO,CACb,IAAMC,EAAY,GAAoB,CAChCC,EAAE,cAAgB,OAAOJ,IAASI,EAAE,MAAQH,GAC9CI,EAAGD,EAAE,QAAQ,CAEjB,EAMA,OAFA,iBAAiB,UAAWD,EAAUG,CAAe,MAExC,CACX,oBAAoB,UAAWH,CAAQ,CACzC,CACF,CACF,GAiBSI,GAEP,CAAE,UACE,CAAE,qBAAsB,CAC9B,IAAMC,kBAAU,IAAI,IAEdC,EAAU,IAAI,iBAAiBX,CAAW,EAOhD,OAJAQ,EAAgB,OAAO,iBAAiB,YAAe,CACrDG,EAAQ,MAAM,CAChB,CAAC,EAEM,CACL,QACSD,EAAQ,IAAIP,CAAG,GAAK,KAG7B,IAAM,GAAU,CACdO,EAAQ,IAAIP,EAAKC,CAAK,CACxB,EAEA,UAAY,GAAU,CACpBO,EAAQ,YAAY,CAAE,MAAK,OAAM,CAAC,CACpC,EAEA,MAAQ,GAAO,CACb,IAAMN,EAAY,GAAoB,CAChCC,EAAE,KAAK,MAAQH,IACjBO,EAAQ,IAAIP,EAAKG,EAAE,KAAK,KAAK,EAE7BC,EAAGD,EAAE,KAAK,KAAK,EAEnB,EAIA,OAFAK,EAAQ,iBAAiB,UAAWN,CAAQ,MAE/B,CACXM,EAAQ,oBAAoB,UAAWN,CAAQ,CACjD,CACF,CACF,CACF,E"}