@canlooks/statio 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 C.CanLiang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,511 @@
1
+ # @canlooks/statio
2
+
3
+ A lightweight, TypeScript-first state management library for React. Built on top of React's `useSyncExternalStore`, Statio provides a minimal yet powerful API with first-class support for **class-based stores**, **computed properties**, **persistence**, and **SSR** — all without boilerplate.
4
+
5
+ ## Features
6
+
7
+ - **Dual store creation** — factory functions *or* ES6 classes, whichever fits your style
8
+ - **Automatic method binding** — `this` in your store methods always points to the current state
9
+ - **Computed properties** — memoized derived values that only recalculate when dependencies change
10
+ - **Selective re-rendering** — components only update when the slice of state they consume changes
11
+ - **Built-in persistence** — `localStorage` / `sessionStorage` support with a single wrapper, customizable storage adapter
12
+ - **SSR-ready** — separate `serverState` for hydration, works with Next.js
13
+ - **Outside-React access** — read, write, and subscribe to state from anywhere
14
+ - **Tiny footprint** — zero dependencies beyond `tslib`
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm i @canlooks/statio
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ### Creating a Store
25
+
26
+ Statio supports two patterns for defining a store. Choose the one you prefer — they have identical runtime behavior.
27
+
28
+ #### Factory Function
29
+
30
+ ```ts
31
+ import { createStore } from '@canlooks/statio'
32
+
33
+ interface CounterStore {
34
+ unused: string
35
+ count: number
36
+ increase(): void
37
+ }
38
+
39
+ const useCounterStore = createStore<CounterStore>((set) => ({
40
+ unused: 'unused property',
41
+ count: 1,
42
+ increase() {
43
+ set({ count: this.count + 1 })
44
+ },
45
+ }))
46
+ ```
47
+
48
+ #### Class
49
+
50
+ ```ts
51
+ import { createStore, type SetStateMethod } from '@canlooks/statio'
52
+
53
+ class CounterStore {
54
+ unused = 'unused property'
55
+ count = 1
56
+
57
+ constructor(private set: SetStateMethod<CounterStore>) {}
58
+
59
+ increase() {
60
+ this.set({ count: this.count + 1 })
61
+ }
62
+ }
63
+
64
+ const useCounterStore = createStore(CounterStore)
65
+ ```
66
+
67
+ ### Using the Store in Components
68
+
69
+ ```tsx
70
+ function Counter() {
71
+ const { count, increase } = useCounterStore()
72
+
73
+ return (
74
+ <div>
75
+ <h1>Count: {count}</h1>
76
+ <button onClick={increase}>+1</button>
77
+ </div>
78
+ )
79
+ }
80
+ ```
81
+
82
+ ### Selective Re-rendering with Selectors
83
+
84
+ Without a selector, the component re-renders on *any* state change. Use a selector function to subscribe to a specific slice:
85
+
86
+ ```tsx
87
+ function Counter() {
88
+ // Only re-renders when `count` changes.
89
+ // `unused` and `increase` are ignored by the diff.
90
+ const { count, increase } = useCounterStore((state) => ({
91
+ count: state.count,
92
+ increase: state.increase,
93
+ }))
94
+
95
+ return (
96
+ <div>
97
+ <h1>Count: {count}</h1>
98
+ <button onClick={increase}>+1</button>
99
+ </div>
100
+ )
101
+ }
102
+ ```
103
+
104
+ **Key-based selector** (syntactic sugar):
105
+
106
+ ```tsx
107
+ function Counter() {
108
+ // Equivalent to: (s) => ({ count: s.count, increase: s.increase })
109
+ const { count, increase } = useCounterStore('count', 'increase')
110
+
111
+ return (
112
+ <div>
113
+ <h1>Count: {count}</h1>
114
+ <button onClick={increase}>+1</button>
115
+ </div>
116
+ )
117
+ }
118
+ ```
119
+
120
+ > **How it works**: selectors use `shallowEqual` by default for object results. You can override equality checks by passing a custom `isEqual` function as the second argument to the selector form.
121
+
122
+ ---
123
+
124
+ ## Advanced Features
125
+
126
+ ### Computed (Derived) Properties
127
+
128
+ Statio provides a `compute` API for memoized derived values. A computed property only re-evaluates when its declared dependencies change.
129
+
130
+ ```ts
131
+ import { createStore, type SetStateMethod, type StoreApi } from '@canlooks/statio'
132
+
133
+ interface ProductStore {
134
+ items: { name: string; price: number }[]
135
+ readonly totalPrice: number
136
+ readonly itemCount: number
137
+ addItem(item: { name: string; price: number }): void
138
+ }
139
+
140
+ const useProductStore = createStore<ProductStore>((set, api) => ({
141
+ items: [],
142
+ get totalPrice() {
143
+ return api.compute(() => {
144
+ return this.items.reduce((sum, i) => sum + i.price, 0)
145
+ }, [this.items])
146
+ },
147
+ get itemCount() {
148
+ return api.compute(() => this.items.length, [this.items])
149
+ },
150
+ addItem(item) {
151
+ set({ items: [...this.items, item] })
152
+ },
153
+ }))
154
+ ```
155
+
156
+ With a class store:
157
+
158
+ ```ts
159
+ class ProductStore {
160
+ items: { name: string; price: number }[] = []
161
+
162
+ constructor(
163
+ private set: SetStateMethod<ProductStore>,
164
+ private api: StoreApi<ProductStore>,
165
+ ) {}
166
+
167
+ get totalPrice() {
168
+ return this.api.compute(() => {
169
+ return this.items.reduce((sum, i) => sum + i.price, 0)
170
+ }, [this.items])
171
+ }
172
+
173
+ get itemCount() {
174
+ return this.api.compute(() => this.items.length, [this.items])
175
+ }
176
+
177
+ addItem(item: { name: string; price: number }) {
178
+ this.set({ items: [...this.items, item] })
179
+ }
180
+ }
181
+ ```
182
+
183
+ **Important**: `compute()` only works inside a getter property. Calling it elsewhere will throw an error.
184
+
185
+ ### Persistence (`storage`)
186
+
187
+ Wrap any store factory with `storage()` to automatically persist state to `localStorage` or `sessionStorage`:
188
+
189
+ ```ts
190
+ import { createStore, storage } from '@canlooks/statio'
191
+
192
+ const useSettingsStore = createStore(
193
+ storage(
194
+ (set) => ({
195
+ theme: 'light' as 'light' | 'dark',
196
+ fontSize: 14,
197
+ setTheme(theme: 'light' | 'dark') {
198
+ set({ theme })
199
+ },
200
+ }),
201
+ { name: 'app-settings' },
202
+ ),
203
+ )
204
+ ```
205
+
206
+ **Options:**
207
+
208
+ | Option | Type | Default | Description |
209
+ |--------|------|---------|-------------|
210
+ | `name` | `string` | *required* | Storage key |
211
+ | `type` | `'localStorage' \| 'sessionStorage'` | `'localStorage'` | Storage backend |
212
+ | `selector` | `(state: S) => T` | auto-selects non-function, non-Api properties | Custom serialization selector |
213
+ | `adapter` | `{ getItem, setItem }` | `window[type]` | Custom storage adapter (e.g., AsyncStorage for React Native) |
214
+
215
+ **How it works:**
216
+
217
+ - The default `selector` automatically picks all non-function properties to persist
218
+ - Writes are **batched** — multiple synchronous `set()` calls in the same tick trigger only one storage write
219
+ - On initialization, previously persisted data is merged into the initial state
220
+
221
+ **Custom adapter example:**
222
+
223
+ ```ts
224
+ storage(MyStore, {
225
+ name: 'my-store',
226
+ adapter: {
227
+ getItem(key) { return AsyncStorage.getItem(key) },
228
+ setItem(key, value) { AsyncStorage.setItem(key, value) },
229
+ },
230
+ })
231
+ ```
232
+
233
+ ### Accessing State Outside React
234
+
235
+ The `useStore` hook exposes additional methods for imperative use:
236
+
237
+ ```ts
238
+ // Read current state without subscribing
239
+ const currentState = useCounterStore.getState()
240
+
241
+ // Update state from outside a component
242
+ useCounterStore.setState({ count: 99 })
243
+
244
+ // Subscribe to changes (returns unsubscribe function)
245
+ const unsub = useCounterStore.subscribe((state) => {
246
+ console.log('State changed:', state)
247
+ })
248
+
249
+ // Subscribe with a selector
250
+ const unsub = useCounterStore.subscribe(
251
+ (state) => state.count,
252
+ (count, prevCount) => {
253
+ console.log(`Count: ${prevCount} → ${count}`)
254
+ },
255
+ )
256
+
257
+ // Stop listening
258
+ useCounterStore.unsubscribe(listener)
259
+ ```
260
+
261
+ ### Server-Side Rendering (SSR)
262
+
263
+ Statio is SSR-compatible. The `storage()` middleware sets `api.serverState` to the initial state snapshot, which is used as the third argument to `useSyncExternalStore` for proper hydration.
264
+
265
+ When using Next.js App Router with a persisted store:
266
+
267
+ ```tsx
268
+ // stores/counter.ts
269
+ import { createStore, storage } from '@canlooks/statio'
270
+
271
+ class CounterStore {
272
+ count = 0
273
+ // ...
274
+ }
275
+
276
+ export const useCounterStore = createStore(
277
+ storage(CounterStore, { name: 'counter' }),
278
+ )
279
+ ```
280
+
281
+ ```tsx
282
+ // app/page.tsx
283
+ 'use client'
284
+
285
+ import { useCounterStore } from '@/stores/counter'
286
+
287
+ export default function Page() {
288
+ const { count } = useCounterStore('count')
289
+ return <div>{count}</div>
290
+ }
291
+ ```
292
+
293
+ ### Batching Updates
294
+
295
+ Multiple synchronous `set()` calls are automatically batched by React 18's automatic batching. For external usage, Statio provides `createBatchAction`:
296
+
297
+ ```ts
298
+ import { createBatchAction } from '@canlooks/statio'
299
+
300
+ const batchedSet = createBatchAction(
301
+ useCounterStore.setState,
302
+ () => console.log('All updates applied'),
303
+ )
304
+
305
+ // These two calls trigger the effect only once
306
+ batchedSet({ count: 1 })
307
+ batchedSet({ count: 2 })
308
+ ```
309
+
310
+ ---
311
+
312
+ ## API Reference
313
+
314
+ ### `createStore(factory)`
315
+
316
+ ```ts
317
+ function createStore<S extends object>(
318
+ factory: StoreFactory<S> | StoreClass<S>
319
+ ): UseStoreHook<S>
320
+ ```
321
+
322
+ Creates a store and returns a `useStore` hook. The factory receives two arguments:
323
+
324
+ | Parameter | Type | Description |
325
+ |-----------|------|-------------|
326
+ | `set` | `SetStateMethod<S>` | Update state (partial or updater function) |
327
+ | `api` | `StoreApi<S>` | Store API (state, getState, compute, etc.) |
328
+
329
+ **Returned hook signatures:**
330
+
331
+ ```ts
332
+ // Subscribe to entire state (re-renders on any change)
333
+ useStore(): S
334
+
335
+ // Subscribe to specific keys (shorthand selector)
336
+ useStore(...keys: (keyof S)[]): Pick<S, typeof keys[number]>
337
+
338
+ // Subscribe with a custom selector
339
+ useStore<T>(selector: (state: S) => T, isEqual?: IsEqual<T>): T
340
+
341
+ // Imperative methods attached to the hook
342
+ useStore.getState(): S
343
+ useStore.setState: SetStateMethod<S>
344
+ useStore.subscribe(...): () => void
345
+ useStore.unsubscribe(listener: Function): void
346
+ ```
347
+
348
+ ### `SetStateMethod<S>`
349
+
350
+ ```ts
351
+ type SetStateMethod<S> = (
352
+ state: Partial<S> | ((state: S) => Partial<S>),
353
+ overwrite?: boolean,
354
+ ) => void
355
+ ```
356
+
357
+ - **Partial update** (default): merges the provided partial into existing state via `Object.assign`
358
+ - **Updater function**: receives current state, returns a partial to merge
359
+ - **Overwrite mode** (`overwrite = true`): replaces the entire state object and re-binds methods/computed properties. Use sparingly — typically only for hydration
360
+
361
+ ### `StoreApi<S>`
362
+
363
+ Passed as the second argument to store factories/constructors:
364
+
365
+ ```ts
366
+ class StoreApi<S> {
367
+ state: S // Current state object
368
+ serverState?: S // Server-side snapshot (for SSR, set by storage middleware)
369
+ setState: SetStateMethod<S>
370
+ getState(): S
371
+ compute: Compute // Memoized derived value helper
372
+ computable: Computable<S>
373
+ }
374
+ ```
375
+
376
+ ### `storage(factory, options)`
377
+
378
+ ```ts
379
+ function storage<S extends object>(
380
+ factory: StoreFactory<S> | StoreClass<S>,
381
+ options: StorageOptions<S>,
382
+ ): StoreFactory<S>
383
+ ```
384
+
385
+ Wraps a store factory with persistence. Returns a new factory to pass to `createStore`.
386
+
387
+ **`StorageOptions<S>`:**
388
+
389
+ ```ts
390
+ type StorageOptions<S> = {
391
+ name: string
392
+ type?: 'localStorage' | 'sessionStorage' // default: 'localStorage'
393
+ selector?<T = S>(state: S): T // custom serialization
394
+ adapter?: {
395
+ getItem(key: string): string | null
396
+ setItem(key: string, value: string): void
397
+ }
398
+ }
399
+ ```
400
+
401
+ ### `compute` / `Computable`
402
+
403
+ ```ts
404
+ type Compute = <T>(factory: () => T, deps: any[]) => T
405
+ ```
406
+
407
+ The `api.compute()` method memoizes a computation based on a dependency array. It uses `shallowEqual` to compare deps — if they haven't changed since the last call, the cached result is returned immediately.
408
+
409
+ Must be called inside a getter property. Each getter gets its own independent memoization cache.
410
+
411
+ ### Utility Functions
412
+
413
+ #### `shallowEqual(a, b)`
414
+
415
+ ```ts
416
+ function shallowEqual(a: any, b: any): boolean
417
+ ```
418
+
419
+ Performs a shallow equality check. Used internally for selector comparison and compute dependency diffing.
420
+
421
+ #### `nextTick(callback?, ...args)`
422
+
423
+ ```ts
424
+ function nextTick<T>(callback?: (...args: T[]) => void, ...args: T[]): AbortablePromise<T>
425
+ ```
426
+
427
+ Schedules a callback for the next microtask (using `queueMicrotask`). Returns an abortable promise — call `.abort()` to cancel.
428
+
429
+ #### `createBatchAction(action, effect)`
430
+
431
+ ```ts
432
+ function createBatchAction<T extends (...a: any[]) => any>(
433
+ action: T,
434
+ effect: () => any,
435
+ ): T
436
+ ```
437
+
438
+ Wraps an action function so that multiple synchronous invocations only trigger the `effect` once (on the next microtask). Used internally by `storage()` to debounce writes.
439
+
440
+ #### `isClass(fn)`
441
+
442
+ ```ts
443
+ function isClass(fn: Function): fn is StoreClass
444
+ ```
445
+
446
+ Type guard that checks whether a function is an ES6 class constructor.
447
+
448
+ #### `getAllPropertyDescriptors(o)`
449
+
450
+ ```ts
451
+ function getAllPropertyDescriptors(o: any): { [p: PropertyKey]: PropertyDescriptor }
452
+ ```
453
+
454
+ Returns all property descriptors of an object, including those inherited from prototype chain (stops at `Object.prototype`, `Array.prototype`, and `Function.prototype`).
455
+
456
+ ---
457
+
458
+ ## TypeScript
459
+
460
+ Statio is written in TypeScript and provides first-class type inference. Store state is fully typed:
461
+
462
+ ```ts
463
+ interface TodoStore {
464
+ todos: { id: number; text: string; done: boolean }[]
465
+ readonly activeCount: number
466
+ addTodo(text: string): void
467
+ toggleTodo(id: number): void
468
+ }
469
+
470
+ // Full type safety — IDE autocompletion on all state properties and methods
471
+ const useTodoStore = createStore<TodoStore>((set, api) => ({
472
+ todos: [],
473
+ get activeCount() {
474
+ return api.compute(() => this.todos.filter(t => !t.done).length, [this.todos])
475
+ },
476
+ addTodo(text) {
477
+ set({ todos: [...this.todos, { id: Date.now(), text, done: false }] })
478
+ },
479
+ toggleTodo(id) {
480
+ set({
481
+ todos: this.todos.map(t =>
482
+ t.id === id ? { ...t, done: !t.done } : t
483
+ ),
484
+ })
485
+ },
486
+ }))
487
+ ```
488
+
489
+ Selectors are also fully typed — the return type is inferred from the selector function.
490
+
491
+ ---
492
+
493
+ ## Comparison
494
+
495
+ | Feature | Statio | Zustand | Jotai | Redux Toolkit |
496
+ |---------|--------|---------|-------|---------------|
497
+ | **Class-based stores** | ✅ | ❌ | ❌ | ❌ |
498
+ | **Computed properties** | ✅ (via `compute`) | ❌ (needs middleware) | ✅ (atoms) | ✅ (selectors) |
499
+ | **Built-in persistence** | ✅ (`storage`) | ✅ (`persist` middleware) | ✅ (`atomWithStorage`) | ❌ (needs middleware) |
500
+ | **Selective re-rendering** | ✅ (selector/shallowEqual) | ✅ (selector/shallow) | ✅ (atomic) | ✅ (selectors) |
501
+ | **Bundle size** | Tiny | Tiny | Small | Medium |
502
+ | **SSR support** | ✅ | ✅ | ✅ | ✅ |
503
+ | **Middleware system** | Wrapper pattern | Middleware API | N/A | Middleware API |
504
+
505
+ Statio is ideal when you want Zustand-like simplicity but prefer class-based organization, or need built-in computed properties without additional middleware.
506
+
507
+ ---
508
+
509
+ ## License
510
+
511
+ MIT
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Api = void 0;
4
+ const compute_1 = require("./compute");
5
+ const util_1 = require("./util");
6
+ class Api {
7
+ onChange;
8
+ serverState;
9
+ state;
10
+ computable;
11
+ constructor(factory, onChange) {
12
+ this.onChange = onChange;
13
+ this.state = (0, util_1.isClass)(factory)
14
+ ? new factory(this.setState, this)
15
+ : factory(this.setState, this);
16
+ this.bindContextAndInitComputable();
17
+ }
18
+ setState = (setStateAction, overwrite) => {
19
+ const newState = typeof setStateAction === 'function' ? setStateAction(this.state) : setStateAction;
20
+ if (overwrite) {
21
+ this.state = newState;
22
+ this.bindContextAndInitComputable();
23
+ }
24
+ else {
25
+ Object.assign(this.state, newState);
26
+ }
27
+ this.onChange(this.state);
28
+ };
29
+ getState = () => {
30
+ return this.state;
31
+ };
32
+ compute = (factory, deps) => {
33
+ return this.computable.get(factory, deps);
34
+ };
35
+ bindContextAndInitComputable() {
36
+ this.computable = new compute_1.Computable(this.state);
37
+ const properties = (0, util_1.getAllPropertyDescriptors)(this.state);
38
+ for (const k in properties) {
39
+ const { get, value } = properties[k];
40
+ if (get) {
41
+ Object.defineProperty(this.state, k, {
42
+ get: this.computable.createGetter(k, () => get.call(this.state))
43
+ });
44
+ }
45
+ else if (typeof value === 'function') {
46
+ this.state[k] = value.bind(this.state);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ exports.Api = Api;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Computable = void 0;
4
+ exports.createCompute = createCompute;
5
+ const util_1 = require("./util");
6
+ const log_1 = require("./log");
7
+ function createCompute() {
8
+ let prevDeps = [];
9
+ let prevResult;
10
+ let hasRun = false;
11
+ return function (factory, deps) {
12
+ if (hasRun && (0, util_1.shallowEqual)(prevDeps, deps)) {
13
+ return prevResult;
14
+ }
15
+ hasRun = true;
16
+ prevDeps = [...deps];
17
+ return prevResult = factory.call(this);
18
+ };
19
+ }
20
+ class Computable {
21
+ state;
22
+ constructor(state) {
23
+ this.state = state;
24
+ }
25
+ property_compute = new Map();
26
+ stack = [];
27
+ createGetter(key, get) {
28
+ return () => {
29
+ try {
30
+ this.stack.push(key);
31
+ return get();
32
+ }
33
+ finally {
34
+ this.stack.pop();
35
+ }
36
+ };
37
+ }
38
+ get(factory, deps) {
39
+ const key = this.stack[this.stack.length - 1];
40
+ if (!key) {
41
+ throw Error(`${log_1.prefix}"compute" method can only be used in getter properties.`);
42
+ }
43
+ let compute = this.property_compute.get(key);
44
+ if (!compute) {
45
+ compute = createCompute();
46
+ this.property_compute.set(key, compute);
47
+ }
48
+ return compute.call(this.state, factory, deps);
49
+ }
50
+ }
51
+ exports.Computable = Computable;