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/index.js.map CHANGED
@@ -1 +1 @@
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}',${JSON.stringify(flattenedConfig)},${handler}]`\n\t})\n\n\treturn `(${restoreScript})([${serializedArgs}])`\n}\n"],"mappings":"wDA+GA,SAAgBsC,EAAgDC,EAAW,CAC1E,OAAOC,OAAOC,QAAQF,CAAM,CAAC,CAACG,KAAK,CAACC,EAAUC,KACtC,CACND,GACCC,EAAYlC,SAAW,CAAA,EAAA,CAAIgC,IAAKG,GAChC,OAAOA,GAAW,SAAWA,EAAOvC,MAAQuC,CAC7C,CAAC,CAEF,CACF,CAEA,SAAgBC,EAA6CP,EAAW,CACvE,OAAOC,OAAOO,YACbP,OAAOC,QAAQF,CAAM,CAAC,CAACG,KAAK,CAACC,EAAUC,KAC/B,CACND,EACAC,EAAYhC,eACV,OAAOgC,EAAYlC,QAAQ,IAAO,SAChCkC,EAAYlC,QAAQ,EAAE,CAACJ,MACvBsC,EAAYlC,QAAQ,GAAG,CAE5B,CACF,CACD,CAEA,IAAMsC,EAAN,KAA6C,CAC5C,GAEA,GAEA,GAAgC,CAAC,EAEjC,GAEA,GAAmD,CAAC,EAEpD,GAA+B,IAAIM,IAEnC,GAAmB,IAAIE,gBAEvBC,YACClB,EACA,CACCL,YAAY,CAAC,EACbC,UAAUlC,EAAoB,CAAEyD,IAAK1D,CAAY,CAAC,GACzB,CAA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,qBAAqBgB,GAAY4E,EAEjCD,IAAiBD,IACpBF,EAAIzF,eAAeiB,GAAY4E,EAEjC,CAEA,OAAOJ,CACR,EACA,CAAE1F,OAAQ,CAAC,EAAGC,eAAgB,CAAC,EAAGC,qBAAsB,CAAC,CAAE,CAC5D,CACD,CACD,CAAC,CACF,EASA,SAAgB8F,EACfC,EACC,CAgCD,MAAO,IAAId,EAAa,MA9BvBvE,MAAMuF,QAAQF,CAAqB,EAChCA,EACA,CAACA,CAAqB,EAAA,CACxBhF,KAAK,CAAEgB,MAAM1D,EAAauC,SAAQwE,aAAc,CACjD,IAAMD,EAAkBtE,OAAOC,QAAQF,CAAM,CAAC,CAACG,KAC7C,CAACC,EAAU,CAAEjC,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"}
1
+ {"version":3,"file":"index.js","names":["toScriptJson","toScriptFunction","DEFAULT_KEY","memoryStorageAdapter","localStorageAdapter","getThemesAndOptions","config","themeKey","themeConfig","option","getDefaultThemes","createThemeStore","createStorage","defaultThemes","currentThemes","persisted","systemOptions","systemOption","mediaQuery","optionWhenMatched","optionWhenNotMatched","defaultPair","mediaQueryLists","listeners","abortController","storage","resolveSystemOption","server","pair","mqList","setThemesAndNotify","createSnapshot","resolvedSystemThemes","resolvedThemes","serverSnapshot","snapshot","themes","prev","listener","applyStored","parsed","stored","toPersist","pairs","setThemes","callback","restoreScript","params","key","flattenedConfig","handler","initial","systemOptionValue","currentValue","systemTheme","acc","createInlineThemeScript","serializedArgs","themeScriptParameters","firstOption","options","resolvedInitialValue","defaultValue","value","media"],"sources":["../src/index.ts"],"sourcesContent":["import { type StorageAdapterCreate, localStorageAdapter } from './storage'\nimport { DEFAULT_KEY, toScriptFunction, toScriptJson } from './utils'\n\nexport * from './storage'\n\ntype ThemeValue = string | number | boolean\n\ntype ThemeOption<T extends ThemeValue = string> = {\n value: T\n media?: readonly [string, T, T]\n}\n\ntype ThemeConfig<T extends ThemeValue = string> =\n | {\n options: ReadonlyArray<T | ThemeOption<T>>\n defaultValue?: T\n }\n | { defaultValue: T; options?: never }\n\n/**\n * Config for `createThemeStore`. Each key is a theme setting (`colorMode`,\n * `contrast`, …) with either:\n *\n * - `options`: the allowed values, plus an optional `defaultValue` (otherwise the\n * first option). One option may be a `{ value, media }` object: when it is\n * selected, the setting follows a media query, using `media[1]` while the\n * query matches and `media[2]` while it doesn't.\n * - `defaultValue` alone: a free value of that type, such as a number.\n *\n * @example\n * const config = {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * contrast: {\n * options: ['normal', 'more'],\n * },\n * sidebarWidth: {\n * defaultValue: 240,\n * },\n * } as const satisfies ThemeStoreConfig\n */\nexport type ThemeStoreConfig = Record<\n string,\n ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>\n>\n\n/**\n * The selected value of each setting, as passed to `setThemes` (e.g.\n * `colorMode: 'system'`). Inferred from your `ThemeStoreConfig`.\n */\nexport type Themes<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : T[K] extends { defaultValue: infer U }\n ? U extends string\n ? string\n : U extends number\n ? number\n : boolean\n : never\n}\n\ntype ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends { media: ReadonlyArray<unknown> }\n ? K\n : never\n : never\n}[keyof T]\n\ntype NonSystemOptionValues<\n T extends ThemeStoreConfig,\n K extends keyof T,\n> = T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeValue\n ? U\n : U extends ThemeOption\n ? U extends { media: ReadonlyArray<unknown> }\n ? never\n : U['value']\n : never\n : never\n\n/**\n * The values setting `K` can resolve to, as found in `resolvedThemes`: its\n * options without the `media` one, or the free value's type.\n */\nexport type ResolvedThemeValue<\n T extends ThemeStoreConfig,\n K extends keyof T,\n> = T[K] extends { options: ReadonlyArray<unknown> }\n ? NonSystemOptionValues<T, K>\n : Themes<T>[K]\n\n/**\n * For each setting with a `media` option, the value that option currently\n * resolves to, whether or not it is selected.\n */\ntype ResolvedSystemThemes<T extends ThemeStoreConfig> = {\n [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>\n}\n\n/** Runtime state for each dimension that defines a `media` option. */\ntype SystemOptions = Record<\n string,\n {\n value: string\n mediaQuery: string\n pair: [string, string]\n defaultPair: [string, string]\n }\n>\n\ntype Snapshot<T extends ThemeStoreConfig> = {\n themes: Themes<T>\n resolvedThemes: Themes<T>\n resolvedSystemThemes: ResolvedSystemThemes<T>\n}\n\n/** The state passed to listeners; see `getSnapshot`. */\nexport type ThemeSnapshot<T extends ThemeStoreConfig> = Snapshot<T>\n\n/**\n * Receives the new state and, except in the inline script (first paint), the\n * state before the change.\n */\ntype Listener<T extends ThemeStoreConfig> = (\n value: Snapshot<T>,\n prev?: Snapshot<T>\n) => void\n\ntype PersistedSystemOptionPairs = Record<string, [string, string]>\n\ntype PersistedState<T extends ThemeStoreConfig> = {\n themes: Partial<Themes<T>>\n systemOptions: PersistedSystemOptionPairs\n}\n\ntype ThemeStoreOptions<T extends ThemeStoreConfig> = {\n persisted?: Partial<PersistedState<T>>\n storage?: StorageAdapterCreate | null\n}\n\ntype ThemeAndOptions<T extends ThemeStoreConfig> = Array<\n {\n [K in keyof T]: [\n K,\n Array<\n T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : never\n >,\n ]\n }[keyof T]\n>\n\n/**\n * Lists each setting with its option values (`{ value, media }` options become\n * their `value`). Useful for rendering a picker for every setting.\n *\n * @example\n * import { getThemesAndOptions } from 'resonare'\n *\n * getThemesAndOptions({\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * },\n * })\n * // [['colorMode', ['light', 'dark', 'system']]]\n */\nexport function getThemesAndOptions<T extends ThemeStoreConfig>(config: T) {\n return Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n (themeConfig.options || []).map((option) => {\n return typeof option === 'object' ? option.value : option\n }),\n ]\n }) as ThemeAndOptions<T>\n}\n\n/**\n * Returns each setting's default: its `defaultValue`, or else its first\n * option.\n *\n * @example\n * import { getDefaultThemes } from 'resonare'\n *\n * getDefaultThemes({\n * colorMode: { options: ['light', 'dark'], defaultValue: 'dark' },\n * }) // { colorMode: 'dark' }\n */\nexport function getDefaultThemes<T extends ThemeStoreConfig>(config: T) {\n return Object.fromEntries(\n Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n themeConfig.defaultValue ??\n (typeof themeConfig.options[0] === 'object'\n ? themeConfig.options[0].value\n : themeConfig.options[0]),\n ]\n })\n ) as Themes<T>\n}\n\n/**\n * Creates a store for the settings in `config`. It saves changes through\n * `storage` (`localStorage` under the key `'resonare'` by default; `null`\n * disables saving), resolves `media` options in the browser, and notifies\n * subscribers.\n *\n * Read state with `getSnapshot()` or `subscribe`.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * },\n * { storage: localStorageAdapter({ key: 'my-app' }) }\n * )\n *\n * // In the browser: load the saved choice and follow other tabs.\n * store.restore()\n * store.sync()\n *\n * store.subscribe(({ resolvedThemes }) => {\n * document.documentElement.dataset.colorMode = resolvedThemes.colorMode\n * })\n *\n * store.setThemes({ colorMode: 'dark' })\n */\nexport function createThemeStore<T extends ThemeStoreConfig>(\n config: T,\n {\n persisted = {},\n storage: createStorage = localStorageAdapter({ key: DEFAULT_KEY }),\n }: ThemeStoreOptions<T> = {}\n) {\n const defaultThemes = getDefaultThemes(config)\n\n let currentThemes: Themes<T> = { ...defaultThemes, ...persisted.themes }\n\n const systemOptions: SystemOptions = {}\n\n for (const themeKey in config) {\n const systemOption = (config[themeKey]!.options || []).find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const {\n value,\n media: [mediaQuery, optionWhenMatched, optionWhenNotMatched],\n } = systemOption\n\n const defaultPair: [string, string] = [\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n\n systemOptions[themeKey] = {\n value,\n mediaQuery,\n pair: [...(persisted.systemOptions?.[themeKey] ?? defaultPair)],\n defaultPair,\n }\n }\n }\n\n const mediaQueryLists: Record<string, MediaQueryList> = {}\n\n const listeners = new Set<Listener<T>>()\n\n const abortController = new AbortController()\n\n const storage = createStorage?.({ abortController })\n\n const resolveSystemOption = (themeKey: string, server?: boolean): string => {\n const { mediaQuery, pair } = systemOptions[themeKey]!\n\n // No media support (e.g. on the server): use the \"not matched\" value.\n if (server || typeof matchMedia === 'undefined') {\n return pair[1]\n }\n\n let mqList = mediaQueryLists[mediaQuery]\n\n if (!mqList) {\n mqList = mediaQueryLists[mediaQuery] = matchMedia(mediaQuery)\n\n mqList.addEventListener(\n 'change',\n () => {\n setThemesAndNotify()\n },\n abortController\n )\n }\n\n return pair[mqList.matches ? 0 : 1]\n }\n\n const createSnapshot = (server?: boolean): Snapshot<T> => {\n const resolvedSystemThemes: Record<string, string> = {}\n\n const resolvedThemes = { ...currentThemes } as Record<string, ThemeValue>\n\n for (const themeKey in systemOptions) {\n resolvedSystemThemes[themeKey] = resolveSystemOption(themeKey, server)\n\n if (resolvedThemes[themeKey] === systemOptions[themeKey]!.value) {\n resolvedThemes[themeKey] = resolvedSystemThemes[themeKey]\n }\n }\n\n return {\n themes: currentThemes,\n resolvedThemes: resolvedThemes as Themes<T>,\n resolvedSystemThemes: resolvedSystemThemes as ResolvedSystemThemes<T>,\n }\n }\n\n const serverSnapshot = createSnapshot(true)\n\n let snapshot = createSnapshot()\n\n const setThemesAndNotify = (themes?: Partial<Themes<T>>): void => {\n currentThemes = { ...currentThemes, ...themes }\n\n const prev = snapshot\n\n snapshot = createSnapshot()\n\n for (const listener of listeners) {\n listener(snapshot, prev)\n }\n }\n\n /** Applies saved state; ignores empty or malformed input. */\n const applyStored = (stored: string | null | undefined): void => {\n let parsed: PersistedState<T> | undefined\n\n try {\n parsed = stored ? JSON.parse(stored) : undefined\n } catch {}\n\n if (!parsed?.themes || typeof parsed.themes !== 'object') {\n return\n }\n\n for (const themeKey in parsed.systemOptions) {\n const pair = parsed.systemOptions[themeKey]\n\n if (pair && systemOptions[themeKey]) {\n systemOptions[themeKey].pair = pair\n }\n }\n\n setThemesAndNotify(parsed.themes)\n }\n\n const toPersist = (): PersistedState<T> => {\n const pairs: PersistedSystemOptionPairs = {}\n\n for (const themeKey in systemOptions) {\n pairs[themeKey] = [...systemOptions[themeKey]!.pair]\n }\n\n return { themes: { ...currentThemes }, systemOptions: pairs }\n }\n\n const setThemes = (\n themes:\n | Partial<Themes<T>>\n | ((currentThemes: Themes<T>) => Partial<Themes<T>>)\n ): void => {\n setThemesAndNotify(\n typeof themes === 'function' ? themes(currentThemes) : themes\n )\n\n if (storage) {\n const stored = JSON.stringify(toPersist())\n\n storage.set(stored)\n\n storage.broadcast?.(stored)\n }\n }\n\n return {\n /**\n * Current state:\n *\n * - `themes`: the selected value of each setting (e.g. `'system'`).\n * - `resolvedThemes`: the same with `media` options resolved (e.g. `'dark'`).\n * - `resolvedSystemThemes`: what each `media` option resolves to, even when\n * it isn't selected.\n *\n * Returns the same object until the next change.\n */\n getSnapshot: (): Snapshot<T> => {\n return snapshot\n },\n\n /**\n * The state as rendered on the server: defaults plus `persisted`, with\n * `media` options resolved to their \"not matched\" value. It never changes,\n * so hydration can match the server HTML even after `restore()`.\n */\n getServerSnapshot: (): Snapshot<T> => {\n return serverSnapshot\n },\n\n /**\n * Updates the given settings (others keep their value), saves to storage,\n * and notifies subscribers.\n *\n * @example\n * store.setThemes({ colorMode: 'dark' })\n *\n * store.setThemes((current) => ({\n * colorMode: current.colorMode === 'dark' ? 'light' : 'dark',\n * }))\n */\n setThemes,\n\n /**\n * Changes which values a `media` option resolves to: `[whenMatched,\n * whenNotMatched]`, replacing `media[1]` and `media[2]` from the config.\n * Saved like `setThemes`.\n *\n * @example\n * // system now picks 'dark-dimmed' when the OS prefers dark\n * store.updateSystemOption('colorMode', ['dark-dimmed', 'light'])\n */\n updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(\n themeKey: K,\n pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]\n ): void => {\n systemOptions[themeKey as string]!.pair = [...pair]\n\n setThemes({})\n },\n\n /**\n * The state to save, e.g. to a database: pass it back as `persisted` when\n * creating the store.\n */\n toPersist,\n\n /**\n * Loads the saved state from storage. Does nothing when nothing is saved.\n * Call it in the browser, e.g. after hydration.\n */\n restore: (): void => {\n applyStored(storage?.get())\n },\n\n /**\n * Calls `callback` with the new state (see `getSnapshot`) and the state\n * before it after every change, including OS preference changes. Returns\n * an unsubscribe function.\n */\n subscribe: (callback: Listener<T>): (() => void) => {\n listeners.add(callback)\n\n return () => {\n listeners.delete(callback)\n }\n },\n\n /**\n * Applies changes saved by other tabs (if the storage adapter supports\n * it); when another tab clears the saved state, resets to the config\n * defaults. Returns a function that stops syncing, or `undefined` when the\n * adapter can't sync.\n */\n sync: (): (() => void) | undefined => {\n return storage?.watch?.((stored) => {\n // `null` means another tab cleared the stored preferences.\n if (stored === null) {\n for (const themeKey in systemOptions) {\n const systemOption = systemOptions[themeKey]!\n\n systemOption.pair = systemOption.defaultPair\n }\n\n setThemesAndNotify(defaultThemes)\n } else {\n applyStored(stored)\n }\n })\n },\n\n /**\n * Removes all subscribers and stops listening to media queries and\n * storage. The store doesn't update after this.\n */\n destroy: (): void => {\n listeners.clear()\n\n abortController.abort()\n },\n }\n}\n\nexport type ThemeStore<T extends ThemeStoreConfig> = ReturnType<\n typeof createThemeStore<T>\n>\n\nconst restoreScript = <T extends ThemeValue>(\n params: Array<\n [\n string,\n Array<[string, T] | [string, T, T, string, T, T]>,\n (state: object) => void,\n ]\n >\n) => {\n params.forEach(([key, flattenedConfig, handler]) => {\n let persisted:\n | {\n themes?: Record<string, T>\n systemOptions?: Record<string, [T, T]>\n }\n | null\n | undefined\n\n // Blocked storage or bad JSON must not stop the handler from running.\n try {\n persisted = JSON.parse(localStorage.getItem(key)!)\n } catch {}\n\n handler(\n flattenedConfig.reduce<{\n themes: Record<string, ThemeValue>\n resolvedThemes: Record<string, ThemeValue>\n resolvedSystemThemes: Record<string, ThemeValue>\n }>(\n (\n acc,\n [\n themeKey,\n initial,\n systemOptionValue,\n mediaQuery,\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n ) => {\n const currentValue = persisted?.themes?.[themeKey] ?? initial\n\n acc.resolvedThemes[themeKey] = acc.themes[themeKey] = currentValue\n\n if (mediaQuery != null) {\n const pair = persisted?.systemOptions?.[themeKey] ?? [\n optionWhenMatched!,\n optionWhenNotMatched!,\n ]\n\n const systemTheme = matchMedia(mediaQuery).matches\n ? pair[0]\n : pair[1]\n\n acc.resolvedSystemThemes[themeKey] = systemTheme\n\n if (currentValue === systemOptionValue) {\n acc.resolvedThemes[themeKey] = systemTheme\n }\n }\n\n return acc\n },\n { themes: {}, resolvedThemes: {}, resolvedSystemThemes: {} }\n )\n )\n })\n}\n\n/** One store for `createInlineThemeScript`. */\nexport type ThemeScriptParameter = {\n /** The store's `localStorage` key; defaults to `'resonare'`. */\n key?: string\n /** The same config passed to `createThemeStore`. */\n config: ThemeStoreConfig\n /**\n * Applies the state to the page; receives the same value as `subscribe`.\n * It is copied into the script as source code, so it can't use variables\n * from outside the function. Typed loosely so a handler fits any config.\n */\n // oxlint-disable-next-line typescript/no-explicit-any\n handler: Listener<any>\n}\n\n/**\n * Returns the source of a small script that reads the saved state from\n * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in\n * the `<head>` so the page has the right theme before first paint. Pass an\n * array to set up several stores.\n *\n * Use the same handler with `store.subscribe` to keep the page updated after\n * that.\n *\n * @example\n * import { createInlineThemeScript } from 'resonare'\n *\n * // config: the same object passed to createThemeStore\n * const themeScript = createInlineThemeScript({\n * key: 'my-app',\n * config,\n * handler: ({ resolvedThemes }) => {\n * const root = document.documentElement\n * root.dataset.colorMode = resolvedThemes.colorMode\n * },\n * })\n *\n * // In <head>:\n * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />\n */\nexport function createInlineThemeScript(\n themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>\n) {\n const serializedArgs = (\n Array.isArray(themeScriptParameters)\n ? themeScriptParameters\n : [themeScriptParameters]\n ).map(({ key = DEFAULT_KEY, config, handler }) => {\n const flattenedConfig = Object.entries(config).map(\n ([themeKey, { options, defaultValue }]) => {\n const firstOption = options?.[0]\n\n const resolvedInitialValue =\n defaultValue ??\n (typeof firstOption === 'object' ? firstOption.value : firstOption!)\n\n const systemOption = options?.find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const { value, media } = systemOption\n\n return [themeKey, resolvedInitialValue, value, ...media]\n }\n\n return [themeKey, resolvedInitialValue]\n }\n )\n\n return `[${toScriptJson(key)},${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AAOA,GAAY8C,EAElDnC,GAAc,KAAM,CACtB,IAAMU,EAAOb,GAAW,gBAAgBR,IAAa,CACnDY,EACAC,CACF,EAEMkC,EAAc,WAAWpC,CAAU,CAAC,CAAC,QACvCU,EAAK,GACLA,EAAK,GAET,EAAI,qBAAqBrB,GAAY+C,EAEjCD,IAAiBD,IACnB,EAAI,eAAe7C,GAAY+C,EAEnC,CAEA,OAAOC,CACT,EACA,CAAE,OAAQ,CAAC,EAAG,eAAgB,CAAC,EAAG,qBAAsB,CAAC,CAAE,CAC7D,CACF,CACF,CAAC,CACH,EA0CA,SAAgBC,EACd,EACA,CACA,IAAMC,GACJ,MAAM,QAAQC,CAAqB,EAC/BA,EACA,CAACA,CAAqB,EAAA,CAC1B,KAAK,CAAE,MAAMxD,EAAa,SAAQ,aAAc,CAChD,IAAM+C,EAAkB,OAAO,QAAQ3C,CAAM,CAAC,CAAC,KAC5C,CAACC,EAAU,CAAE,UAAS,mBAAoB,CACzC,IAAMoD,EAAcC,IAAU,GAExBC,EACJC,IACC,OAAOH,GAAgB,SAAWA,EAAY,MAAQA,GAEnD1C,EAAe2C,GAAS,KAC3B,GACQ,OAAOnD,GAAW,UAAY,CAAC,CAACA,EAAO,KAElD,EAEA,GAAIQ,EAAc,CAChB,GAAM,CAAE,QAAO,SAAUA,EAEzB,MAAO,CAACV,EAAUsD,EAAsBE,EAAO,GAAGC,CAAK,CACzD,CAEA,MAAO,CAACzD,EAAUsD,CAAoB,CACxC,CACF,EAEA,MAAO,IAAI7D,EAAagD,CAAG,EAAE,GAAGhD,EAAaiD,CAAe,EAAE,GAAGhD,EAAiBiD,CAAO,EAAE,EAC7F,CAAC,EAED,MAAO,IAAIJ,EAAc,KAAKW,EAAe,GAC/C,C"}
@@ -0,0 +1,65 @@
1
+ import { n as combine, t as Effect } from "./effects-core-DPJyVK-w.js";
2
+ import { ThemeSnapshot } from "./lite.js";
3
+ /**
4
+ * Turns `run(state, prev, options)` into a factory of effects that work both
5
+ * with `store.subscribe` and as (part of) the inline script's `handler`.
6
+ * `run` is copied into the script as source code, so it can't use variables
7
+ * from outside the function; pass what it needs through `options`, which must
8
+ * be JSON-serializable. `prev` is `undefined` on first paint.
9
+ *
10
+ * @example
11
+ * const favicon = defineEffect<{ light: string; dark: string }>(
12
+ * ({ resolvedTheme }, _prev, options) => {
13
+ * document.querySelector('link[rel=icon]')!.href = options[resolvedTheme]
14
+ * }
15
+ * )
16
+ *
17
+ * const applyTheme = combine(
18
+ * setDataAttributes(),
19
+ * favicon({ light: '/light.svg', dark: '/dark.svg' })
20
+ * )
21
+ */
22
+ export declare const defineEffect: <O extends object = Record<never, never>>(run: (state: ThemeSnapshot, prev: ThemeSnapshot | undefined, options: O) => void) => (options?: O) => Effect;
23
+ /**
24
+ * Writes the resolved theme to a `data-*` attribute on `<html>`:
25
+ * `data-theme="dark"` by default, or another name through `key` (e.g.
26
+ * `'colorScheme'` for `data-color-scheme`).
27
+ */
28
+ export declare const setDataAttributes: (options?: {
29
+ key?: string;
30
+ }) => Effect;
31
+ /**
32
+ * Adds a class for the resolved theme on `<html>`: `light` or `dark` by
33
+ * default, e.g. for Tailwind's or shadcn's `.dark` selectors. Rename them, or
34
+ * pass `null` for no class (e.g. `{ light: null }` for only `.dark`);
35
+ * `undefined` keeps the default. The other theme's class is removed.
36
+ */
37
+ export declare const setClassNames: ({ light, dark }?: {
38
+ light?: string | null;
39
+ dark?: string | null;
40
+ }) => Effect;
41
+ /**
42
+ * Sets the CSS `color-scheme` of `<html>`, so scrollbars, form controls and
43
+ * the default canvas match.
44
+ */
45
+ export declare const setColorScheme: () => Effect;
46
+ /**
47
+ * Keeps `<meta name="theme-color">` in sync with the theme, so the browser UI
48
+ * follows the user's choice rather than the OS. Existing tags (media-based
49
+ * ones included) all get the color; with none, one is added. Give a color for
50
+ * each theme, or `cssVar` to read one from `<html>` (list this after the
51
+ * effect that sets your attributes).
52
+ */
53
+ export declare const setThemeColor: (options: {
54
+ light: string;
55
+ dark: string;
56
+ } | {
57
+ cssVar: string;
58
+ }) => Effect;
59
+ /**
60
+ * Turns off CSS transitions for one frame when the theme changes, so colors
61
+ * switch at once instead of animating. Does nothing on first paint.
62
+ */
63
+ export declare const disableTransitions: () => Effect;
64
+ export { type Effect, combine };
65
+ //# sourceMappingURL=lite-effects.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-effects.d.ts","names":[],"sources":["../src/lite-effects.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAsCa,eACX,mBAAmB,sBAEnB,MACE,OAAO,eACP,MAAM,2BACN,SAAS,gBAEP,UAAU,MAAM;;;;;;qBAOT,oBAAiB;EAAe;MAAsB;;;;;;;qBAmBtD,kBAAa,OAAA;EAGrB;EAAuB;MAA8B;;;;;qBAmB7C,sBAAqB;;;;;;;;qBAWrB,gBAAa;EACb;EAAe;;EAAmB;MAC5C;;;;;qBAYU,0BAAyB"}
@@ -0,0 +1,2 @@
1
+ import{a as e,c as t,i as n,n as r,o as i,r as a,s as o,t as s}from"./effects-core-CuoeZrRP.js";const c=e=>e.resolvedTheme,l=a,u=(e={})=>r((e,{key:t})=>({[t??`theme`]:e.resolvedTheme}),i,e),d=({light:e,dark:t}={})=>r(e=>({theme:e.resolvedTheme}),n,{theme:{light:e===void 0?`light`:e,dark:t===void 0?`dark`:t}}),f=()=>r(c,e,{}),p=e=>r(c,t,`cssVar`in e?e:{values:e}),m=()=>r(c,o,{},!0);export{s as combine,l as defineEffect,m as disableTransitions,d as setClassNames,f as setColorScheme,u as setDataAttributes,p as setThemeColor};
2
+ //# sourceMappingURL=lite-effects.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-effects.js","names":["defineCoreEffect","runColorScheme","runThemeColor","runClassNames","createEffect","runDataAttributes","defineEffect$1","runDisableTransitions","combine","selectTheme","state","defineEffect","setDataAttributes","key","options","setClassNames","light","dark","setColorScheme","setThemeColor","disableTransitions"],"sources":["../src/lite-effects.ts"],"sourcesContent":["import {\n type Effect,\n combine,\n createEffect,\n defineEffect as defineCoreEffect,\n runClassNames,\n runColorScheme,\n runDataAttributes,\n runDisableTransitions,\n runThemeColor,\n} from './effects-core'\nimport type { ThemeSnapshot } from './lite'\n\nexport { type Effect, combine }\n\nconst selectTheme = (state: ThemeSnapshot): string => {\n return state.resolvedTheme\n}\n\n/**\n * Turns `run(state, prev, options)` into a factory of effects that work both\n * with `store.subscribe` and as (part of) the inline script's `handler`.\n * `run` is copied into the script as source code, so it can't use variables\n * from outside the function; pass what it needs through `options`, which must\n * be JSON-serializable. `prev` is `undefined` on first paint.\n *\n * @example\n * const favicon = defineEffect<{ light: string; dark: string }>(\n * ({ resolvedTheme }, _prev, options) => {\n * document.querySelector('link[rel=icon]')!.href = options[resolvedTheme]\n * }\n * )\n *\n * const applyTheme = combine(\n * setDataAttributes(),\n * favicon({ light: '/light.svg', dark: '/dark.svg' })\n * )\n */\nexport const defineEffect = defineCoreEffect as <\n O extends object = Record<never, never>,\n>(\n run: (\n state: ThemeSnapshot,\n prev: ThemeSnapshot | undefined,\n options: O\n ) => void\n) => (options?: O) => Effect\n\n/**\n * Writes the resolved theme to a `data-*` attribute on `<html>`:\n * `data-theme=\"dark\"` by default, or another name through `key` (e.g.\n * `'colorScheme'` for `data-color-scheme`).\n */\nexport const setDataAttributes = (options: { key?: string } = {}): Effect => {\n return createEffect(\n (\n state: ThemeSnapshot,\n { key }: { key?: string }\n ): Record<string, unknown> => {\n return { [key ?? 'theme']: state.resolvedTheme }\n },\n runDataAttributes,\n options\n )\n}\n\n/**\n * Adds a class for the resolved theme on `<html>`: `light` or `dark` by\n * default, e.g. for Tailwind's or shadcn's `.dark` selectors. Rename them, or\n * pass `null` for no class (e.g. `{ light: null }` for only `.dark`);\n * `undefined` keeps the default. The other theme's class is removed.\n */\nexport const setClassNames = ({\n light,\n dark,\n}: { light?: string | null; dark?: string | null } = {}): Effect => {\n return createEffect(\n (state: ThemeSnapshot): Record<string, unknown> => {\n return { theme: state.resolvedTheme }\n },\n runClassNames,\n {\n theme: {\n light: light === undefined ? 'light' : light,\n dark: dark === undefined ? 'dark' : dark,\n },\n }\n )\n}\n\n/**\n * Sets the CSS `color-scheme` of `<html>`, so scrollbars, form controls and\n * the default canvas match.\n */\nexport const setColorScheme = (): Effect => {\n return createEffect(selectTheme, runColorScheme, {})\n}\n\n/**\n * Keeps `<meta name=\"theme-color\">` in sync with the theme, so the browser UI\n * follows the user's choice rather than the OS. Existing tags (media-based\n * ones included) all get the color; with none, one is added. Give a color for\n * each theme, or `cssVar` to read one from `<html>` (list this after the\n * effect that sets your attributes).\n */\nexport const setThemeColor = (\n options: { light: string; dark: string } | { cssVar: string }\n): Effect => {\n return createEffect(\n selectTheme,\n runThemeColor,\n 'cssVar' in options ? options : { values: options }\n )\n}\n\n/**\n * Turns off CSS transitions for one frame when the theme changes, so colors\n * switch at once instead of animating. Does nothing on first paint.\n */\nexport const disableTransitions = (): Effect => {\n return createEffect(selectTheme, runDisableTransitions, {}, true)\n}\n"],"mappings":"A,gGAeA,MAAMS,EAAe,GACZC,EAAM,cAsBFC,EAAeX,EAefY,GAAqB,EAA4B,CAAC,IACtDR,GAEH,EACA,CAAE,UAEK,EAAGS,GAAO,SAAUH,EAAM,aAAc,GAEjDL,EACAS,CACF,EASWC,GAAiB,CAC5B,QACA,QACmD,CAAC,IAC7CX,EACJ,IACQ,CAAE,MAAOM,EAAM,aAAc,GAEtCP,EACA,CACE,MAAO,CACL,MAAOa,IAAU,IAAA,GAAY,QAAUA,EACvC,KAAMC,IAAS,IAAA,GAAY,OAASA,CACtC,CACF,CACF,EAOWC,MACJd,EAAaK,EAAaR,EAAgB,CAAC,CAAC,EAUxCkB,EACX,GAEOf,EACLK,EACAP,EACA,WAAYY,EAAUA,EAAU,CAAE,OAAQA,CAAQ,CACpD,EAOWM,MACJhB,EAAaK,EAAaF,EAAuB,CAAC,EAAG,EAAI,E"}
@@ -1,36 +1,45 @@
1
1
  import { ThemeStore } from "./lite.js";
2
-
3
- //#region src/lite-react.d.ts
4
2
  /**
5
- * Subscribes a React component to a lite (light/dark/system) 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
- * import { createThemeStore } from 'resonare/lite'
9
- * import { useResonare } from 'resonare/lite/react'
8
+ * import { createThemeStore } from 'resonare/lite'
9
+ * import { useResonare } from 'resonare/lite/react'
10
10
  *
11
- * const store = createThemeStore()
11
+ * const store = createThemeStore()
12
12
  *
13
- * export function ThemeToggle() {
14
- * const { theme, resolvedTheme, systemTheme, setTheme } = useResonare(store)
13
+ * function ThemeToggle() {
14
+ * const { resolvedTheme, setTheme } = useResonare(store)
15
15
  *
16
- * // ...
17
- * }
18
- * ```
16
+ * return (
17
+ * <button
18
+ * onClick={() => {
19
+ * setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')
20
+ * }}
21
+ * >
22
+ * {resolvedTheme}
23
+ * </button>
24
+ * )
25
+ * }
19
26
  */
20
- declare function useResonare(store: ThemeStore): {
27
+ export declare function useResonare(store: ThemeStore): {
28
+ theme: "dark" | "light" | "system";
29
+ resolvedTheme: "dark" | "light";
30
+ systemTheme: "dark" | "light";
21
31
  destroy: () => void;
22
32
  restore: () => void;
23
- setTheme: (theme: ("system" | "light" | "dark") | ((current: "system" | "light" | "dark") => "system" | "light" | "dark")) => void;
33
+ setTheme: (next: ("dark" | "light" | "system") | ((current: "dark" | "light" | "system") => "dark" | "light" | "system")) => void;
24
34
  subscribe: (callback: (value: {
25
- theme: "system" | "light" | "dark";
26
- resolvedTheme: "light" | "dark";
27
- systemTheme: "light" | "dark";
35
+ theme: "dark" | "light" | "system";
36
+ resolvedTheme: "dark" | "light";
37
+ systemTheme: "dark" | "light";
38
+ }, prev?: {
39
+ theme: "dark" | "light" | "system";
40
+ resolvedTheme: "dark" | "light";
41
+ systemTheme: "dark" | "light";
28
42
  }) => void) => (() => void);
29
43
  sync: () => (() => void) | undefined;
30
- theme: "system" | "light" | "dark";
31
- resolvedTheme: "light" | "dark";
32
- systemTheme: "light" | "dark";
33
44
  };
34
- //#endregion
35
- export { useResonare };
36
45
  //# sourceMappingURL=lite-react.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lite-react.d.ts","names":[],"sources":["../src/lite-react.ts"],"mappings":";;;;;AAmBA;;;;;;;;;;;;;;iBAAgB,WAAA,CAAY,KAAA,EAAO,UAAU"}
1
+ {"version":3,"file":"lite-react.d.ts","names":[],"sources":["../src/lite-react.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;wBA6BgB,YAAY,OAAO"}
@@ -1,2 +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};
1
+ import{c as e}from"react/compiler-runtime";import*as t from"react";function n(n){let r=e(7),{destroy:i,getServerSnapshot:a,getSnapshot:o,restore:s,setTheme:c,subscribe:l,sync:u}=n,d=t.useSyncExternalStore(l,o,a),f;return r[0]!==i||r[1]!==s||r[2]!==c||r[3]!==d||r[4]!==l||r[5]!==u?(f={...d,destroy:i,restore:s,setTheme:c,subscribe:l,sync:u},r[0]=i,r[1]=s,r[2]=c,r[3]=d,r[4]=l,r[5]=u,r[6]=f):f=r[6],f}export{n as useResonare};
2
2
  //# sourceMappingURL=lite-react.js.map
@@ -1 +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"}
1
+ {"version":3,"file":"lite-react.js","names":["{ ...snapshot, destroy, restore, setTheme, subscribe, sync }","_c","React","useResonare","$","c","store","snapshot","subscribe","getSnapshot","getServerSnapshot","t0","destroy","restore","setTheme","sync"],"sources":["../src/lite-react.ts"],"sourcesContent":["import * as React from 'react'\n\nimport type { ThemeStore } from './lite'\n\n/**\n * Returns the store's current state (see `store.getSnapshot()`) and its\n * methods, and re-renders the component when the state changes. Server\n * rendering and hydration are handled automatically.\n *\n * @example\n * import { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/react'\n *\n * const store = createThemeStore()\n *\n * function ThemeToggle() {\n * const { resolvedTheme, setTheme } = useResonare(store)\n *\n * return (\n * <button\n * onClick={() => {\n * setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')\n * }}\n * >\n * {resolvedTheme}\n * </button>\n * )\n * }\n */\nexport function useResonare(store: ThemeStore) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setTheme,\n subscribe,\n sync,\n } = store\n\n const snapshot = React.useSyncExternalStore(\n subscribe,\n getSnapshot,\n getServerSnapshot\n )\n\n return { ...snapshot, destroy, restore, setTheme, subscribe, sync }\n}\n"],"mappings":"A,mEA6BA,SAAgBG,EAAY,EAAmB,C,WACvC,CACJ,UACA,oBACA,cACA,UACA,WACA,YACA,QACEG,EAEEC,EAAWL,EAAM,qBACrBM,EACAC,EACAC,CACF,EAEOV,EAAP,OAAsBI,EAAA,KAAAQ,GAAAR,EAAA,KAASS,GAAAT,EAAA,KAASU,GAAAV,EAAA,KAA5BG,GAAAH,EAAA,KAAsCI,GAAAJ,EAAA,KAAWW,GAAtD,EAAA,CAAE,GAAGR,EAAU,UAAS,UAAS,WAAU,YAAW,MAAK,EAA5C,EAAA,GAAAK,EAAS,EAAA,GAAAC,EAAS,EAAA,GAAAC,EAA5B,EAAA,GAAAP,EAAsC,EAAA,GAAAC,EAAW,EAAA,GAAAO,E,eAAtDf,CACT,C"}
@@ -0,0 +1,46 @@
1
+ import { ThemeStore } from "./lite.js";
2
+ /**
3
+ * Returns the store's state as signals (`theme()`, `resolvedTheme()`,
4
+ * `systemTheme()`) 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 { createThemeStore } from 'resonare/lite'
10
+ * import { useResonare } from 'resonare/lite/solid'
11
+ *
12
+ * const store = createThemeStore()
13
+ *
14
+ * function ThemeToggle() {
15
+ * const { resolvedTheme, setTheme } = useResonare(store)
16
+ *
17
+ * return (
18
+ * <button
19
+ * onClick={() => {
20
+ * setTheme(resolvedTheme() === 'dark' ? 'light' : 'dark')
21
+ * }}
22
+ * >
23
+ * {resolvedTheme()}
24
+ * </button>
25
+ * )
26
+ * }
27
+ */
28
+ export declare function useResonare(store: ThemeStore): {
29
+ theme: () => "dark" | "light" | "system";
30
+ resolvedTheme: () => "dark" | "light";
31
+ systemTheme: () => "dark" | "light";
32
+ destroy: () => void;
33
+ restore: () => void;
34
+ setTheme: (next: ("dark" | "light" | "system") | ((current: "dark" | "light" | "system") => "dark" | "light" | "system")) => void;
35
+ subscribe: (callback: (value: {
36
+ theme: "dark" | "light" | "system";
37
+ resolvedTheme: "dark" | "light";
38
+ systemTheme: "dark" | "light";
39
+ }, prev?: {
40
+ theme: "dark" | "light" | "system";
41
+ resolvedTheme: "dark" | "light";
42
+ systemTheme: "dark" | "light";
43
+ }) => void) => (() => void);
44
+ sync: () => (() => void) | undefined;
45
+ };
46
+ //# sourceMappingURL=lite-solid.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-solid.d.ts","names":[],"sources":["../src/lite-solid.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;wBA8BgB,YAAY,OAAO"}
@@ -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,setTheme:l,subscribe:u,sync:d}=i,f=!!r.context,[p,m]=e(f?o():s()),h=u(e=>{m(()=>e)});return t(h),f&&n(()=>{m(()=>s())}),{theme:()=>p().theme,resolvedTheme:()=>p().resolvedTheme,systemTheme:()=>p().systemTheme,destroy:a,restore:c,setTheme:l,subscribe:u,sync:d}}export{i as useResonare};
2
+ //# sourceMappingURL=lite-solid.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-solid.js","names":["useResonare","store","hydrating","sharedConfig","snapshot","setSnapshot","createSignal","getServerSnapshot","getSnapshot","unsubscribe","subscribe","value","onCleanup","onMount"],"sources":["../src/lite-solid.ts"],"sourcesContent":["import { createSignal, onCleanup, onMount, sharedConfig } from 'solid-js'\n\nimport type { ThemeStore } from './lite'\n\n/**\n * Returns the store's state as signals (`theme()`, `resolvedTheme()`,\n * `systemTheme()`) 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 { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/solid'\n *\n * const store = createThemeStore()\n *\n * function ThemeToggle() {\n * const { resolvedTheme, setTheme } = useResonare(store)\n *\n * return (\n * <button\n * onClick={() => {\n * setTheme(resolvedTheme() === 'dark' ? 'light' : 'dark')\n * }}\n * >\n * {resolvedTheme()}\n * </button>\n * )\n * }\n */\nexport function useResonare(store: ThemeStore) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setTheme,\n subscribe,\n sync,\n } = store\n\n // 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 theme: () => {\n return snapshot().theme\n },\n resolvedTheme: () => {\n return snapshot().resolvedTheme\n },\n systemTheme: () => {\n return snapshot().systemTheme\n },\n destroy,\n restore,\n setTheme,\n subscribe,\n sync,\n }\n}\n"],"mappings":"A,sFA8BA,SAAgBA,EAAY,EAAmB,CAC7C,GAAM,CACJ,UACA,oBACA,cACA,UACA,WACA,YACA,QACEC,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,UACSJ,EAAS,CAAC,CAAC,MAEpB,kBACSA,EAAS,CAAC,CAAC,cAEpB,gBACSA,EAAS,CAAC,CAAC,YAEpB,UACA,UACA,WACA,YACA,MACF,CACF,C"}
@@ -0,0 +1,45 @@
1
+ import { ThemeStore } from "./lite.js";
2
+ /**
3
+ * Returns the store's state (`theme`, `resolvedTheme`, `systemTheme`), each
4
+ * read through `.current`, and its methods. `.current` is reactive in
5
+ * templates, `$derived` and `$effect`, and the store is subscribed only while
6
+ * something reads it. Hydration needs nothing extra: Svelte fixes any markup
7
+ * that differs from the server's.
8
+ *
9
+ * @example
10
+ * <script lang="ts">
11
+ * import { createThemeStore } from 'resonare/lite'
12
+ * import { useResonare } from 'resonare/lite/svelte'
13
+ *
14
+ * const store = createThemeStore()
15
+ * const { resolvedTheme, setTheme } = useResonare(store)
16
+ * </script>
17
+ *
18
+ * <p>Theme: {resolvedTheme.current}</p>
19
+ * <button onclick={() => setTheme('dark')}>Dark</button>
20
+ */
21
+ export declare function useResonare(store: ThemeStore): {
22
+ theme: {
23
+ readonly current: "dark" | "light" | "system";
24
+ };
25
+ resolvedTheme: {
26
+ readonly current: "dark" | "light";
27
+ };
28
+ systemTheme: {
29
+ readonly current: "dark" | "light";
30
+ };
31
+ destroy: () => void;
32
+ restore: () => void;
33
+ setTheme: (next: ("dark" | "light" | "system") | ((current: "dark" | "light" | "system") => "dark" | "light" | "system")) => void;
34
+ subscribe: (callback: (value: {
35
+ theme: "dark" | "light" | "system";
36
+ resolvedTheme: "dark" | "light";
37
+ systemTheme: "dark" | "light";
38
+ }, prev?: {
39
+ theme: "dark" | "light" | "system";
40
+ resolvedTheme: "dark" | "light";
41
+ systemTheme: "dark" | "light";
42
+ }) => void) => (() => void);
43
+ sync: () => (() => void) | undefined;
44
+ };
45
+ //# sourceMappingURL=lite-svelte.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-svelte.d.ts","names":[],"sources":["../src/lite-svelte.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;wBAuBgB,YAAY,OAAO;;aAiBzB;;;aAKA;;;aAKA"}
@@ -0,0 +1,2 @@
1
+ import{createSubscriber as e}from"svelte/reactivity";function t(t){let{destroy:n,getSnapshot:r,restore:i,setTheme:a,subscribe:o,sync:s}=t,c=e(e=>o(()=>{e()})),l=()=>(c(),r());return{theme:{get current(){return l().theme}},resolvedTheme:{get current(){return l().resolvedTheme}},systemTheme:{get current(){return l().systemTheme}},destroy:n,restore:i,setTheme:a,subscribe:o,sync:s}}export{t as useResonare};
2
+ //# sourceMappingURL=lite-svelte.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-svelte.js","names":["useResonare","store","track","createSubscriber","subscribe","update","read","getSnapshot"],"sources":["../src/lite-svelte.ts"],"sourcesContent":["import { createSubscriber } from 'svelte/reactivity'\n\nimport type { ThemeStore } from './lite'\n\n/**\n * Returns the store's state (`theme`, `resolvedTheme`, `systemTheme`), each\n * read through `.current`, and its methods. `.current` is reactive in\n * templates, `$derived` and `$effect`, and the store is subscribed only while\n * something reads it. Hydration needs nothing extra: Svelte fixes any markup\n * that differs from the server's.\n *\n * @example\n * <script lang=\"ts\">\n * import { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/svelte'\n *\n * const store = createThemeStore()\n * const { resolvedTheme, setTheme } = useResonare(store)\n * </script>\n *\n * <p>Theme: {resolvedTheme.current}</p>\n * <button onclick={() => setTheme('dark')}>Dark</button>\n */\nexport function useResonare(store: ThemeStore) {\n const { destroy, getSnapshot, restore, setTheme, subscribe, sync } = store\n\n const track = createSubscriber((update) => {\n return subscribe(() => {\n update()\n })\n })\n\n const read = () => {\n track()\n\n return getSnapshot()\n }\n\n return {\n theme: {\n get current() {\n return read().theme\n },\n },\n resolvedTheme: {\n get current() {\n return read().resolvedTheme\n },\n },\n systemTheme: {\n get current() {\n return read().systemTheme\n },\n },\n destroy,\n restore,\n setTheme,\n subscribe,\n sync,\n }\n}\n"],"mappings":"A,qDAuBA,SAAgBA,EAAY,EAAmB,CAC7C,GAAM,CAAE,UAAS,cAAa,UAAS,WAAU,YAAW,QAASC,EAE/DC,EAAQC,EAAkB,GACvBC,MAAgB,CACrBC,EAAO,CACT,CAAC,CACF,EAEKC,OACJJ,EAAM,EAECK,EAAY,GAGrB,MAAO,CACL,MAAO,CACL,IAAI,SAAU,CACZ,OAAOD,EAAK,CAAC,CAAC,KAChB,CACF,EACA,cAAe,CACb,IAAI,SAAU,CACZ,OAAOA,EAAK,CAAC,CAAC,aAChB,CACF,EACA,YAAa,CACX,IAAI,SAAU,CACZ,OAAOA,EAAK,CAAC,CAAC,WAChB,CACF,EACA,UACA,UACA,WACA,YACA,MACF,CACF,C"}
@@ -0,0 +1,53 @@
1
+ import { ThemeStore } from "./lite.js";
2
+ import { ComputedRef } from "vue";
3
+ type UseResonareOptions = {
4
+ /**
5
+ * Set this in server-rendered apps. The first render then uses the server
6
+ * state so hydration matches the server HTML, and switches to the live state
7
+ * once mounted. Leave it off in client-only apps, where it would show the
8
+ * server state for one frame.
9
+ */
10
+ hydrate?: boolean;
11
+ };
12
+ /**
13
+ * Returns the store's state as computed refs (`theme`, `resolvedTheme`,
14
+ * `systemTheme`) and its methods. Call it in `setup` (or inside an
15
+ * `effectScope`); the subscription ends when the component unmounts or the
16
+ * scope stops.
17
+ *
18
+ * @example
19
+ * <script setup lang="ts">
20
+ * import { createThemeStore } from 'resonare/lite'
21
+ * import { useResonare } from 'resonare/lite/vue'
22
+ *
23
+ * const store = createThemeStore()
24
+ *
25
+ * // hydrate: true only in server-rendered apps
26
+ * const { resolvedTheme, setTheme } = useResonare(store, { hydrate: true })
27
+ * </script>
28
+ *
29
+ * <template>
30
+ * <p>Theme: {{ resolvedTheme }}</p>
31
+ * <button @click="setTheme('dark')">Dark</button>
32
+ * </template>
33
+ */
34
+ export declare function useResonare(store: ThemeStore, { hydrate }?: UseResonareOptions): {
35
+ theme: ComputedRef<ReturnType<ThemeStore['getSnapshot']>['theme']>;
36
+ resolvedTheme: ComputedRef<ReturnType<ThemeStore['getSnapshot']>['resolvedTheme']>;
37
+ systemTheme: ComputedRef<ReturnType<ThemeStore['getSnapshot']>['systemTheme']>;
38
+ destroy: () => void;
39
+ restore: () => void;
40
+ setTheme: (next: ("dark" | "light" | "system") | ((current: "dark" | "light" | "system") => "dark" | "light" | "system")) => void;
41
+ subscribe: (callback: (value: {
42
+ theme: "dark" | "light" | "system";
43
+ resolvedTheme: "dark" | "light";
44
+ systemTheme: "dark" | "light";
45
+ }, prev?: {
46
+ theme: "dark" | "light" | "system";
47
+ resolvedTheme: "dark" | "light";
48
+ systemTheme: "dark" | "light";
49
+ }) => void) => (() => void);
50
+ sync: () => (() => void) | undefined;
51
+ };
52
+ export {};
53
+ //# sourceMappingURL=lite-vue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-vue.d.ts","names":[],"sources":["../src/lite-vue.ts"],"mappings":";;KAYK;;;;;;;EAOH;;;;;;;;;;;;;;;;;;;;;;;;wBAyBc,YACd,OAAO,cACL,YAAmB;EAgDb,OAAA,YAAY,WAAW;EAGvB,eAAA,YAAY,WAAW;EAGvB,aAAA,YAAY,WAAW"}
@@ -0,0 +1,2 @@
1
+ import{computed as e,getCurrentInstance as t,onMounted as n,onScopeDispose as r,onUnmounted as i,shallowRef as a}from"vue";function o(o,{hydrate:s=!1}={}){let{destroy:c,getServerSnapshot:l,getSnapshot:u,restore:d,setTheme:f,subscribe:p,sync:m}=o,h=t(),g=a(s&&h?l():u()),_,v=()=>{g.value=u(),_=p(e=>{g.value=e})},y=()=>{_?.()};return h?(n(v),i(y)):(v(),r(y)),{theme:e(()=>g.value.theme),resolvedTheme:e(()=>g.value.resolvedTheme),systemTheme:e(()=>g.value.systemTheme),destroy:c,restore:d,setTheme:f,subscribe:p,sync:m}}export{o as useResonare};
2
+ //# sourceMappingURL=lite-vue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lite-vue.js","names":["useResonare","store","instance","getCurrentInstance","snapshot","shallowRef","hydrate","getServerSnapshot","getSnapshot","unsubscribe","start","subscribe","value","stop","onMounted","onUnmounted","onScopeDispose","computed"],"sources":["../src/lite-vue.ts"],"sourcesContent":["import {\n type ComputedRef,\n computed,\n getCurrentInstance,\n onMounted,\n onScopeDispose,\n onUnmounted,\n shallowRef,\n} from 'vue'\n\nimport type { ThemeStore } from './lite'\n\ntype UseResonareOptions = {\n /**\n * Set this in server-rendered apps. The first render then uses the server\n * state so hydration matches the server HTML, and switches to the live state\n * once mounted. Leave it off in client-only apps, where it would show the\n * server state for one frame.\n */\n hydrate?: boolean\n}\n\n/**\n * Returns the store's state as computed refs (`theme`, `resolvedTheme`,\n * `systemTheme`) and its methods. Call it in `setup` (or inside an\n * `effectScope`); the subscription ends when the component unmounts or the\n * scope stops.\n *\n * @example\n * <script setup lang=\"ts\">\n * import { createThemeStore } from 'resonare/lite'\n * import { useResonare } from 'resonare/lite/vue'\n *\n * const store = createThemeStore()\n *\n * // hydrate: true only in server-rendered apps\n * const { resolvedTheme, setTheme } = useResonare(store, { hydrate: true })\n * </script>\n *\n * <template>\n * <p>Theme: {{ resolvedTheme }}</p>\n * <button @click=\"setTheme('dark')\">Dark</button>\n * </template>\n */\nexport function useResonare(\n store: ThemeStore,\n { hydrate = false }: UseResonareOptions = {}\n) {\n const {\n destroy,\n getServerSnapshot,\n getSnapshot,\n restore,\n setTheme,\n subscribe,\n sync,\n } = store\n\n const instance = getCurrentInstance()\n\n const snapshot = shallowRef(\n hydrate && instance ? getServerSnapshot() : getSnapshot()\n )\n\n let unsubscribe: (() => unknown) | undefined\n\n const start = () => {\n snapshot.value = getSnapshot()\n\n unsubscribe = subscribe((value) => {\n snapshot.value = value\n })\n }\n\n const stop = () => {\n unsubscribe?.()\n }\n\n // Components subscribe on mount, which never runs during server rendering,\n // so the server never holds a subscription. Lifecycle hooks are used because\n // server rendering may set up components without an active effect scope.\n if (instance) {\n onMounted(start)\n\n onUnmounted(stop)\n } else {\n start()\n\n onScopeDispose(stop)\n }\n\n return {\n theme: computed(() => {\n return snapshot.value.theme\n }) as ComputedRef<ReturnType<ThemeStore['getSnapshot']>['theme']>,\n resolvedTheme: computed(() => {\n return snapshot.value.resolvedTheme\n }) as ComputedRef<ReturnType<ThemeStore['getSnapshot']>['resolvedTheme']>,\n systemTheme: computed(() => {\n return snapshot.value.systemTheme\n }) as ComputedRef<ReturnType<ThemeStore['getSnapshot']>['systemTheme']>,\n destroy,\n restore,\n setTheme,\n subscribe,\n sync,\n }\n}\n"],"mappings":"A,2HA4CA,SAAgBA,EACd,EACA,CAAE,UAAU,IAA8B,CAAC,EAC3C,CACA,GAAM,CACJ,UACA,oBACA,cACA,UACA,WACA,YACA,QACEC,EAEEC,EAAWC,EAAmB,EAE9BC,EAAWC,EACfC,GAAWJ,EAAWK,EAAkB,EAAIC,EAAY,CAC1D,EAEIC,EAEEC,MAAc,CAClB,EAAS,MAAQF,EAAY,EAE7B,EAAcG,EAAW,GAAU,CACjC,EAAS,MAAQC,CACnB,CAAC,CACH,EAEMC,MAAa,CACjBJ,IAAc,CAChB,EAeA,OAVIP,GACFY,EAAUJ,CAAK,EAEfK,EAAYF,CAAI,IAEhBH,EAAM,EAENM,EAAeH,CAAI,GAGd,CACL,MAAOI,MACEb,EAAS,MAAM,KACvB,EACD,cAAea,MACNb,EAAS,MAAM,aACvB,EACD,YAAaa,MACJb,EAAS,MAAM,WACvB,EACD,UACA,UACA,WACA,YACA,MACF,CACF,C"}