resonare 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +398 -270
- 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 +233 -30
- 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 +31 -22
- package/dist/lite-react.d.ts.map +1 -1
- package/dist/lite-react.js +1 -1
- package/dist/lite-react.js.map +1 -1
- package/dist/lite-solid.d.ts +46 -0
- package/dist/lite-solid.d.ts.map +1 -0
- package/dist/lite-solid.js +2 -0
- package/dist/lite-solid.js.map +1 -0
- package/dist/lite-svelte.d.ts +45 -0
- package/dist/lite-svelte.d.ts.map +1 -0
- package/dist/lite-svelte.js +2 -0
- package/dist/lite-svelte.js.map +1 -0
- package/dist/lite-vue.d.ts +53 -0
- package/dist/lite-vue.d.ts.map +1 -0
- package/dist/lite-vue.js +2 -0
- package/dist/lite-vue.js.map +1 -0
- package/dist/lite.d.ts +110 -23
- 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 +62 -38
- package/dist/react.d.ts.map +1 -1
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/solid.d.ts +99 -0
- package/dist/solid.d.ts.map +1 -0
- package/dist/solid.js +2 -0
- package/dist/solid.js.map +1 -0
- package/dist/storage-CsXjZKyt.d.ts +65 -0
- package/dist/storage-CsXjZKyt.d.ts.map +1 -0
- package/dist/storage-fOH2xeQ1.js +2 -0
- package/dist/storage-fOH2xeQ1.js.map +1 -0
- package/dist/svelte.d.ts +101 -0
- package/dist/svelte.d.ts.map +1 -0
- package/dist/svelte.js +2 -0
- package/dist/svelte.js.map +1 -0
- package/dist/utils-CWI4hy3w.js +2 -0
- package/dist/utils-CWI4hy3w.js.map +1 -0
- package/dist/vue.d.ts +97 -0
- package/dist/vue.d.ts.map +1 -0
- package/dist/vue.js +2 -0
- package/dist/vue.js.map +1 -0
- package/package.json +75 -32
- package/dist/storage-B5xjLRee.js +0 -2
- package/dist/storage-B5xjLRee.js.map +0 -1
- package/dist/storage-DGYV332J.d.ts +0 -23
- package/dist/storage-DGYV332J.d.ts.map +0 -1
|
@@ -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/D,CAAC,CACD,OAAO,OAAO,EAEjB,OAAOD,GACJ,EAAO,IAAS,CACf,IAAK,IAAMC,KAAYc,EACrBd,EAASS,EAAOC,CAAI,CAExB,EACAK,EAAM,SAAW,GAAKA,EAAM,EAAE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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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@
|
|
|
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
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-
|
|
2
|
-
|
|
3
|
-
//#region src/index.d.ts
|
|
1
|
+
import { a as memoryStorageAdapter, i as localStorageAdapter, n as StorageAdapterCreate, r as StorageAdapterCreator, t as StorageAdapter } from "./storage-CsXjZKyt.js";
|
|
4
2
|
type ThemeValue = string | number | boolean;
|
|
5
3
|
type ThemeOption<T extends ThemeValue = string> = {
|
|
6
4
|
value: T;
|
|
7
|
-
media?: [string, T, T];
|
|
5
|
+
media?: readonly [string, T, T];
|
|
8
6
|
};
|
|
9
7
|
type ThemeConfig<T extends ThemeValue = string> = {
|
|
10
8
|
options: ReadonlyArray<T | ThemeOption<T>>;
|
|
@@ -13,29 +11,81 @@ type ThemeConfig<T extends ThemeValue = string> = {
|
|
|
13
11
|
defaultValue: T;
|
|
14
12
|
options?: never;
|
|
15
13
|
};
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Config for `createThemeStore`. Each key is a theme setting (`colorMode`,
|
|
16
|
+
* `contrast`, …) with either:
|
|
17
|
+
*
|
|
18
|
+
* - `options`: the allowed values, plus an optional `defaultValue` (otherwise the
|
|
19
|
+
* first option). One option may be a `{ value, media }` object: when it is
|
|
20
|
+
* selected, the setting follows a media query, using `media[1]` while the
|
|
21
|
+
* query matches and `media[2]` while it doesn't.
|
|
22
|
+
* - `defaultValue` alone: a free value of that type, such as a number.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* const config = {
|
|
26
|
+
* colorMode: {
|
|
27
|
+
* options: [
|
|
28
|
+
* 'light',
|
|
29
|
+
* 'dark',
|
|
30
|
+
* {
|
|
31
|
+
* value: 'system',
|
|
32
|
+
* media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
|
|
33
|
+
* },
|
|
34
|
+
* ],
|
|
35
|
+
* defaultValue: 'system',
|
|
36
|
+
* },
|
|
37
|
+
* contrast: {
|
|
38
|
+
* options: ['normal', 'more'],
|
|
39
|
+
* },
|
|
40
|
+
* sidebarWidth: {
|
|
41
|
+
* defaultValue: 240,
|
|
42
|
+
* },
|
|
43
|
+
* } as const satisfies ThemeStoreConfig
|
|
44
|
+
*/
|
|
45
|
+
export type ThemeStoreConfig = Record<string, ThemeConfig<string> | ThemeConfig<number> | ThemeConfig<boolean>>;
|
|
46
|
+
/**
|
|
47
|
+
* The selected value of each setting, as passed to `setThemes` (e.g.
|
|
48
|
+
* `colorMode: 'system'`). Inferred from your `ThemeStoreConfig`.
|
|
49
|
+
*/
|
|
50
|
+
export type Themes<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
|
|
18
51
|
options: ReadonlyArray<infer U>;
|
|
19
52
|
} ? U extends ThemeOption ? U['value'] : U : T[K] extends {
|
|
20
53
|
defaultValue: infer U;
|
|
21
|
-
} ? U extends string ? string : U extends number ? number : boolean : never };
|
|
54
|
+
} ? U extends string ? string : U extends number ? number : boolean : never; };
|
|
22
55
|
type ThemeKeysWithSystemOption<T extends ThemeStoreConfig> = { [K in keyof T]: T[K] extends {
|
|
23
56
|
options: ReadonlyArray<infer U>;
|
|
24
57
|
} ? U extends {
|
|
25
58
|
media: ReadonlyArray<unknown>;
|
|
26
|
-
} ? K : never : never }[keyof T];
|
|
59
|
+
} ? K : never : never; }[keyof T];
|
|
27
60
|
type NonSystemOptionValues<T extends ThemeStoreConfig, K extends keyof T> = T[K] extends {
|
|
28
61
|
options: ReadonlyArray<infer U>;
|
|
29
62
|
} ? U extends ThemeValue ? U : U extends ThemeOption ? U extends {
|
|
30
|
-
media:
|
|
63
|
+
media: ReadonlyArray<unknown>;
|
|
31
64
|
} ? never : U['value'] : never : never;
|
|
32
|
-
|
|
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];
|
|
72
|
+
/**
|
|
73
|
+
* For each setting with a `media` option, the value that option currently
|
|
74
|
+
* resolves to, whether or not it is selected.
|
|
75
|
+
*/
|
|
76
|
+
type ResolvedSystemThemes<T extends ThemeStoreConfig> = { [K in ThemeKeysWithSystemOption<T>]: NonSystemOptionValues<T, K>; };
|
|
33
77
|
type Snapshot<T extends ThemeStoreConfig> = {
|
|
34
78
|
themes: Themes<T>;
|
|
35
79
|
resolvedThemes: Themes<T>;
|
|
36
80
|
resolvedSystemThemes: ResolvedSystemThemes<T>;
|
|
37
81
|
};
|
|
38
|
-
|
|
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;
|
|
39
89
|
type PersistedSystemOptionPairs = Record<string, [string, string]>;
|
|
40
90
|
type PersistedState<T extends ThemeStoreConfig> = {
|
|
41
91
|
themes: Partial<Themes<T>>;
|
|
@@ -47,34 +97,187 @@ type ThemeStoreOptions<T extends ThemeStoreConfig> = {
|
|
|
47
97
|
};
|
|
48
98
|
type ThemeAndOptions<T extends ThemeStoreConfig> = Array<{ [K in keyof T]: [K, Array<T[K] extends {
|
|
49
99
|
options: ReadonlyArray<infer U>;
|
|
50
|
-
} ? U extends ThemeOption ? U['value'] : U : never>] }[keyof T]>;
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
100
|
+
} ? U extends ThemeOption ? U['value'] : U : never>]; }[keyof T]>;
|
|
101
|
+
/**
|
|
102
|
+
* Lists each setting with its option values (`{ value, media }` options become
|
|
103
|
+
* their `value`). Useful for rendering a picker for every setting.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* import { getThemesAndOptions } from 'resonare'
|
|
107
|
+
*
|
|
108
|
+
* getThemesAndOptions({
|
|
109
|
+
* colorMode: {
|
|
110
|
+
* options: [
|
|
111
|
+
* 'light',
|
|
112
|
+
* 'dark',
|
|
113
|
+
* {
|
|
114
|
+
* value: 'system',
|
|
115
|
+
* media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
|
|
116
|
+
* },
|
|
117
|
+
* ],
|
|
118
|
+
* },
|
|
119
|
+
* })
|
|
120
|
+
* // [['colorMode', ['light', 'dark', 'system']]]
|
|
121
|
+
*/
|
|
122
|
+
export declare function getThemesAndOptions<T extends ThemeStoreConfig>(config: T): ThemeAndOptions<T>;
|
|
123
|
+
/**
|
|
124
|
+
* Returns each setting's default: its `defaultValue`, or else its first
|
|
125
|
+
* option.
|
|
126
|
+
*
|
|
127
|
+
* @example
|
|
128
|
+
* import { getDefaultThemes } from 'resonare'
|
|
129
|
+
*
|
|
130
|
+
* getDefaultThemes({
|
|
131
|
+
* colorMode: { options: ['light', 'dark'], defaultValue: 'dark' },
|
|
132
|
+
* }) // { colorMode: 'dark' }
|
|
133
|
+
*/
|
|
134
|
+
export declare function getDefaultThemes<T extends ThemeStoreConfig>(config: T): Themes<T>;
|
|
135
|
+
/**
|
|
136
|
+
* Creates a store for the settings in `config`. It saves changes through
|
|
137
|
+
* `storage` (`localStorage` under the key `'resonare'` by default; `null`
|
|
138
|
+
* disables saving), resolves `media` options in the browser, and notifies
|
|
139
|
+
* subscribers.
|
|
140
|
+
*
|
|
141
|
+
* Read state with `getSnapshot()` or `subscribe`.
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* import { createThemeStore, localStorageAdapter } from 'resonare'
|
|
145
|
+
*
|
|
146
|
+
* const store = createThemeStore(
|
|
147
|
+
* {
|
|
148
|
+
* colorMode: {
|
|
149
|
+
* options: [
|
|
150
|
+
* 'light',
|
|
151
|
+
* 'dark',
|
|
152
|
+
* {
|
|
153
|
+
* value: 'system',
|
|
154
|
+
* media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
|
|
155
|
+
* },
|
|
156
|
+
* ],
|
|
157
|
+
* defaultValue: 'system',
|
|
158
|
+
* },
|
|
159
|
+
* },
|
|
160
|
+
* { storage: localStorageAdapter({ key: 'my-app' }) }
|
|
161
|
+
* )
|
|
162
|
+
*
|
|
163
|
+
* // In the browser: load the saved choice and follow other tabs.
|
|
164
|
+
* store.restore()
|
|
165
|
+
* store.sync()
|
|
166
|
+
*
|
|
167
|
+
* store.subscribe(({ resolvedThemes }) => {
|
|
168
|
+
* document.documentElement.dataset.colorMode = resolvedThemes.colorMode
|
|
169
|
+
* })
|
|
170
|
+
*
|
|
171
|
+
* store.setThemes({ colorMode: 'dark' })
|
|
172
|
+
*/
|
|
173
|
+
export declare function createThemeStore<T extends ThemeStoreConfig>(config: T, { persisted, storage: createStorage }?: ThemeStoreOptions<T>): {
|
|
174
|
+
/**
|
|
175
|
+
* Current state:
|
|
176
|
+
*
|
|
177
|
+
* - `themes`: the selected value of each setting (e.g. `'system'`).
|
|
178
|
+
* - `resolvedThemes`: the same with `media` options resolved (e.g. `'dark'`).
|
|
179
|
+
* - `resolvedSystemThemes`: what each `media` option resolves to, even when
|
|
180
|
+
* it isn't selected.
|
|
181
|
+
*
|
|
182
|
+
* Returns the same object until the next change.
|
|
183
|
+
*/
|
|
62
184
|
getSnapshot: () => Snapshot<T>;
|
|
185
|
+
/**
|
|
186
|
+
* The state as rendered on the server: defaults plus `persisted`, with
|
|
187
|
+
* `media` options resolved to their "not matched" value. It never changes,
|
|
188
|
+
* so hydration can match the server HTML even after `restore()`.
|
|
189
|
+
*/
|
|
190
|
+
getServerSnapshot: () => Snapshot<T>;
|
|
191
|
+
/**
|
|
192
|
+
* Updates the given settings (others keep their value), saves to storage,
|
|
193
|
+
* and notifies subscribers.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* store.setThemes({ colorMode: 'dark' })
|
|
197
|
+
*
|
|
198
|
+
* store.setThemes((current) => ({
|
|
199
|
+
* colorMode: current.colorMode === 'dark' ? 'light' : 'dark',
|
|
200
|
+
* }))
|
|
201
|
+
*/
|
|
63
202
|
setThemes: (themes: Partial<Themes<T>> | ((currentThemes: Themes<T>) => Partial<Themes<T>>)) => void;
|
|
203
|
+
/**
|
|
204
|
+
* Changes which values a `media` option resolves to: `[whenMatched,
|
|
205
|
+
* whenNotMatched]`, replacing `media[1]` and `media[2]` from the config.
|
|
206
|
+
* Saved like `setThemes`.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* // system now picks 'dark-dimmed' when the OS prefers dark
|
|
210
|
+
* store.updateSystemOption('colorMode', ['dark-dimmed', 'light'])
|
|
211
|
+
*/
|
|
64
212
|
updateSystemOption: <K extends ThemeKeysWithSystemOption<T>>(themeKey: K, pair: [NonSystemOptionValues<T, K>, NonSystemOptionValues<T, K>]) => void;
|
|
213
|
+
/**
|
|
214
|
+
* The state to save, e.g. to a database: pass it back as `persisted` when
|
|
215
|
+
* creating the store.
|
|
216
|
+
*/
|
|
65
217
|
toPersist: () => PersistedState<T>;
|
|
218
|
+
/**
|
|
219
|
+
* Loads the saved state from storage. Does nothing when nothing is saved.
|
|
220
|
+
* Call it in the browser, e.g. after hydration.
|
|
221
|
+
*/
|
|
66
222
|
restore: () => void;
|
|
223
|
+
/**
|
|
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.
|
|
227
|
+
*/
|
|
67
228
|
subscribe: (callback: Listener<T>) => (() => void);
|
|
229
|
+
/**
|
|
230
|
+
* Applies changes saved by other tabs (if the storage adapter supports
|
|
231
|
+
* it); when another tab clears the saved state, resets to the config
|
|
232
|
+
* defaults. Returns a function that stops syncing, or `undefined` when the
|
|
233
|
+
* adapter can't sync.
|
|
234
|
+
*/
|
|
68
235
|
sync: () => (() => void) | undefined;
|
|
236
|
+
/**
|
|
237
|
+
* Removes all subscribers and stops listening to media queries and
|
|
238
|
+
* storage. The store doesn't update after this.
|
|
239
|
+
*/
|
|
69
240
|
destroy: () => void;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
241
|
+
};
|
|
242
|
+
export type ThemeStore<T extends ThemeStoreConfig> = ReturnType<typeof createThemeStore<T>>;
|
|
243
|
+
/** One store for `createInlineThemeScript`. */
|
|
244
|
+
export type ThemeScriptParameter = {
|
|
245
|
+
/** The store's `localStorage` key; defaults to `'resonare'`. */
|
|
246
|
+
key?: string;
|
|
247
|
+
/** The same config passed to `createThemeStore`. */
|
|
74
248
|
config: ThemeStoreConfig;
|
|
249
|
+
/**
|
|
250
|
+
* Applies the state to the page; receives the same value as `subscribe`.
|
|
251
|
+
* It is copied into the script as source code, so it can't use variables
|
|
252
|
+
* from outside the function. Typed loosely so a handler fits any config.
|
|
253
|
+
*/
|
|
75
254
|
handler: Listener<any>;
|
|
76
255
|
};
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
256
|
+
/**
|
|
257
|
+
* Returns the source of a small script that reads the saved state from
|
|
258
|
+
* `localStorage` and runs `handler` with it. Put it in an inline `<script>` in
|
|
259
|
+
* the `<head>` so the page has the right theme before first paint. Pass an
|
|
260
|
+
* array to set up several stores.
|
|
261
|
+
*
|
|
262
|
+
* Use the same handler with `store.subscribe` to keep the page updated after
|
|
263
|
+
* that.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* import { createInlineThemeScript } from 'resonare'
|
|
267
|
+
*
|
|
268
|
+
* // config: the same object passed to createThemeStore
|
|
269
|
+
* const themeScript = createInlineThemeScript({
|
|
270
|
+
* key: 'my-app',
|
|
271
|
+
* config,
|
|
272
|
+
* handler: ({ resolvedThemes }) => {
|
|
273
|
+
* const root = document.documentElement
|
|
274
|
+
* root.dataset.colorMode = resolvedThemes.colorMode
|
|
275
|
+
* },
|
|
276
|
+
* })
|
|
277
|
+
*
|
|
278
|
+
* // In <head>:
|
|
279
|
+
* // <script dangerouslySetInnerHTML={{ __html: themeScript }} />
|
|
280
|
+
*/
|
|
281
|
+
export declare function createInlineThemeScript(themeScriptParameters: ThemeScriptParameter | Array<ThemeScriptParameter>): string;
|
|
282
|
+
export { StorageAdapter, StorageAdapterCreate, StorageAdapterCreator, localStorageAdapter, memoryStorageAdapter };
|
|
80
283
|
//# sourceMappingURL=index.d.ts.map
|
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,oBAAoB;IACjC,4BAEE;KAML,0BAA0B,UAAU,uBACtC,WAAW,IAAI,EAAE;EAAa,SAAS,oBAAoB;IACxD;EAAY,OAAO;IACjB,2BAGA;KAEH,sBACH,UAAU,kBACV,gBAAgB,KACd,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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
|