resonare 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +398 -270
  2. package/dist/effects-core-CuoeZrRP.js +2 -0
  3. package/dist/effects-core-CuoeZrRP.js.map +1 -0
  4. package/dist/effects-core-DPJyVK-w.d.ts +14 -0
  5. package/dist/effects-core-DPJyVK-w.d.ts.map +1 -0
  6. package/dist/effects.d.ts +105 -0
  7. package/dist/effects.d.ts.map +1 -0
  8. package/dist/effects.js +2 -0
  9. package/dist/effects.js.map +1 -0
  10. package/dist/index.d.ts +233 -30
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/index.js.map +1 -1
  14. package/dist/lite-effects.d.ts +65 -0
  15. package/dist/lite-effects.d.ts.map +1 -0
  16. package/dist/lite-effects.js +2 -0
  17. package/dist/lite-effects.js.map +1 -0
  18. package/dist/lite-react.d.ts +31 -22
  19. package/dist/lite-react.d.ts.map +1 -1
  20. package/dist/lite-react.js +1 -1
  21. package/dist/lite-react.js.map +1 -1
  22. package/dist/lite-solid.d.ts +46 -0
  23. package/dist/lite-solid.d.ts.map +1 -0
  24. package/dist/lite-solid.js +2 -0
  25. package/dist/lite-solid.js.map +1 -0
  26. package/dist/lite-svelte.d.ts +45 -0
  27. package/dist/lite-svelte.d.ts.map +1 -0
  28. package/dist/lite-svelte.js +2 -0
  29. package/dist/lite-svelte.js.map +1 -0
  30. package/dist/lite-vue.d.ts +53 -0
  31. package/dist/lite-vue.d.ts.map +1 -0
  32. package/dist/lite-vue.js +2 -0
  33. package/dist/lite-vue.js.map +1 -0
  34. package/dist/lite.d.ts +110 -23
  35. package/dist/lite.d.ts.map +1 -1
  36. package/dist/lite.js +1 -1
  37. package/dist/lite.js.map +1 -1
  38. package/dist/react.d.ts +62 -38
  39. package/dist/react.d.ts.map +1 -1
  40. package/dist/react.js +1 -1
  41. package/dist/react.js.map +1 -1
  42. package/dist/solid.d.ts +99 -0
  43. package/dist/solid.d.ts.map +1 -0
  44. package/dist/solid.js +2 -0
  45. package/dist/solid.js.map +1 -0
  46. package/dist/storage-CsXjZKyt.d.ts +65 -0
  47. package/dist/storage-CsXjZKyt.d.ts.map +1 -0
  48. package/dist/storage-fOH2xeQ1.js +2 -0
  49. package/dist/storage-fOH2xeQ1.js.map +1 -0
  50. package/dist/svelte.d.ts +101 -0
  51. package/dist/svelte.d.ts.map +1 -0
  52. package/dist/svelte.js +2 -0
  53. package/dist/svelte.js.map +1 -0
  54. package/dist/utils-CWI4hy3w.js +2 -0
  55. package/dist/utils-CWI4hy3w.js.map +1 -0
  56. package/dist/vue.d.ts +97 -0
  57. package/dist/vue.d.ts.map +1 -0
  58. package/dist/vue.js +2 -0
  59. package/dist/vue.js.map +1 -0
  60. package/package.json +75 -32
  61. package/dist/storage-B5xjLRee.js +0 -2
  62. package/dist/storage-B5xjLRee.js.map +0 -1
  63. package/dist/storage-DGYV332J.d.ts +0 -23
  64. package/dist/storage-DGYV332J.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,46 +1,50 @@
1
- # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=black&color=green)](https://www.npmjs.com/package/resonare) [![bundle size](https://img.shields.io/bundlephobia/minzip/resonare?labelColor=black&color=green)](https://bundlephobia.com/package/resonare)
1
+ # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=cb0000&color=000)](https://www.npmjs.com/package/resonare) [![bundle size](https://img.shields.io/bundlejs/size/resonare?labelColor=007ec6&color=000)](https://bundlejs.com/?q=resonare)
2
2
 
