resonare 0.1.6 → 0.2.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=black&color=blue)](https://www.npmjs.com/package/resonare)
1
+ # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=black&color=green)](https://www.npmjs.com/package/resonare) [![bundle size](https://img.shields.io/bundlephobia/minzip/resonare?labelColor=black&color=green)](https://bundlephobia.com/package/resonare)
2
2
 
3
- A state store for multi-dimensional themes and user preferences. [Check out the demo](https://resonare.universse.workers.dev).
3
+ A state store for multi-dimensional themes and user preferences. [Check out the demo](https://resonare.phuoccss.workers.dev).
4
4
 
5
5
  ## Features
6
6
 
@@ -143,6 +143,10 @@ themeStore.getThemes()
143
143
  // e.g.: { colorScheme: 'dark', contrast: 'standard', sidebarWidth: 240 }
144
144
  themeStore.getResolvedThemes()
145
145
 
146
+ // get resolved system options
147
+ // e.g.: { colorScheme: 'dark' }
148
+ themeStore.getResolvedSystemThemes()
149
+
146
150
  // update theme
147
151
  themeStore.setThemes({ colorScheme: 'light', sidebarWidth: 280 })
148
152
 
package/dist/index.d.ts CHANGED
@@ -1,52 +1,5 @@
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
1
+ import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-DGYV332J.js";
2
+
50
3
  //#region src/index.d.ts
51
4
  type ThemeValue = string | number | boolean;
52
5
  type ThemeOption<T extends ThemeValue = string> = {
@@ -55,21 +8,17 @@ type ThemeOption<T extends ThemeValue = string> = {
55
8
  };
56
9
  type ThemeConfig<T extends ThemeValue = string> = {
57
10
  options: ReadonlyArray<T | ThemeOption<T>>;
58
- initialValue?: T;
11
+ defaultValue?: T;
59
12
  } | {
60
- initialValue: T;
13
+ defaultValue: T;
61
14
  options?: never;
62
15
  };
63
16
  type ThemeStoreConfig = Record<string, ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>>;
64
17
  type Themes<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
65
18
  options: ReadonlyArray<infer U>;
66
19
  } ? U extends ThemeOption ? U['value'] : U : T[K] extends {
67
- initialValue: infer U;
20
+ defaultValue: infer U;
68
21
  } ? U extends string ? string : U extends number ? number : boolean : never };
69
- type Listener<T extends ThemeStoreConfig> = (value: {
70
- themes: Themes<T>;
71
- resolvedThemes: Themes<T>;
72
- }) => void;
73
22
  type ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
74
23
  options: ReadonlyArray<infer U>;
75
24
  } ? U extends {
@@ -80,13 +29,20 @@ type NonSystemOptionValues<T extends ThemeStoreConfig, K extends keyof T> = T[K]
80
29
  } ? U extends ThemeValue ? U : U extends ThemeOption ? U extends {
81
30
  media: [string, string, string];
82
31
  } ? never : U['value'] : never : never;
83
- type SystemOptions<T extends ThemeStoreConfig> = { [K in ThemeKeysWithSystemOption<T>]?: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>] };
32
+ type ResolvedSystemThemes<T extends ThemeStoreConfig> = { [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K> };
33
+ type Snapshot<T extends ThemeStoreConfig> = {
34
+ themes: Themes<T>;
35
+ resolvedThemes: Themes<T>;
36
+ resolvedSystemThemes: ResolvedSystemThemes<T>;
37
+ };
38
+ type Listener<T extends ThemeStoreConfig> = (value: Snapshot<T>) => void;
39
+ type PersistedSystemOptionPairs = Record<string, [string, string]>;
84
40
  type PersistedState<T extends ThemeStoreConfig> = {
85
41
  themes: Partial<Themes<T>>;
86
- systemOptions: SystemOptions<T>;
42
+ systemOptions: PersistedSystemOptionPairs;
87
43
  };
88
44
  type ThemeStoreOptions<T extends ThemeStoreConfig> = {
89
- initialState?: Partial<PersistedState<T>>;
45
+ persisted?: Partial<PersistedState<T>>;
90
46
  storage?: StorageAdapterCreate | null;
91
47
  };
92
48
  type ThemeAndOptions<T extends ThemeStoreConfig> = Array<{ [K in keyof T]: [K, Array<T[K] extends {
@@ -97,18 +53,19 @@ declare function getDefaultThemes<T extends ThemeStoreConfig>(config: T): Themes
97
53
  declare class ThemeStore<T extends ThemeStoreConfig> {
98
54
  #private;
99
55
  constructor(config: T, {
100
- initialState,
56
+ persisted,
101
57
  storage
102
58
  }?: ThemeStoreOptions<T>);
103
59
  getThemes: () => Themes<T>;
104
60
  getResolvedThemes: () => Themes<T>;
61
+ getResolvedSystemThemes: () => ResolvedSystemThemes<T>;
62
+ getSnapshot: () => Snapshot<T>;
105
63
  setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
106
- updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(themeKey: K, [ifMatch, ifNotMatch]: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]) => void;
64
+ updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(themeKey: K, pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]) => void;
107
65
  toPersist: () => PersistedState<T>;
108
66
  restore: () => void;
109
67
  subscribe: (callback: Listener<T>) => (() => void);
110
68
  sync: () => (() => void) | undefined;
111
- /** Clears subscribers and aborts media-query listeners tied to this store instance. */
112
69
  destroy: () => void;
113
70
  }
114
71
  declare function createThemeStore<T extends ThemeStoreConfig>(config: T, options?: ThemeStoreOptions<T>): ThemeStore<T>;
@@ -117,29 +74,6 @@ type ThemeScriptParameter = {
117
74
  config: ThemeStoreConfig;
118
75
  handler: Listener<any>;
119
76
  };
120
- /**
121
- * Creates an IIFE script string that reads persisted themes from `localStorage` and runs your handlers immediately.
122
- *
123
- * Useful for avoiding flash of incorrect styles.
124
- * @example
125
- * ```tsx
126
- * import { createInlineThemeScript } from 'resonare'
127
- *
128
- * const inlineScript = createInlineThemeScript([
129
- * {
130
- * key: 'my-app',
131
- * config: {
132
- * colorMode: { options: ['light', 'dark'] },
133
- * },
134
- * handler: ({ resolvedThemes }) => {
135
- * document.documentElement.dataset.colorMode = String(
136
- * resolvedThemes.colorMode,
137
- * )
138
- * },
139
- * },
140
- * ])
141
- * ```
142
- */
143
77
  declare function createInlineThemeScript(themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>): string;
144
78
  //#endregion
145
79
  export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, ThemeScriptParameter, type ThemeStore, ThemeStoreConfig, Themes, createInlineThemeScript, createThemeStore, getDefaultThemes, getThemesAndOptions, localStorageAdapter, memoryStorageAdapter };
@@ -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,oBAAA;AARL;;;;;;;;;;;;AAAA,cAsBa,mBAAA,EAAqB,qBAAA;EACjC,GAAA;EACA,IAAA;AAAA;;;;;;;;;;AAFD;;;;cAuDa,oBAAA,EAAsB,qBAAA;EAClC,GAAA;AAAA;;;KCnFI,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,KAQjC,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,IACd,CAAA,2BAEC,CAAA;AAAA,KAMD,QAAA,WAAmB,gBAAA,KAAqB,KAAA;EAC5C,MAAA,EAAQ,MAAA,CAAO,CAAA;EACf,cAAA,EA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EACR,OAAA,EAAS,QAAQ;AAAA;AAAA,iBAGF,uBAAA,CACf,qBAAA,EAAuB,oBAAA,GAAuB,KAAA,CAAM,oBAAA"}
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={};#o=new Set;#s=new AbortController;constructor(n,{initialState:r={},storage:a=t({key:e})}={}){let o={};this.#e=i(n),this.#t={...this.#e,...r.themes},this.#n=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=(t.options||[]).map(t=>typeof t==`object`?(t.media&&(o[e]=[t.media[1],t.media[2]]),[String(t.value),t]):[String(t),{value:t}]);return[e,Object.fromEntries(n)]})),this.#r={...o,...r.systemOptions},this.#i=a?.({abortController:this.#s})??null}getThemes=()=>this.#t;getResolvedThemes=()=>Object.fromEntries(Object.entries(this.#t).map(([e,t])=>{let n=this.#n[e]?.[t];return[e,n?this.#l({themeKey:e,option:n}):t]}));setThemes=e=>{let t=typeof e==`function`?e(this.#t):e;this.#c({...this.#t,...t});let n=this.toPersist();this.#i&&(this.#i.set(n),this.#i.broadcast?.(n))};updateSystemOption=(e,[t,n])=>{this.#r[e]=[t,n],this.setThemes({...this.#t})};toPersist=()=>({themes:this.#t,systemOptions:this.#r});restore=()=>{let e=this.#i?.get();if(!e){this.#c({...this.#e});return}this.#r={...this.#r,...e.systemOptions},this.#c({...this.#e,...e.themes})};subscribe=e=>(this.#o.add(e),()=>{this.#o.delete(e)});sync=()=>{if(this.#i?.watch)return this.#i.watch(e=>{this.#r=e.systemOptions,this.#c(e.themes)})};destroy=()=>{this.#o.clear(),this.#s.abort()};#c=e=>{this.#t=e;for(let e of this.#o)e({themes:this.#t,resolvedThemes:this.getResolvedThemes()})};#l=({themeKey:e,option:t})=>{if(!t.media||!(typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0))return t.value;let n=this.#a,[r]=t.media;if(!n[r]){let i=window.matchMedia(r);n[r]=i,i.addEventListener(`change`,()=>{this.#t[e]===t.value&&this.#c({...this.#t})},{signal:this.#s.signal})}let[i,a]=this.#r[e];return n[r].matches?i:a}};function o(e,t={}){return new a(e,t)}const s=e=>{e.forEach(([e,t,n])=>{let r=JSON.parse(localStorage.getItem(e)||`{}`).themes??{};n(t.reduce((e,[t,n,i,a,o,s])=>{let c=r[t]??n;return e.resolvedThemes[t]=e.themes[t]=c,c===i&&(e.resolvedThemes[t]=matchMedia(a).matches?o:s),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,r,o]}=a;return[e,i,t,n,r,o]}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{n as e,r as t,t as n}from"./storage-B5xjLRee.js";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.defaultValue??(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(e,{persisted:r={},storage:a=n({key:t})}={}){this.#e={...i(e),...r.themes},this.#n=Object.fromEntries(Object.entries(e).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,this.#t=this.#c()}getThemes=()=>this.#e;getResolvedThemes=()=>Object.fromEntries(Object.entries(this.#e).map(([e,t])=>{let n=this.#n[e];return[e,n&&t===n.value?this.#u(e):t]}));getResolvedSystemThemes=()=>Object.fromEntries(Object.keys(this.#n).map(e=>[e,this.#u(e)]));getSnapshot=()=>this.#t;setThemes=e=>{let t=typeof e==`function`?e(this.#e):e;if(this.#l(t),this.#r){let e=JSON.stringify(this.toPersist());this.#r.set(e),this.#r.broadcast?.(e)}};updateSystemOption=(e,t)=>{this.#n[e].pair=t,this.setThemes({})};toPersist=()=>({themes:this.#e,systemOptions:Object.fromEntries(Object.entries(this.#n).map(([e,{pair:t}])=>[e,t]))});restore=()=>{let e=this.#r?.get();if(!e){this.#l();return}let t=JSON.parse(e);this.#s(t.systemOptions),this.#l(t.themes)};subscribe=e=>(this.#a.add(e),()=>this.#a.delete(e));sync=()=>{if(this.#r?.watch)return this.#r.watch(e=>{if(!e)return;let t=JSON.parse(e);this.#s(t.systemOptions),this.#l(t.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=()=>({themes:this.#e,resolvedThemes:this.getResolvedThemes(),resolvedSystemThemes:this.getResolvedSystemThemes()});#l=e=>{this.#e={...this.#e,...e},this.#t=this.#c();for(let e of this.#a)e(this.#t)};#u=e=>{let{value:t,mediaQuery:n,pair:r}=this.#n[e];return typeof matchMedia>`u`?t:(this.#i[n]||(this.#i[n]=window.matchMedia(n),this.#i[n].addEventListener(`change`,()=>{this.#l()},{signal:this.#o.signal})),this.#i[n].matches?r[0]:r[1])}};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,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 c(e){return`(${s})([${(Array.isArray(e)?e:[e]).map(({key:e=t,config:n,handler:r})=>{let i=Object.entries(n).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`['${e}',${JSON.stringify(i)},${r}]`})}])`}export{c as createInlineThemeScript,o as createThemeStore,i as getDefaultThemes,r as getThemesAndOptions,n as localStorageAdapter,e 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","KeyedThemeStoreConfig","Themes","K","U","Listener","themes","resolvedThemes","ThemeKeysWithSystemOption","NonSystemOptionValues","SystemOptions","PersistedState","Partial","systemOptions","ThemeStoreOptions","initialState","storage","ThemeAndOptions","Array","getThemesAndOptions","config","Object","entries","map","themeKey","themeConfig","option","getDefaultThemes","fromEntries","ThemeStore","defaultThemes","currentThemes","keyedConfig","mediaQueryCache","MediaQueryList","listeners","Set","abortController","AbortController","constructor","key","String","getThemes","getResolvedThemes","optionKey","resolveThemeOption","setThemes","updatedThemes","setThemesAndNotify","stateToPersist","toPersist","set","broadcast","updateSystemOption","ifMatch","ifNotMatch","restore","persistedState","get","subscribe","callback","add","delete","sync","watch","destroy","clear","abort","#setThemesAndNotify","listener","#resolveThemeOption","window","document","createElement","cache","mediaQuery","mediaQueryList","matchMedia","addEventListener","signal","matches","createThemeStore","restoreScript","params","forEach","flattenedConfig","handler","persistedThemes","JSON","parse","localStorage","getItem","reduce","acc","initial","systemOptionValue","currentValue","ThemeScriptParameter","createInlineThemeScript","themeScriptParameters","serializedArgs","isArray","firstOption","resolvedInitialValue","systemOption","find","Required","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\n// { [themeKey]: { [optionKey]: ThemeOption } }\ntype KeyedThemeStoreConfig<T extends ThemeStoreConfig> = {\n\t[K in keyof T]: Record<string, ThemeOption>\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 Listener<T extends ThemeStoreConfig> = (value: {\n\tthemes: Themes<T>\n\tresolvedThemes: Themes<T>\n}) => void\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 SystemOptions<T extends ThemeStoreConfig> = {\n\t[K in ThemeKeysWithSystemOption<T>]?: [\n\t\tNonSystemOptionValues<T, K>,\n\t\tNonSystemOptionValues<T, K>,\n\t]\n}\n\ntype PersistedState<T extends ThemeStoreConfig> = {\n\tthemes: Partial<Themes<T>>\n\tsystemOptions: SystemOptions<T>\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#keyedConfig: KeyedThemeStoreConfig<T>\n\n\t#systemOptions: SystemOptions<T>\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\tconst systemOptions: Record<string, [ThemeValue, ThemeValue]> = {}\n\n\t\tthis.#defaultThemes = getDefaultThemes(config)\n\n\t\tthis.#currentThemes = { ...this.#defaultThemes, ...initialState.themes }\n\n\t\tthis.#keyedConfig = Object.fromEntries(\n\t\t\tObject.entries(config).map(([themeKey, themeConfig]) => {\n\t\t\t\tconst entries = (themeConfig.options || []).map((option) => {\n\t\t\t\t\tif (typeof option === 'object') {\n\t\t\t\t\t\tif (option.media) {\n\t\t\t\t\t\t\tsystemOptions[themeKey] = [option.media[1], option.media[2]]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn [String(option.value), option]\n\t\t\t\t\t}\n\n\t\t\t\t\treturn [String(option), { value: option }]\n\t\t\t\t})\n\n\t\t\t\treturn [themeKey, Object.fromEntries(entries)]\n\t\t\t}),\n\t\t) as KeyedThemeStoreConfig<T>\n\n\t\tthis.#systemOptions = { ...systemOptions, ...initialState.systemOptions }\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 option = this.#keyedConfig[themeKey]?.[optionKey]\n\n\t\t\t\treturn [\n\t\t\t\t\tthemeKey,\n\t\t\t\t\toption ? this.#resolveThemeOption({ themeKey, option }) : optionKey,\n\t\t\t\t]\n\t\t\t}),\n\t\t) as Themes<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\t[ifMatch, ifNotMatch]: [\n\t\t\tNonSystemOptionValues<T, K>,\n\t\t\tNonSystemOptionValues<T, K>,\n\t\t],\n\t): void => {\n\t\tthis.#systemOptions[themeKey] = [ifMatch, ifNotMatch]\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: this.#systemOptions,\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.#systemOptions = {\n\t\t\t...this.#systemOptions,\n\t\t\t...persistedState.systemOptions,\n\t\t}\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 () => {\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((persistedState) => {\n\t\t\tthis.#systemOptions = (persistedState as PersistedState<T>).systemOptions\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#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})\n\t\t}\n\t}\n\n\t#resolveThemeOption = ({\n\t\tthemeKey,\n\t\toption,\n\t}: {\n\t\tthemeKey: string\n\t\toption: ThemeOption\n\t}): string => {\n\t\tif (!option.media) return option.value\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 option.value\n\t\t}\n\n\t\tconst cache = this.#mediaQueryCache\n\n\t\tconst [mediaQuery] = option.media\n\n\t\tif (!cache[mediaQuery]) {\n\t\t\tconst mediaQueryList = window.matchMedia(mediaQuery)\n\n\t\t\tcache[mediaQuery] = mediaQueryList\n\n\t\t\tmediaQueryList.addEventListener(\n\t\t\t\t'change',\n\t\t\t\t() => {\n\t\t\t\t\tif (this.#currentThemes[themeKey] === option.value) {\n\t\t\t\t\t\tthis.#setThemesAndNotify({ ...this.#currentThemes })\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ signal: this.#abortController.signal },\n\t\t\t)\n\t\t}\n\n\t\tconst [ifMatch, ifNotMatch] = this.#systemOptions[themeKey]!\n\n\t\treturn cache[mediaQuery].matches ? ifMatch : ifNotMatch\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[string, Array<[string, T] | [string, T, T, string, T, T]>, Listener<any>]\n\t>,\n) => {\n\tparams.forEach(([key, flattenedConfig, handler]) => {\n\t\tconst persistedThemes =\n\t\t\tJSON.parse(localStorage.getItem(key) || '{}').themes ?? {}\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\tifMatch,\n\t\t\t\t\t\tifNotMatch,\n\t\t\t\t\t],\n\t\t\t\t) => {\n\t\t\t\t\tconst currentValue = persistedThemes[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\tacc.resolvedThemes[themeKey] = matchMedia(mediaQuery!).matches\n\t\t\t\t\t\t\t? ifMatch!\n\t\t\t\t\t\t\t: ifNotMatch!\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>\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 {\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tmedia: [mediaQuery, ifMatch, ifNotMatch],\n\t\t\t\t\t} = systemOption\n\n\t\t\t\t\treturn [\n\t\t\t\t\t\tthemeKey,\n\t\t\t\t\t\tresolvedInitialValue,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tmediaQuery,\n\t\t\t\t\t\tifMatch,\n\t\t\t\t\t\tifNotMatch,\n\t\t\t\t\t]\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,GAAMmB,QAAQJ,EAAI,EAAI,OAAO,CAGvDZ,IAAMC,GAAkB,CACvBc,OAAOlB,GAAMoB,QAAQL,EAAKC,KAAKK,UAAUjB,EAAM,CAAC,EAGjDE,MAAQC,GAAO,CACd,IAAMe,EAAa,IAAIZ,gBAmBvB,OAjBAQ,OAAOK,iBACN,UACCC,GAAM,CACFA,EAAEC,cAAgBP,OAAOlB,IAEzBwB,EAAET,MAAQA,GAEdR,EAAGS,KAAKC,MAAMO,EAAEE,SAAU,CAAC,EAE5B,CACCC,OAAQC,YAAYC,IAAI,CACvBpB,EAAgBkB,OAChBL,EAAWK,OACX,CAAA,CAEH,CAAC,KAEY,CACZL,EAAWQ,OAAO,GAGpB,EAiBUC,GAEP,CAAEhB,UACC,CAAEN,qBAAsB,CAC/B,IAAMuB,EAAU,IAAIC,IACdC,EAAU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CACjB,GAAM,CACLhH,QACAE,MAAO,CAACiF,EAAYrB,EAASC,IAC1BiD,EAEJ,MAAO,CACNhF,EACA+E,EACA/G,EACAmF,EACArB,EACAC,EACA,CAGF,MAAO,CAAC/B,EAAU+E,EAAqB,EAExC,CAED,MAAO,KAAK/D,EAAG,KAAMgD,KAAKmB,UAAUtB,EAAgB,CAAA,IAAKC,EAAO,IAGrB,CAAA"}
1
+ {"version":3,"file":"index.js","names":["DEFAULT_KEY","localStorageAdapter","StorageAdapter","StorageAdapterCreate","ThemeValue","ThemeOption","value","T","media","ThemeConfig","options","ReadonlyArray","defaultValue","ThemeStoreConfig","Record","Themes","K","U","ThemeKeysWithSystemOption","NonSystemOptionValues","ResolvedSystemThemes","SystemOptions","mediaQuery","pair","Snapshot","themes","resolvedThemes","resolvedSystemThemes","Listener","PersistedSystemOptionPairs","PersistedState","Partial","systemOptions","ThemeStoreOptions","persisted","storage","ThemeAndOptions","Array","getThemesAndOptions","config","Object","entries","map","themeKey","themeConfig","option","getDefaultThemes","fromEntries","ThemeStore","currentThemes","snapshot","mediaQueryCache","MediaQueryList","listeners","Set","abortController","AbortController","constructor","key","flatMap","systemOption","find","Required","optionWhenMatched","optionWhenNotMatched","createSnapshot","getThemes","getResolvedThemes","optionKey","resolveSystemOption","getResolvedSystemThemes","keys","getSnapshot","setThemes","updatedThemes","setThemesAndNotify","stored","JSON","stringify","toPersist","set","broadcast","updateSystemOption","restore","get","parse","applyPersistedSystemOptions","subscribe","callback","add","delete","sync","watch","destroy","clear","abort","#applyPersistedSystemOptions","forEach","#createSnapshot","#setThemesAndNotify","listener","#resolveSystemOption","matchMedia","window","addEventListener","signal","matches","createThemeStore","restoreScript","params","flattenedConfig","handler","localStorage","getItem","reduce","acc","initial","systemOptionValue","currentValue","systemTheme","ThemeScriptParameter","createInlineThemeScript","themeScriptParameters","serializedArgs","isArray","firstOption","resolvedInitialValue"],"sources":["../src/index.ts"],"sourcesContent":["import { DEFAULT_KEY } from './constants'\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\tdefaultValue?: T\n\t }\n\t| { defaultValue: 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 { defaultValue: 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 Snapshot<T extends ThemeStoreConfig> = {\n\tthemes: Themes<T>\n\tresolvedThemes: Themes<T>\n\tresolvedSystemThemes: 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\tthemes: Partial<Themes<T>>\n\tsystemOptions: PersistedSystemOptionPairs\n}\n\ntype ThemeStoreOptions<T extends ThemeStoreConfig> = {\n\tpersisted?: 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.defaultValue ??\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#currentThemes: Themes<T>\n\n\t#snapshot: Snapshot<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\tpersisted = {},\n\t\t\tstorage = localStorageAdapter({ key: DEFAULT_KEY }),\n\t\t}: ThemeStoreOptions<T> = {},\n\t) {\n\t\tthis.#currentThemes = { ...getDefaultThemes(config), ...persisted.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: persisted.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\n\t\tthis.#snapshot = this.#createSnapshot()\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\tgetSnapshot = (): Snapshot<T> => {\n\t\treturn this.#snapshot\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(updatedThemes)\n\n\t\tif (this.#storage) {\n\t\t\tconst stored = JSON.stringify(this.toPersist())\n\n\t\t\tthis.#storage.set(stored)\n\n\t\t\tthis.#storage.broadcast?.(stored)\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({})\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 stored = this.#storage?.get()\n\n\t\tif (!stored) {\n\t\t\tthis.#setThemesAndNotify()\n\t\t\treturn\n\t\t}\n\n\t\tconst persisted = JSON.parse(stored) as PersistedState<T>\n\n\t\tthis.#applyPersistedSystemOptions(persisted.systemOptions)\n\n\t\tthis.#setThemesAndNotify(persisted.themes)\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((stored) => {\n\t\t\tif (!stored) return\n\n\t\t\tconst persisted = JSON.parse(stored) as PersistedState<T>\n\n\t\t\tthis.#applyPersistedSystemOptions(persisted.systemOptions)\n\n\t\t\tthis.#setThemesAndNotify(persisted.themes)\n\t\t})\n\t}\n\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#createSnapshot = (): Snapshot<T> => ({\n\t\tthemes: this.#currentThemes,\n\t\tresolvedThemes: this.getResolvedThemes(),\n\t\tresolvedSystemThemes: this.getResolvedSystemThemes(),\n\t})\n\n\t#setThemesAndNotify = (themes?: Partial<Themes<T>>): void => {\n\t\tthis.#currentThemes = { ...this.#currentThemes, ...themes }\n\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#resolveSystemOption = (themeKey: string): string => {\n\t\tconst { value, mediaQuery, pair } = this.#systemOptions[themeKey]!\n\n\t\tif (typeof matchMedia === 'undefined') return value\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()\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[string, Array<[string, T] | [string, T, T, string, T, T]>, Listener<any>]\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\tresolvedSystemThemes: 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 (mediaQuery != null) {\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\tconst systemTheme = matchMedia(mediaQuery).matches\n\t\t\t\t\t\t\t? pair[0]\n\t\t\t\t\t\t\t: pair[1]\n\n\t\t\t\t\t\tacc.resolvedSystemThemes[themeKey] = systemTheme\n\n\t\t\t\t\t\tif (currentValue === systemOptionValue) {\n\t\t\t\t\t\t\tacc.resolvedThemes[themeKey] = systemTheme\n\t\t\t\t\t\t}\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: {}, resolvedSystemThemes: {} },\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>\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 = DEFAULT_KEY, config, handler }) => {\n\t\tconst flattenedConfig = Object.entries(config).map(\n\t\t\t([themeKey, { options, defaultValue }]) => {\n\t\t\t\tconst firstOption = options?.[0]\n\n\t\t\t\tconst resolvedInitialValue =\n\t\t\t\t\tdefaultValue ??\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}',${JS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EjC,UAASE,mBAAoB,CAC1C,IAAMiH,EAAcnH,IAAU,GAExBoH,EACLlH,IACC,OAAOiH,GAAgB,SAAWA,EAAYvH,MAAQuH,GAElDjE,EAAelD,GAASmD,KAC5BhB,GACA,OAAOA,GAAW,UAAY,CAAC,CAACA,EAAOrC,KACzC,EAEA,GAAIoD,EAAc,CACjB,GAAM,CAAEtD,QAAOE,SAAUoD,EAEzB,MAAO,CAACjB,EAAUmF,EAAsBxH,EAAO,GAAGE,CAAK,CACxD,CAEA,MAAO,CAACmC,EAAUmF,CAAoB,CACvC,CACD,EAEA,MAAO,KAAKpE,EAAG,IAAKmB,KAAKC,UAAUgC,CAAe,EAAC,GAAIC,EAAO,EAC/D,CAE8BY,EAAc,GAC7C"}
@@ -0,0 +1,36 @@
1
+ import { ThemeStore } from "./lite.js";
2
+
3
+ //#region src/lite-react.d.ts
4
+ /**
5
+ * Subscribes a React component to a lite (light/dark/system) theme store.
6
+ * @example
7
+ * ```tsx
8
+ * import { createThemeStore } from 'resonare/lite'
9
+ * import { useResonare } from 'resonare/lite/react'
10
+ *
11
+ * const store = createThemeStore()
12
+ *
13
+ * export function ThemeToggle() {
14
+ * const { theme, resolvedTheme, systemTheme, setTheme } = useResonare(store)
15
+ *
16
+ * // ...
17
+ * }
18
+ * ```
19
+ */
20
+ declare function useResonare(store: ThemeStore): {
21
+ destroy: () => void;
22
+ restore: () => void;
23
+ setTheme: (theme: ("system" | "light" | "dark") | ((current: "system" | "light" | "dark") => "system" | "light" | "dark")) => void;
24
+ subscribe: (callback: (value: {
25
+ theme: "system" | "light" | "dark";
26
+ resolvedTheme: "light" | "dark";
27
+ systemTheme: "light" | "dark";
28
+ }) => void) => (() => void);
29
+ sync: () => (() => void) | undefined;
30
+ theme: "system" | "light" | "dark";
31
+ resolvedTheme: "light" | "dark";
32
+ systemTheme: "light" | "dark";
33
+ };
34
+ //#endregion
35
+ export { useResonare };
36
+ //# sourceMappingURL=lite-react.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-react.d.ts","names":[],"sources":["../src/lite-react.ts"],"mappings":";;;;;AAmBA;;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,KAAA,EAAO,UAAU"}
@@ -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,getSnapshot:a,restore:o,setTheme:s,subscribe:c,sync:l}=n,u=t.useSyncExternalStore(c,a,a),d;return r[0]!==i||r[1]!==o||r[2]!==s||r[3]!==u||r[4]!==c||r[5]!==l?(d={...u,destroy:i,restore:o,setTheme:s,subscribe:c,sync:l},r[0]=i,r[1]=o,r[2]=s,r[3]=u,r[4]=c,r[5]=l,r[6]=d):d=r[6],d}export{n as useResonare};
2
+ //# sourceMappingURL=lite-react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-react.js","names":["React","ThemeStore","useResonare","store","$","_c","destroy","getSnapshot","restore","setTheme","subscribe","sync","snapshot","useSyncExternalStore","t0"],"sources":["../src/lite-react.ts"],"sourcesContent":["import * as React from 'react'\nimport type { ThemeStore } from './lite'\n\n/**\n * Subscribes a React component to a lite (light/dark/system) theme store.\n * @example\n * ```tsx\n * import { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/react'\n *\n * const store = createThemeStore()\n *\n * export function ThemeToggle() {\n * const { theme, resolvedTheme, systemTheme, setTheme } = useResonare(store)\n *\n * // ...\n * }\n * ```\n */\nexport function useResonare(store: ThemeStore) {\n\tconst { destroy, getSnapshot, restore, setTheme, subscribe, sync } = store\n\n\tconst snapshot = React.useSyncExternalStore(\n\t\tsubscribe,\n\t\tgetSnapshot,\n\t\tgetSnapshot,\n\t)\n\n\treturn { ...snapshot, destroy, restore, setTheme, subscribe, sync }\n}\n"],"mappings":"mEAmBA,SAAOE,EAAAC,EAAA,CAAA,IAAAC,EAAAC,EAAA,CAAA,EACN,CAAAC,UAAAC,cAAAC,UAAAC,WAAAC,YAAAC,QAAqER,EAErES,EAAiBZ,EAAKa,qBACrBH,EACAH,EACAA,CACD,EAACO,EAEkE,OAFlEV,EAAA,KAAAE,GAAAF,EAAA,KAAAI,GAAAJ,EAAA,KAAAK,GAAAL,EAAA,KAAAQ,GAAAR,EAAA,KAAAM,GAAAN,EAAA,KAAAO,GAEMG,EAAA,CAAA,GAAKF,EAAQN,UAAAE,UAAAC,WAAAC,YAAAC,MAA8C,EAACP,EAAA,GAAAE,EAAAF,EAAA,GAAAI,EAAAJ,EAAA,GAAAK,EAAAL,EAAA,GAAAQ,EAAAR,EAAA,GAAAM,EAAAN,EAAA,GAAAO,EAAAP,EAAA,GAAAU,GAAAA,EAAAV,EAAA,GAA5DU,CAA4D"}
package/dist/lite.d.ts ADDED
@@ -0,0 +1,43 @@
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
4
+ type Theme = 'system' | 'light' | 'dark';
5
+ type ResolvedTheme = 'light' | 'dark';
6
+ type Snapshot = {
7
+ theme: Theme;
8
+ resolvedTheme: ResolvedTheme;
9
+ systemTheme: ResolvedTheme;
10
+ };
11
+ type Listener = (value: Snapshot) => void;
12
+ type ThemeStoreOptions = {
13
+ persisted?: Theme;
14
+ storage?: StorageAdapterCreate | null;
15
+ };
16
+ declare class ThemeStore {
17
+ #private;
18
+ constructor({
19
+ persisted,
20
+ storage
21
+ }?: ThemeStoreOptions);
22
+ getTheme: () => Theme;
23
+ getResolvedTheme: () => ResolvedTheme;
24
+ getSystemTheme: () => ResolvedTheme;
25
+ getSnapshot: () => Snapshot;
26
+ setTheme: (theme: Theme | ((current: Theme) => Theme)) => void;
27
+ restore: () => void;
28
+ subscribe: (callback: Listener) => (() => void);
29
+ sync: () => (() => void) | undefined;
30
+ destroy: () => void;
31
+ }
32
+ declare function createThemeStore(options?: ThemeStoreOptions): ThemeStore;
33
+ type ThemeScriptParameter = {
34
+ key?: string;
35
+ handler: Listener;
36
+ };
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 };
43
+ //# sourceMappingURL=lite.d.ts.map
@@ -0,0 +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"}
package/dist/lite.js ADDED
@@ -0,0 +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};
2
+ //# sourceMappingURL=lite.js.map
@@ -0,0 +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"}
package/dist/react.d.ts CHANGED
@@ -6,50 +6,44 @@ import { ThemeStore, ThemeStoreConfig, Themes } from "./index.js";
6
6
  * @example
