resonare 0.1.7 → 0.3.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 (46) hide show
  1. package/README.md +329 -270
  2. package/dist/index.d.ts +220 -102
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/lite-react.d.ts +41 -0
  7. package/dist/lite-react.d.ts.map +1 -0
  8. package/dist/lite-react.js +2 -0
  9. package/dist/lite-react.js.map +1 -0
  10. package/dist/lite-solid.d.ts +42 -0
  11. package/dist/lite-solid.d.ts.map +1 -0
  12. package/dist/lite-solid.js +2 -0
  13. package/dist/lite-solid.js.map +1 -0
  14. package/dist/lite-svelte.d.ts +41 -0
  15. package/dist/lite-svelte.d.ts.map +1 -0
  16. package/dist/lite-svelte.js +2 -0
  17. package/dist/lite-svelte.js.map +1 -0
  18. package/dist/lite-vue.d.ts +49 -0
  19. package/dist/lite-vue.d.ts.map +1 -0
  20. package/dist/lite-vue.js +2 -0
  21. package/dist/lite-vue.js.map +1 -0
  22. package/dist/lite.d.ts +124 -0
  23. package/dist/lite.d.ts.map +1 -0
  24. package/dist/lite.js +2 -0
  25. package/dist/lite.js.map +1 -0
  26. package/dist/react.d.ts +39 -30
  27. package/dist/react.d.ts.map +1 -1
  28. package/dist/react.js +1 -1
  29. package/dist/react.js.map +1 -1
  30. package/dist/solid.d.ts +84 -0
  31. package/dist/solid.d.ts.map +1 -0
  32. package/dist/solid.js +2 -0
  33. package/dist/solid.js.map +1 -0
  34. package/dist/storage-BqWA8jeP.js +2 -0
  35. package/dist/storage-BqWA8jeP.js.map +1 -0
  36. package/dist/storage-CsXjZKyt.d.ts +65 -0
  37. package/dist/storage-CsXjZKyt.d.ts.map +1 -0
  38. package/dist/svelte.d.ts +86 -0
  39. package/dist/svelte.d.ts.map +1 -0
  40. package/dist/svelte.js +2 -0
  41. package/dist/svelte.js.map +1 -0
  42. package/dist/vue.d.ts +82 -0
  43. package/dist/vue.d.ts.map +1 -0
  44. package/dist/vue.js +2 -0
  45. package/dist/vue.js.map +1 -0
  46. package/package.json +75 -32
package/README.md CHANGED
@@ -1,46 +1,42 @@
1
- # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=black&color=blue)](https://www.npmjs.com/package/resonare)
1
+ # Resonare [![Version](https://img.shields.io/npm/v/resonare.svg?labelColor=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
21
16
 
22
17
  ## Installation
23
18
 
24
- To install:
25
-
26
19
  ```bash
27
20
  npm i resonare
28
21
  # or
29
- yarn add resonare
30
- # or
31
22
  pnpm add resonare
23
+ # or
24
+ yarn add resonare
32
25
  ```
33
26
 
34
- ## Basic Usage
27
+ The framework bindings need React 19+, Solid 1.6+, Svelte 5.7+ or Vue 3.2+.
28
+
29
+ ## Quick start
35
30
 
36
- ### 1. Create inline script
31
+ ### 1. Describe your settings
37
32
 
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.
33
+ 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]`.
39
34
 
40
35
  ```ts
41
- import { createInlineThemeScript, type ThemeStoreConfig } from 'resonare'
36
+ // theme.ts
37
+ import { type ThemeScriptParameter, type ThemeStoreConfig } from 'resonare'
42
38
 
