@oxog/state 1.0.0 → 1.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.
package/README.md CHANGED
@@ -8,11 +8,14 @@ Zero-dependency reactive state management for any framework.
8
8
 
9
9
  ## Features
10
10
 
11
- - **Zero Dependencies** - No runtime dependencies, smaller bundle size
11
+ - **Zero Dependencies** - No runtime dependencies (React is an optional peer for the hooks)
12
12
  - **Framework Agnostic** - Works with React, Vue, Svelte, or vanilla JS
13
- - **TypeScript Native** - Built with strict mode, full type inference
14
- - **Plugin System** - Extend with persist, devtools, history, sync, immer
15
- - **Tiny Bundle** - Less than 2KB gzipped for core
13
+ - **TypeScript Native** - Built with strict mode; actions are typed from their definitions
14
+ - **Plugin System** - Extend with persist, devtools, history, sync, logger, effects, validate
15
+ - **Slices & Computed** - Modular state organization with derived values
16
+ - **Store Federation** - Combine multiple stores for large applications
17
+ - **Small** - About 3 KB gzipped for the core store when tree-shaken
18
+ - **ESM, CommonJS and a CDN build** - `import`, `require()` or `<script>` (`window.OxogState`)
16
19
 
17
20
  ## Installation
18
21
 
@@ -30,27 +33,31 @@ pnpm add @oxog/state
30
33
 
31
34
  ## Quick Start
32
35
 
33
- ```typescript
36
+ ```tsx
34
37
  import { createStore, useStore } from '@oxog/state';
35
38
 
36
- // Create a store with state and actions
37
- const store = createStore({
38
- count: 0,
39
- increment: (state) => ({ count: state.count + 1 }),
40
- decrement: (state) => ({ count: state.count - 1 }),
41
- });
39
+ // State plus actions. An action receives the current state (and any
40
+ // arguments) and returns the part of the state to update.
41
+ const store = createStore(
42
+ { count: 0 },
43
+ {
44
+ increment: (state) => ({ count: state.count + 1 }),
45
+ incrementBy: (state, by: number) => ({ count: state.count + by }),
46
+ }
47
+ );
42
48
 
43
49
  // Use in React
44
50
  function Counter() {
45
51
  const count = useStore(store, (s) => s.count);
46
52
  const increment = useStore(store, (s) => s.increment);
47
53
 
48
- return <button onClick={increment}>{count}</button>;
54
+ return <button onClick={() => increment()}>{count}</button>;
49
55
  }
50
56
 
51
57
  // Use in vanilla JS
52
58
  store.subscribe((state) => console.log(state.count));
53
- store.increment();
59
+ store.getState().increment(); // actions live on the state...
60
+ store.incrementBy(5); // ...and on the store
54
61
  ```
55
62
 
56
63
  ## API Reference
@@ -59,22 +66,33 @@ store.increment();
59
66
 
60
67
  #### `createStore(initialState, actions?)`
61
68
 
62
- Creates a reactive store.
69
+ Creates a reactive store. Actions can be defined in three ways; each one is
70
+ bound to the store and available both as `store.name(...args)` and as
71
+ `store.getState().name(...args)`.
63
72
 
64
73
  ```typescript