7
7
  * ```tsx
8
8
  * export function ThemeToggle() {
9
- * const { themes, resolvedThemes, setThemes } = useResonare(store)
9
+ * const { themes, resolvedThemes, resolvedSystemThemes, setThemes } = useResonare(store)
10
10
  *
11
11
  * // ...
12
12
  * }
13
13
  * ```
14
14
  */
15
15
  declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>): {
16
- themes: Themes<T>;
17
- resolvedThemes: Themes<T>;
18
16
  destroy: () => void;
19
17
  restore: () => void;
20
18
  setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
21
19
  subscribe: (callback: (value: {
22
20
  themes: Themes<T>;
23
21
  resolvedThemes: Themes<T>;
24
- }) => void) => (() => void);
25
- sync: () => (() => void) | undefined;
26
- toPersist: () => {
27
- themes: Partial<Themes<T>>;
28
- systemOptions: { [K_1 in { [K in keyof T]: T[K] extends {
22
+ resolvedSystemThemes: { [K_1 in { [K in keyof T]: T[K] extends {
29
23
  options: ReadonlyArray<infer U>;
30
24
  } ? U extends {
31
25
  media: ReadonlyArray<unknown>;
32
- } ? K : never : never }[keyof T]]?: [T[K_1] extends {
33
- options: ReadonlyArray<infer U>;
34
- } ? U extends string | number | boolean ? U : U extends {
35
- value: string;
36
- media?: [string, string, string];
37
- } ? U extends {
38
- media: [string, string, string];
39
- } ? never : U["value"] : never : never, T[K_1] extends {
26
+ } ? K : never : never }[keyof T]]: T[K_1] extends {
40
27
  options: ReadonlyArray<infer U>;
41
28
  } ? U extends string | number | boolean ? U : U extends {
42
29
  value: string;
43
30
  media?: [string, string, string];
44
31
  } ? U extends {
45
32
  media: [string, string, string];
46
- } ? never : U["value"] : never : never] };
33
+ } ? never : U["value"] : never : never };
34
+ }) => void) => (() => void);
35
+ sync: () => (() => void) | undefined;
36
+ toPersist: () => {
37
+ themes: Partial<Themes<T>>;
38
+ systemOptions: {
39
+ [x: string]: [string, string];
40
+ };
47
41
  };