3
- A state store for multi-dimensional themes and user preferences. [Check out the demo](https://resonare.phuoccss.workers.dev).
3
+ A small state store for themes and user preferences: color scheme, contrast, spacing, sidebar width, or any other setting your UI offers. [Check out the demo](https://resonare.phuoccss.workers.dev).
4
4
 
5
5
  ## Features
6
6
 
7
- - Define and manage themes and user preferences, e.g.:
8
- - Color scheme: system, light, dark
9
- - Contrast preference: standard, high
10
- - Spacing: compact, comfortable, spacious
11
- - Showing, hiding, or collapsing sidebar/sections
12
- - etc.
13
- - Framework-agnostic
14
- - Prevent flicker on page load
15
- - Honor system preferences
16
- - Support sections with independent theming
17
- - Sync theme selection across tabs and windows
18
- - Flexible client-side persistence options, defaulting to localStorage
19
- - Support server-side persistence
20
- - Type-safe
7
+ - **Any number of settings**, each with its own options and default
8
+ - **Follows the OS** through media queries, e.g. `system` resolves to `light` or `dark`
9
+ - **No flash on page load:** an inline script applies saved settings before first paint
10
+ - **Saves choices** in `localStorage` by default, or anywhere you like (`sessionStorage`, memory, cookies, your server)
11
+ - **Syncs across tabs and windows**
12
+ - **Server rendering** without hydration mismatches
13
+ - **Framework bindings** for React, Solid, Svelte and Vue, or use it with plain JavaScript
14
+ - **Type-safe:** option values are inferred from your config
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
21
17
 
22
18
  ## Installation
23
19
 
24
- To install:
25
-
26
20
  ```bash
27
21
  npm i resonare
28
22
  # or
29
- yarn add resonare
30
- # or
31
23
  pnpm add resonare
24
+ # or
25
+ yarn add resonare
32
26
  ```
33
27
 
34
- ## Basic Usage
28
+ The framework bindings need React 19+, Solid 1.6+, Svelte 5.7+ or Vue 3.2+.
35
29
 
36
- ### 1. Create inline script
30
+ ## Quick start
37
31
 
38
- When storing theme selection in `localStorage`, an inline `<script>` that restores user preferences and updates the DOM before first paint is required to prevent flicker.
32
+ ### 1. Describe your settings
39
33
 
40
- ```ts
41
- import { createInlineThemeScript, type ThemeStoreConfig } from 'resonare'
34
+ Each key is a setting. List its `options`; the first one is the default unless you set `defaultValue`. One option can follow a media query: `media: [query, valueWhenMatched, valueWhenNotMatched]`.
42
35
 
43
- const CONFIG = {
36
+ ```ts
37
+ // theme.ts
38
+ import { type ThemeStoreConfig } from 'resonare'
39
+ import {
40
+ combine,
41
+ disableTransitions,
42
+ setColorScheme,
43
+ setDataAttributes,
44
+ setThemeColor,
45
+ } from 'resonare/effects'
46
+
47
+ export const CONFIG = {
44
48
  colorScheme: {
45
49
  options: [
46
50
  {
@@ -51,328 +55,452 @@ const CONFIG = {
51
55
  'dark',
52
56
  ],
53
57
  },
58
+ contrast: {
59
+ options: ['standard', 'high'],
60
+ },
54
61
  } as const satisfies ThemeStoreConfig
55
62
 
63
+ export const applyThemes = combine(
64
+ setDataAttributes(),
65
+ setColorScheme(),
66
+ setThemeColor({ values: { light: '#fff', dark: '#000' } }),
67
+ disableTransitions()
68
+ )
69
+ ```
70
+
71
+ Then style your page from those attributes:
72
+
73
+ ```css
74
+ :root[data-color-scheme='dark'] {
75
+ --background: #000;
76
+ }
77
+ ```
78
+
79
+ ### 2. Add the inline script
80
+
81
+ The script reads the saved settings and runs your handler before the page is painted, so users never see the wrong theme. Put it in the `<head>`:
82
+
83
+ ```ts
84
+ import { createInlineThemeScript } from 'resonare'
85
+
86
+ import { CONFIG, applyThemes } from './theme'
87
+
56
88
  export const themeScript = createInlineThemeScript({
57
89
  config: CONFIG,
58
- handler: ({ resolvedThemes }) => {
59
- Object.entries(resolvedThemes).forEach(([key, value]) => {
60
- document.documentElement.dataset[key] = value
61
- })
62
- },
90
+ handler: applyThemes,
63
91
  })
64
92
  ```
65
93
 
66
- ### 2. Inject inline script
67
-
68
- Inject the script into the `<head>` of your HTML document. The exact pattern differs by framework. Here are some examples.
69
-
70
94
  ```tsx
71
- // React.js
72
- <script suppressHydrationWarning>{themeScript}</script>
95
+ // React
96
+ <script dangerouslySetInnerHTML={{ __html: themeScript }} />
73
97
 
74
- // TanStack Router/Start
75
- import { ScriptOnce } from '@tanstack/router'
98
+ // TanStack Start
99
+ import { ScriptOnce } from '@tanstack/react-router'
76
100
 
77
101
  <ScriptOnce>{themeScript}</ScriptOnce>
78
102
 
79
- // Astro.js
103
+ // Astro
80
104
  <script is:inline set:html={themeScript} />
81
105
  ```
82
106
 
83
- ### 3. Initialize the store
107
+ ### 3. Create the store
84
108
 
85
- Refer to the [Framework Integration](#framework-integration) section for examples.
109
+ ```ts
110
+ import { createThemeStore } from 'resonare'
86
111
 
87
- ## API
112
+ import { CONFIG, applyThemes } from './theme'
88
113
 
89
- ### `createThemeStore`
114
+ export const store = createThemeStore(CONFIG)
90
115
 
91
- ```ts
92
- import {
93
- createThemeStore,
94
- localStorageAdapter,
95
- type ThemeStoreConfig,
96
- } from 'resonare'
116
+ if (typeof window !== 'undefined') {
117
+ store.subscribe(applyThemes) // keep the page in sync with every change
118
+ store.restore() // load the saved settings
119
+ store.sync() // follow changes made in other tabs
120
+ }
121
+ ```
97
122
 
98
- const CONFIG = {
99
- colorScheme: {
100
- options: [
101
- {
102
- value: 'system',
103
- media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
104
- },
105
- 'light',
106
- 'dark',
107
- ],
108
- },
109
- contrast: {
110
- options: [
111
- {
112
- value: 'system',
113
- media: [
114
- '(prefers-contrast: more) and (forced-colors: none)',
115
- 'high',
116
- 'standard',
117
- ],
118
- },
119
- 'standard',
120
- 'high',
121
- ],
122
- initialValue: 'standard',
123
- },
124
- sidebarWidth: {
125
- initialValue: 240,
126
- },
127
- } as const satisfies ThemeStoreConfig
123
+ ### 4. Use it in your UI
128
124
 
129
- const themeStore = createThemeStore(CONFIG, {
130
- // optional, useful for server-side persistence
131
- initialState: persistedStateFromDb, // persisted state returned by themeStore.toPersist()
125
+ ```tsx
126
+ import { useResonare } from 'resonare/react'
132
127
 
133
- // optional, specify your own client storage or null to disable client-side persistence
134
- // localStorage is used by default
135
- storage: localStorageAdapter({ key: 'resonare' }),
128
+ function ColorSchemeSelect() {
129
+ const { themes, setThemes } = useResonare(store)
130
+
131
+ return (
132
+ <select
133
+ value={themes.colorScheme}
134
+ onChange={(e) => {
135
+ setThemes({ colorScheme: e.target.value as typeof themes.colorScheme })
136
+ }}
137
+ >
138
+ <option value='system'>System</option>
139
+ <option value='light'>Light</option>
140
+ <option value='dark'>Dark</option>
141
+ </select>
142
+ )
143
+ }
144
+ ```
145
+
146
+ See [Frameworks](#frameworks) for Solid, Svelte and Vue.
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' },
136
172
  })
173
+ setThemeColor<Config>({ values: { light: '#fff', dark: '#000' } }) // every value needs a color
174
+ disableTransitions<Config>({ keys: ['colorScheme', 'contrast'] })
175
+ ```
137
176
 
138
- // get current theme selection
139
- // e.g.: { colorScheme: 'system', contrast: 'standard', sidebarWidth: 240 }
140
- themeStore.getThemes()
177
+ ### Your own effects
141
178
 
142
- // get resolved theme selection (after media queries)
143
- // e.g.: { colorScheme: 'dark', contrast: 'standard', sidebarWidth: 240 }
144
- themeStore.getResolvedThemes()
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.
145
180
 
146
- // get resolved system options
147
- // e.g.: { colorScheme: 'dark' }
148
- themeStore.getResolvedSystemThemes()
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
+ ```
149
196
 
150
- // update theme
151
- themeStore.setThemes({ colorScheme: 'light', sidebarWidth: 280 })
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.
152
198
 
153
- // get state to persist, useful for server-side persistence
154
- // to restore, pass the returned object to createThemeStore's initialState
155
- themeStore.toPersist()
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.
156
200
 
157
- // restore persisted state from client-side storage
158
- themeStore.restore()
201
+ ```ts
202
+ document.startViewTransition(() => {
203
+ store.setThemes({ colorScheme: 'dark' })
204
+ })
205
+ ```
159
206
 
160
- // sync user preferences across tabs/windows if supported by the storage adapter
161
- const stopSync = themeStore.sync()
207
+ ## State
162
208
 
163
- stopSync?.()
209
+ Every listener, snapshot and binding gives you three views of the state:
164
210
 
165
- // subscribe to theme changes
166
- const unsubscribe = themeStore.subscribe(({ themes, resolvedThemes }) => {
167
- Object.entries(resolvedThemes).forEach(([key, value]) => {
168
- if (key === 'sidebarWidth') {
169
- document.documentElement.style.setProperty('--sidebar-width', `${value}px`)
170
- } else {
171
- document.documentElement.dataset[key] = value
172
- }
173
- })
211
+ | Field | Example | Meaning |
212
+ | ---------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
213
+ | `themes` | `{ colorScheme: 'system', contrast: 'standard' }` | What the user selected |
214
+ | `resolvedThemes` | `{ colorScheme: 'dark', contrast: 'standard' }` | The same, with media options resolved. Use this to style the page |
215
+ | `resolvedSystemThemes` | `{ colorScheme: 'dark' }` | What each media option resolves to right now, even when it isn't selected. Useful for showing "System (dark)" |
216
+
217
+ ## API
218
+
219
+ ### `createThemeStore(config, options?)`
220
+
221
+ ```ts
222
+ const store = createThemeStore(CONFIG, {
223
+ // Where to save settings. Defaults to localStorage under the key 'resonare'.
224
+ // Pass null to not save at all.
225
+ storage: localStorageAdapter({ key: 'my-app' }),
226
+
227
+ // Initial state, e.g. loaded from your database (see Server-side persistence).
228
+ persisted: savedState,
174
229
  })
230
+ ```
175
231
 
176
- unsubscribe()
232
+ | Method | Description |
233
+ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
234
+ | `getSnapshot()` | Current [state](#state). Returns the same object until the next change |
235
+ | `getServerSnapshot()` | The state as rendered on the server (see [Server-side rendering](#server-side-rendering)) |
236
+ | `setThemes(partial)` | Updates the given settings, saves them and notifies subscribers. Also accepts a function: `setThemes((current) => ({ ... }))` |
237
+ | `updateSystemOption(key, [whenMatched, whenNotMatched])` | Changes what a media option resolves to, e.g. `updateSystemOption('colorScheme', ['dark-dimmed', 'light'])` |
238
+ | `subscribe(callback)` | Calls `callback(state, prev)` after every change, including OS preference changes. Returns an unsubscribe function |
239
+ | `restore()` | Loads the saved state from storage. Does nothing when nothing is saved |
240
+ | `sync()` | Applies changes made in other tabs. Returns a function that stops syncing |
241
+ | `toPersist()` | The state to save elsewhere; pass it back as `persisted` |
242
+ | `destroy()` | Removes all subscribers and listeners |
177
243
 
178
- // destroy the store and clean up event listeners
179
- themeStore.destroy()
244
+ ### `createInlineThemeScript(params)`
245
+
246
+ Returns the source of the inline script.
247
+
248
+ ```ts
249
+ createInlineThemeScript({
250
+ key: 'my-app', // the store's storage key; defaults to 'resonare'
251
+ config: CONFIG, // the same config as the store
252
+ handler: applyThemes, // receives the same state as subscribe
253
+ })
180
254
  ```
181
255
 
182
- ### `createInlineThemeScript`
256
+ - The handler is copied into the script as source code, so it can't use variables from outside the function. Define any constants inside it.
257
+ - The script only reads `localStorage`. With other storage, apply settings on the server instead (see [Server-side persistence](#server-side-persistence)).
258
+ - To run several independent stores, e.g. separate settings for different sections of a page, pass an array with one entry per store, each with its own `key`.
183
259
 
184
- Generates a self-contained script string that restores persisted user preferences before first paint.
260
+ ### Helpers
185
261
 
186
262
  ```ts
187
- import { createInlineThemeScript, type ThemeStoreConfig } from 'resonare'
263
+ import { getDefaultThemes, getThemesAndOptions } from 'resonare'
264
+
265
+ getThemesAndOptions(CONFIG)
266
+ // [['colorScheme', ['system', 'light', 'dark']], ['contrast', ['standard', 'high']]]
267
+
268
+ getDefaultThemes(CONFIG)
269
+ // { colorScheme: 'system', contrast: 'standard' }
270
+ ```
271
+
272
+ `getThemesAndOptions` is handy for rendering a picker for every setting.
188
273
 
274
+ ### Settings without options
275
+
276
+ A setting can have just a `defaultValue`, for free values such as numbers:
277
+
278
+ ```ts
189
279
  const CONFIG = {
190
- colorScheme: {
191
- options: [
192
- {
193
- value: 'system',
194
- media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
195
- },
196
- 'light',
197
- 'dark',
198
- ],
199
- },
280
+ sidebarWidth: { defaultValue: 240 },
200
281
  } as const satisfies ThemeStoreConfig
201
282
 
202
- const script = createInlineThemeScript({
203
- config: CONFIG,
204
- handler: ({ resolvedThemes }) => {
205
- Object.entries(resolvedThemes).forEach(([key, value]) => {
206
- document.documentElement.dataset[key] = value
207
- })
283
+ store.setThemes({ sidebarWidth: 320 })
284
+ ```
285
+
286
+ ### Storage
287
+
288
+ | Adapter | Use it when |
289
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------ |
290
+ | `localStorageAdapter({ key })` (default) | Settings should survive reloads in this browser. Syncs across tabs |
291
+ | `localStorageAdapter({ key, type: 'sessionStorage' })` | Settings should last only for the tab's session |
292
+ | `memoryStorageAdapter({ key })` | You save settings yourself (e.g. to your server) but still want tabs to stay in sync |
293
+ | `null` | You don't want anything saved |
294
+
295
+ If storage is blocked or full, reads return nothing and writes are skipped; the store keeps working in memory.
296
+
297
+ You can write your own adapter. It receives an `AbortController` that is aborted when the store is destroyed. `watch` and `broadcast` are optional and only needed for `sync()`. For example, a cookie lets your server read the settings:
298
+
299
+ ```ts
300
+ import { type StorageAdapterCreate } from 'resonare'
301
+
302
+ const cookieStorage: StorageAdapterCreate = () => ({
303
+ get: () => {
304
+ const value = document.cookie.match(/(?:^|; )theme=([^;]*)/)?.[1]
305
+
306
+ return value ? decodeURIComponent(value) : null
307
+ },
308
+ set: (value) => {
309
+ document.cookie = `theme=${encodeURIComponent(value)}; path=/; max-age=31536000`
208
310
  },
209
311
  })
312
+
313
+ const store = createThemeStore(CONFIG, { storage: cookieStorage })
210
314
  ```
211
315
 
212
- ## Framework Integration
316
+ ## Frameworks
213
317
 
214
- ### React
318
+ Every binding takes a store and returns its state plus its methods (`setThemes`, `restore`, `sync`, …).
215
319
 
216
- #### Client-side persistence
320
+ ### React
217
321
 
218
322
  ```tsx
219
- import {
220
- createInlineThemeScript,
221
- createThemeStore,
222
- getThemesAndOptions,
223
- type ThemeScriptParameter,
224
- } from 'resonare'
225
323
  import { useResonare } from 'resonare/react'
226
324
 
227
- const PARAM = {
228
- key: 'demo',
229
- config: {
230
- colorScheme: {
231
- options: [
232
- {
233
- value: 'system',
234
- media: ['(prefers-color-scheme: dark)', 'dark', 'light'],
235
- },
236
- 'light',
237
- 'dark',
238
- ],
239
- },
240
- contrast: {
241
- options: [
242
- {
243
- value: 'system',
244
- media: [
245
- '(prefers-contrast: more) and (forced-colors: none)',
246
- 'high',
247
- 'standard',
248
- ],
249
- },
250
- 'standard',
251
- 'high',
252
- ],
253
- },
254
- },
255
- handler: ({ resolvedThemes }) => {
256
- Object.entries(resolvedThemes).forEach(([key, value]) => {
257
- document.documentElement.dataset[key] = String(value)
258
- })
259
- },
260
- } as const satisfies ThemeScriptParameter
325
+ const { themes, resolvedThemes, setThemes } = useResonare(store)
326
+ ```
327
+
328
+ Re-renders when the state changes. Server rendering is handled automatically.
261
329
 
262
- export const themeScript = createInlineThemeScript(PARAM)
330
+ ### Solid
263
331
 
264
- const themeStore = createThemeStore(PARAM.config)
332
+ ```tsx
333
+ import { useResonare } from 'resonare/solid'
265
334
 
335
+ const { themes, setThemes } = useResonare(store)
266
336
 
267
- function ThemeSelect() {
268
- const { themes, setThemes } = useResonare(themeStore)
337
+ return <p>{themes().colorScheme}</p>
338
+ ```
269
339
 
270
- React.useEffect(() => {
271
- const unsubscribe = subscribe(PARAM.handler)
340
+ State values are signals. Call it inside a component; the subscription ends when the component is cleaned up.
341
+
342
+ ### Svelte
343
+
344
+ ```svelte
345
+ <script lang="ts">
346
+ import { useResonare } from 'resonare/svelte'
347
+
348
+ const { themes, setThemes } = useResonare(store)
349
+ </script>
350
+
351
+ <p>{themes.current.colorScheme}</p>
352
+ <button onclick={() => setThemes({ colorScheme: 'dark' })}>Dark</button>
353
+ ```
354
+
355
+ Read state through `.current`. It's reactive in templates, `$derived` and `$effect`, and the store is only subscribed while something reads it.
356
+
357
+ ### Vue
358
+
359
+ ```vue
360
+ <script setup lang="ts">
361
+ import { useResonare } from 'resonare/vue'
272
362
 
273
- const stopSync = sync()
363
+ const { themes, setThemes } = useResonare(store, { hydrate: true })
364
+ </script>
274
365
 
275
- restore()
366
+ <template>
367
+ <p>{{ themes.colorScheme }}</p>
368
+ <button @click="setThemes({ colorScheme: 'dark' })">Dark</button>
369
+ </template>
370
+ ```
371
+
372
+ State values are computed refs. Call it in `setup`. Pass `{ hydrate: true }` only in server-rendered apps (see below).
373
+
374
+ ## Server-side rendering
375
+
376
+ The server can't know the user's OS preference or what's saved in their browser. It renders the defaults (plus `persisted`, if you pass it), with media options resolved to their "not matched" value: `system` renders as `light`. `getServerSnapshot()` returns exactly that state, and it never changes.
377
+
378
+ The bindings use it so that hydration matches the server HTML, then switch to the live state:
379
+
380
+ - **React** and **Solid:** automatic.
381
+ - **Svelte:** nothing needed; Svelte fixes mismatched markup while hydrating.
382
+ - **Vue:** pass `useResonare(store, { hydrate: true })`. Leave it off in client-only apps, where it would show the server state for one frame.
383
+
384
+ To avoid a flash of the wrong theme:
385
+
386
+ - **Change the page with `store.subscribe(handler)`**, using the same handler as the inline script. Don't set `data-*` attributes from values returned by `useResonare`: until hydration finishes, those are the server values.
387
+ - **Style theme-dependent markup with CSS** keyed off those attributes, rather than branching on `resolvedThemes`. For example, render both a sun and a moon icon and hide one with `[data-color-scheme='dark'] .sun { display: none }`.
388
+ - **Pass the same `persisted` on the server and the client.** If it's per user (e.g. from a cookie), create one store per request instead of sharing a module-level store.
389
+
390
+ ## Server-side persistence
391
+
392
+ To save settings to your own backend instead of the browser, load them on the server and pass them as `persisted`. Render the page's theme attributes on the server from `store.getServerSnapshot().resolvedThemes`; the page then arrives with the right theme, so the inline script isn't needed for saved settings.
393
+
394
+ ```tsx
395
+ import { createThemeStore, memoryStorageAdapter } from 'resonare'
396
+ import { useResonare } from 'resonare/react'
397
+
398
+ export function ThemeSelect({ savedState }) {
399
+ const [store] = React.useState(() => {
400
+ return createThemeStore(CONFIG, {
401
+ persisted: savedState, // from your database
402
+ // Tab sync in the browser only; null skips it (and on the server)
403
+ storage:
404
+ typeof window === 'undefined'
405
+ ? null
406
+ : memoryStorageAdapter({ key: 'my-app' }),
407
+ })
408
+ })
409
+
410
+ const { themes, setThemes } = useResonare(store)
411
+
412
+ React.useEffect(() => {
413
+ const unsubscribe = store.subscribe(applyThemes)
414
+ const stopSync = store.sync()
276
415
 
277
416
  return () => {
278
417
  stopSync?.()
279
-
280
418
  unsubscribe()
281
419
  }
282
- }, [subscribe, restore, sync])
283
-
284
- return getThemesAndOptions(PARAM.config).map(([theme, options]) => (
285
- <div key={theme}>
286
- <label htmlFor={theme}>{theme}</label>
287
- <select
288
- id={theme}
289
- name={theme}
290
- onChange={(e) => {
291
- setThemes({ [theme]: e.target.value })
292
- }}
293
- value={themes[theme]}
294
- >
295
- {options.map((option) => (
296
- <option key={option} value={option}>
297
- {option}
298
- </option>
299
- ))}
300
- </select>
301
- </div>
302
- ))
420
+ }, [store])
421
+
422
+ return (
423
+ <select
424
+ value={themes.colorScheme}
425
+ onChange={async (e) => {
426
+ setThemes({ colorScheme: e.target.value as typeof themes.colorScheme })
427
+ await saveToDatabase(store.toPersist())
428
+ }}
429
+ >
430
+ {/* options */}
431
+ </select>
432
+ )
303
433
  }
304
434
  ```
305
435
 
306
- #### Server-side persistence
436
+ `system` still depends on the OS preference, which the server can't see. If you offer it, keep the inline script so it can resolve `system` before paint.
307
437
 
308
- The inline script is not required.
438
+ ## Lite
309
439
 
310
- ```tsx
311
- import * as React from 'react'
440
+ For a single light / dark / system preference, `resonare/lite` is smaller and needs no config.
441
+
442
+ ```ts
443
+ import { createInlineThemeScript, createThemeStore } from 'resonare/lite'
312
444
  import {
313
- createThemeStore,
314
- getThemesAndOptions,
315
- memoryStorageAdapter,
316
- type ThemeStoreConfig,
317
- } from 'resonare'
318
- import { useResonare } from 'resonare/react'
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
+ )
459
+
460
+ // Put this in the <head>, as above.
461
+ export const themeScript = createInlineThemeScript({ handler: applyTheme })
462
+
463
+ export const store = createThemeStore()
464
+
465
+ if (typeof window !== 'undefined') {
466
+ store.subscribe(applyTheme)
467
+ store.restore()
468
+ store.sync()
469
+ }
319
470
 
320
- const CONFIG = {
321
- colorScheme: {
322
- options: ['light', 'dark'],
323
- },
324
- contrast: {
325
- options: ['standard', 'high'],
326
- },
327
- } as const satisfies ThemeStoreConfig
471
+ store.setTheme('dark')
472
+ store.setTheme((current) => (current === 'dark' ? 'light' : 'dark'))
473
+ ```
328
474
 
329
- export function ThemeSelect({ persistedStateFromDb }) {
330
- const [themeStore] = React.useState(() =>
331
- createThemeStore(CONFIG, {
332
- initialState: persistedStateFromDb,
333
- // pass null instead if syncing across tabs/windows is not needed
334
- storage: memoryStorageAdapter({ key: 'resonare' }),
335
- }),
336
- )
475
+ The state has three fields:
337
476
 
338
- const { themes, setThemes, subscribe, sync } = useResonare(themeStore)
477
+ | Field | Values | Meaning |
478
+ | --------------- | ------------------------------- | ---------------------------------------------------- |
479
+ | `theme` | `'system' \| 'light' \| 'dark'` | What the user selected |
480
+ | `resolvedTheme` | `'light' \| 'dark'` | The same, with `system` resolved |
481
+ | `systemTheme` | `'light' \| 'dark'` | The OS preference, even when `system` isn't selected |
339
482
 
340
- React.useEffect(() => {
341
- const unsubscribe = subscribe(({ resolvedThemes }) => {
342
- Object.entries(resolvedThemes).forEach(([key, value]) => {
343
- document.documentElement.dataset[key] = String(value)
344
- })
345
- })
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'`).
346
484
 
347
- const stopSync = sync()
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.
348
486
 
349
- return () => {
350
- stopSync?.()
487
+ ## Changing options later
351
488
 
352
- unsubscribe()
489
+ Saved values are used as they are: Resonare doesn't check them against your config. If you rename or remove an option, migrate the saved data yourself. A small script before the theme script works well, since it runs before both the inline script and the store read the data:
490
+
491
+ ```html
492
+ <script>
493
+ try {
494
+ const saved = JSON.parse(localStorage.getItem('my-app'))
495
+
496
+ if (saved?.themes?.colorScheme === 'dark-modern') {
497
+ saved.themes.colorScheme = 'dark'
498
+ localStorage.setItem('my-app', JSON.stringify(saved))
353
499
  }
354
- }, [subscribe, sync])
355
-
356
- return getThemesAndOptions(CONFIG).map(([theme, options]) => (
357
- <div key={theme}>
358
- <label htmlFor={theme}>{theme}</label>
359
- <select
360
- id={theme}
361
- name={theme}
362
- onChange={async (e) => {
363
- setThemes({ [theme]: e.target.value })
364
-
365
- await saveToDb(themeStore.toPersist())
366
- }}
367
- value={themes[theme]}
368
- >
369
- {options.map((option) => (
370
- <option key={option} value={option}>
371
- {option}
372
- </option>
373
- ))}
374
- </select>
375
- </div>
376
- ))
377
- }
500
+ } catch {}
501
+ </script>
378
502
  ```
503
+
504
+ ## License
505
+
506
+ MIT