43
- const CONFIG = {
39
+ export const CONFIG = {
44
40
  colorScheme: {
45
41
  options: [
46
42
  {
@@ -51,328 +47,391 @@ const CONFIG = {
51
47
  'dark',
52
48
  ],
53
49
  },
50
+ contrast: {
51
+ options: ['standard', 'high'],
52
+ },
54
53
  } as const satisfies ThemeStoreConfig
55
54
 
55
+ // Applies the settings to the page, e.g. as data-color-scheme="dark".
56
+ // It is also copied into the inline script as source code, so it must not use
57
+ // any variables from outside the function.
58
+ export const applyThemes: ThemeScriptParameter['handler'] = ({
59
+ resolvedThemes,
60
+ }) => {
61
+ for (const [key, value] of Object.entries(resolvedThemes)) {
62
+ document.documentElement.dataset[key] = String(value)
63
+ }
64
+ }
65
+ ```
66
+
67
+ Then style your page from those attributes:
68
+
69
+ ```css
70
+ :root[data-color-scheme='dark'] {
71
+ color-scheme: dark;
72
+ --background: #000;
73
+ }
74
+ ```
75
+
76
+ ### 2. Add the inline script
77
+
78
+ 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>`:
79
+
80
+ ```ts
81
+ import { createInlineThemeScript } from 'resonare'
82
+
83
+ import { CONFIG, applyThemes } from './theme'
84
+
56
85
  export const themeScript = createInlineThemeScript({
57
86
  config: CONFIG,
58
- handler: ({ resolvedThemes }) => {
59
- Object.entries(resolvedThemes).forEach(([key, value]) => {
60
- document.documentElement.dataset[key] = value
61
- })
62
- },
87
+ handler: applyThemes,
63
88
  })
64
89
  ```
65
90
 
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
91
  ```tsx
71
- // React.js
72
- <script suppressHydrationWarning>{themeScript}</script>
92
+ // React
93
+ <script dangerouslySetInnerHTML={{ __html: themeScript }} />
73
94
 
74
- // TanStack Router/Start
75
- import { ScriptOnce } from '@tanstack/router'
95
+ // TanStack Start
96
+ import { ScriptOnce } from '@tanstack/react-router'
76
97
 
77
98
  <ScriptOnce>{themeScript}</ScriptOnce>
78
99
 
79
- // Astro.js
100
+ // Astro
80
101
  <script is:inline set:html={themeScript} />
81
102
  ```
82
103
 
83
- ### 3. Initialize the store
84
-
85
- Refer to the [Framework Integration](#framework-integration) section for examples.
104
+ ### 3. Create the store
86
105
 
87
- ## API
106
+ ```ts
107
+ import { createThemeStore } from 'resonare'
88
108
 
89
- ### `createThemeStore`
109
+ import { CONFIG, applyThemes } from './theme'
90
110
 
91
- ```ts
92
- import {
93
- createThemeStore,
94
- localStorageAdapter,
95
- type ThemeStoreConfig,
96
- } from 'resonare'
111
+ export const store = createThemeStore(CONFIG)
97
112
 
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
113
+ if (typeof window !== 'undefined') {
114
+ store.subscribe(applyThemes) // keep the page in sync with every change
115
+ store.restore() // load the saved settings
116
+ store.sync() // follow changes made in other tabs
117
+ }
118
+ ```
128
119
 
129
- const themeStore = createThemeStore(CONFIG, {
130
- // optional, useful for server-side persistence
131
- initialState: persistedStateFromDb, // persisted state returned by themeStore.toPersist()
120
+ ### 4. Use it in your UI
132
121
 
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' }),
136
- })
122
+ ```tsx
123
+ import { useResonare } from 'resonare/react'
137
124
 
138
- // get current theme selection
139
- // e.g.: { colorScheme: 'system', contrast: 'standard', sidebarWidth: 240 }
140
- themeStore.getThemes()
125
+ function ColorSchemeSelect() {
126
+ const { themes, setThemes } = useResonare(store)
127
+
128
+ return (
129
+ <select
130
+ value={themes.colorScheme}
131
+ onChange={(e) => {
132
+ setThemes({ colorScheme: e.target.value as typeof themes.colorScheme })
133
+ }}
134
+ >
135
+ <option value='system'>System</option>
136
+ <option value='light'>Light</option>
137
+ <option value='dark'>Dark</option>
138
+ </select>
139
+ )
140
+ }
141
+ ```
141
142
 
142
- // get resolved theme selection (after media queries)
143
- // e.g.: { colorScheme: 'dark', contrast: 'standard', sidebarWidth: 240 }
144
- themeStore.getResolvedThemes()
143
+ See [Frameworks](#frameworks) for Solid, Svelte and Vue.
145
144
 
146
- // get resolved system options
147
- // e.g.: { colorScheme: 'dark' }
148
- themeStore.getResolvedSystemThemes()
145
+ ## State
149
146
 
150
- // update theme
151
- themeStore.setThemes({ colorScheme: 'light', sidebarWidth: 280 })
147
+ Every listener, snapshot and binding gives you three views of the state:
152
148
 
153
- // get state to persist, useful for server-side persistence
154
- // to restore, pass the returned object to createThemeStore's initialState
155
- themeStore.toPersist()
149
+ | Field | Example | Meaning |
150
+ | ---------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
151
+ | `themes` | `{ colorScheme: 'system', contrast: 'standard' }` | What the user selected |
152
+ | `resolvedThemes` | `{ colorScheme: 'dark', contrast: 'standard' }` | The same, with media options resolved. Use this to style the page |
153
+ | `resolvedSystemThemes` | `{ colorScheme: 'dark' }` | What each media option resolves to right now, even when it isn't selected. Useful for showing "System (dark)" |
156
154
 
157
- // restore persisted state from client-side storage
158
- themeStore.restore()
155
+ ## API
159
156
 
160
- // sync user preferences across tabs/windows if supported by the storage adapter
161
- const stopSync = themeStore.sync()
157
+ ### `createThemeStore(config, options?)`
162
158
 
163
- stopSync?.()
159
+ ```ts
160
+ const store = createThemeStore(CONFIG, {
161
+ // Where to save settings. Defaults to localStorage under the key 'resonare'.
162
+ // Pass null to not save at all.
163
+ storage: localStorageAdapter({ key: 'my-app' }),
164
164
 
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
- })
165
+ // Initial state, e.g. loaded from your database (see Server-side persistence).
166
+ persisted: savedState,
174
167
  })
168
+ ```
169
+
170
+ | Method | Description |
171
+ | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
172
+ | `getSnapshot()` | Current [state](#state). Returns the same object until the next change |
173
+ | `getServerSnapshot()` | The state as rendered on the server (see [Server-side rendering](#server-side-rendering)) |
174
+ | `setThemes(partial)` | Updates the given settings, saves them and notifies subscribers. Also accepts a function: `setThemes((current) => ({ ... }))` |
175
+ | `updateSystemOption(key, [whenMatched, whenNotMatched])` | Changes what a media option resolves to, e.g. `updateSystemOption('colorScheme', ['dark-dimmed', 'light'])` |
176
+ | `subscribe(callback)` | Calls `callback` with the new state after every change, including OS preference changes. Returns an unsubscribe function |
177
+ | `restore()` | Loads the saved state from storage. Does nothing when nothing is saved |
178
+ | `sync()` | Applies changes made in other tabs. Returns a function that stops syncing |
179
+ | `toPersist()` | The state to save elsewhere; pass it back as `persisted` |
180
+ | `destroy()` | Removes all subscribers and listeners |
175
181
 
176
- unsubscribe()
182
+ ### `createInlineThemeScript(params)`
177
183
 
178
- // destroy the store and clean up event listeners
179
- themeStore.destroy()
184
+ Returns the source of the inline script.
185
+
186
+ ```ts
187
+ createInlineThemeScript({
188
+ key: 'my-app', // the store's storage key; defaults to 'resonare'
189
+ config: CONFIG, // the same config as the store
190
+ handler: applyThemes, // receives the same state as subscribe
191
+ })
180
192
  ```
181
193
 
182
- ### `createInlineThemeScript`
194
+ - 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.
195
+ - The script only reads `localStorage`. With other storage, apply settings on the server instead (see [Server-side persistence](#server-side-persistence)).
196
+ - 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
197
 
184
- Generates a self-contained script string that restores persisted user preferences before first paint.
198
+ ### Helpers
185
199
 
186
200
  ```ts
187
- import { createInlineThemeScript, type ThemeStoreConfig } from 'resonare'
201
+ import { getDefaultThemes, getThemesAndOptions } from 'resonare'
202
+
203
+ getThemesAndOptions(CONFIG)
204
+ // [['colorScheme', ['system', 'light', 'dark']], ['contrast', ['standard', 'high']]]
205
+
206
+ getDefaultThemes(CONFIG)
207
+ // { colorScheme: 'system', contrast: 'standard' }
208
+ ```
188
209
 
210
+ `getThemesAndOptions` is handy for rendering a picker for every setting.
211
+
212
+ ### Settings without options
213
+
214
+ A setting can have just a `defaultValue`, for free values such as numbers:
215
+
216
+ ```ts
189
217
  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
- },
218
+ sidebarWidth: { defaultValue: 240 },
200
219
  } as const satisfies ThemeStoreConfig