48
42
  updateSystemOption: <K extends { [K_1 in keyof T]: T[K_1] extends {
49
43
  options: ReadonlyArray<infer U>;
50
44
  } ? U extends {
51
45
  media: ReadonlyArray<unknown>;
52
- } ? K_1 : never : never }[keyof T]>(themeKey: K, [ifMatch, ifNotMatch]: [T[K] extends {
46
+ } ? K_1 : never : never }[keyof T]>(themeKey: K, pair: [T[K] extends {
53
47
  options: ReadonlyArray<infer U>;
54
48
  } ? U extends string | number | boolean ? U : U extends {
55
49
  value: string;
@@ -64,6 +58,20 @@ declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>):
64
58
  } ? U extends {
65
59
  media: [string, string, string];
66
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>;
65
+ } ? U extends {
66
+ 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 };
67
75
  };
68
76
  //#endregion
69
77
  export { useResonare };
@@ -1 +1 @@
1
- {"version":3,"file":"react.d.ts","names":[],"sources":["../src/react.ts"],"mappings":";;;;;AAcA;;;;;;;;;iBAAgB,WAAA,WAAsB,gBAAA,CAAA,CAAkB,KAAA,EAAO,UAAA,CAAW,CAAA"}
1
+ {"version":3,"file":"react.d.ts","names":[],"sources":["../src/react.ts"],"mappings":";;;;;AAcA;;;;;;;;;iBAAgB,WAAA,WAAsB,gBAAA,EAAkB,KAAA,EAAO,UAAA,CAAW,CAAA"}
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(13),{destroy:i,getResolvedThemes:a,getThemes:o,restore:s,setThemes:c,subscribe:l,sync:u,toPersist:d,updateSystemOption:f}=n,p=t.useSyncExternalStore(l,o,o),m;r[0]!==a||r[1]!==p?(m=a(p),r[0]=a,r[1]=p,r[2]=m):m=r[2];let h;return r[3]!==i||r[4]!==s||r[5]!==c||r[6]!==l||r[7]!==u||r[8]!==m||r[9]!==p||r[10]!==d||r[11]!==f?(h={themes:p,resolvedThemes:m,destroy:i,restore:s,setThemes:c,subscribe:l,sync:u,toPersist:d,updateSystemOption:f},r[3]=i,r[4]=s,r[5]=c,r[6]=l,r[7]=u,r[8]=m,r[9]=p,r[10]=d,r[11]=f,r[12]=h):h=r[12],h}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,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};
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","getResolvedThemes","getThemes","restore","setThemes","subscribe","sync","toPersist","updateSystemOption","themes","useSyncExternalStore","t0","t1","resolvedThemes"],"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, setThemes } = useResonare(store)\n *\n * // ...\n * }\n * ```\n */\nexport function useResonare<T extends ThemeStoreConfig>(store: ThemeStore<T>) {\n\tconst {\n\t\tdestroy,\n\t\tgetResolvedThemes,\n\t\tgetThemes,\n\t\trestore,\n\t\tsetThemes,\n\t\tsubscribe,\n\t\tsync,\n\t\ttoPersist,\n\t\tupdateSystemOption,\n\t} = store\n\n\tconst themes = React.useSyncExternalStore(subscribe, getThemes, getThemes)\n\n\treturn {\n\t\tthemes,\n\t\t// @ts-expect-error - workaround for React compiler as getResolvedThemes is not called again without 'themes' dependency\n\t\tresolvedThemes: getResolvedThemes(themes),\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,GAAA,CACN,CAAAC,UAAAC,oBAAAC,YAAAC,UAAAC,YAAAC,YAAAC,OAAAC,YAAAC,sBAUIX,EAEJY,EAAehB,EAAKiB,qBAAsBL,EAAWH,EAAWA,EAAU,CAAAS,EAAAb,EAAA,KAAAG,GAAAH,EAAA,KAAAW,GAKzDE,EAAAV,EAAkBQ,EAAO,CAAAX,EAAA,GAAAG,EAAAH,EAAA,GAAAW,EAAAX,EAAA,GAAAa,GAAAA,EAAAb,EAAA,GAAA,IAAAc,EAQzC,OARyCd,EAAA,KAAAE,GAAAF,EAAA,KAAAK,GAAAL,EAAA,KAAAM,GAAAN,EAAA,KAAAO,GAAAP,EAAA,KAAAQ,GAAAR,EAAA,KAAAa,GAAAb,EAAA,KAAAW,GAAAX,EAAA,MAAAS,GAAAT,EAAA,MAAAU,GAHnCI,EAAA,CAAAH,SAAAI,eAGUF,EAAyBX,UAAAG,UAAAC,YAAAC,YAAAC,OAAAC,YAAAC,qBAQzC,CAAAV,EAAA,GAAAE,EAAAF,EAAA,GAAAK,EAAAL,EAAA,GAAAM,EAAAN,EAAA,GAAAO,EAAAP,EAAA,GAAAQ,EAAAR,EAAA,GAAAa,EAAAb,EAAA,GAAAW,EAAAX,EAAA,IAAAS,EAAAT,EAAA,IAAAU,EAAAV,EAAA,IAAAc,GAAAA,EAAAd,EAAA,IAXMc"}
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"}
@@ -0,0 +1,2 @@
1
+ const e=`resonare`,t=`resonare/lite`,n=({key:e,type:t=`localStorage`})=>({abortController:n})=>({get:()=>window[t].getItem(e),set:n=>{window[t].setItem(e,n)},watch:r=>{let i=new AbortController;return window.addEventListener(`storage`,n=>{n.storageArea===window[t]&&n.key===e&&r(n.newValue)},{signal:AbortSignal.any([n.signal,i.signal])}),()=>{i.abort()}}}),r=({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()}}}};export{t as i,r as n,e as r,n as t};
2
+ //# sourceMappingURL=storage-B5xjLRee.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-B5xjLRee.js","names":["DEFAULT_KEY","DEFAULT_LITE_KEY","DEFAULT_KEY","StorageAdapter","get","set","value","broadcast","watch","cb","StorageAdapterCreate","abortController","AbortController","StorageAdapterCreator","options","Options","localStorageAdapter","key","type","window","getItem","setItem","controller","addEventListener","e","storageArea","newValue","signal","AbortSignal","any","abort","memoryStorageAdapter","storage","Map","channel","BroadcastChannel","postMessage","data"],"sources":["../src/constants.ts","../src/storage.ts"],"sourcesContent":["export const DEFAULT_KEY = 'resonare'\nexport const DEFAULT_LITE_KEY = 'resonare/lite'\n","import { DEFAULT_KEY } from './constants'\n\nexport type StorageAdapter = {\n\tget: () => string | null\n\tset: (value: string) => void\n\tbroadcast?: (value: string) => void\n\twatch?: (cb: (value: string | null) => 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\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 window[type].getItem(key)\n\t\t\t},\n\n\t\t\tset: (value) => {\n\t\t\t\twindow[type].setItem(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\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(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\nexport const memoryStorageAdapter: StorageAdapterCreator<{\n\tkey: string\n}> = ({ key }) => {\n\treturn ({ abortController }) => {\n\t\tconst storage = new Map<string, string>()\n\n\t\tconst channel = new BroadcastChannel(DEFAULT_KEY)\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) => {\n\t\t\t\tstorage.set(key, value)\n\t\t\t},\n\n\t\t\tbroadcast: (value) => {\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"],"mappings":"AAAA,MAAaA,EAAc,WACdC,EAAmB,gBCkBnBe,GAGP,CAAEC,MAAKC,OAAO,mBACX,CAAEP,sBACF,CACNP,QACQe,OAAOD,EAAK,CAACE,QAAQH,CAAG,EAGhCZ,IAAMC,GAAU,CACfa,OAAOD,EAAK,CAACG,QAAQJ,EAAKX,CAAK,CAChC,EAEAE,MAAQC,GAAO,CACd,IAAMa,EAAa,IAAIV,gBAmBvB,OAjBAO,OAAOI,iBACN,UACCC,GAAM,CACFA,EAAEC,cAAgBN,OAAOD,IAEzBM,EAAEP,MAAQA,GAEdR,EAAGe,EAAEE,QAAQ,CACd,EACA,CACCC,OAAQC,YAAYC,IAAI,CACvBlB,EAAgBgB,OAChBL,EAAWK,MAAM,CACjB,CACF,CACD,MAEa,CACZL,EAAWQ,MAAM,CAClB,CACD,CACD,GAIWC,GAEP,CAAEd,UACC,CAAEN,qBAAsB,CAC/B,IAAMqB,EAAU,IAAIC,IAEdC,EAAU,IAAIC,iBAAiBjC,CAAW,EAEhD,MAAO,CACNE,QACQ4B,EAAQ5B,IAAIa,CAAG,GAAK,KAG5BZ,IAAMC,GAAU,CACf0B,EAAQ3B,IAAIY,EAAKX,CAAK,CACvB,EAEAC,UAAYD,GAAU,CACrB4B,EAAQE,YAAY,CAAEnB,MAAKX,OAAM,CAAC,CACnC,EAEAE,MAAQC,GAAO,CACd,IAAMa,EAAa,IAAIV,gBAiBvB,OAfAsB,EAAQX,iBACP,UACCC,GAAM,CACFA,EAAEa,KAAKpB,MAAQA,GAEnBR,EAAGe,EAAEa,KAAK/B,KAAK,CAChB,EACA,CACCqB,OAAQC,YAAYC,IAAI,CACvBlB,EAAgBgB,OAChBL,EAAWK,MAAM,CACjB,CACF,CACD,MAEa,CACZL,EAAWQ,MAAM,CAClB,CACD,CACD,CACD"}
@@ -0,0 +1,23 @@
1
+ //#region src/storage.d.ts
2
+ type StorageAdapter = {
3
+ get: () => string | null;
4
+ set: (value: string) => void;
5
+ broadcast?: (value: string) => void;
6
+ watch?: (cb: (value: string | null) => void) => () => void;
7
+ };
8
+ type StorageAdapterCreate = ({
9
+ abortController
10
+ }: {
11
+ abortController: AbortController;
12
+ }) => StorageAdapter;
13
+ type StorageAdapterCreator<Options> = (options: Options) => StorageAdapterCreate;
14
+ declare const localStorageAdapter: StorageAdapterCreator<{
15
+ key: string;
16
+ type?: 'localStorage' | 'sessionStorage';
17
+ }>;
18
+ declare const memoryStorageAdapter: StorageAdapterCreator<{
19
+ key: string;
20
+ }>;
21
+ //#endregion
22
+ export { memoryStorageAdapter as a, localStorageAdapter as i, StorageAdapterCreate as n, StorageAdapterCreator as r, StorageAdapter as t };
23
+ //# sourceMappingURL=storage-DGYV332J.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-DGYV332J.d.ts","names":[],"sources":["../src/storage.ts"],"mappings":";KAEY,cAAA;EACX,GAAA;EACA,GAAA,GAAM,KAAA;EACN,SAAA,IAAa,KAAA;EACb,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;AAAA,cAEZ,mBAAA,EAAqB,qBAAqB;EACtD,GAAA;EACA,IAAA;AAAA;AAAA,cAwCY,oBAAA,EAAsB,qBAAqB;EACvD,GAAG;AAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resonare",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Resonare",
5
5
  "keywords": [
6
6
  "theming",
@@ -9,7 +9,7 @@
9
9
  ],
10
10
  "repository": {
11
11
  "type": "git",
12
- "url": "https://github.com/universse/resonare.git",
12
+ "url": "https://github.com/phuoccss/resonare.git",
13
13
  "directory": "resonare"
14
14
  },
15
15
  "license": "MIT",
@@ -24,6 +24,14 @@
24
24
  "./react": {
25
25
  "types": "./dist/react.d.ts",
26
26
  "import": "./dist/react.js"
27
+ },
28
+ "./lite": {
29
+ "types": "./dist/lite.d.ts",
30
+ "import": "./dist/lite.js"
31
+ },
32
+ "./lite/react": {
33
+ "types": "./dist/lite-react.d.ts",
34
+ "import": "./dist/lite-react.js"
27
35
  }
28
36
  },
29
37
  "types": "./dist/index.d.ts",
@@ -45,7 +53,7 @@
45
53
  "react": "19.2.5",
46
54
  "react-dom": "19.2.5",
47
55
  "size-limit": "12.1.0",
48
- "tsdown": "0.21.10",
56
+ "tsdown": "0.22.1",
49
57
  "typescript": "6.0.3",
50
58
  "vite": "8.0.10",
51
59
  "vitest": "4.1.5"