resonare 0.3.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.
- package/README.md +91 -22
- package/dist/effects-core-CuoeZrRP.js +2 -0
- package/dist/effects-core-CuoeZrRP.js.map +1 -0
- package/dist/effects-core-DPJyVK-w.d.ts +14 -0
- package/dist/effects-core-DPJyVK-w.d.ts.map +1 -0
- package/dist/effects.d.ts +105 -0
- package/dist/effects.d.ts.map +1 -0
- package/dist/effects.js +2 -0
- package/dist/effects.js.map +1 -0
- package/dist/index.d.ts +18 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lite-effects.d.ts +65 -0
- package/dist/lite-effects.d.ts.map +1 -0
- package/dist/lite-effects.js +2 -0
- package/dist/lite-effects.js.map +1 -0
- package/dist/lite-react.d.ts +4 -0
- package/dist/lite-solid.d.ts +4 -0
- package/dist/lite-svelte.d.ts +4 -0
- package/dist/lite-vue.d.ts +4 -0
- package/dist/lite.d.ts +10 -4
- package/dist/lite.d.ts.map +1 -1
- package/dist/lite.js +1 -1
- package/dist/lite.js.map +1 -1
- package/dist/react.d.ts +16 -1
- package/dist/solid.d.ts +16 -1
- package/dist/storage-fOH2xeQ1.js +2 -0
- package/dist/storage-fOH2xeQ1.js.map +1 -0
- package/dist/svelte.d.ts +16 -1
- package/dist/utils-CWI4hy3w.js +2 -0
- package/dist/utils-CWI4hy3w.js.map +1 -0
- package/dist/vue.d.ts +16 -1
- package/package.json +9 -1
- package/dist/storage-BqWA8jeP.js +0 -2
- package/dist/storage-BqWA8jeP.js.map +0 -1
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@ A small state store for themes and user preferences: color scheme, contrast, spa
|
|
|
13
13
|
- **Framework bindings** for React, Solid, Svelte and Vue, or use it with plain JavaScript
|
|
14
14
|
- **Type-safe:** option values are inferred from your config
|
|
15
15
|
- **Lite version** for when all you need is light / dark / system
|
|
16
|
+
- **Ready-made effects** for `data-*` attributes, `color-scheme`, `<meta name="theme-color">` and switching without transition flashes
|
|
16
17
|
|
|
17
18
|
## Installation
|
|
18
19
|
|
|
@@ -34,7 +35,14 @@ Each key is a setting. List its `options`; the first one is the default unless y
|
|
|
34
35
|
|
|
35
36
|
```ts
|
|
36
37
|
// theme.ts
|
|
37
|
-
import { type
|
|
38
|
+
import { type ThemeStoreConfig } from 'resonare'
|
|
39
|
+
import {
|
|
40
|
+
combine,
|
|
41
|
+
disableTransitions,
|
|
42
|
+
setColorScheme,
|
|
43
|
+
setDataAttributes,
|
|
44
|
+
setThemeColor,
|
|
45
|
+
} from 'resonare/effects'
|
|
38
46
|
|
|
39
47
|
export const CONFIG = {
|
|
40
48
|
colorScheme: {
|
|
@@ -52,23 +60,18 @@ export const CONFIG = {
|
|
|
52
60
|
},
|
|
53
61
|
} as const satisfies ThemeStoreConfig
|
|
54
62
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
for (const [key, value] of Object.entries(resolvedThemes)) {
|
|
62
|
-
document.documentElement.dataset[key] = String(value)
|
|
63
|
-
}
|
|
64
|
-
}
|
|
63
|
+
export const applyThemes = combine(
|
|
64
|
+
setDataAttributes(),
|
|
65
|
+
setColorScheme(),
|
|
66
|
+
setThemeColor({ values: { light: '#fff', dark: '#000' } }),
|
|
67
|
+
disableTransitions()
|
|
68
|
+
)
|
|
65
69
|
```
|
|
66
70
|
|
|
67
71
|
Then style your page from those attributes:
|
|
68
72
|
|
|
69
73
|
```css
|
|
70
74
|
:root[data-color-scheme='dark'] {
|
|
71
|
-
color-scheme: dark;
|
|
72
75
|
--background: #000;
|
|
73
76
|
}
|
|
74
77
|
```
|
|
@@ -142,6 +145,65 @@ function ColorSchemeSelect() {
|
|
|
142
145
|
|
|
143
146
|
See [Frameworks](#frameworks) for Solid, Svelte and Vue.
|
|
144
147
|
|
|
148
|
+
## Effects
|
|
149
|
+
|
|
150
|
+
`resonare/effects` (and `resonare/lite/effects`) has the side effects most apps need when the theme changes. Each one works both with `store.subscribe` and as the inline script's `handler`, so the page is right on first paint and stays right afterwards. Combine them into one handler with `combine(...)`; they run in order.
|
|
151
|
+
|
|
152
|
+
| Effect | What it does |
|
|
153
|
+
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
154
|
+
| `setDataAttributes()` | Writes every resolved setting to `<html>`, e.g. `data-color-scheme="dark"` |
|
|
155
|
+
| `setClassNames({ [setting]: { [value]: className } })` | Adds a class on `<html>` per mapped setting, chosen by its resolved value, e.g. `{ colorScheme: { dark: 'dark', 'dark-dimmed': 'dark' } }` for Tailwind's or shadcn's `.dark`. Unmapped values (or `null`) add no class, and every mapped class is removed once it no longer applies |
|
|
156
|
+
| `setColorScheme({ key?, values? })` | Sets the CSS `color-scheme` on `<html>`, so scrollbars and form controls match. Map custom values with `values: { 'dark-dimmed': 'dark' }` |
|
|
157
|
+
| `setThemeColor({ key?, values })` | Keeps `<meta name="theme-color">` in sync, so the browser's toolbar follows the user's choice instead of the OS. It sets the `content` of every theme-color tag, media-based ones included (Safari picks up content changes, not added or removed tags), and adds one if there is none |
|
|
158
|
+
| `setThemeColor({ key?, cssVar })` | The same, reading the color from a CSS variable on `<html>`. List it after `setDataAttributes()`, and put the inline script after your stylesheet so the variable is there on first paint |
|
|
159
|
+
| `disableTransitions({ keys? })` | Turns off CSS transitions for one frame when any of `keys` (default `['colorScheme']`) changes, so colors switch at once instead of animating. Does nothing on first paint or when other settings change |
|
|
160
|
+
|
|
161
|
+
`key` is the setting that holds the color scheme and defaults to `'colorScheme'`. Put any theme-color tags before the inline script, so it finds them on first paint.
|
|
162
|
+
|
|
163
|
+
Pass your config's type to check setting names and values, e.g. a typo in a value, a stale option after a rename, or a value with no theme color:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
type Config = typeof CONFIG
|
|
167
|
+
|
|
168
|
+
setClassNames<Config>({ colorScheme: { dark: 'dark' } })
|
|
169
|
+
setColorScheme<Config>({
|
|
170
|
+
key: 'colorScheme',
|
|
171
|
+
values: { 'dark-dimmed': 'dark' },
|
|
172
|
+
})
|
|
173
|
+
setThemeColor<Config>({ values: { light: '#fff', dark: '#000' } }) // every value needs a color
|
|
174
|
+
disableTransitions<Config>({ keys: ['colorScheme', 'contrast'] })
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Your own effects
|
|
178
|
+
|
|
179
|
+
A plain handler can't use variables from outside itself, because it is copied into the inline script as source code. `defineEffect` gets around that: it copies your function together with its options, which must be JSON-serializable.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { combine, defineEffect, setDataAttributes } from 'resonare/effects'
|
|
183
|
+
|
|
184
|
+
const favicon = defineEffect<typeof CONFIG, Record<string, string>>(
|
|
185
|
+
({ resolvedThemes }, prev, icons) => {
|
|
186
|
+
document.querySelector<HTMLLinkElement>('link[rel=icon]')!.href =
|
|
187
|
+
icons[resolvedThemes.colorScheme]!
|
|
188
|
+
}
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
export const applyThemes = combine(
|
|
192
|
+
setDataAttributes(),
|
|
193
|
+
favicon({ light: '/icon-light.svg', dark: '/icon-dark.svg' })
|
|
194
|
+
)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Every listener receives the state before the change as its second argument (`prev`). It is `undefined` in the inline script, which makes "only on a real change" logic easy.
|
|
198
|
+
|
|
199
|
+
To animate the switch with a [view transition](https://developer.mozilla.org/docs/Web/API/View_Transition_API), wrap the setter: subscribers run synchronously, so the new theme is applied inside the callback.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
document.startViewTransition(() => {
|
|
203
|
+
store.setThemes({ colorScheme: 'dark' })
|
|
204
|
+
})
|
|
205
|
+
```
|
|
206
|
+
|
|
145
207
|
## State
|
|
146
208
|
|
|
147
209
|
Every listener, snapshot and binding gives you three views of the state:
|
|
@@ -173,7 +235,7 @@ const store = createThemeStore(CONFIG, {
|
|
|
173
235
|
| `getServerSnapshot()` | The state as rendered on the server (see [Server-side rendering](#server-side-rendering)) |
|
|
174
236
|
| `setThemes(partial)` | Updates the given settings, saves them and notifies subscribers. Also accepts a function: `setThemes((current) => ({ ... }))` |
|
|
175
237
|
| `updateSystemOption(key, [whenMatched, whenNotMatched])` | Changes what a media option resolves to, e.g. `updateSystemOption('colorScheme', ['dark-dimmed', 'light'])` |
|
|
176
|
-
| `subscribe(callback)` | Calls `callback`
|
|
238
|
+
| `subscribe(callback)` | Calls `callback(state, prev)` after every change, including OS preference changes. Returns an unsubscribe function |
|
|
177
239
|
| `restore()` | Loads the saved state from storage. Does nothing when nothing is saved |
|
|
178
240
|
| `sync()` | Applies changes made in other tabs. Returns a function that stops syncing |
|
|
179
241
|
| `toPersist()` | The state to save elsewhere; pass it back as `persisted` |
|
|
@@ -378,15 +440,22 @@ export function ThemeSelect({ savedState }) {
|
|
|
378
440
|
For a single light / dark / system preference, `resonare/lite` is smaller and needs no config.
|
|
379
441
|
|
|
380
442
|
```ts
|
|
443
|
+
import { createInlineThemeScript, createThemeStore } from 'resonare/lite'
|
|
381
444
|
import {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
445
|
+
combine,
|
|
446
|
+
disableTransitions,
|
|
447
|
+
setColorScheme,
|
|
448
|
+
setDataAttributes,
|
|
449
|
+
setThemeColor,
|
|
450
|
+
} from 'resonare/lite/effects'
|
|
451
|
+
|
|
452
|
+
// data-theme="dark", plus the same effects as the full version.
|
|
453
|
+
const applyTheme = combine(
|
|
454
|
+
setDataAttributes(),
|
|
455
|
+
setColorScheme(),
|
|
456
|
+
setThemeColor({ light: '#fff', dark: '#000' }),
|
|
457
|
+
disableTransitions()
|
|
458
|
+
)
|
|
390
459
|
|
|
391
460
|
// Put this in the <head>, as above.
|
|
392
461
|
export const themeScript = createInlineThemeScript({ handler: applyTheme })
|
|
@@ -413,7 +482,7 @@ The state has three fields:
|
|
|
413
482
|
|
|
414
483
|
The store has the same methods as the full one, except `setTheme` instead of `setThemes` and no `updateSystemOption` or `toPersist`. It saves to `localStorage` under the key `'resonare/lite'` by default, and the same `storage` and `persisted` options apply (`persisted` is just the theme, e.g. `'dark'`).
|
|
415
484
|
|
|
416
|
-
The bindings live under `resonare/lite/react`, `resonare/lite/solid`, `resonare/lite/svelte` and `resonare/lite/vue`, and work like the full ones.
|
|
485
|
+
The bindings live under `resonare/lite/react`, `resonare/lite/solid`, `resonare/lite/svelte` and `resonare/lite/vue`, and the effects under `resonare/lite/effects`. They work like the full ones, except that `setDataAttributes({ key })` names the attribute (`data-theme` by default), `setClassNames({ light?, dark? })` adds `light` or `dark` (rename them, or pass `null` for no class; `undefined` keeps the default), `setThemeColor` takes `{ light, dark }` or `{ cssVar }`, and there's no `key`, `keys` or config type elsewhere.
|
|
417
486
|
|
|
418
487
|
## Changing options later
|
|
419
488
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{i as e,r as t}from"./utils-CWI4hy3w.js";const n=/* @__PURE__ */ new WeakMap,r=(e,t)=>(n.set(e,t),e.toString=()=>t?`s=>${t}`:`()=>{}`,e),i=(n,i,a,o)=>{let s=e(a),c=s===`{}`?s:`o`,l=`(${t(i)})((${t(n)})(s,${c}),${c})`;return r((e,t)=>{i(n(e,a),a,t===void 0?void 0:n(t,a))},o?``:c===`o`?`{const o=${s};${l}}`:`{${l}}`)},a=n=>(i={})=>r((e,t)=>{n(e,t,i)},`{(${t(n)})(s,void 0,${e(i)})}`),o=(...e)=>{let i=e.map(e=>n.get(e)??`(${t(e)})(s);`).filter(Boolean);return r((t,n)=>{for(let r of e)r(t,n)},i.length===1&&i[0].startsWith(`{`)?i[0]:i.length>0?`{${i.join(``)}}`:``)},s=e=>{for(let t in e)document.documentElement.dataset[t]=String(e[t])},c=(e,t)=>{let{classList:n}=document.documentElement;for(let r in t){let i=t[r]??{},a=i[String(e[r])];for(let e in i){let t=i[e];t&&t!==a&&n.remove(t)}a&&n.add(a)}},l=(e,{values:t})=>{document.documentElement.style.colorScheme=t?.[e]??e},u=(e,{values:t,cssVar:n})=>{let r=n?getComputedStyle(document.documentElement).getPropertyValue(n).trim():t?.[e];if(!r)return;let i=document.querySelectorAll(`meta[name="theme-color"]`);if(i.length){i.forEach(e=>{e.content=r});return}let a=document.createElement(`meta`);a.name=`theme-color`,a.content=r,document.head.append(a)},d=(e,t,n)=>{if(n===void 0||n===e)return;let r=document.createElement(`style`);r.textContent=`*,*::before,*::after{transition:none!important}`,document.head.append(r),requestAnimationFrame(()=>{requestAnimationFrame(()=>{r.remove()})})};export{l as a,u as c,c as i,i as n,s as o,a as r,d as s,o as t};
|
|
2
|
+
//# sourceMappingURL=effects-core-CuoeZrRP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects-core-CuoeZrRP.js","names":["toScriptJson","toScriptFunction","blocks","withBlock","listener","block","createEffect","json","options","o","call","run","select","state","prev","skipFirstPaint","defineEffect","combine","listeners","parts","runDataAttributes","key","values","runClassNames","classes","names","current","value","name","classList","runColorScheme","runThemeColor","color","cssVar","metas","meta","runDisableTransitions","style"],"sources":["../src/effects-core.ts"],"sourcesContent":["import { toScriptFunction, toScriptJson } from './utils'\n\n/**\n * A listener that also works in the inline script: its `toString()` returns\n * self-contained source (the function plus its options as JSON), which\n * `createInlineThemeScript` embeds instead of the closure.\n */\n// `any` by default so one effect fits any store's `subscribe` and the inline\n// script's `handler`, whatever the config.\n// oxlint-disable-next-line typescript/no-explicit-any\nexport type Effect<S = any> = (state: S, prev?: S) => void\n\ntype Select<S, O, V> = (state: S, options: O) => V\n\n// Options come before `prev` so the inline script, where there is never a\n// previous state, can leave it out.\ntype Run<O, V> = (value: V, options: O, prev?: V) => void\n\n/**\n * Script source of an effect with nothing to do on first paint; `combine`\n * leaves it out of the script.\n */\nconst NOOP = '()=>{}'\n\n/**\n * Each effect's script source as a statement block using the state `s`, so\n * `combine` can join effects without wrapping each in a function. An empty\n * string means \"nothing to do on first paint\".\n */\nconst blocks = new WeakMap<Effect, string>()\n\nconst withBlock = <S>(listener: Effect<S>, block: string): Effect<S> => {\n blocks.set(listener, block)\n\n listener.toString = () => {\n return block ? `s=>${block}` : NOOP\n }\n\n return listener\n}\n\n/**\n * Builds an effect from `select`, which picks the value the effect cares\n * about from the state (so the same `run` serves the full and lite stores),\n * and `run`, which applies it. Both are copied into the inline script as\n * source code, so neither may use variables from outside the function.\n * `options` must be JSON-serializable. With `skipFirstPaint`, the effect only\n * reacts to changes and stays out of the inline script.\n */\nexport const createEffect = <S, O extends object, V>(\n select: Select<S, O, V>,\n run: Run<O, V>,\n options: O,\n skipFirstPaint?: boolean\n): Effect => {\n const json = toScriptJson(options)\n\n // Empty options are cheaper written out than kept in a variable.\n const o = json === '{}' ? json : 'o'\n\n const call = `(${toScriptFunction(run)})((${toScriptFunction(select)})(s,${o}),${o})`\n\n return withBlock<S>(\n (state, prev) => {\n run(\n select(state, options),\n options,\n prev === undefined ? undefined : select(prev, options)\n )\n },\n skipFirstPaint ? '' : o === 'o' ? `{const o=${json};${call}}` : `{${call}}`\n )\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 */\nexport const defineEffect = <S, O extends object = Record<never, never>>(\n run: (state: S, prev: S | undefined, options: O) => void\n) => {\n return (options = {} as O): Effect<S> => {\n return withBlock<S>(\n (state, prev) => {\n run(state, prev, options)\n },\n `{(${toScriptFunction(run)})(s,void 0,${toScriptJson(options)})}`\n )\n }\n}\n\n/**\n * Runs several listeners in order as one. The result works with\n * `store.subscribe` and as the inline script's `handler`, as long as every\n * part does (effects, or plain self-contained functions).\n */\nexport const combine = <S>(...listeners: Array<Effect<S>>): Effect<S> => {\n const parts = listeners\n .map((listener) => {\n // Plain functions have no block; call them with the state.\n return blocks.get(listener) ?? `(${toScriptFunction(listener)})(s);`\n })\n .filter(Boolean)\n\n return withBlock<S>(\n (state, prev) => {\n for (const listener of listeners) {\n listener(state, prev)\n }\n },\n parts.length === 1 && parts[0]!.startsWith('{')\n ? parts[0]!\n : parts.length > 0\n ? `{${parts.join('')}}`\n : ''\n )\n}\n\n// Shared `run` functions. Each is stringified into the inline script, so it\n// must stay self-contained.\n\nexport const runDataAttributes: Run<object, Record<string, unknown>> = (\n values\n) => {\n for (const key in values) {\n document.documentElement.dataset[key] = String(values[key])\n }\n}\n\n/** Setting → resolved value → class name (`null` or missing: no class). */\nexport type ClassMap = Record<\n string,\n Partial<Record<string, string | null>> | undefined\n>\n\nexport const runClassNames: Run<ClassMap, Record<string, unknown>> = (\n values,\n classes\n) => {\n const { classList } = document.documentElement\n\n for (const key in classes) {\n const names = classes[key] ?? {}\n\n const current = names[String(values[key])]\n\n // Every class the setting can add is listed, so drop all but the current\n // one; this also corrects classes rendered by the server or left over.\n for (const value in names) {\n const name = names[value]\n\n if (name && name !== current) {\n classList.remove(name)\n }\n }\n\n if (current) {\n classList.add(current)\n }\n }\n}\n\nexport const runColorScheme: Run<\n { values?: Record<string, string> },\n string\n> = (value, { values }) => {\n document.documentElement.style.colorScheme = values?.[value] ?? value\n}\n\nexport const runThemeColor: Run<\n { values?: Record<string, string>; cssVar?: string },\n string\n> = (value, { values, cssVar }) => {\n const color = cssVar\n ? getComputedStyle(document.documentElement).getPropertyValue(cssVar).trim()\n : values?.[value]\n\n if (!color) {\n return\n }\n\n // Safari picks up `content` changes on existing tags, but not reliably tags\n // being added, removed or losing `media`. So set every tag, media-based\n // ones included: whichever matches the OS then shows the user's choice.\n const metas = document.querySelectorAll<HTMLMetaElement>(\n 'meta[name=\"theme-color\"]'\n )\n\n if (metas.length) {\n metas.forEach((meta) => {\n meta.content = color\n })\n\n return\n }\n\n const meta = document.createElement('meta')\n\n meta.name = 'theme-color'\n\n meta.content = color\n\n document.head.append(meta)\n}\n\nexport const runDisableTransitions: Run<object, string> = (\n value,\n _options,\n prev\n) => {\n // Nothing animates on first paint, and other settings changing must not\n // cut their transitions short.\n if (prev === undefined || prev === value) {\n return\n }\n\n const style = document.createElement('style')\n\n style.textContent = '*,*::before,*::after{transition:none!important}'\n\n document.head.append(style)\n\n // Remove once a frame has been styled with the new theme, so no listener\n // order or late attribute change can start a transition.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n style.remove()\n })\n })\n}\n"],"mappings":"A,+CAsBA,MAOME,kBAAS,IAAI,QAEbC,GAAgB,EAAqB,KACzCD,EAAO,IAAIE,EAAUC,CAAK,EAE1B,EAAS,aACAA,EAAQ,MAAMA,IAAU,SAG1BD,GAWIE,GACX,EACA,EACA,EACA,IACW,CACX,IAAMC,EAAOP,EAAaQ,CAAO,EAG3BC,EAAIF,IAAS,KAAOA,EAAO,IAE3BG,EAAO,IAAIT,EAAiBU,CAAG,EAAE,KAAKV,EAAiBW,CAAM,EAAE,MAAMH,EAAE,IAAIA,EAAE,GAEnF,OAAON,GACJ,EAAO,IAAS,CACfQ,EACEC,EAAOC,EAAOL,CAAO,EACrBA,EACAM,IAAS,IAAA,GAAY,IAAA,GAAYF,EAAOE,EAAMN,CAAO,CACvD,CACF,EACAO,EAAiB,GAAKN,IAAM,IAAM,YAAYF,EAAK,GAAGG,EAAK,GAAK,IAAIA,EAAK,EAC3E,CACF,EASaM,EACX,IAEQ,EAAU,CAAC,IACVb,GACJ,EAAO,IAAS,CACfQ,EAAIE,EAAOC,EAAMN,CAAO,CAC1B,EACA,KAAKP,EAAiBU,CAAG,EAAE,aAAaX,EAAaQ,CAAO,EAAE,GAChE,EASSS,GAAc,GAAGC,IAA2C,CACvE,IAAMC,EAAQD,EACX,IAAK,GAEGhB,EAAO,IAAIE,CAAQ,GAAK,IAAIH,EAAiBG,CAAQ,EAAE,MAC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A,IAAaA,IAASa,EACjC,OAGF,IAAMU,EAAQ,SAAS,cAAc,OAAO,EAE5C,EAAM,YAAc,kDAEpB,SAAS,KAAK,OAAOA,CAAK,EAI1B,0BAA4B,CAC1B,0BAA4B,CAC1BA,EAAM,OAAO,CACf,CAAC,CACH,CAAC,CACH,E"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A listener that also works in the inline script: its `toString()` returns
|
|
3
|
+
* self-contained source (the function plus its options as JSON), which
|
|
4
|
+
* `createInlineThemeScript` embeds instead of the closure.
|
|
5
|
+
*/
|
|
6
|
+
type Effect<S = any> = (state: S, prev?: S) => void;
|
|
7
|
+
/**
|
|
8
|
+
* Runs several listeners in order as one. The result works with
|
|
9
|
+
* `store.subscribe` and as the inline script's `handler`, as long as every
|
|
10
|
+
* part does (effects, or plain self-contained functions).
|
|
11
|
+
*/
|
|
12
|
+
declare const combine: <S>(...listeners: Array<Effect<S>>) => Effect<S>;
|
|
13
|
+
export { combine as n, Effect as t };
|
|
14
|
+
//# sourceMappingURL=effects-core-DPJyVK-w.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects-core-DPJyVK-w.d.ts","names":[],"sources":["../src/effects-core.ts"],"mappings":";;;;;KAUY,OAAO,YAAY,OAAO,GAAG,OAAO;;;;;;cAyFnC,UAAW,MAAC,WAAgB,MAAM,OAAO,QAAM,OAAO"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { n as combine, t as Effect } from "./effects-core-DPJyVK-w.js";
|
|
2
|
+
import { ResolvedThemeValue, ThemeSnapshot, ThemeStoreConfig } from "./index.js";
|
|
3
|
+
/** The settings of `T`. */
|
|
4
|
+
type SettingKey<T extends ThemeStoreConfig> = Extract<keyof T, string>;
|
|
5
|
+
/**
|
|
6
|
+
* What setting `K` resolves to, as the string a map is looked up with. Any
|
|
7
|
+
* string when no config type is given.
|
|
8
|
+
*/
|
|
9
|
+
type ValueKey<T extends ThemeStoreConfig, K extends keyof T> = string extends keyof T ? string : `${Extract<ResolvedThemeValue<T, K>, string | number | boolean>}`;
|
|
10
|
+
/** `O` only when `T` has a `colorScheme` setting, the default `key`. */
|
|
11
|
+
type WithDefaultKey<T extends ThemeStoreConfig, O> = 'colorScheme' extends keyof T ? O : never;
|
|
12
|
+
/** Options may be left out only when the default `key` exists. */
|
|
13
|
+
type OptionalArgs<T extends ThemeStoreConfig, O> = 'colorScheme' extends keyof T ? [options?: O] : [options: O];
|
|
14
|
+
type ColorSchemeOptions<T extends ThemeStoreConfig> = { [K in SettingKey<T>]: {
|
|
15
|
+
/** The setting to follow; defaults to `'colorScheme'`. */
|
|
16
|
+
key: K;
|
|
17
|
+
/** Maps values that aren't valid `color-scheme` values. */
|
|
18
|
+
values?: Partial<Record<ValueKey<T, K>, string>>;
|
|
19
|
+
}; }[SettingKey<T>] | WithDefaultKey<T, {
|
|
20
|
+
key?: undefined;
|
|
21
|
+
values?: Partial<Record<ValueKey<T, 'colorScheme' & keyof T>, string>>;
|
|
22
|
+
}>;
|
|
23
|
+
type ThemeColorSource<V extends string> = {
|
|
24
|
+
/** A color for every value the setting can resolve to. */
|
|
25
|
+
values: Record<V, string>;
|
|
26
|
+
cssVar?: never;
|
|
27
|
+
} | {
|
|
28
|
+
/** A CSS variable on `<html>` holding the color. */
|
|
29
|
+
cssVar: string;
|
|
30
|
+
values?: never;
|
|
31
|
+
};
|
|
32
|
+
type ThemeColorOptions<T extends ThemeStoreConfig> = { [K in SettingKey<T>]: {
|
|
33
|
+
/** The setting to follow; defaults to `'colorScheme'`. */
|
|
34
|
+
key: K;
|
|
35
|
+
} & ThemeColorSource<ValueKey<T, K>>; }[SettingKey<T>] | WithDefaultKey<T, {
|
|
36
|
+
key?: undefined;
|
|
37
|
+
} & ThemeColorSource<ValueKey<T, 'colorScheme' & keyof T>>>;
|
|
38
|
+
type ClassNamesOptions<T extends ThemeStoreConfig> = { [K in SettingKey<T>]?: Partial<Record<ValueKey<T, K>, string | null>>; };
|
|
39
|
+
type TransitionsOptions<T extends ThemeStoreConfig> = {
|
|
40
|
+
/** The settings whose change cuts transitions; defaults to `['colorScheme']`. */
|
|
41
|
+
keys: Array<SettingKey<T>>;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* Turns `run(state, prev, options)` into a factory of effects that work both
|
|
45
|
+
* with `store.subscribe` and as (part of) the inline script's `handler`.
|
|
46
|
+
* `run` is copied into the script as source code, so it can't use variables
|
|
47
|
+
* from outside the function; pass what it needs through `options`, which must
|
|
48
|
+
* be JSON-serializable. `prev` is `undefined` on first paint.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const fontSize = defineEffect<typeof CONFIG, { scale: number }>(
|
|
52
|
+
* ({ resolvedThemes }, _prev, { scale }) => {
|
|
53
|
+
* const px = { sm: 14, md: 16, lg: 18 }[resolvedThemes.fontSize] * scale
|
|
54
|
+
* document.documentElement.style.fontSize = `${px}px`
|
|
55
|
+
* }
|
|
56
|
+
* )
|
|
57
|
+
*
|
|
58
|
+
* const applyThemes = combine(setDataAttributes(), fontSize({ scale: 1 }))
|
|
59
|
+
*/
|
|
60
|
+
export declare const defineEffect: <T extends ThemeStoreConfig = ThemeStoreConfig, O extends object = Record<never, never>>(run: (state: ThemeSnapshot<T>, prev: ThemeSnapshot<T> | undefined, options: O) => void) => (options?: O) => Effect;
|
|
61
|
+
/**
|
|
62
|
+
* Writes every resolved setting to a `data-*` attribute on `<html>`, e.g.
|
|
63
|
+
* `data-color-scheme="dark"`.
|
|
64
|
+
*/
|
|
65
|
+
export declare const setDataAttributes: () => Effect;
|
|
66
|
+
/**
|
|
67
|
+
* Adds a class on `<html>` for each mapped setting, chosen by its resolved
|
|
68
|
+
* value, e.g. `class="dark"` for Tailwind's or shadcn's `.dark` selectors.
|
|
69
|
+
* Values that aren't mapped (or map to `null`) add no class. Every class in
|
|
70
|
+
* the map is removed when it no longer applies, so the classes stay right
|
|
71
|
+
* even if the page started with stale ones. Pass the config type to check
|
|
72
|
+
* settings and values.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* setClassNames<typeof CONFIG>({
|
|
76
|
+
* colorScheme: { dark: 'dark', 'dark-dimmed': 'dark' },
|
|
77
|
+
* contrast: { high: 'high-contrast' },
|
|
78
|
+
* })
|
|
79
|
+
*/
|
|
80
|
+
export declare const setClassNames: <T extends ThemeStoreConfig = ThemeStoreConfig>(classes: ClassNamesOptions<T>) => Effect;
|
|
81
|
+
/**
|
|
82
|
+
* Sets the CSS `color-scheme` of `<html>`, so scrollbars, form controls and
|
|
83
|
+
* the default canvas match. Follows `key` (default `'colorScheme'`); map
|
|
84
|
+
* custom values with `values`, e.g. `{ 'dark-dimmed': 'dark' }`. Pass the
|
|
85
|
+
* config type to check `key` and `values`.
|
|
86
|
+
*/
|
|
87
|
+
export declare const setColorScheme: <T extends ThemeStoreConfig = ThemeStoreConfig>(...args: OptionalArgs<T, ColorSchemeOptions<T>>) => Effect;
|
|
88
|
+
/**
|
|
89
|
+
* Keeps `<meta name="theme-color">` in sync with `key` (default
|
|
90
|
+
* `'colorScheme'`), so the browser UI follows the user's choice rather than
|
|
91
|
+
* the OS. Existing tags (media-based ones included) all get the color; with
|
|
92
|
+
* none, one is added. Give a color for every value, or `cssVar` to read one
|
|
93
|
+
* from `<html>` (list this after the effect that sets your attributes). Pass
|
|
94
|
+
* the config type to check `key` and that no value is missing a color.
|
|
95
|
+
*/
|
|
96
|
+
export declare const setThemeColor: <T extends ThemeStoreConfig = ThemeStoreConfig>(options: ThemeColorOptions<T>) => Effect;
|
|
97
|
+
/**
|
|
98
|
+
* Turns off CSS transitions for one frame when any of `keys` (default
|
|
99
|
+
* `['colorScheme']`) changes, so colors switch at once instead of animating.
|
|
100
|
+
* Does nothing on first paint or when other settings change. Pass the config
|
|
101
|
+
* type to check `keys`.
|
|
102
|
+
*/
|
|
103
|
+
export declare const disableTransitions: <T extends ThemeStoreConfig = ThemeStoreConfig>(...args: OptionalArgs<T, Partial<TransitionsOptions<T>>>) => Effect;
|
|
104
|
+
export { type Effect, combine };
|
|
105
|
+
//# sourceMappingURL=effects.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects.d.ts","names":[],"sources":["../src/effects.ts"],"mappings":";;;KAwBK,WAAW,UAAU,oBAAoB,cAAc;;;;;KAMvD,SACH,UAAU,kBACV,gBAAgB,0BACO,gBAElB,QAAQ,mBAAmB,GAAG;;KAGhC,eACH,UAAU,kBACV,iCAC8B,IAAI;;KAG/B,aAAa,UAAU,kBAAkB,iCAAiC,KAC1E,UAAU,MACV,SAAS;KAET,mBAAmB,UAAU,uBAE3B,KAAK,WAAW;;EAEf,KAAK;;EAEL,SAAS,QAAQ,OAAO,SAAS,GAAG;KAEtC,WAAW,MACb,eACE;EAEE;EACA,SAAS,QAAQ,OAAO,SAAS,yBAAyB;;KAI7D,iBAAiB;;EAGhB,QAAQ,OAAO;EACf;;;EAIA;EACA;;KAGD,kBAAkB,UAAU,uBAE1B,KAAK,WAAW;;EAEf,KAAK;IACH,iBAAiB,SAAS,GAAG,OACjC,WAAW,MACb,eACE;EACE;IAAoB,iBACpB,SAAS,yBAAyB;KAIrC,kBAAkB,UAAU,uBAC9B,KAAK,WAAW,MAAM,QAAQ,OAAO,SAAS,GAAG;KAG/C,mBAAmB,UAAU;;EAEhC,MAAM,MAAM,WAAW;;;;;;;;;;;;;;;;;;;qBAwBZ,eACX,UAAU,mBAAmB,kBAC7B,mBAAmB,sBAEnB,MACE,OAAO,cAAc,IACrB,MAAM,cAAc,gBACpB,SAAS,gBAEP,UAAU,MAAM;;;;;qBAMT,yBAAwB;;;;;;;;;;;;;;;qBAwBxB,gBAQN,UAAU,mBAAmB,kBAClC,SAAS,kBAAkB,OACxB;;;;;;;qBAQQ,iBAIN,UAAU,mBAAmB,qBAC/B,MAAM,aAAa,GAAG,mBAAmB,QACzC;;;;;;;;;qBAUQ,gBAMN,UAAU,mBAAmB,kBAClC,SAAS,kBAAkB,OACxB;;;;;;;qBAQQ,qBAeN,UAAU,mBAAmB,qBAC/B,MAAM,aAAa,GAAG,QAAQ,mBAAmB,SACjD"}
|
package/dist/effects.js
ADDED
|
@@ -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,t)=>e.resolvedThemes[t.key??`colorScheme`],l=a,u=()=>r(e=>e.resolvedThemes,i,{}),d=(e=>r(e=>e.resolvedThemes,n,e)),f=((t={})=>r(c,e,t)),p=(e=>r(c,t,e)),m=((e={})=>r((e,{keys:t})=>JSON.stringify(t.map(t=>e.resolvedThemes[t])),o,{keys:e.keys??[`colorScheme`]},!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=effects.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effects.js","names":["defineCoreEffect","runColorScheme","runThemeColor","runClassNames","createEffect","runDataAttributes","defineEffect$1","runDisableTransitions","combine","selectKey","state","options","defineEffect","setDataAttributes","setClassNames","classes","setColorScheme","setThemeColor","disableTransitions","keys","key"],"sources":["../src/effects.ts"],"sourcesContent":["import {\n type ClassMap,\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 {\n ResolvedThemeValue,\n ThemeSnapshot,\n ThemeStoreConfig,\n} from './index'\n\nexport { type Effect, combine }\n\n/** Any store's state; effects don't depend on a particular config. */\ntype AnySnapshot = { resolvedThemes: Record<string, unknown> }\n\n/** The settings of `T`. */\ntype SettingKey<T extends ThemeStoreConfig> = Extract<keyof T, string>\n\n/**\n * What setting `K` resolves to, as the string a map is looked up with. Any\n * string when no config type is given.\n */\ntype ValueKey<\n T extends ThemeStoreConfig,\n K extends keyof T,\n> = string extends keyof T\n ? string\n : `${Extract<ResolvedThemeValue<T, K>, string | number | boolean>}`\n\n/** `O` only when `T` has a `colorScheme` setting, the default `key`. */\ntype WithDefaultKey<\n T extends ThemeStoreConfig,\n O,\n> = 'colorScheme' extends keyof T ? O : never\n\n/** Options may be left out only when the default `key` exists. */\ntype OptionalArgs<T extends ThemeStoreConfig, O> = 'colorScheme' extends keyof T\n ? [options?: O]\n : [options: O]\n\ntype ColorSchemeOptions<T extends ThemeStoreConfig> =\n | {\n [K in SettingKey<T>]: {\n /** The setting to follow; defaults to `'colorScheme'`. */\n key: K\n /** Maps values that aren't valid `color-scheme` values. */\n values?: Partial<Record<ValueKey<T, K>, string>>\n }\n }[SettingKey<T>]\n | WithDefaultKey<\n T,\n {\n key?: undefined\n values?: Partial<Record<ValueKey<T, 'colorScheme' & keyof T>, string>>\n }\n >\n\ntype ThemeColorSource<V extends string> =\n | {\n /** A color for every value the setting can resolve to. */\n values: Record<V, string>\n cssVar?: never\n }\n | {\n /** A CSS variable on `<html>` holding the color. */\n cssVar: string\n values?: never\n }\n\ntype ThemeColorOptions<T extends ThemeStoreConfig> =\n | {\n [K in SettingKey<T>]: {\n /** The setting to follow; defaults to `'colorScheme'`. */\n key: K\n } & ThemeColorSource<ValueKey<T, K>>\n }[SettingKey<T>]\n | WithDefaultKey<\n T,\n { key?: undefined } & ThemeColorSource<\n ValueKey<T, 'colorScheme' & keyof T>\n >\n >\n\ntype ClassNamesOptions<T extends ThemeStoreConfig> = {\n [K in SettingKey<T>]?: Partial<Record<ValueKey<T, K>, string | null>>\n}\n\ntype TransitionsOptions<T extends ThemeStoreConfig> = {\n /** The settings whose change cuts transitions; defaults to `['colorScheme']`. */\n keys: Array<SettingKey<T>>\n}\n\nconst selectKey = (state: AnySnapshot, options: { key?: string }): string => {\n return state.resolvedThemes[options.key ?? 'colorScheme'] as string\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 fontSize = defineEffect<typeof CONFIG, { scale: number }>(\n * ({ resolvedThemes }, _prev, { scale }) => {\n * const px = { sm: 14, md: 16, lg: 18 }[resolvedThemes.fontSize] * scale\n * document.documentElement.style.fontSize = `${px}px`\n * }\n * )\n *\n * const applyThemes = combine(setDataAttributes(), fontSize({ scale: 1 }))\n */\nexport const defineEffect = defineCoreEffect as <\n T extends ThemeStoreConfig = ThemeStoreConfig,\n O extends object = Record<never, never>,\n>(\n run: (\n state: ThemeSnapshot<T>,\n prev: ThemeSnapshot<T> | undefined,\n options: O\n ) => void\n) => (options?: O) => Effect\n\n/**\n * Writes every resolved setting to a `data-*` attribute on `<html>`, e.g.\n * `data-color-scheme=\"dark\"`.\n */\nexport const setDataAttributes = (): Effect => {\n return createEffect(\n (state: AnySnapshot): Record<string, unknown> => {\n return state.resolvedThemes\n },\n runDataAttributes,\n {}\n )\n}\n\n/**\n * Adds a class on `<html>` for each mapped setting, chosen by its resolved\n * value, e.g. `class=\"dark\"` for Tailwind's or shadcn's `.dark` selectors.\n * Values that aren't mapped (or map to `null`) add no class. Every class in\n * the map is removed when it no longer applies, so the classes stay right\n * even if the page started with stale ones. Pass the config type to check\n * settings and values.\n *\n * @example\n * setClassNames<typeof CONFIG>({\n * colorScheme: { dark: 'dark', 'dark-dimmed': 'dark' },\n * contrast: { high: 'high-contrast' },\n * })\n */\nexport const setClassNames = ((classes: ClassMap): Effect => {\n return createEffect(\n (state: AnySnapshot): Record<string, unknown> => {\n return state.resolvedThemes\n },\n runClassNames,\n classes\n )\n}) as <T extends ThemeStoreConfig = ThemeStoreConfig>(\n classes: ClassNamesOptions<T>\n) => Effect\n\n/**\n * Sets the CSS `color-scheme` of `<html>`, so scrollbars, form controls and\n * the default canvas match. Follows `key` (default `'colorScheme'`); map\n * custom values with `values`, e.g. `{ 'dark-dimmed': 'dark' }`. Pass the\n * config type to check `key` and `values`.\n */\nexport const setColorScheme = ((\n options: { key?: string; values?: Record<string, string> } = {}\n): Effect => {\n return createEffect(selectKey, runColorScheme, options)\n}) as <T extends ThemeStoreConfig = ThemeStoreConfig>(\n ...args: OptionalArgs<T, ColorSchemeOptions<T>>\n) => Effect\n\n/**\n * Keeps `<meta name=\"theme-color\">` in sync with `key` (default\n * `'colorScheme'`), so the browser UI follows the user's choice rather than\n * the OS. Existing tags (media-based ones included) all get the color; with\n * none, one is added. Give a color for every value, or `cssVar` to read one\n * from `<html>` (list this after the effect that sets your attributes). Pass\n * the config type to check `key` and that no value is missing a color.\n */\nexport const setThemeColor = ((options: {\n key?: string\n values?: Record<string, string>\n cssVar?: string\n}): Effect => {\n return createEffect(selectKey, runThemeColor, options)\n}) as <T extends ThemeStoreConfig = ThemeStoreConfig>(\n options: ThemeColorOptions<T>\n) => Effect\n\n/**\n * Turns off CSS transitions for one frame when any of `keys` (default\n * `['colorScheme']`) changes, so colors switch at once instead of animating.\n * Does nothing on first paint or when other settings change. Pass the config\n * type to check `keys`.\n */\nexport const disableTransitions = ((\n options: { keys?: Array<string> } = {}\n): Effect => {\n return createEffect(\n (state: AnySnapshot, { keys }: { keys: Array<string> }): string => {\n return JSON.stringify(\n keys.map((key) => {\n return state.resolvedThemes[key]\n })\n )\n },\n runDisableTransitions,\n { keys: options.keys ?? ['colorScheme'] },\n true\n )\n}) as <T extends ThemeStoreConfig = ThemeStoreConfig>(\n ...args: OptionalArgs<T, Partial<TransitionsOptions<T>>>\n) => Effect\n"],"mappings":"A,gGAoGA,MAAMS,GAAa,EAAoB,IAC9BC,EAAM,eAAeC,EAAQ,KAAO,eAoBhCC,EAAeZ,EAefa,MACJT,EACJ,GACQM,EAAM,eAEfL,EACA,CAAC,CACH,EAiBWS,GAAkB,GACtBV,EACJ,GACQM,EAAM,eAEfP,EACAY,CACF,GAWWC,IACX,EAA6D,CAAC,IAEvDZ,EAAaK,EAAWR,EAAgBU,CAAO,GAa3CM,GAAkB,GAKtBb,EAAaK,EAAWP,EAAeS,CAAO,GAW1CO,IACX,EAAoC,CAAC,IAE9Bd,GACJ,EAAoB,CAAE,UACd,KAAK,UACVe,EAAK,IAAK,GACDT,EAAM,eAAeU,EAC7B,CACH,EAEFb,EACA,CAAE,KAAMI,EAAQ,MAAQ,CAAC,aAAa,CAAE,EACxC,EACF,G"}
|
package/dist/index.d.ts
CHANGED
|
@@ -62,6 +62,13 @@ type NonSystemOptionValues<T extends ThemeStoreConfig, K extends keyof T> = T[K]
|
|
|
62
62
|
} ? U extends ThemeValue ? U : U extends ThemeOption ? U extends {
|
|
63
63
|
media: ReadonlyArray<unknown>;
|
|
64
64
|
} ? never : U['value'] : never : never;
|
|
65
|
+
/**
|
|
66
|
+
* The values setting `K` can resolve to, as found in `resolvedThemes`: its
|
|
67
|
+
* options without the `media` one, or the free value's type.
|
|
68
|
+
*/
|
|
69
|
+
export type ResolvedThemeValue<T extends ThemeStoreConfig, K extends keyof T> = T[K] extends {
|
|
70
|
+
options: ReadonlyArray<unknown>;
|
|
71
|
+
} ? NonSystemOptionValues<T, K> : Themes<T>[K];
|
|
65
72
|
/**
|
|
66
73
|
* For each setting with a `media` option, the value that option currently
|
|
67
74
|
* resolves to, whether or not it is selected.
|
|
@@ -72,7 +79,13 @@ type Snapshot<T extends ThemeStoreConfig> = {
|
|
|
72
79
|
resolvedThemes: Themes<T>;
|
|
73
80
|
resolvedSystemThemes: ResolvedSystemThemes<T>;
|
|
74
81
|
};
|
|
75
|
-
|
|
82
|
+
/** The state passed to listeners; see `getSnapshot`. */
|
|
83
|
+
export type ThemeSnapshot<T extends ThemeStoreConfig> = Snapshot<T>;
|
|
84
|
+
/**
|
|
85
|
+
* Receives the new state and, except in the inline script (first paint), the
|
|
86
|
+
* state before the change.
|
|
87
|
+
*/
|
|
88
|
+
type Listener<T extends ThemeStoreConfig> = (value: Snapshot<T>, prev?: Snapshot<T>) => void;
|
|
76
89
|
type PersistedSystemOptionPairs = Record<string, [string, string]>;
|
|
77
90
|
type PersistedState<T extends ThemeStoreConfig> = {
|
|
78
91
|
themes: Partial<Themes<T>>;
|
|
@@ -208,9 +221,9 @@ export declare function createThemeStore<T extends ThemeStoreConfig>(config: T,
|
|
|
208
221
|
*/
|
|
209
222
|
restore: () => void;
|
|
210
223
|
/**
|
|
211
|
-
* Calls `callback` with the new state (see `getSnapshot`)
|
|
212
|
-
* change, including OS preference changes. Returns
|
|
213
|
-
* function.
|
|
224
|
+
* Calls `callback` with the new state (see `getSnapshot`) and the state
|
|
225
|
+
* before it after every change, including OS preference changes. Returns
|
|
226
|
+
* an unsubscribe function.
|
|
214
227
|
*/
|
|
215
228
|
subscribe: (callback: Listener<T>) => (() => void);
|
|
216
229
|
/**
|
|
@@ -236,7 +249,7 @@ export type ThemeScriptParameter = {
|
|
|
236
249
|
/**
|
|
237
250
|
* Applies the state to the page; receives the same value as `subscribe`.
|
|
238
251
|
* It is copied into the script as source code, so it can't use variables
|
|
239
|
-
* from outside the function.
|
|
252
|
+
* from outside the function. Typed loosely so a handler fits any config.
|
|
240
253
|
*/
|
|
241
254
|
handler: Listener<any>;
|
|
242
255
|
};
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";KAKK;KAEA,YAAY,UAAU;EACzB,OAAO;EACP,0BAA0B,GAAG;;KAG1B,YAAY,UAAU;EAErB,SAAS,cAAc,IAAI,YAAY;EACvC,eAAe;;EAEf,cAAc;EAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAiCX,mBAAmB,eAE7B,sBAAsB,sBAAsB;;;;;YAOlC,OAAO,UAAU,uBAC1B,WAAW,IAAI,EAAE;EAAa,SAAS,oBAAoB;IACxD,UAAU,cACR,aACA,IACF,EAAE;EAAa,o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;EA6D7B,qBAAA,UAAU,0BAA0B,IAAE,UAC/C,GAAC,OACJ,sBAAsB,GAAG,IAAI,sBAAsB,GAAG;;;;;EA5E3C,iBAAA,eAAe;;;;;EA6FtB;;;;;;EASS,YAAA,UAAA,SAAS;;;;;;;EAcrB;;;;;EAqBG;;YAQL,WAAW,UAAU,oBAAoB,kBAC5C,iBAAiB;;YAyEd;;EAEV;;EAEA,QAAQ;;;;;;EAOR,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA4BK,wBACd,uBAAuB,uBAAuB,MAAM"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{i as e,r as t,t as n}from"./utils-CWI4hy3w.js";import{n as r,t as i}from"./storage-fOH2xeQ1.js";function a(e){return Object.entries(e).map(([e,t])=>[e,(t.options||[]).map(e=>typeof e==`object`?e.value:e)])}function o(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.defaultValue??(typeof t.options[0]==`object`?t.options[0].value:t.options[0])]))}function s(e,{persisted:t={},storage:r=i({key:n})}={}){let a=o(e),s={...a,...t.themes},c={};for(let n in e){let r=(e[n].options||[]).find(e=>typeof e==`object`&&!!e.media);if(r){let{value:e,media:[i,a,o]}=r,s=[a,o];c[n]={value:e,mediaQuery:i,pair:[...t.systemOptions?.[n]??s],defaultPair:s}}}let l={},u=/* @__PURE__ */ new Set,d=new AbortController,f=r?.({abortController:d}),p=(e,t)=>{let{mediaQuery:n,pair:r}=c[e];if(t||typeof matchMedia>`u`)return r[1];let i=l[n];return i||(i=l[n]=matchMedia(n),i.addEventListener(`change`,()=>{_()},d)),r[+!i.matches]},m=e=>{let t={},n={...s};for(let r in c)t[r]=p(r,e),n[r]===c[r].value&&(n[r]=t[r]);return{themes:s,resolvedThemes:n,resolvedSystemThemes:t}},h=m(!0),g=m(),_=e=>{s={...s,...e};let t=g;g=m();for(let e of u)e(g,t)},v=e=>{let t;try{t=e?JSON.parse(e):void 0}catch{}if(t?.themes&&typeof t.themes==`object`){for(let e in t.systemOptions){let n=t.systemOptions[e];n&&c[e]&&(c[e].pair=n)}_(t.themes)}},y=()=>{let e={};for(let t in c)e[t]=[...c[t].pair];return{themes:{...s},systemOptions:e}},b=e=>{if(_(typeof e==`function`?e(s):e),f){let e=JSON.stringify(y());f.set(e),f.broadcast?.(e)}};return{getSnapshot:()=>g,getServerSnapshot:()=>h,setThemes:b,updateSystemOption:(e,t)=>{c[e].pair=[...t],b({})},toPersist:y,restore:()=>{v(f?.get())},subscribe:e=>(u.add(e),()=>{u.delete(e)}),sync:()=>f?.watch?.(e=>{if(e===null){for(let e in c){let t=c[e];t.pair=t.defaultPair}_(a)}else v(e)}),destroy:()=>{u.clear(),d.abort()}}}const c=e=>{e.forEach(([e,t,n])=>{let r;try{r=JSON.parse(localStorage.getItem(e))}catch{}n(t.reduce((e,[t,n,i,a,o,s])=>{let c=r?.themes?.[t]??n;if(e.resolvedThemes[t]=e.themes[t]=c,a!=null){let n=r?.systemOptions?.[t]??[o,s],l=matchMedia(a).matches?n[0]:n[1];e.resolvedSystemThemes[t]=l,c===i&&(e.resolvedThemes[t]=l)}return e},{themes:{},resolvedThemes:{},resolvedSystemThemes:{}}))})};function l(r){let i=(Array.isArray(r)?r:[r]).map(({key:r=n,config:i,handler:a})=>{let o=Object.entries(i).map(([e,{options:t,defaultValue:n}])=>{let r=t?.[0],i=n??(typeof r==`object`?r.value:r),a=t?.find(e=>typeof e==`object`&&!!e.media);if(a){let{value:t,media:n}=a;return[e,i,t,...n]}return[e,i]});return`[${e(r)},${e(o)},${t(a)}]`});return`(${c})([${i}])`}export{l as createInlineThemeScript,s as createThemeStore,o as getDefaultThemes,a as getThemesAndOptions,i as localStorageAdapter,r as memoryStorageAdapter};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["DEFAULT_KEY","toScriptJson","localStorageAdapter","getThemesAndOptions","config","themeKey","themeConfig","option","getDefaultThemes","createThemeStore","createStorage","defaultThemes","currentThemes","persisted","systemOptions","systemOption","mediaQuery","optionWhenMatched","optionWhenNotMatched","defaultPair","mediaQueryLists","listeners","abortController","storage","resolveSystemOption","server","pair","mqList","setThemesAndNotify","createSnapshot","resolvedSystemThemes","resolvedThemes","serverSnapshot","snapshot","themes","listener","applyStored","parsed","stored","toPersist","pairs","setThemes","callback","restoreScript","params","key","flattenedConfig","handler","initial","systemOptionValue","currentValue","systemTheme","acc","createInlineThemeScript","serializedArgs","themeScriptParameters","firstOption","options","resolvedInitialValue","defaultValue","value","media","toScriptFunction","memoryStorageAdapter"],"sources":["../src/index.ts"],"sourcesContent":["import { DEFAULT_KEY } from './constants'\nimport { toScriptFunction, toScriptJson } from './script'\nimport { type StorageAdapterCreate, localStorageAdapter } from './storage'\n\nexport * from './storage'\n\ntype ThemeValue = string | number | boolean\n\ntype ThemeOption<T extends ThemeValue = string> = {\n value: T\n media?: readonly [string, T, T]\n}\n\ntype ThemeConfig<T extends ThemeValue = string> =\n | {\n options: ReadonlyArray<T | ThemeOption<T>>\n defaultValue?: T\n }\n | { defaultValue: T; options?: never }\n\n/**\n * Config for `createThemeStore`. Each key is a theme setting (`colorMode`,\n * `contrast`, …) with either:\n *\n * - `options`: the allowed values, plus an optional `defaultValue` (otherwise the\n * first option). One option may be a `{ value, media }` object: when it is\n * selected, the setting follows a media query, using `media[1]` while the\n * query matches and `media[2]` while it doesn't.\n * - `defaultValue` alone: a free value of that type, such as a number.\n *\n * @example\n * const config = {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * contrast: {\n * options: ['normal', 'more'],\n * },\n * sidebarWidth: {\n * defaultValue: 240,\n * },\n * } as const satisfies ThemeStoreConfig\n */\nexport type ThemeStoreConfig = Record<\n string,\n ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>\n>\n\n/**\n * The selected value of each setting, as passed to `setThemes` (e.g.\n * `colorMode: 'system'`). Inferred from your `ThemeStoreConfig`.\n */\nexport type Themes<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : T[K] extends { defaultValue: infer U }\n ? U extends string\n ? string\n : U extends number\n ? number\n : boolean\n : never\n}\n\ntype ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = {\n [K in keyof T]: T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends { media: ReadonlyArray<unknown> }\n ? K\n : never\n : never\n}[keyof T]\n\ntype NonSystemOptionValues<\n T extends ThemeStoreConfig,\n K extends keyof T,\n> = T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeValue\n ? U\n : U extends ThemeOption\n ? U extends { media: ReadonlyArray<unknown> }\n ? never\n : U['value']\n : never\n : never\n\n/**\n * For each setting with a `media` option, the value that option currently\n * resolves to, whether or not it is selected.\n */\ntype ResolvedSystemThemes<T extends ThemeStoreConfig> = {\n [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>\n}\n\n/** Runtime state for each dimension that defines a `media` option. */\ntype SystemOptions = Record<\n string,\n {\n value: string\n mediaQuery: string\n pair: [string, string]\n defaultPair: [string, string]\n }\n>\n\ntype Snapshot<T extends ThemeStoreConfig> = {\n themes: Themes<T>\n resolvedThemes: Themes<T>\n resolvedSystemThemes: ResolvedSystemThemes<T>\n}\n\ntype Listener<T extends ThemeStoreConfig> = (value: Snapshot<T>) => void\n\ntype PersistedSystemOptionPairs = Record<string, [string, string]>\n\ntype PersistedState<T extends ThemeStoreConfig> = {\n themes: Partial<Themes<T>>\n systemOptions: PersistedSystemOptionPairs\n}\n\ntype ThemeStoreOptions<T extends ThemeStoreConfig> = {\n persisted?: Partial<PersistedState<T>>\n storage?: StorageAdapterCreate | null\n}\n\ntype ThemeAndOptions<T extends ThemeStoreConfig> = Array<\n {\n [K in keyof T]: [\n K,\n Array<\n T[K] extends { options: ReadonlyArray<infer U> }\n ? U extends ThemeOption\n ? U['value']\n : U\n : never\n >,\n ]\n }[keyof T]\n>\n\n/**\n * Lists each setting with its option values (`{ value, media }` options become\n * their `value`). Useful for rendering a picker for every setting.\n *\n * @example\n * import { getThemesAndOptions } from 'resonare'\n *\n * getThemesAndOptions({\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * },\n * })\n * // [['colorMode', ['light', 'dark', 'system']]]\n */\nexport function getThemesAndOptions<T extends ThemeStoreConfig>(config: T) {\n return Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n (themeConfig.options || []).map((option) => {\n return typeof option === 'object' ? option.value : option\n }),\n ]\n }) as ThemeAndOptions<T>\n}\n\n/**\n * Returns each setting's default: its `defaultValue`, or else its first\n * option.\n *\n * @example\n * import { getDefaultThemes } from 'resonare'\n *\n * getDefaultThemes({\n * colorMode: { options: ['light', 'dark'], defaultValue: 'dark' },\n * }) // { colorMode: 'dark' }\n */\nexport function getDefaultThemes<T extends ThemeStoreConfig>(config: T) {\n return Object.fromEntries(\n Object.entries(config).map(([themeKey, themeConfig]) => {\n return [\n themeKey,\n themeConfig.defaultValue ??\n (typeof themeConfig.options[0] === 'object'\n ? themeConfig.options[0].value\n : themeConfig.options[0]),\n ]\n })\n ) as Themes<T>\n}\n\n/**\n * Creates a store for the settings in `config`. It saves changes through\n * `storage` (`localStorage` under the key `'resonare'` by default; `null`\n * disables saving), resolves `media` options in the browser, and notifies\n * subscribers.\n *\n * Read state with `getSnapshot()` or `subscribe`.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * {\n * colorMode: {\n * options: [\n * 'light',\n * 'dark',\n * {\n * value: 'system',\n * media: ['(prefers-color-scheme: dark)', 'dark', 'light'],\n * },\n * ],\n * defaultValue: 'system',\n * },\n * },\n * { storage: localStorageAdapter({ key: 'my-app' }) }\n * )\n *\n * // In the browser: load the saved choice and follow other tabs.\n * store.restore()\n * store.sync()\n *\n * store.subscribe(({ resolvedThemes }) => {\n * document.documentElement.dataset.colorMode = resolvedThemes.colorMode\n * })\n *\n * store.setThemes({ colorMode: 'dark' })\n */\nexport function createThemeStore<T extends ThemeStoreConfig>(\n config: T,\n {\n persisted = {},\n storage: createStorage = localStorageAdapter({ key: DEFAULT_KEY }),\n }: ThemeStoreOptions<T> = {}\n) {\n const defaultThemes = getDefaultThemes(config)\n\n let currentThemes: Themes<T> = { ...defaultThemes, ...persisted.themes }\n\n const systemOptions: SystemOptions = {}\n\n for (const themeKey in config) {\n const systemOption = (config[themeKey]!.options || []).find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const {\n value,\n media: [mediaQuery, optionWhenMatched, optionWhenNotMatched],\n } = systemOption\n\n const defaultPair: [string, string] = [\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n\n systemOptions[themeKey] = {\n value,\n mediaQuery,\n pair: [...(persisted.systemOptions?.[themeKey] ?? defaultPair)],\n defaultPair,\n }\n }\n }\n\n const mediaQueryLists: Record<string, MediaQueryList> = {}\n\n const listeners = new Set<Listener<T>>()\n\n const abortController = new AbortController()\n\n const storage = createStorage?.({ abortController })\n\n const resolveSystemOption = (themeKey: string, server?: boolean): string => {\n const { mediaQuery, pair } = systemOptions[themeKey]!\n\n // No media support (e.g. on the server): use the \"not matched\" value.\n if (server || typeof matchMedia === 'undefined') {\n return pair[1]\n }\n\n let mqList = mediaQueryLists[mediaQuery]\n\n if (!mqList) {\n mqList = mediaQueryLists[mediaQuery] = matchMedia(mediaQuery)\n\n mqList.addEventListener(\n 'change',\n () => {\n setThemesAndNotify()\n },\n abortController\n )\n }\n\n return pair[mqList.matches ? 0 : 1]\n }\n\n const createSnapshot = (server?: boolean): Snapshot<T> => {\n const resolvedSystemThemes: Record<string, string> = {}\n\n const resolvedThemes = { ...currentThemes } as Record<string, ThemeValue>\n\n for (const themeKey in systemOptions) {\n resolvedSystemThemes[themeKey] = resolveSystemOption(themeKey, server)\n\n if (resolvedThemes[themeKey] === systemOptions[themeKey]!.value) {\n resolvedThemes[themeKey] = resolvedSystemThemes[themeKey]\n }\n }\n\n return {\n themes: currentThemes,\n resolvedThemes: resolvedThemes as Themes<T>,\n resolvedSystemThemes: resolvedSystemThemes as ResolvedSystemThemes<T>,\n }\n }\n\n const serverSnapshot = createSnapshot(true)\n\n let snapshot = createSnapshot()\n\n const setThemesAndNotify = (themes?: Partial<Themes<T>>): void => {\n currentThemes = { ...currentThemes, ...themes }\n\n snapshot = createSnapshot()\n\n for (const listener of listeners) {\n listener(snapshot)\n }\n }\n\n /** Applies saved state; ignores empty or malformed input. */\n const applyStored = (stored: string | null | undefined): void => {\n let parsed: PersistedState<T> | undefined\n\n try {\n parsed = stored ? JSON.parse(stored) : undefined\n } catch {}\n\n if (!parsed?.themes || typeof parsed.themes !== 'object') {\n return\n }\n\n for (const themeKey in parsed.systemOptions) {\n const pair = parsed.systemOptions[themeKey]\n\n if (pair && systemOptions[themeKey]) {\n systemOptions[themeKey].pair = pair\n }\n }\n\n setThemesAndNotify(parsed.themes)\n }\n\n const toPersist = (): PersistedState<T> => {\n const pairs: PersistedSystemOptionPairs = {}\n\n for (const themeKey in systemOptions) {\n pairs[themeKey] = [...systemOptions[themeKey]!.pair]\n }\n\n return { themes: { ...currentThemes }, systemOptions: pairs }\n }\n\n const setThemes = (\n themes:\n | Partial<Themes<T>>\n | ((currentThemes: Themes<T>) => Partial<Themes<T>>)\n ): void => {\n setThemesAndNotify(\n typeof themes === 'function' ? themes(currentThemes) : themes\n )\n\n if (storage) {\n const stored = JSON.stringify(toPersist())\n\n storage.set(stored)\n\n storage.broadcast?.(stored)\n }\n }\n\n return {\n /**\n * Current state:\n *\n * - `themes`: the selected value of each setting (e.g. `'system'`).\n * - `resolvedThemes`: the same with `media` options resolved (e.g. `'dark'`).\n * - `resolvedSystemThemes`: what each `media` option resolves to, even when\n * it isn't selected.\n *\n * Returns the same object until the next change.\n */\n getSnapshot: (): Snapshot<T> => {\n return snapshot\n },\n\n /**\n * The state as rendered on the server: defaults plus `persisted`, with\n * `media` options resolved to their \"not matched\" value. It never changes,\n * so hydration can match the server HTML even after `restore()`.\n */\n getServerSnapshot: (): Snapshot<T> => {\n return serverSnapshot\n },\n\n /**\n * Updates the given settings (others keep their value), saves to storage,\n * and notifies subscribers.\n *\n * @example\n * store.setThemes({ colorMode: 'dark' })\n *\n * store.setThemes((current) => ({\n * colorMode: current.colorMode === 'dark' ? 'light' : 'dark',\n * }))\n */\n setThemes,\n\n /**\n * Changes which values a `media` option resolves to: `[whenMatched,\n * whenNotMatched]`, replacing `media[1]` and `media[2]` from the config.\n * Saved like `setThemes`.\n *\n * @example\n * // system now picks 'dark-dimmed' when the OS prefers dark\n * store.updateSystemOption('colorMode', ['dark-dimmed', 'light'])\n */\n updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(\n themeKey: K,\n pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]\n ): void => {\n systemOptions[themeKey as string]!.pair = [...pair]\n\n setThemes({})\n },\n\n /**\n * The state to save, e.g. to a database: pass it back as `persisted` when\n * creating the store.\n */\n toPersist,\n\n /**\n * Loads the saved state from storage. Does nothing when nothing is saved.\n * Call it in the browser, e.g. after hydration.\n */\n restore: (): void => {\n applyStored(storage?.get())\n },\n\n /**\n * Calls `callback` with the new state (see `getSnapshot`) after every\n * change, including OS preference changes. Returns an unsubscribe\n * function.\n */\n subscribe: (callback: Listener<T>): (() => void) => {\n listeners.add(callback)\n\n return () => {\n listeners.delete(callback)\n }\n },\n\n /**\n * Applies changes saved by other tabs (if the storage adapter supports\n * it); when another tab clears the saved state, resets to the config\n * defaults. Returns a function that stops syncing, or `undefined` when the\n * adapter can't sync.\n */\n sync: (): (() => void) | undefined => {\n return storage?.watch?.((stored) => {\n // `null` means another tab cleared the stored preferences.\n if (stored === null) {\n for (const themeKey in systemOptions) {\n const systemOption = systemOptions[themeKey]!\n\n systemOption.pair = systemOption.defaultPair\n }\n\n setThemesAndNotify(defaultThemes)\n } else {\n applyStored(stored)\n }\n })\n },\n\n /**\n * Removes all subscribers and stops listening to media queries and\n * storage. The store doesn't update after this.\n */\n destroy: (): void => {\n listeners.clear()\n\n abortController.abort()\n },\n }\n}\n\nexport type ThemeStore<T extends ThemeStoreConfig> = ReturnType<\n typeof createThemeStore<T>\n>\n\nconst restoreScript = <T extends ThemeValue>(\n params: Array<\n [string, Array<[string, T] | [string, T, T, string, T, T]>, Listener<any>]\n >\n) => {\n params.forEach(([key, flattenedConfig, handler]) => {\n let persisted: any\n\n // Blocked storage or bad JSON must not stop the handler from running.\n try {\n persisted = JSON.parse(localStorage.getItem(key)!)\n } catch {}\n\n handler(\n flattenedConfig.reduce<{\n themes: Record<string, ThemeValue>\n resolvedThemes: Record<string, ThemeValue>\n resolvedSystemThemes: Record<string, ThemeValue>\n }>(\n (\n acc,\n [\n themeKey,\n initial,\n systemOptionValue,\n mediaQuery,\n optionWhenMatched,\n optionWhenNotMatched,\n ]\n ) => {\n const currentValue = persisted?.themes?.[themeKey] ?? initial\n\n acc.resolvedThemes[themeKey] = acc.themes[themeKey] = currentValue\n\n if (mediaQuery != null) {\n const pair = persisted?.systemOptions?.[themeKey] ?? [\n optionWhenMatched!,\n optionWhenNotMatched!,\n ]\n\n const systemTheme = matchMedia(mediaQuery).matches\n ? pair[0]\n : pair[1]\n\n acc.resolvedSystemThemes[themeKey] = systemTheme\n\n if (currentValue === systemOptionValue) {\n acc.resolvedThemes[themeKey] = systemTheme\n }\n }\n\n return acc\n },\n { themes: {}, resolvedThemes: {}, resolvedSystemThemes: {} }\n )\n )\n })\n}\n\n/** One store for `createInlineThemeScript`. */\nexport type ThemeScriptParameter = {\n /** The store's `localStorage` key; defaults to `'resonare'`. */\n key?: string\n /** The same config passed to `createThemeStore`. */\n config: ThemeStoreConfig\n /**\n * Applies the state to the page; receives the same value as `subscribe`.\n * It is copied into the script as source code, so it can't use variables\n * from outside the function.\n */\n handler: Listener<any>\n}\n\n/**\n * Returns the source of a small script that reads the saved state from\n * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in\n * the `<head>` so the page has the right theme before first paint. Pass an\n * array to set up several stores.\n *\n * Use the same handler with `store.subscribe` to keep the page updated after\n * that.\n *\n * @example\n * import { createInlineThemeScript } from 'resonare'\n *\n * // config: the same object passed to createThemeStore\n * const themeScript = createInlineThemeScript({\n * key: 'my-app',\n * config,\n * handler: ({ resolvedThemes }) => {\n * const root = document.documentElement\n * root.dataset.colorMode = resolvedThemes.colorMode\n * },\n * })\n *\n * // In <head>:\n * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />\n */\nexport function createInlineThemeScript(\n themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>\n) {\n const serializedArgs = (\n Array.isArray(themeScriptParameters)\n ? themeScriptParameters\n : [themeScriptParameters]\n ).map(({ key = DEFAULT_KEY, config, handler }) => {\n const flattenedConfig = Object.entries(config).map(\n ([themeKey, { options, defaultValue }]) => {\n const firstOption = options?.[0]\n\n const resolvedInitialValue =\n defaultValue ??\n (typeof firstOption === 'object' ? firstOption.value : firstOption!)\n\n const systemOption = options?.find(\n (option): option is Required<ThemeOption> => {\n return typeof option === 'object' && !!option.media\n }\n )\n\n if (systemOption) {\n const { value, media } = systemOption\n\n return [themeKey, resolvedInitialValue, value, ...media]\n }\n\n return [themeKey, resolvedInitialValue]\n }\n )\n\n return `[${toScriptJson(key)},${toScriptJson(flattenedConfig)},${toScriptFunction(handler)}]`\n })\n\n return `(${restoreScript})([${serializedArgs}])`\n}\n"],"mappings":"A,4DA0KA,SAAgBG,EAAgD,EAAW,CACzE,OAAO,OAAO,QAAQC,CAAM,CAAC,CAAC,KAAK,CAACC,EAAUC,KACrC,CACLD,GACCC,E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EAEnC,CAEA,OAAOC,CACT,EACA,CAAE,OAAQ,CAAC,EAAG,eAAgB,CAAC,EAAG,qBAAsB,CAAC,CAAE,CAC7D,CACF,CACF,CAAC,CACH,EAyCA,SAAgBC,EACd,EACA,CACA,IAAMC,GACJ,MAAM,QAAQC,CAAqB,EAC/BA,EACA,CAACA,CAAqB,EAAA,CAC1B,KAAK,CAAE,MAAMvD,EAAa,SAAQ,aAAc,CAChD,IAAM8C,EAAkB,OAAO,QAAQ1C,CAAM,CAAC,CAAC,KAC5C,CAACC,EAAU,CAAE,UAAS,mBAAoB,CACzC,IAAMmD,EAAcC,IAAU,GAExBC,EACJC,IACC,OAAOH,GAAgB,SAAWA,EAAY,MAAQA,GAEnDzC,EAAe0C,GAAS,KAC3B,GACQ,OAAOlD,GAAW,UAAY,CAAC,CAACA,EAAO,KAElD,EAEA,GAAIQ,EAAc,CAChB,GAAM,CAAE,QAAO,SAAUA,EAEzB,MAAO,CAACV,EAAUqD,EAAsBE,EAAO,GAAGC,CAAK,CACzD,CAEA,MAAO,CAACxD,EAAUqD,CAAoB,CACxC,CACF,EAEA,MAAO,IAAIzD,EAAa4C,CAAG,EAAE,GAAG5C,EAAa6C,CAAe,EAAE,GAAGgB,EAAiBf,CAAO,EAAE,EAC7F,CAAC,EAED,MAAO,IAAIJ,EAAc,KAAKW,EAAe,GAC/C,C"}
|
|
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)},${toScriptJson(flattenedConfig)},${toScriptFunction(handler)}]`\n })\n\n return `(${restoreScript})([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W,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"}
|
package/dist/lite-react.d.ts
CHANGED
|
@@ -35,6 +35,10 @@ export declare function useResonare(store: ThemeStore): {
|
|
|
35
35
|
theme: "dark" | "light" | "system";
|
|
36
36
|
resolvedTheme: "dark" | "light";
|
|
37
37
|
systemTheme: "dark" | "light";
|
|
38
|
+
}, prev?: {
|
|
39
|
+
theme: "dark" | "light" | "system";
|
|
40
|
+
resolvedTheme: "dark" | "light";
|
|
41
|
+
systemTheme: "dark" | "light";
|
|
38
42
|
}) => void) => (() => void);
|
|
39
43
|
sync: () => (() => void) | undefined;
|
|
40
44
|
};
|
package/dist/lite-solid.d.ts
CHANGED
|
@@ -36,6 +36,10 @@ export declare function useResonare(store: ThemeStore): {
|
|
|
36
36
|
theme: "dark" | "light" | "system";
|
|
37
37
|
resolvedTheme: "dark" | "light";
|
|
38
38
|
systemTheme: "dark" | "light";
|
|
39
|
+
}, prev?: {
|
|
40
|
+
theme: "dark" | "light" | "system";
|
|
41
|
+
resolvedTheme: "dark" | "light";
|
|
42
|
+
systemTheme: "dark" | "light";
|
|
39
43
|
}) => void) => (() => void);
|
|
40
44
|
sync: () => (() => void) | undefined;
|
|
41
45
|
};
|
package/dist/lite-svelte.d.ts
CHANGED
|
@@ -35,6 +35,10 @@ export declare function useResonare(store: ThemeStore): {
|
|
|
35
35
|
theme: "dark" | "light" | "system";
|
|
36
36
|
resolvedTheme: "dark" | "light";
|
|
37
37
|
systemTheme: "dark" | "light";
|
|
38
|
+
}, prev?: {
|
|
39
|
+
theme: "dark" | "light" | "system";
|
|
40
|
+
resolvedTheme: "dark" | "light";
|
|
41
|
+
systemTheme: "dark" | "light";
|
|
38
42
|
}) => void) => (() => void);
|
|
39
43
|
sync: () => (() => void) | undefined;
|
|
40
44
|
};
|
package/dist/lite-vue.d.ts
CHANGED
|
@@ -42,6 +42,10 @@ export declare function useResonare(store: ThemeStore, { hydrate }?: UseResonare
|
|
|
42
42
|
theme: "dark" | "light" | "system";
|
|
43
43
|
resolvedTheme: "dark" | "light";
|
|
44
44
|
systemTheme: "dark" | "light";
|
|
45
|
+
}, prev?: {
|
|
46
|
+
theme: "dark" | "light" | "system";
|
|
47
|
+
resolvedTheme: "dark" | "light";
|
|
48
|
+
systemTheme: "dark" | "light";
|
|
45
49
|
}) => void) => (() => void);
|
|
46
50
|
sync: () => (() => void) | undefined;
|
|
47
51
|
};
|
package/dist/lite.d.ts
CHANGED
|
@@ -6,7 +6,13 @@ type Snapshot = {
|
|
|
6
6
|
resolvedTheme: ResolvedTheme;
|
|
7
7
|
systemTheme: ResolvedTheme;
|
|
8
8
|
};
|
|
9
|
-
|
|
9
|
+
/** The state passed to listeners; see `getSnapshot`. */
|
|
10
|
+
export type ThemeSnapshot = Snapshot;
|
|
11
|
+
/**
|
|
12
|
+
* Receives the new state and, except in the inline script (first paint), the
|
|
13
|
+
* state before the change.
|
|
14
|
+
*/
|
|
15
|
+
type Listener = (value: Snapshot, prev?: Snapshot) => void;
|
|
10
16
|
type ThemeStoreOptions = {
|
|
11
17
|
persisted?: Theme;
|
|
12
18
|
storage?: StorageAdapterCreate | null;
|
|
@@ -67,9 +73,9 @@ export declare function createThemeStore({ persisted, storage: createStorage }?:
|
|
|
67
73
|
*/
|
|
68
74
|
restore: () => void;
|
|
69
75
|
/**
|
|
70
|
-
* Calls `callback` with the new state (see `getSnapshot`)
|
|
71
|
-
* change, including OS preference changes. Returns
|
|
72
|
-
* function.
|
|
76
|
+
* Calls `callback` with the new state (see `getSnapshot`) and the state
|
|
77
|
+
* before it after every change, including OS preference changes. Returns
|
|
78
|
+
* an unsubscribe function.
|
|
73
79
|
*/
|
|
74
80
|
subscribe: (callback: Listener) => (() => void);
|
|
75
81
|
/**
|
package/dist/lite.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lite.d.ts","names":[],"sources":["../src/lite.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"lite.d.ts","names":[],"sources":["../src/lite.ts"],"mappings":";KAKK;KAEA;KAEA;EACH,OAAO;EACP,eAAe;EACf,aAAa;;;YAIH,gBAAgB;;;;;KAMvB,YAAY,OAAO,UAAU,OAAO;KAEpC;EACH,YAAY;EACZ,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA4BI,mBACd,WACA,SAAS,kBACR;;;;;;;;;;EAoEC,mBAAiB;;;;;;EASjB,yBAAuB;;;;;;;;EAWvB,WAAQ,MAAS,UAAU,SAAS,UAAU;;;;;EAY9C;;;;;;EAaA,YAAS,UAAa;;;;;;;EActB;;;;;EAUA;;YAQQ,aAAa,kBAAkB;;YAoB/B;;EAEV;;;;;;EAMA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;wBAyBK,0BACd,KACA,WACC"}
|
package/dist/lite.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,n as t,
|
|
1
|
+
import{i as e,n as t,r as n}from"./utils-CWI4hy3w.js";import{n as r,t as i}from"./storage-fOH2xeQ1.js";function a({persisted:e,storage:n=i({key:t})}={}){let r=e??`system`,a,o=/* @__PURE__ */ new Set,s=new AbortController,c=n?.({abortController:s}),l=e=>e||typeof matchMedia>`u`?`light`:(a||(a=matchMedia(`(prefers-color-scheme: dark)`),a.addEventListener(`change`,()=>{p(r)},s)),a.matches?`dark`:`light`),u=e=>{let t=l(e);return{theme:r,resolvedTheme:r===`system`?t:r,systemTheme:t}},d=u(!0),f=u(),p=e=>{r=e;let t=f;f=u();for(let e of o)e(f,t)};return{getSnapshot:()=>f,getServerSnapshot:()=>d,setTheme:e=>{p(typeof e==`function`?e(r):e),c?.set(r),c?.broadcast?.(r)},restore:()=>{let e=c?.get();e&&p(e)},subscribe:e=>(o.add(e),()=>{o.delete(e)}),sync:()=>c?.watch?.(e=>{p(e??`system`)}),destroy:()=>{o.clear(),s.abort()}}}const o=(e,t)=>{let n=`system`;try{n=localStorage.getItem(e)??n}catch{}let r=matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`;t({theme:n,resolvedTheme:n===`system`?r:n,systemTheme:r})};function s({key:r=t,handler:i}){return`(${o})(${e(r)},${n(i)})`}export{s as createInlineThemeScript,a as createThemeStore,i as localStorageAdapter,r as memoryStorageAdapter};
|
|
2
2
|
//# sourceMappingURL=lite.js.map
|
package/dist/lite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lite.js","names":["toScriptJson","
|
|
1
|
+
{"version":3,"file":"lite.js","names":["toScriptJson","DEFAULT_LITE_KEY","toScriptFunction","memoryStorageAdapter","localStorageAdapter","createThemeStore","createStorage","theme","persisted","mediaQuery","listeners","abortController","storage","resolveSystemTheme","server","setThemeAndNotify","createSnapshot","systemTheme","serverSnapshot","snapshot","next","prev","listener","stored","callback","restoreScript","key","handler","createInlineThemeScript"],"sources":["../src/lite.ts"],"sourcesContent":["import { type StorageAdapterCreate, localStorageAdapter } from './storage'\nimport { DEFAULT_LITE_KEY, toScriptFunction, toScriptJson } from './utils'\n\nexport * from './storage'\n\ntype Theme = 'system' | 'light' | 'dark'\n\ntype ResolvedTheme = 'light' | 'dark'\n\ntype Snapshot = {\n theme: Theme\n resolvedTheme: ResolvedTheme\n systemTheme: ResolvedTheme\n}\n\n/** The state passed to listeners; see `getSnapshot`. */\nexport type ThemeSnapshot = Snapshot\n\n/**\n * Receives the new state and, except in the inline script (first paint), the\n * state before the change.\n */\ntype Listener = (value: Snapshot, prev?: Snapshot) => void\n\ntype ThemeStoreOptions = {\n persisted?: Theme\n storage?: StorageAdapterCreate | null\n}\n\n/**\n * Creates a store for a single light / dark / system preference. It saves\n * changes through `storage` (`localStorage` under the key `'resonare/lite'` by\n * default; `null` disables saving), follows `prefers-color-scheme` while the\n * preference is `system`, and notifies subscribers.\n *\n * Read state with `getSnapshot()` or `subscribe`.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare/lite'\n *\n * const store = createThemeStore({\n * storage: localStorageAdapter({ key: 'my-app' }),\n * })\n *\n * // In the browser: load the saved choice and follow other tabs.\n * store.restore()\n * store.sync()\n *\n * store.subscribe(({ resolvedTheme }) => {\n * document.documentElement.dataset.theme = resolvedTheme\n * })\n *\n * store.setTheme('dark')\n */\nexport function createThemeStore({\n persisted,\n storage: createStorage = localStorageAdapter({ key: DEFAULT_LITE_KEY }),\n}: ThemeStoreOptions = {}) {\n let theme: Theme = persisted ?? 'system'\n\n let mediaQuery: MediaQueryList | undefined\n\n const listeners = new Set<Listener>()\n\n const abortController = new AbortController()\n\n const storage = createStorage?.({ abortController })\n\n // No media support (e.g. on the server): `system` is `light`.\n const resolveSystemTheme = (server?: boolean): ResolvedTheme => {\n if (server || typeof matchMedia === 'undefined') {\n return 'light'\n }\n\n if (!mediaQuery) {\n mediaQuery = matchMedia('(prefers-color-scheme: dark)')\n\n mediaQuery.addEventListener(\n 'change',\n () => {\n setThemeAndNotify(theme)\n },\n abortController\n )\n }\n\n return mediaQuery.matches ? 'dark' : 'light'\n }\n\n const createSnapshot = (server?: boolean): Snapshot => {\n const systemTheme = resolveSystemTheme(server)\n\n return {\n theme,\n resolvedTheme: theme === 'system' ? systemTheme : theme,\n systemTheme,\n }\n }\n\n const serverSnapshot = createSnapshot(true)\n\n let snapshot = createSnapshot()\n\n const setThemeAndNotify = (next: Theme): void => {\n theme = next\n\n const prev = snapshot\n\n snapshot = createSnapshot()\n\n for (const listener of listeners) {\n listener(snapshot, prev)\n }\n }\n\n return {\n /**\n * Current state:\n *\n * - `theme`: the selected preference (`'system'`, `'light'` or `'dark'`).\n * - `resolvedTheme`: `'light'` or `'dark'`, with `system` resolved.\n * - `systemTheme`: the OS preference, even when `system` isn't selected.\n *\n * Returns the same object until the next change.\n */\n getSnapshot: (): Snapshot => {\n return snapshot\n },\n\n /**\n * The state as rendered on the server: `persisted` (or `system`), with the\n * OS preference taken as `light`. It never changes, so hydration can match\n * the server HTML even after `restore()`.\n */\n getServerSnapshot: (): Snapshot => {\n return serverSnapshot\n },\n\n /**\n * Sets the preference, saves it to storage, and notifies subscribers.\n *\n * @example\n * store.setTheme('dark')\n * store.setTheme((current) => (current === 'dark' ? 'light' : 'dark'))\n */\n setTheme: (next: Theme | ((current: Theme) => Theme)): void => {\n setThemeAndNotify(typeof next === 'function' ? next(theme) : next)\n\n storage?.set(theme)\n\n storage?.broadcast?.(theme)\n },\n\n /**\n * Loads the saved preference from storage. Does nothing when nothing is\n * saved. Call it in the browser, e.g. after hydration.\n */\n restore: (): void => {\n const stored = storage?.get() as Theme | null | undefined\n\n if (stored) {\n setThemeAndNotify(stored)\n }\n },\n\n /**\n * Calls `callback` with the new state (see `getSnapshot`) and the state\n * before it after every change, including OS preference changes. Returns\n * an unsubscribe function.\n */\n subscribe: (callback: Listener): (() => void) => {\n listeners.add(callback)\n\n return () => {\n listeners.delete(callback)\n }\n },\n\n /**\n * Applies changes saved by other tabs (if the storage adapter supports\n * it); when another tab clears the saved value, resets to `system`.\n * Returns a function that stops syncing, or `undefined` when the adapter\n * can't sync.\n */\n sync: (): (() => void) | undefined => {\n return storage?.watch?.((stored) => {\n setThemeAndNotify((stored ?? 'system') as Theme)\n })\n },\n\n /**\n * Removes all subscribers and stops listening to the OS preference and\n * storage. The store doesn't update after this.\n */\n destroy: (): void => {\n listeners.clear()\n\n abortController.abort()\n },\n }\n}\n\nexport type ThemeStore = ReturnType<typeof createThemeStore>\n\nconst restoreScript = (key: string, handler: Listener) => {\n let theme: Theme = 'system'\n\n // Blocked storage must not stop the handler from running.\n try {\n theme = (localStorage.getItem(key) ?? theme) as Theme\n } catch {}\n\n const systemTheme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light'\n\n const resolvedTheme = theme === 'system' ? systemTheme : theme\n\n handler({ theme, resolvedTheme, systemTheme })\n}\n\n/** Options for `createInlineThemeScript`. */\nexport type ThemeScriptParameter = {\n /** The store's `localStorage` key; defaults to `'resonare/lite'`. */\n key?: string\n /**\n * Applies the state to the page; receives the same value as `subscribe`.\n * It is copied into the script as source code, so it can't use variables\n * from outside the function.\n */\n handler: Listener\n}\n\n/**\n * Returns the source of a small script that reads the saved preference from\n * `localStorage` and runs `handler` with it. Put it in an inline `<script>` in\n * the `<head>` so the page has the right theme before first paint.\n *\n * Use the same handler with `store.subscribe` to keep the page updated after\n * that.\n *\n * @example\n * import { createInlineThemeScript, createThemeStore } from 'resonare/lite'\n *\n * const handler = ({ resolvedTheme }) => {\n * document.documentElement.dataset.theme = resolvedTheme\n * }\n *\n * const themeScript = createInlineThemeScript({ key: 'my-app', handler })\n * // In <head>:\n * // <script dangerouslySetInnerHTML={{ __html: themeScript }} />\n *\n * const store = createThemeStore()\n * store.subscribe(handler)\n */\nexport function createInlineThemeScript({\n key = DEFAULT_LITE_KEY,\n handler,\n}: ThemeScriptParameter) {\n return `(${restoreScript})(${toScriptJson(key)},${toScriptFunction(handler)})`\n}\n"],"mappings":"A,uGAsDA,SAAgBK,EAAiB,CAC/B,YACA,QAASC,EAAgBF,EAAoB,CAAE,IAAKH,CAAiB,CAAC,GACjD,CAAC,EAAG,CACzB,IAAIM,EAAeC,GAAa,SAE5BC,EAEEC,kBAAY,IAAI,IAEhBC,EAAkB,IAAI,gBAEtBC,EAAUN,IAAgB,CAAE,iBAAgB,CAAC,EAG7CO,EAAsB,GACtBC,GAAU,OAAO,WAAe,IAC3B,SAGJL,IACH,EAAa,WAAW,8BAA8B,EAEtDA,E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G,EAAE,GAAGxB,EAAiByB,CAAO,EAAE,EAC9E,C"}
|
package/dist/react.d.ts
CHANGED
|
@@ -56,7 +56,22 @@ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStor
|
|
|
56
56
|
} ? U extends {
|
|
57
57
|
media: ReadonlyArray<unknown>;
|
|
58
58
|
} ? never : U["value"] : never : never; };
|
|
59
|
-
}
|
|
59
|
+
}, prev?: {
|
|
60
|
+
themes: Themes<T>;
|
|
61
|
+
resolvedThemes: Themes<T>;
|
|
62
|
+
resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
|
|
63
|
+
options: ReadonlyArray<infer U>;
|
|
64
|
+
} ? U extends {
|
|
65
|
+
media: ReadonlyArray<unknown>;
|
|
66
|
+
} ? K : never : never; }[keyof T]]: T[K] extends {
|
|
67
|
+
options: ReadonlyArray<infer U>;
|
|
68
|
+
} ? U extends string | number | boolean ? U : U extends {
|
|
69
|
+
value: string;
|
|
70
|
+
media?: readonly [string, string, string] | undefined;
|
|
71
|
+
} ? U extends {
|
|
72
|
+
media: ReadonlyArray<unknown>;
|
|
73
|
+
} ? never : U["value"] : never : never; };
|
|
74
|
+
} | undefined) => void) => () => void;
|
|
60
75
|
sync: () => (() => void) | undefined;
|
|
61
76
|
toPersist: () => {
|
|
62
77
|
themes: Partial<Themes<T>>;
|
package/dist/solid.d.ts
CHANGED
|
@@ -53,7 +53,22 @@ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStor
|
|
|
53
53
|
} ? U extends {
|
|
54
54
|
media: ReadonlyArray<unknown>;
|
|
55
55
|
} ? never : U["value"] : never : never; };
|
|
56
|
-
}
|
|
56
|
+
}, prev?: {
|
|
57
|
+
themes: Themes<T>;
|
|
58
|
+
resolvedThemes: Themes<T>;
|
|
59
|
+
resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
|
|
60
|
+
options: ReadonlyArray<infer U>;
|
|
61
|
+
} ? U extends {
|
|
62
|
+
media: ReadonlyArray<unknown>;
|
|
63
|
+
} ? K : never : never; }[keyof T]]: T[K] extends {
|
|
64
|
+
options: ReadonlyArray<infer U>;
|
|
65
|
+
} ? U extends string | number | boolean ? U : U extends {
|
|
66
|
+
value: string;
|
|
67
|
+
media?: readonly [string, string, string] | undefined;
|
|
68
|
+
} ? U extends {
|
|
69
|
+
media: ReadonlyArray<unknown>;
|
|
70
|
+
} ? never : U["value"] : never : never; };
|
|
71
|
+
} | undefined) => void) => () => void;
|
|
57
72
|
sync: () => (() => void) | undefined;
|
|
58
73
|
toPersist: () => {
|
|
59
74
|
themes: Partial<Themes<T>>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./utils-CWI4hy3w.js";const t=({key:e,type:t=`localStorage`})=>({abortController:n})=>({get:()=>{try{return window[t].getItem(e)}catch{return null}},set:n=>{try{window[t].setItem(e,n)}catch{}},watch:r=>{let i=n=>{n.storageArea===window[t]&&n.key===e&&r(n.newValue)};return addEventListener(`storage`,i,n),()=>{removeEventListener(`storage`,i)}}}),n=({key:t})=>({abortController:n})=>{let r=/* @__PURE__ */ new Map,i=new BroadcastChannel(e);return n.signal.addEventListener(`abort`,()=>{i.close()}),{get:()=>r.get(t)??null,set:e=>{r.set(t,e)},broadcast:e=>{i.postMessage({key:t,value:e})},watch:e=>{let n=n=>{n.data.key===t&&(r.set(t,n.data.value),e(n.data.value))};return i.addEventListener(`message`,n),()=>{i.removeEventListener(`message`,n)}}}};export{n,t};
|
|
2
|
+
//# sourceMappingURL=storage-fOH2xeQ1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage-fOH2xeQ1.js","names":["DEFAULT_KEY","localStorageAdapter","type","key","value","listener","e","cb","abortController","memoryStorageAdapter","storage","channel"],"sources":["../src/storage.ts"],"sourcesContent":["import { DEFAULT_KEY } from './utils'\n\n/**\n * Where a store saves its state. Values are strings: the full store saves\n * JSON, the lite store saves the theme name.\n */\nexport type StorageAdapter = {\n /** Returns the saved value, or `null` when nothing is saved. */\n get: () => string | null\n /** Saves a value. */\n set: (value: string) => void\n /** Optional: tells other tabs about a value just saved with `set`. */\n broadcast?: (value: string) => void\n /**\n * Optional: calls `cb` when another tab saves a value (`null` when it clears\n * it). Returns a function that stops watching. Used by `store.sync()`.\n */\n watch?: (cb: (value: string | null) => void) => () => void\n}\n\n/**\n * What a store's `storage` option takes: a function that creates the adapter.\n * `abortController` is aborted when the store is destroyed; use it to remove\n * listeners.\n */\nexport type StorageAdapterCreate = ({\n abortController,\n}: {\n abortController: AbortController\n}) => StorageAdapter\n\n/**\n * Shape of the built-in adapters such as `localStorageAdapter`: takes options\n * (like the key) and returns a {@link StorageAdapterCreate}.\n */\nexport type StorageAdapterCreator<Options> = (\n options: Options\n) => StorageAdapterCreate\n\n/**\n * Saves the store in `localStorage` (default) or `sessionStorage` under `key`,\n * and supports `store.sync()` across tabs. If storage is blocked or full,\n * reads return nothing and writes are skipped.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] } },\n * { storage: localStorageAdapter({ key: 'app', type: 'localStorage' }) }\n * )\n */\nexport const localStorageAdapter: StorageAdapterCreator<{\n key: string\n type?: 'localStorage' | 'sessionStorage'\n}> = ({ key, type = 'localStorage' }) => {\n return ({ abortController }) => {\n return {\n // Storage access throws when it is blocked (e.g. cookies disabled,\n // sandboxed iframes) or full.\n get: () => {\n try {\n return window[type].getItem(key)\n } catch {\n return null\n }\n },\n\n set: (value) => {\n try {\n window[type].setItem(key, value)\n } catch {}\n },\n\n watch: (cb) => {\n const listener = (e: StorageEvent) => {\n if (e.storageArea === window[type] && e.key === key) {\n cb(e.newValue)\n }\n }\n\n // Passing the controller as options (it has `signal`) removes the\n // listener when the store is destroyed.\n addEventListener('storage', listener, abortController)\n\n return () => {\n removeEventListener('storage', listener)\n }\n },\n }\n }\n}\n\n/**\n * Keeps the store in memory only, and supports `store.sync()` across tabs\n * through `BroadcastChannel`. Use it when you save the state yourself (e.g.\n * `toPersist()` to a database) and don't want it in `localStorage`.\n *\n * @example\n * import { createThemeStore, memoryStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] } },\n * { storage: memoryStorageAdapter({ key: 'app' }) }\n * )\n */\nexport const memoryStorageAdapter: StorageAdapterCreator<{\n key: string\n}> = ({ key }) => {\n return ({ abortController }) => {\n const storage = new Map<string, string>()\n\n const channel = new BroadcastChannel(DEFAULT_KEY)\n\n // An open channel keeps a Node process alive.\n abortController.signal.addEventListener('abort', () => {\n channel.close()\n })\n\n return {\n get: () => {\n return storage.get(key) ?? null\n },\n\n set: (value) => {\n storage.set(key, value)\n },\n\n broadcast: (value) => {\n channel.postMessage({ key, value })\n },\n\n watch: (cb) => {\n const listener = (e: MessageEvent) => {\n if (e.data.key === key) {\n storage.set(key, e.data.value)\n\n cb(e.data.value)\n }\n }\n\n channel.addEventListener('message', listener)\n\n return () => {\n channel.removeEventListener('message', listener)\n }\n },\n }\n }\n}\n"],"mappings":"A,wCAoDA,MAAaC,GAGP,CAAE,MAAK,OAAO,mBACV,CAAE,sBACD,CAGL,QAAW,CACT,GAAI,CACF,OAAO,OAAOC,EAAK,CAAC,QAAQC,CAAG,CACjC,MAAQ,CACN,OAAO,IACT,CACF,EAEA,IAAM,GAAU,CACd,GAAI,CACF,OAAOD,EAAK,CAAC,QAAQC,EAAKC,CAAK,CACjC,MAAQ,CAAC,CACX,EAEA,MAAQ,GAAO,CACb,IAAMC,EAAY,GAAoB,CAChCC,EAAE,cAAgB,OAAOJ,IAASI,EAAE,MAAQH,GAC9CI,EAAGD,EAAE,QAAQ,CAEjB,EAMA,OAFA,iBAAiB,UAAWD,EAAUG,CAAe,MAExC,CACX,oBAAoB,UAAWH,CAAQ,CACzC,CACF,CACF,GAiBSI,GAEP,CAAE,UACE,CAAE,qBAAsB,CAC9B,IAAMC,kBAAU,IAAI,IAEdC,EAAU,IAAI,iBAAiBX,CAAW,EAOhD,OAJAQ,EAAgB,OAAO,iBAAiB,YAAe,CACrDG,EAAQ,MAAM,CAChB,CAAC,EAEM,CACL,QACSD,EAAQ,IAAIP,CAAG,GAAK,KAG7B,IAAM,GAAU,CACdO,EAAQ,IAAIP,EAAKC,CAAK,CACxB,EAEA,UAAY,GAAU,CACpBO,EAAQ,YAAY,CAAE,MAAK,OAAM,CAAC,CACpC,EAEA,MAAQ,GAAO,CACb,IAAMN,EAAY,GAAoB,CAChCC,EAAE,KAAK,MAAQH,IACjBO,EAAQ,IAAIP,EAAKG,EAAE,KAAK,KAAK,EAE7BC,EAAGD,EAAE,KAAK,KAAK,EAEnB,EAIA,OAFAK,EAAQ,iBAAiB,UAAWN,CAAQ,MAE/B,CACXM,EAAQ,oBAAoB,UAAWN,CAAQ,CACjD,CACF,CACF,CACF,E"}
|
package/dist/svelte.d.ts
CHANGED
|
@@ -55,7 +55,22 @@ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStor
|
|
|
55
55
|
} ? U extends {
|
|
56
56
|
media: ReadonlyArray<unknown>;
|
|
57
57
|
} ? never : U["value"] : never : never; };
|
|
58
|
-
}
|
|
58
|
+
}, prev?: {
|
|
59
|
+
themes: Themes<T>;
|
|
60
|
+
resolvedThemes: Themes<T>;
|
|
61
|
+
resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
|
|
62
|
+
options: ReadonlyArray<infer U>;
|
|
63
|
+
} ? U extends {
|
|
64
|
+
media: ReadonlyArray<unknown>;
|
|
65
|
+
} ? K : never : never; }[keyof T]]: T[K] extends {
|
|
66
|
+
options: ReadonlyArray<infer U>;
|
|
67
|
+
} ? U extends string | number | boolean ? U : U extends {
|
|
68
|
+
value: string;
|
|
69
|
+
media?: readonly [string, string, string] | undefined;
|
|
70
|
+
} ? U extends {
|
|
71
|
+
media: ReadonlyArray<unknown>;
|
|
72
|
+
} ? never : U["value"] : never : never; };
|
|
73
|
+
} | undefined) => void) => () => void;
|
|
59
74
|
sync: () => (() => void) | undefined;
|
|
60
75
|
toPersist: () => {
|
|
61
76
|
themes: Partial<Themes<T>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-CWI4hy3w.js","names":["DEFAULT_KEY","DEFAULT_LITE_KEY","toScriptJson","value","toScriptFunction","source","handler"],"sources":["../src/utils.ts"],"sourcesContent":["export const DEFAULT_KEY = 'resonare'\nexport const DEFAULT_LITE_KEY = 'resonare/lite'\n\n/**\n * `JSON.stringify` for embedding in an inline `<script>`: `<` is escaped so a\n * value containing `</script>` cannot close the tag.\n */\nexport const toScriptJson = (value: unknown): string => {\n return JSON.stringify(value).replace(/</g, '\\\\u003c')\n}\n\n/**\n * Source of `handler` as a JavaScript expression. Object-method shorthand\n * (`handler() {}`) stringifies to something that is not an expression on its\n * own, so it is wrapped back into an object literal.\n */\nexport const toScriptFunction = (\n handler: (...args: Array<never>) => unknown\n): string => {\n const source = String(handler)\n\n return /^(async\\s*)?(function\\b|\\(|[\\w$]+\\s*=>)/.test(source)\n ? source\n : `Object.values({${source}})[0]`\n}\n"],"mappings":"AAAA,MAAaA,EAAc,WACdC,EAAmB,gBAMnBC,EAAgB,GACpB,KAAK,UAAUC,CAAK,CAAC,CAAC,QAAQ,KAAM,SAAS,EAQzCC,EACX,GACW,CACX,IAAMC,EAAS,OAAOC,CAAO,EAE7B,MAAO,0CAA0C,KAAKD,CAAM,EACxDA,EACA,kBAAkBA,EAAO,MAC/B,E"}
|
package/dist/vue.d.ts
CHANGED
|
@@ -50,7 +50,22 @@ export declare function useResonare<T extends ThemeStoreConfig>(store: ThemeStor
|
|
|
50
50
|
} ? U extends {
|
|
51
51
|
media: ReadonlyArray<unknown>;
|
|
52
52
|
} ? never : U["value"] : never : never; };
|
|
53
|
-
}
|
|
53
|
+
}, prev?: {
|
|
54
|
+
themes: Themes<T>;
|
|
55
|
+
resolvedThemes: Themes<T>;
|
|
56
|
+
resolvedSystemThemes: { [K in { [K in keyof T]: T[K] extends {
|
|
57
|
+
options: ReadonlyArray<infer U>;
|
|
58
|
+
} ? U extends {
|
|
59
|
+
media: ReadonlyArray<unknown>;
|
|
60
|
+
} ? K : never : never; }[keyof T]]: T[K] extends {
|
|
61
|
+
options: ReadonlyArray<infer U>;
|
|
62
|
+
} ? U extends string | number | boolean ? U : U extends {
|
|
63
|
+
value: string;
|
|
64
|
+
media?: readonly [string, string, string] | undefined;
|
|
65
|
+
} ? U extends {
|
|
66
|
+
media: ReadonlyArray<unknown>;
|
|
67
|
+
} ? never : U["value"] : never : never; };
|
|
68
|
+
} | undefined) => void) => () => void;
|
|
54
69
|
sync: () => (() => void) | undefined;
|
|
55
70
|
toPersist: () => {
|
|
56
71
|
themes: Partial<Themes<T>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "resonare",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Resonare",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dark mode",
|
|
@@ -41,6 +41,10 @@
|
|
|
41
41
|
"types": "./dist/vue.d.ts",
|
|
42
42
|
"import": "./dist/vue.js"
|
|
43
43
|
},
|
|
44
|
+
"./effects": {
|
|
45
|
+
"types": "./dist/effects.d.ts",
|
|
46
|
+
"import": "./dist/effects.js"
|
|
47
|
+
},
|
|
44
48
|
"./lite": {
|
|
45
49
|
"types": "./dist/lite.d.ts",
|
|
46
50
|
"import": "./dist/lite.js"
|
|
@@ -60,6 +64,10 @@
|
|
|
60
64
|
"./lite/vue": {
|
|
61
65
|
"types": "./dist/lite-vue.d.ts",
|
|
62
66
|
"import": "./dist/lite-vue.js"
|
|
67
|
+
},
|
|
68
|
+
"./lite/effects": {
|
|
69
|
+
"types": "./dist/lite-effects.d.ts",
|
|
70
|
+
"import": "./dist/lite-effects.js"
|
|
63
71
|
}
|
|
64
72
|
},
|
|
65
73
|
"publishConfig": {
|
package/dist/storage-BqWA8jeP.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=`resonare`,t=`resonare/lite`,n=e=>JSON.stringify(e).replace(/</g,`\\u003c`),r=e=>{let t=String(e);return/^(async\s*)?(function\b|\(|[\w$]+\s*=>)/.test(t)?t:`Object.values({${t}})[0]`},i=({key:e,type:t=`localStorage`})=>({abortController:n})=>({get:()=>{try{return window[t].getItem(e)}catch{return null}},set:n=>{try{window[t].setItem(e,n)}catch{}},watch:r=>{let i=n=>{n.storageArea===window[t]&&n.key===e&&r(n.newValue)};return addEventListener(`storage`,i,n),()=>{removeEventListener(`storage`,i)}}}),a=({key:t})=>({abortController:n})=>{let r=/* @__PURE__ */ new Map,i=new BroadcastChannel(e);return n.signal.addEventListener(`abort`,()=>{i.close()}),{get:()=>r.get(t)??null,set:e=>{r.set(t,e)},broadcast:e=>{i.postMessage({key:t,value:e})},watch:e=>{let n=n=>{n.data.key===t&&(r.set(t,n.data.value),e(n.data.value))};return i.addEventListener(`message`,n),()=>{i.removeEventListener(`message`,n)}}}};export{e as a,n as i,a as n,t as o,r,i as t};
|
|
2
|
-
//# sourceMappingURL=storage-BqWA8jeP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"storage-BqWA8jeP.js","names":["DEFAULT_KEY","DEFAULT_LITE_KEY","toScriptJson","value","toScriptFunction","source","handler","localStorageAdapter","type","key","listener","e","cb","abortController","memoryStorageAdapter","storage","channel"],"sources":["../src/constants.ts","../src/script.ts","../src/storage.ts"],"sourcesContent":["export const DEFAULT_KEY = 'resonare'\nexport const DEFAULT_LITE_KEY = 'resonare/lite'\n","/**\n * `JSON.stringify` for embedding in an inline `<script>`: `<` is escaped so a\n * value containing `</script>` cannot close the tag.\n */\nexport const toScriptJson = (value: unknown): string => {\n return JSON.stringify(value).replace(/</g, '\\\\u003c')\n}\n\n/**\n * Source of `handler` as a JavaScript expression. Object-method shorthand\n * (`handler() {}`) stringifies to something that is not an expression on its\n * own, so it is wrapped back into an object literal.\n */\nexport const toScriptFunction = (handler: Function): string => {\n const source = String(handler)\n\n return /^(async\\s*)?(function\\b|\\(|[\\w$]+\\s*=>)/.test(source)\n ? source\n : `Object.values({${source}})[0]`\n}\n","import { DEFAULT_KEY } from './constants'\n\n/**\n * Where a store saves its state. Values are strings: the full store saves\n * JSON, the lite store saves the theme name.\n */\nexport type StorageAdapter = {\n /** Returns the saved value, or `null` when nothing is saved. */\n get: () => string | null\n /** Saves a value. */\n set: (value: string) => void\n /** Optional: tells other tabs about a value just saved with `set`. */\n broadcast?: (value: string) => void\n /**\n * Optional: calls `cb` when another tab saves a value (`null` when it clears\n * it). Returns a function that stops watching. Used by `store.sync()`.\n */\n watch?: (cb: (value: string | null) => void) => () => void\n}\n\n/**\n * What a store's `storage` option takes: a function that creates the adapter.\n * `abortController` is aborted when the store is destroyed; use it to remove\n * listeners.\n */\nexport type StorageAdapterCreate = ({\n abortController,\n}: {\n abortController: AbortController\n}) => StorageAdapter\n\n/**\n * Shape of the built-in adapters such as `localStorageAdapter`: takes options\n * (like the key) and returns a {@link StorageAdapterCreate}.\n */\nexport type StorageAdapterCreator<Options> = (\n options: Options\n) => StorageAdapterCreate\n\n/**\n * Saves the store in `localStorage` (default) or `sessionStorage` under `key`,\n * and supports `store.sync()` across tabs. If storage is blocked or full,\n * reads return nothing and writes are skipped.\n *\n * @example\n * import { createThemeStore, localStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] } },\n * { storage: localStorageAdapter({ key: 'app', type: 'localStorage' }) }\n * )\n */\nexport const localStorageAdapter: StorageAdapterCreator<{\n key: string\n type?: 'localStorage' | 'sessionStorage'\n}> = ({ key, type = 'localStorage' }) => {\n return ({ abortController }) => {\n return {\n // Storage access throws when it is blocked (e.g. cookies disabled,\n // sandboxed iframes) or full.\n get: () => {\n try {\n return window[type].getItem(key)\n } catch {\n return null\n }\n },\n\n set: (value) => {\n try {\n window[type].setItem(key, value)\n } catch {}\n },\n\n watch: (cb) => {\n const listener = (e: StorageEvent) => {\n if (e.storageArea === window[type] && e.key === key) {\n cb(e.newValue)\n }\n }\n\n // Passing the controller as options (it has `signal`) removes the\n // listener when the store is destroyed.\n addEventListener('storage', listener, abortController)\n\n return () => {\n removeEventListener('storage', listener)\n }\n },\n }\n }\n}\n\n/**\n * Keeps the store in memory only, and supports `store.sync()` across tabs\n * through `BroadcastChannel`. Use it when you save the state yourself (e.g.\n * `toPersist()` to a database) and don't want it in `localStorage`.\n *\n * @example\n * import { createThemeStore, memoryStorageAdapter } from 'resonare'\n *\n * const store = createThemeStore(\n * { colorMode: { options: ['light', 'dark'] } },\n * { storage: memoryStorageAdapter({ key: 'app' }) }\n * )\n */\nexport const memoryStorageAdapter: StorageAdapterCreator<{\n key: string\n}> = ({ key }) => {\n return ({ abortController }) => {\n const storage = new Map<string, string>()\n\n const channel = new BroadcastChannel(DEFAULT_KEY)\n\n // An open channel keeps a Node process alive.\n abortController.signal.addEventListener('abort', () => {\n channel.close()\n })\n\n return {\n get: () => {\n return storage.get(key) ?? null\n },\n\n set: (value) => {\n storage.set(key, value)\n },\n\n broadcast: (value) => {\n channel.postMessage({ key, value })\n },\n\n watch: (cb) => {\n const listener = (e: MessageEvent) => {\n if (e.data.key === key) {\n storage.set(key, e.data.value)\n\n cb(e.data.value)\n }\n }\n\n channel.addEventListener('message', listener)\n\n return () => {\n channel.removeEventListener('message', listener)\n }\n },\n }\n }\n}\n"],"mappings":"AAAA,MAAaA,EAAc,WACdC,EAAmB,gBCGnBC,EAAgB,GACpB,KAAK,UAAUC,CAAK,CAAC,CAAC,QAAQ,KAAM,SAAS,EAQzCC,EAAoB,GAA8B,CAC7D,IAAMC,EAAS,OAAOC,CAAO,EAE7B,MAAO,0CAA0C,KAAKD,CAAM,EACxDA,EACA,kBAAkBA,EAAO,MAC/B,ECiCaE,GAGP,CAAE,MAAK,OAAO,mBACV,CAAE,sBACD,CAGL,QAAW,CACT,GAAI,CACF,OAAO,OAAOC,EAAK,CAAC,QAAQC,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