201
220
 
202
- const script = createInlineThemeScript({
203
- config: CONFIG,
204
- handler: ({ resolvedThemes }) => {
205
- Object.entries(resolvedThemes).forEach(([key, value]) => {
206
- document.documentElement.dataset[key] = value
207
- })
221
+ store.setThemes({ sidebarWidth: 320 })
222
+ ```
223
+
224
+ ### Storage
225
+
226
+ | Adapter | Use it when |
227
+ | ------------------------------------------------------ | ------------------------------------------------------------------------------------ |
228
+ | `localStorageAdapter({ key })` (default) | Settings should survive reloads in this browser. Syncs across tabs |
229
+ | `localStorageAdapter({ key, type: 'sessionStorage' })` | Settings should last only for the tab's session |
230
+ | `memoryStorageAdapter({ key })` | You save settings yourself (e.g. to your server) but still want tabs to stay in sync |
231
+ | `null` | You don't want anything saved |
232
+
233
+ If storage is blocked or full, reads return nothing and writes are skipped; the store keeps working in memory.
234
+
235
+ 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:
236
+
237
+ ```ts
238
+ import { type StorageAdapterCreate } from 'resonare'
239
+
240
+ const cookieStorage: StorageAdapterCreate = () => ({
241
+ get: () => {
242
+ const value = document.cookie.match(/(?:^|; )theme=([^;]*)/)?.[1]
243
+
244
+ return value ? decodeURIComponent(value) : null
245
+ },
246
+ set: (value) => {
247
+ document.cookie = `theme=${encodeURIComponent(value)}; path=/; max-age=31536000`
208
248
  },
209
249
  })
250
+
251
+ const store = createThemeStore(CONFIG, { storage: cookieStorage })
210
252
  ```
211
253
 
212
- ## Framework Integration
254
+ ## Frameworks
213
255
 
214
- ### React
256
+ Every binding takes a store and returns its state plus its methods (`setThemes`, `restore`, `sync`, …).
215
257
 
216
- #### Client-side persistence
258
+ ### React
217
259
 
218
260
  ```tsx
219
- import {
220
- createInlineThemeScript,
221
- createThemeStore,
222
- getThemesAndOptions,
223
- type ThemeScriptParameter,
224
- } from 'resonare'
225
261
  import { useResonare } from 'resonare/react'
226
262
 
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
263
+ const { themes, resolvedThemes, setThemes } = useResonare(store)
264
+ ```
261
265
 
262
- export const themeScript = createInlineThemeScript(PARAM)
266
+ Re-renders when the state changes. Server rendering is handled automatically.
263
267
 
264
- const themeStore = createThemeStore(PARAM.config)
268
+ ### Solid
265
269
 
270
+ ```tsx
271
+ import { useResonare } from 'resonare/solid'
266
272
 
267
- function ThemeSelect() {
268
- const { themes, setThemes } = useResonare(themeStore)
273
+ const { themes, setThemes } = useResonare(store)
269
274
 
270
- React.useEffect(() => {
271
- const unsubscribe = subscribe(PARAM.handler)
275
+ return <p>{themes().colorScheme}</p>
276
+ ```
277
+
278
+ State values are signals. Call it inside a component; the subscription ends when the component is cleaned up.
279
+
280
+ ### Svelte
281
+
282
+ ```svelte
283
+ <script lang="ts">
284
+ import { useResonare } from 'resonare/svelte'
285
+
286
+ const { themes, setThemes } = useResonare(store)
287
+ </script>
288
+
289
+ <p>{themes.current.colorScheme}</p>
290
+ <button onclick={() => setThemes({ colorScheme: 'dark' })}>Dark</button>
291
+ ```
292
+
293
+ Read state through `.current`. It's reactive in templates, `$derived` and `$effect`, and the store is only subscribed while something reads it.
294
+
295
+ ### Vue
296
+
297
+ ```vue
298
+ <script setup lang="ts">
299
+ import { useResonare } from 'resonare/vue'
300
+
301
+ const { themes, setThemes } = useResonare(store, { hydrate: true })
302
+ </script>
303
+
304
+ <template>
305
+ <p>{{ themes.colorScheme }}</p>
306
+ <button @click="setThemes({ colorScheme: 'dark' })">Dark</button>
307
+ </template>
308
+ ```
309
+
310
+ State values are computed refs. Call it in `setup`. Pass `{ hydrate: true }` only in server-rendered apps (see below).
311
+
312
+ ## Server-side rendering
313
+
314
+ 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.
315
+
316
+ The bindings use it so that hydration matches the server HTML, then switch to the live state:
317
+
318
+ - **React** and **Solid:** automatic.
319
+ - **Svelte:** nothing needed; Svelte fixes mismatched markup while hydrating.
320
+ - **Vue:** pass `useResonare(store, { hydrate: true })`. Leave it off in client-only apps, where it would show the server state for one frame.
321
+
322
+ To avoid a flash of the wrong theme:
272
323
 
273
- const stopSync = sync()
324
+ - **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.
325
+ - **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 }`.
326
+ - **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.
274
327
 
275
- restore()
328
+ ## Server-side persistence
329
+
330
+ 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.
331
+
332
+ ```tsx
333
+ import { createThemeStore, memoryStorageAdapter } from 'resonare'
334
+ import { useResonare } from 'resonare/react'
335
+
336
+ export function ThemeSelect({ savedState }) {
337
+ const [store] = React.useState(() => {
338
+ return createThemeStore(CONFIG, {
339
+ persisted: savedState, // from your database
340
+ // Tab sync in the browser only; null skips it (and on the server)
341
+ storage:
342
+ typeof window === 'undefined'
343
+ ? null
344
+ : memoryStorageAdapter({ key: 'my-app' }),
345
+ })
346
+ })
347
+
348
+ const { themes, setThemes } = useResonare(store)
349
+
350
+ React.useEffect(() => {
351
+ const unsubscribe = store.subscribe(applyThemes)
352
+ const stopSync = store.sync()
276
353
 
277
354
  return () => {
278
355
  stopSync?.()
279
-
280
356
  unsubscribe()
281
357
  }
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
- ))
358
+ }, [store])
359
+
360
+ return (
361
+ <select
362
+ value={themes.colorScheme}
363
+ onChange={async (e) => {
364
+ setThemes({ colorScheme: e.target.value as typeof themes.colorScheme })
365
+ await saveToDatabase(store.toPersist())
366
+ }}
367
+ >
368
+ {/* options */}
369
+ </select>
370
+ )
303
371
  }
304
372
  ```
305
373
 
306
- #### Server-side persistence
374
+ `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
375
 
308
- The inline script is not required.
376
+ ## Lite
309
377
 
310
- ```tsx
311
- import * as React from 'react'
378
+ For a single light / dark / system preference, `resonare/lite` is smaller and needs no config.
379
+
380
+ ```ts
312
381
  import {
382
+ type ThemeScriptParameter,
383
+ createInlineThemeScript,
313
384
  createThemeStore,
314
- getThemesAndOptions,
315
- memoryStorageAdapter,
316
- type ThemeStoreConfig,
317
- } from 'resonare'
318
- import { useResonare } from 'resonare/react'
385
+ } from 'resonare/lite'
319
386
 
320
- const CONFIG = {
321
- colorScheme: {
322
- options: ['light', 'dark'],
323
- },
324
- contrast: {
325
- options: ['standard', 'high'],
326
- },
327
- } as const satisfies ThemeStoreConfig
387
+ const applyTheme: ThemeScriptParameter['handler'] = ({ resolvedTheme }) => {
388
+ document.documentElement.dataset.theme = resolvedTheme
389
+ }
328
390
 
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
- )
391
+ // Put this in the <head>, as above.
392
+ export const themeScript = createInlineThemeScript({ handler: applyTheme })
337
393
 
338
- const { themes, setThemes, subscribe, sync } = useResonare(themeStore)
394
+ export const store = createThemeStore()
339
395
 
340
- React.useEffect(() => {
341
- const unsubscribe = subscribe(({ resolvedThemes }) => {
342
- Object.entries(resolvedThemes).forEach(([key, value]) => {
343
- document.documentElement.dataset[key] = String(value)
344
- })
345
- })
396
+ if (typeof window !== 'undefined') {
397
+ store.subscribe(applyTheme)
398
+ store.restore()
399
+ store.sync()
400
+ }
346
401
 
347
- const stopSync = sync()
402
+ store.setTheme('dark')
403
+ store.setTheme((current) => (current === 'dark' ? 'light' : 'dark'))
404
+ ```
348
405
 
349
- return () => {
350
- stopSync?.()
406
+ The state has three fields:
351
407
 
352
- unsubscribe()
408
+ | Field | Values | Meaning |
409
+ | --------------- | ------------------------------- | ---------------------------------------------------- |
410
+ | `theme` | `'system' \| 'light' \| 'dark'` | What the user selected |
411
+ | `resolvedTheme` | `'light' \| 'dark'` | The same, with `system` resolved |
412
+ | `systemTheme` | `'light' \| 'dark'` | The OS preference, even when `system` isn't selected |
413
+
414
+ 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
+
416
+ The bindings live under `resonare/lite/react`, `resonare/lite/solid`, `resonare/lite/svelte` and `resonare/lite/vue`, and work like the full ones.
417
+
418
+ ## Changing options later
419
+
420
+ 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:
421
+
422
+ ```html
423
+ <script>
424
+ try {
425
+ const saved = JSON.parse(localStorage.getItem('my-app'))
426
+
427
+ if (saved?.themes?.colorScheme === 'dark-modern') {
428
+ saved.themes.colorScheme = 'dark'
429
+ localStorage.setItem('my-app', JSON.stringify(saved))
353
430
  }
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
- }
431
+ } catch {}
432
+ </script>
378
433
  ```
434
+
435
+ ## License
436
+
437
+ MIT