65
- // Inline actions
66
- const store = createStore({
67
- count: 0,
68
- increment: (state) => ({ count: state.count + 1 }),
69
- });
70
-
71
- // Separate actions
72
- const store = createStore(
74
+ // Separate actions (recommended in TypeScript: `state` is typed automatically)
75
+ const counter = createStore(
73
76
  { count: 0 },
74
77
  { increment: (state) => ({ count: state.count + 1 }) }
75
78
  );
79
+
80
+ // Inline actions, prefixed with $ (the $ is dropped from the name)
81
+ const inline = createStore({
82
+ count: 0,
83
+ $increment: (state: { count: number }) => ({ count: state.count + 1 }),
84
+ });
85
+ inline.increment();
86
+
87
+ // Fluent builder
88
+ const fluent = createStore({ count: 0 })
89
+ .action('increment', (state) => ({ count: state.count + 1 }));
90
+ fluent.increment();
76
91
  ```
77
92
 
93
+ An action that returns nothing (`undefined`) does not update the state or
94
+ notify subscribers.
95
+
78
96
  #### `batch(fn)`
79
97
 
80
98
  Batch multiple updates into a single notification.
@@ -92,19 +110,31 @@ batch(() => {
92
110
 
93
111
  | Method | Description |
94
112
  |--------|-------------|
95
- | `getState()` | Get current state |
96
- | `setState(partial)` | Update state with partial object |
113
+ | `getState()` | Get the current state |
114
+ | `setState(partial)` | Shallow-merge a partial object (or the result of `(state) => partial`) |
97
115
  | `merge(partial)` | Deep merge state |
98
- | `reset()` | Reset to initial state |
99
- | `subscribe(listener, selector?)` | Subscribe to changes |
100
- | `use(plugin, options?)` | Add plugin |
101
- | `destroy()` | Cleanup store |
116
+ | `reset()` | Reset to the initial state |
117
+ | `subscribe(listener)` | Call `listener(state, prevState)` on every change |
118
+ | `subscribe(selector, listener, equalityFn?)` | Call `listener(value, prevValue)` when the selected value changes (default equality: shallow) |
119
+ | `use(plugin)` | Add a plugin |
120
+ | `destroy()` | Clean up the store and its plugins |
121
+
122
+ Notes on subscriber semantics:
123
+
124
+ - A listener that throws is reported (`console.error('Store error:', …)` and the
125
+ plugins' `onError`) and does not stop the other listeners.
126
+ - A `setState` called from inside a listener is delivered after the current
127
+ notification pass, so every listener sees the changes in order and ends on
128
+ the latest state.
129
+ - A listener added during a notification is first called for the next change.
130
+ - `getState()` returns the live state object. Treat it as read-only: mutating
131
+ it bypasses subscribers. Use `setState`, `merge` or the `immer` plugin.
102
132
 
103
133
  ### React Hooks
104
134
 
105
135
  #### `useStore(store, selector?, equalityFn?)`
106
136
 
107
- Subscribe to store state in React components.
137
+ Subscribe to store state in React components (built on `useSyncExternalStore`).
108
138
 
109
139
  ```typescript
110
140
  // Full state
@@ -113,18 +143,88 @@ const state = useStore(store);
113
143
  // With selector
114
144
  const count = useStore(store, (s) => s.count);
115
145
 
116
- // With custom equality
117
- const user = useStore(store, (s) => s.user, deepEqual);
146
+ // With custom equality: no re-render while the user id stays the same
147
+ const user = useStore(store, (s) => s.user, (a, b) => a?.id === b?.id);
148
+ ```
149
+
150
+ Selectors may return new objects or arrays: the result is compared with the
151
+ equality function (shallow by default) and the previous value is reused when
152
+ equal, so this does not cause extra renders or render loops.
153
+
154
+ #### `useShallow(selector)` <sup>v1.2</sup>
155
+
156
+ Wrap selectors returning objects so the same reference is returned while the
157
+ values are shallowly equal.
158
+
159
+ ```typescript
160
+ import { useStore, useShallow } from '@oxog/state';
161
+
162
+ const data = useStore(store, useShallow((s) => ({ a: s.a, b: s.b })));
163
+ ```
164
+
165
+ #### `useStoreSelector(store, selectors)` <sup>v1.2</sup>
166
+
167
+ Select multiple values with named selectors.
168
+
169
+ ```typescript
170
+ import { useStoreSelector } from '@oxog/state';
171
+
172
+ const { userCount, totalRevenue } = useStoreSelector(store, {
173
+ userCount: (s) => s.users.length,
174
+ totalRevenue: (s) => s.orders.reduce((sum, o) => sum + o.total, 0),
175
+ });
176
+ ```
177
+
178
+ #### `useStoreActions(store, ...actionNames)` <sup>v1.2</sup>
179
+
180
+ Get multiple actions with stable references.
181
+
182
+ ```typescript
183
+ import { useStoreActions } from '@oxog/state';
184
+
185
+ const { increment, decrement } = useStoreActions(store, 'increment', 'decrement');
186
+ ```
187
+
188
+ #### `useSetState(store)` <sup>v1.2</sup>
189
+
190
+ Get a stable setState function for partial updates.
191
+
192
+ ```tsx
193
+ import { useSetState } from '@oxog/state';
194
+
195
+ function Form() {
196
+ const setState = useSetState(store);
197
+
198
+ return <input onChange={(e) => setState({ name: e.target.value })} />;
199
+ }
200
+ ```
201
+
202
+ #### `useTransientSubscribe(store, selector, callback, equalityFn?)` <sup>v1.2</sup>
203
+
204
+ Subscribe to state changes without causing re-renders.
205
+
206
+ ```tsx
207
+ import { useTransientSubscribe } from '@oxog/state';
208
+
209
+ function Analytics() {
210
+ useTransientSubscribe(
211
+ store,
212
+ (s) => s.pageViews,
213
+ (views) => analytics.track('page_view', { count: views })
214
+ );
215
+
216
+ return <div>Tracking active</div>;
217
+ }
118
218
  ```
119
219
 
120
220
  #### `useCreateStore(initialState)`
121
221
 
122
- Create a store scoped to component lifecycle.
222
+ Create a store scoped to the component lifecycle.
123
223
 
124
224
  ```typescript
125
225
  function MyComponent() {
126
226
  const store = useCreateStore({ count: 0 });
127
- // Store is destroyed when component unmounts
227
+ // The store is destroyed after the component unmounts (StrictMode safe)
128
228
  }
129
229
  ```
130
230
 
@@ -136,154 +236,367 @@ Get a stable action reference.
136
236
  const increment = useAction(store, 'increment');
137
237
  ```
138
238
 
239
+ ## Patterns <sup>v1.2</sup>
240
+
241
+ ### Slices
242
+
243
+ Organize state into modular slices. A slice creator receives `set` and `get`
244
+ and returns state values and action functions.
245
+
246
+ ```typescript
247
+ import { createSlice, combineSlices, resetSlices } from '@oxog/state';
248
+
249
+ const userSlice = createSlice('user', (set) => ({
250
+ name: '',
251
+ email: '',
252
+ login: (name: string, email: string) => set({ name, email }),
253
+ logout: () => set({ name: '', email: '' }),
254
+ }));
255
+
256
+ const cartSlice = createSlice('cart', (set, get) => ({
257
+ items: [] as string[],
258
+ addItem: (item: string) => set({ items: [...get().items, item] }),
259
+ }));
260
+
261
+ const store = combineSlices(userSlice, cartSlice);
262
+
263
+ store.login('John', 'john@example.com');
264
+ store.addItem('book');
265
+ store.getState().name; // 'John'
266
+
267
+ resetSlices(store, 'cart'); // resets only the cart slice
268
+ ```
269
+
270
+ `createNamespacedSlice(namespace, creator)` keeps a slice's state under
271
+ `state[namespace]`; `extendStore(store, ...slices)` adds slices to an existing
272
+ store.
273
+
274
+ ### Computed Values
275
+
276
+ Derive memoized values from a store.
277
+
278
+ ```typescript
279
+ import { createStore, computed } from '@oxog/state';
280
+
281
+ const store = createStore({
282
+ items: [{ price: 10, qty: 2 }, { price: 20, qty: 1 }],
283
+ });
284
+
285
+ const totalItems = computed(store, (state) =>
286
+ state.items.reduce((sum, i) => sum + i.qty, 0)
287
+ );
288
+ const totalPrice = computed(store, (state) =>
289
+ state.items.reduce((sum, i) => sum + i.price * i.qty, 0)
290
+ );
291
+
292
+ console.log(totalItems()); // 3
293
+ console.log(totalPrice()); // 40
294
+ totalPrice.subscribe((value, prev) => console.log(`total ${prev} -> ${value}`));
295
+ ```
296
+
297
+ Reading a computed value is always up to date, also from inside another
298
+ store listener. `combineComputed([a, b], ([a, b]) => …)` derives from several
299
+ computed values without observing a half-updated combination.
300
+
301
+ ### Store Federation
302
+
303
+ Combine multiple stores into a unified interface.
304
+
305
+ ```typescript
306
+ import { createStore, createFederation } from '@oxog/state';
307
+
308
+ const userStore = createStore({ name: 'John' });
309
+ const cartStore = createStore({ items: [] as string[] });
310
+ const settingsStore = createStore({ theme: 'dark' });
311
+
312
+ const federation = createFederation({
313
+ user: userStore,
314
+ cart: cartStore,
315
+ settings: settingsStore,
316
+ });
317
+
318
+ // Access all stores
319
+ const state = federation.getState();
320
+ console.log(state.user.name, state.cart.items, state.settings.theme);
321
+
322
+ // Subscribe to one store
323
+ federation.subscribeStore('user', (userState) => {
324
+ console.log('User changed:', userState);
325
+ });
326
+
327
+ // Subscribe to all stores
328
+ federation.subscribe((state, prevState, changedStore) => {
329
+ console.log(`${String(changedStore)} changed`);
330
+ });
331
+ ```
332
+
139
333
  ## Plugins
140
334
 
141
335
  ### Persist
142
336
 
143
- Persist state to localStorage or custom storage.
337
+ Persist state to `localStorage` (the default) or any storage with
338
+ `getItem`/`setItem`/`removeItem`.
144
339
 
145
340
  ```typescript
146
- import { persist } from '@oxog/state';
147
-
148
- const store = createStore({ count: 0 })
149
- .use(persist({ key: 'my-app' }));
341
+ import { createStore, persist } from '@oxog/state';
150
342
 
151
- // With options
152
343
  const store = createStore({ count: 0, temp: '' })
153
344
  .use(persist({
154
345
  key: 'my-app',
155
- storage: sessionStorage,
156
- whitelist: ['count'], // Only persist count
346
+ storage: localStorage,
347
+ version: 1,
348
+ migrate: (state, version) => state as { count: number; temp: string },
349
+ partialize: (state) => ({ count: state.count }), // Only persist count
350
+ writeDebounce: 100,
351
+ onRehydrateStorage: (state) => console.log('Hydrated:', state),
352
+ onPersistError: (error) => console.warn('Could not save state', error),
157
353
  }));
158
354
  ```
159
355
 
356
+ Hydration ignores `__proto__` keys in stored data, corrupt stored data is
357
+ reported through `onPersistError` (or `console.error`) instead of throwing,
358
+ and write errors such as a full storage quota are reported the same way.
359
+ Without `window` (SSR) the default storage does nothing.
360
+
160
361
  ### DevTools
161
362
 
162
- Connect to Redux DevTools Extension.
363
+ Connect to the Redux DevTools Extension. Without the extension the plugin does
364
+ nothing.
163
365
 
164
366
  ```typescript
165
- import { devtools } from '@oxog/state';
367
+ import { createStore, devtools } from '@oxog/state';
166
368
 
167
369
  const store = createStore({ count: 0 })
168
370
  .use(devtools({ name: 'My Store' }));
169
371
  ```
170
372
 
373
+ Time travel (jump, commit, rollback, reset) applies the state DevTools sends.
374
+
171
375
  ### History
172
376
 
173
377
  Add undo/redo functionality.
174
378
 
175
379
  ```typescript
176
- import { history } from '@oxog/state';
380
+ import { createStore, history, hasHistory } from '@oxog/state';
177
381
 
178
382
  const store = createStore({ count: 0 })
179
383
  .use(history({ limit: 50 }));
180
384
 
181
385
  store.setState({ count: 1 });
182
386
  store.setState({ count: 2 });
183
- store.undo(); // { count: 1 }
184
- store.redo(); // { count: 2 }
387
+ if (hasHistory(store)) {
388
+ store.undo(); // { count: 1 }
389
+ store.redo(); // { count: 2 }
390
+ }
185
391
  ```
186
392
 
187
393
  ### Sync
188
394
 
189
- Synchronize state across browser tabs.
395
+ Synchronize state across browser tabs (BroadcastChannel). Every local change is
396
+ sent to the other tabs; when the plugin is installed the current state is
397
+ broadcast once. Action functions are not sent.
190
398
 
191
399
  ```typescript
192
- import { sync } from '@oxog/state';
400
+ import { createStore, sync } from '@oxog/state';
193
401
 
194
402
  const store = createStore({ count: 0 })
195
403
  .use(sync({ channel: 'my-app' }));
196
404
  ```
197
405
 
198
- ### Immer
199
-
200
- Use mutable syntax for immutable updates.
406
+ ### Immer-style updates
201
407
 
202
408
  ```typescript
203
- import { immer } from '@oxog/state';
409
+ import { createStore, immer, produce } from '@oxog/state';
204
410
 
205
- const store = createStore({
206
- users: [{ id: 1, name: 'John' }],
207
- }).use(immer());
411
+ const store = createStore({ todos: [{ text: 'a', done: false }] }).use(immer());
208
412
 
209
- store.setState((draft) => {
210
- draft.users[0].name = 'Jane';
211
- draft.users.push({ id: 2, name: 'Bob' });
212
- });
413
+ // With the plugin, setState also accepts a recipe that mutates a draft
414
+ // (in TypeScript, cast setState or use produce directly).
415
+ store.setState(produce(store.getState(), (draft) => {
416
+ for (const todo of draft.todos) todo.done = true;
417
+ draft.todos.push({ text: 'b', done: false });
418
+ }));
213
419
  ```
214
420
 
215
- ### Selector
421
+ `produce` copies only what changed (untouched branches keep their identity) and
422
+ never mutates the base state.
216
423
 
217
- Add computed/derived values.
424
+ ### Logger <sup>v1.2</sup>
425
+
426
+ Development logging with diff, timestamps, and filtering.
218
427
 
219
428
  ```typescript
220
- import { selector } from '@oxog/state';
429
+ import { createStore, logger } from '@oxog/state';
430
+
431
+ const store = createStore({ count: 0 })
432
+ .use(logger({
433
+ level: 'debug',
434
+ collapsed: true,
435
+ diff: true,
436
+ timestamp: true,
437
+ filter: (state, prevState) => state.count > 0,
438
+ }));
439
+ ```
440
+
441
+ ### Effects <sup>v1.2</sup>
442
+
443
+ Reactive side effects with debounce, cleanup and cancellation.
444
+
445
+ ```typescript
446
+ import { createStore, effects, createEffect } from '@oxog/state';
221
447
 
222
448
  const store = createStore({
223
- items: [],
224
- filter: 'all',
225
- }).use(selector({
226
- filteredItems: (state) => {
227
- if (state.filter === 'all') return state.items;
228
- return state.items.filter((i) => i.status === state.filter);
229
- },
230
- itemCount: (state) => state.items.length,
449
+ searchTerm: '',
450
+ results: [] as string[],
451
+ })
452
+ .use(effects({
453
+ effects: [
454
+ createEffect(
455
+ 'search',
456
+ (state) => state.searchTerm,
457
+ async (term, _prev, { setState, signal }) => {
458
+ const res = await fetch(`/api/search?q=${term}`, { signal });
459
+ const results = await res.json();
460
+ setState({ results });
461
+ },
462
+ { debounce: 300 }
463
+ ),
464
+ ],
231
465
  }));
232
466
  ```
233
467
 
468
+ When the selected value changes again, the previous run becomes inactive: its
469
+ `signal` is aborted, `isActive()` returns `false`, and its `setState` calls are
470
+ ignored, so a slow earlier request cannot overwrite a newer result. Cleanup
471
+ functions returned by an effect run before the next run and when the store is
472
+ destroyed.
473
+
474
+ ### Validate <sup>v1.2</sup>
475
+
476
+ Schema-agnostic validation with Zod, Yup, or custom validators.
477
+
478
+ ```typescript
479
+ import { createStore, validate, type ValidationAPI } from '@oxog/state';
480
+ import { z } from 'zod';
481
+
482
+ const schema = z.object({
483
+ email: z.string().email(),
484
+ age: z.number().min(0).max(150),
485
+ });
486
+
487
+ const store = createStore({ email: '', age: 0 })
488
+ .use(validate({
489
+ schema,
490
+ on: 'change', // validate after every change ('manual': only on validate())
491
+ onError: (errors) => console.error(errors),
492
+ }));
493
+
494
+ const validation = store as typeof store & ValidationAPI;
495
+ validation.validate(); // { valid, errors }
496
+ validation.isValid();
497
+ ```
498
+
499
+ Validation runs after the state has changed; it reports errors but does not
500
+ reject updates. `throwOnError: true` makes `validate()` throw.
501
+
234
502
  ## Async Actions
235
503
 
236
- Handle async operations with async actions.
504
+ Actions can be async: the resolved partial state is applied.
237
505
 
238
506
  ```typescript
239
- const store = createStore({
240
- data: null,
241
- loading: false,
242
- error: null,
243
- fetch: async (state, url: string) => {
244
- store.setState({ loading: true, error: null });
245
- try {
246
- const res = await fetch(url);
247
- const data = await res.json();
248
- return { data, loading: false };
249
- } catch (error) {
250
- return { error, loading: false };
251
- }
252
- },
507
+ const store = createStore({ data: null as unknown, loading: false, error: null as unknown });
508
+
509
+ const api = store.action('fetch', async (_state, url: string) => {
510
+ store.setState({ loading: true, error: null });
511
+ try {
512
+ const res = await fetch(url);
513
+ return { data: await res.json(), loading: false };
514
+ } catch (error) {
515
+ return { error, loading: false };
516
+ }
253
517
  });
254
518
 
255
- await store.fetch('/api/users');
519
+ await api.fetch('/api/users'); // also available as store.getState().fetch(...)
256
520
  ```
257
521
 
522
+ The `state` argument is the state when the action was called. If an async
523
+ action can run concurrently, read `store.getState()` after `await`, or guard
524
+ against out-of-order results (the `effects` plugin does this for you).
525
+
258
526
  ## TypeScript
259
527
 
260
- Full TypeScript support with type inference.
528
+ Types are inferred from the initial state and the actions.
261
529
 
262
530
  ```typescript
531
+ import { createStore, type Store } from '@oxog/state';
532
+
533
+ interface User {
534
+ id: number;
535
+ name: string;
536
+ }
537
+
263
538
  interface State {
264
539
  count: number;
265
540
  user: User | null;
266
541
  }
267
542
 
268
- interface Actions {
269
- increment: (state: State) => Partial<State>;
270
- setUser: (state: State, user: User) => Partial<State>;
271
- }
543
+ const initialState: State = { count: 0, user: null };
272
544
 
273
- const store = createStore<State, Actions>(
274
- { count: 0, user: null },
275
- {
276
- increment: (s) => ({ count: s.count + 1 }),
277
- setUser: (s, user) => ({ user }),
278
- }
279
- );
545
+ const store = createStore(initialState, {
546
+ increment: (s) => ({ count: s.count + 1 }),
547
+ setUser: (_s, user: User) => ({ user }),
548
+ });
549
+
550
+ store.setUser({ id: 1, name: 'Ada' }); // typed arguments
551
+ const plain: Store<State> = createStore<State>({ count: 0, user: null });
552
+ ```
553
+
554
+ ## Testing <sup>v1.2</sup>
555
+
556
+ Testing utilities for stores.
557
+
558
+ ```typescript
559
+ import { createTestStore, spyOnStore, mockAction, snapshot } from '@oxog/state';
560
+
561
+ // Isolated test store with a spy and assertions
562
+ const { store, spy, assert, destroy } = createTestStore({
563
+ initialState: { count: 0 },
564
+ });
565
+ store.setState({ count: 1 });
566
+ assert.toEqual({ count: 1 });
567
+ spy?.changes.length; // 1
568
+
569
+ // Spy on an existing store
570
+ const otherSpy = spyOnStore(store);
571
+ await otherSpy.waitFor((s) => s.count > 1);
572
+
573
+ // Track calls
574
+ const increment = mockAction((n: number) => n + 1);
575
+ increment(1);
576
+ increment.callCount; // 1
577
+
578
+ // JSON snapshot of the state
579
+ expect(snapshot(store)).toMatchSnapshot();
580
+ destroy();
280
581
  ```
281
582
 
583
+ ## CDN
584
+
585
+ ```html
586
+ <script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
587
+ <script src="https://unpkg.com/@oxog/state/dist/iife/index.global.js"></script>
588
+ <script>
589
+ const store = OxogState.createStore({ count: 0 });
590
+ </script>
591
+ ```
592
+
593
+ React is only needed for the hooks; the global build uses `window.React`.
594
+
282
595
  ## Browser Support
283
596
 
284
- - Chrome 60+
285
- - Firefox 55+
286
- - Safari 12+
597
+ - Chrome 66+
598
+ - Firefox 57+
599
+ - Safari 12.1+
287
600
  - Edge 79+
288
601
 
289
602
  ## Documentation