r-state-tree 0.3.1 → 0.4.1

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,13 +8,18 @@ Reactive state management featuring store trees, computed child stores, and snap
8
8
  pnpm add r-state-tree
9
9
  ```
10
10
 
11
+ ### Requirements
12
+
13
+ This library uses [TC39 Stage 3 Decorators](https://github.com/tc39/proposal-decorators) and requires TypeScript 5.0+ with `target: "es2022"` or higher.
14
+
15
+ The library includes a decorator metadata polyfill for runtimes that don't yet natively support `Symbol.metadata`.
16
+
11
17
  ## Stores
12
18
 
13
19
  Stores describe reactive state containers composed into a tree.
14
20
 
15
21
  ```ts
16
- import Store, { createStore, mount } from "r-state-tree";
17
- import { child } from "r-state-tree/decorators";
22
+ import { Store, createStore, mount, child } from "r-state-tree";
18
23
 
19
24
  class TodoStore extends Store {
20
25
  props = { title: "" };
@@ -44,58 +49,330 @@ import { updateStore } from "r-state-tree";
44
49
  updateStore(app.todo, { title: "Ship release" });
45
50
  ```
46
51
 
52
+ ### Child stores
53
+
54
+ Use `@child` for both single child stores and arrays.
55
+
56
+ ```ts
57
+ import { child } from "r-state-tree";
58
+
59
+ class ListStore extends Store {
60
+ items = ["Buy milk", "Walk dog"];
61
+
62
+ @child get todos() {
63
+ return this.items.map((title, i) =>
64
+ createStore(TodoStore, { title, key: i })
65
+ );
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### Lifecycle hooks
71
+
72
+ Stores support lifecycle methods:
73
+
74
+ ```ts
75
+ class TodoStore extends Store {
76
+ storeDidMount() {
77
+ console.log("Store mounted");
78
+ }
79
+
80
+ storeWillUnmount() {
81
+ console.log("Store will unmount");
82
+ }
83
+ }
84
+ ```
85
+
86
+ ### Reactions
87
+
88
+ Create side effects that run when reactive values change:
89
+
90
+ ```ts
91
+ class TodoStore extends Store {
92
+ storeDidMount() {
93
+ this.reaction(
94
+ () => this.props.title,
95
+ (title) => console.log("Title changed:", title)
96
+ );
97
+ }
98
+ }
99
+ ```
100
+
101
+ ### Context
102
+
103
+ Share data across the store tree without prop drilling:
104
+
105
+ ```ts
106
+ import { createContext } from "r-state-tree";
107
+
108
+ const ThemeContext = createContext<"light" | "dark">("light");
109
+
110
+ class AppStore extends Store {
111
+ theme = "dark";
112
+
113
+ [ThemeContext.provide]() {
114
+ return this.theme;
115
+ }
116
+
117
+ @child get todo() {
118
+ return createStore(TodoStore);
119
+ }
120
+ }
121
+
122
+ class TodoStore extends Store {
123
+ get theme() {
124
+ return ThemeContext.consume(this);
125
+ }
126
+ }
127
+
128
+ const app = mount(createStore(AppStore));
129
+ app.todo.theme; // "dark"
130
+ ```
131
+
132
+ Context is reactive and updates automatically when the provided value changes.
133
+
47
134
  ### Actions and batching
48
135
 
49
- `runInBatch` groups updates to avoid redundant reactions.
136
+ `batch` groups updates to avoid redundant reactions.
50
137
 
51
138
  ```ts
52
- import { runInBatch } from "r-state-tree";
139
+ import { batch } from "r-state-tree";
53
140
 
54
- runInBatch(() => {
141
+ batch(() => {
55
142
  app.todo.props.title = "Refactor";
56
143
  });
57
144
  ```
58
145
 
146
+ ## Observable classes
147
+
148
+ For reactive class instances outside the Model/Store system, use `@observable` and `@computed` decorators:
149
+
150
+ ```ts
151
+ import { Observable, observable, computed, effect } from "r-state-tree";
152
+
153
+ class Counter extends Observable {
154
+ @observable count = 0;
155
+ @observable step = 1;
156
+
157
+ @computed get doubled() {
158
+ return this.count * 2;
159
+ }
160
+
161
+ increment() {
162
+ this.count += this.step;
163
+ }
164
+ }
165
+
166
+ const counter = new Counter();
167
+
168
+ effect(() => {
169
+ console.log("Count:", counter.count, "Doubled:", counter.doubled);
170
+ });
171
+
172
+ counter.increment(); // Triggers the effect
173
+ ```
174
+
175
+ **Important:** Class instances require explicit `@observable` and `@computed` decorators. Properties without decorators are **not** reactive.
176
+
177
+ ### Plain objects (implicit reactivity)
178
+
179
+ Plain objects wrapped with `observable()` use implicit reactivity for backward compatibility:
180
+
181
+ ```ts
182
+ import { observable, effect } from "r-state-tree";
183
+
184
+ const state = observable({ count: 0 });
185
+
186
+ effect(() => {
187
+ console.log(state.count); // All properties are reactive
188
+ });
189
+
190
+ state.count++; // Triggers the effect
191
+ ```
192
+
59
193
  ## Models and snapshots
60
194
 
61
195
  Models capture persistent state with snapshot utilities.
62
196
 
63
197
  ```ts
64
- import Model from "r-state-tree/model/Model";
65
198
  import {
199
+ Model,
200
+ state,
201
+ identifier,
66
202
  applySnapshot,
67
203
  onSnapshot,
68
- onSnapshotDiff,
69
204
  toSnapshot,
70
205
  } from "r-state-tree";
71
206
 
72
207
  class TodoModel extends Model {
73
- static types = {
74
- title: stateType,
75
- assignee: modelRefType,
76
- };
77
-
78
- title = "";
208
+ @identifier id = 0;
209
+ @state title = "";
210
+ @state completed = false;
79
211
  }
80
212
 
81
- const todo = new TodoModel();
213
+ const todo = TodoModel.create({ id: 1, title: "Learn signals" });
82
214
 
83
215
  const stop = onSnapshot(todo, (snapshot) => {
84
- console.log(snapshot.title);
216
+ console.log(snapshot); // { id: 1, title: "Learn signals", completed: false }
85
217
  });
86
218
 
87
- applySnapshot(todo, { title: "Learn signals" });
219
+ todo.title = "Learn r-state-tree";
88
220
  stop();
89
221
  ```
90
222
 
223
+ ### Model lifecycle hooks
224
+
225
+ Models support lifecycle methods:
226
+
227
+ ```ts
228
+ class TodoModel extends Model {
229
+ @child tags: TagModel[] = [];
230
+
231
+ modelDidInit(snapshot?, ...args: unknown[]) {
232
+ // Called when model is created via Model.create()
233
+ // Receives the snapshot and any additional arguments passed to create()
234
+ console.log("Model initialized", snapshot);
235
+ }
236
+
237
+ modelDidAttach() {
238
+ // Called when this model is attached as a child to another model
239
+ console.log("Model attached to parent");
240
+ }
241
+
242
+ modelWillDetach() {
243
+ // Called when this model is detached from its parent
244
+ console.log("Model will be detached");
245
+ }
246
+ }
247
+ ```
248
+
249
+ ### Model decorators
250
+
251
+ Use decorators to configure model properties:
252
+
253
+ ```ts
254
+ import { Model, state, identifier, child, modelRef } from "r-state-tree";
255
+
256
+ class User extends Model {
257
+ @identifier id = 0;
258
+ @state name = "";
259
+ }
260
+
261
+ class TodoModel extends Model {
262
+ @identifier id = 0;
263
+ @state title = "";
264
+ @modelRef assignee?: User; // Reference to another model by ID
265
+ @child metadata = MetadataModel.create(); // Nested child model
266
+ @child tags: TagModel[] = []; // Array of child models
267
+ }
268
+ ```
269
+
270
+ The `@child` and `@modelRef` decorators support both single values and arrays. You can also specify the child type using `@child(ChildType)`:
271
+
272
+ ```ts
273
+ class TodoModel extends Model {
274
+ @child(TagModel) tags: TagModel[] = []; // Type-safe array of child models
275
+ @child(TagModel) primaryTag: TagModel | null = null; // Can switch between single and array at runtime
276
+ }
277
+ ```
278
+
279
+ ### Model references
280
+
281
+ Reference models by ID using `@modelRef`:
282
+
283
+ ```ts
284
+ class ProjectModel extends Model {
285
+ @identifier id = 0;
286
+ @child users: User[] = [];
287
+ @modelRef owner?: User; // Single reference
288
+ @modelRef assignees: User[] = []; // Array of references
289
+
290
+ assignOwner(userId: number) {
291
+ // Find user by ID and set as owner
292
+ const user = this.users.find((u) => u.id === userId);
293
+ this.owner = user;
294
+ }
295
+ }
296
+
297
+ const project = ProjectModel.create({
298
+ id: 1,
299
+ users: [
300
+ { id: 1, name: "Alice" },
301
+ { id: 2, name: "Bob" },
302
+ ],
303
+ owner: { id: 1 }, // Reference by ID in snapshot
304
+ });
305
+
306
+ project.owner?.name; // "Alice"
307
+ ```
308
+
309
+ Both `@child` and `@modelRef` support runtime type switching between single values and arrays:
310
+
311
+ ```ts
312
+ class ItemModel extends Model {
313
+ @identifier id = 0;
314
+ @state value = 0;
315
+ }
316
+
317
+ class ContainerModel extends Model {
318
+ @child(ItemModel) items: ItemModel | ItemModel[]; // Can be single or array
319
+
320
+ setSingle() {
321
+ this.items = ItemModel.create({ id: 1, value: 10 });
322
+ }
323
+
324
+ setArray() {
325
+ this.items = [
326
+ ItemModel.create({ id: 2, value: 20 }),
327
+ ItemModel.create({ id: 3, value: 30 }),
328
+ ];
329
+ }
330
+ }
331
+ ```
332
+
91
333
  ### Snapshot diffs
92
334
 
93
- Use `onSnapshotDiff` to receive undo/redo payloads.
335
+ Use `onSnapshotDiff` to receive undo/redo payloads:
94
336
 
95
337
  ```ts
96
- const off = onSnapshotDiff(todo, ({ undo, redo }) => {
97
- // undo and redo contain patch-like snapshots
338
+ const history: SnapshotDiff[] = [];
339
+
340
+ const off = onSnapshotDiff(todo, (diff) => {
341
+ history.push(diff);
98
342
  });
343
+
344
+ todo.title = "New title";
345
+ todo.completed = true;
346
+
347
+ // Undo
348
+ applySnapshot(todo, history[history.length - 1].undo);
349
+
350
+ // Redo
351
+ applySnapshot(todo, history[history.length - 1].redo);
352
+ ```
353
+
354
+ ### Context with Models
355
+
356
+ Models also support context:
357
+
358
+ ```ts
359
+ const AuthContext = createContext<User | null>(null);
360
+
361
+ class AppModel extends Model {
362
+ @child currentUser = User.create({ id: 1, name: "Alice" });
363
+
364
+ [AuthContext.provide]() {
365
+ return this.currentUser;
366
+ }
367
+
368
+ @child project = ProjectModel.create();
369
+ }
370
+
371
+ class ProjectModel extends Model {
372
+ get currentUser() {
373
+ return AuthContext.consume(this);
374
+ }
375
+ }
99
376
  ```
100
377
 
101
378
  ## Testing
@@ -0,0 +1,13 @@
1
+ import type Model from "./model/Model";
2
+ import type Store from "./store/Store";
3
+ declare const CONTEXT_SYMBOL: unique symbol;
4
+ declare const HAS_DEFAULT: unique symbol;
5
+ export interface Context<T> {
6
+ readonly [CONTEXT_SYMBOL]: symbol;
7
+ readonly [HAS_DEFAULT]: boolean;
8
+ readonly defaultValue: T | undefined;
9
+ readonly provide: symbol;
10
+ consume(instance: Model | Store): T;
11
+ }
12
+ export declare function createContext<T>(defaultValue?: T): Context<T>;
13
+ export {};
@@ -1,7 +1,6 @@
1
+ import "@tsmetadata/polyfill";
1
2
  export declare const child: any;
2
- export declare const children: any;
3
- export declare const model: any;
4
3
  export declare const modelRef: any;
5
- export declare const modelRefs: any;
4
+ export declare const model: any;
6
5
  export declare const identifier: any;
7
6
  export declare const state: any;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
+ import "@tsmetadata/polyfill";
1
2
  import Store, { createStore, updateStore } from "./store/Store";
2
3
  import Model from "./model/Model";
3
4
  import { mount, unmount, onSnapshot, toSnapshot, applySnapshot, onSnapshotDiff } from "./api";
4
- export { createStore, Store, Model, mount, unmount, updateStore, onSnapshot, onSnapshotDiff, toSnapshot, applySnapshot, };
5
- export { observable, source, reportChanged, reportObserved, getSignal, isObservable, createSignal, createAtom, createComputed, createReaction, createListener, runInBatch, runInUntracked, createEffect, Observable, } from "./observables";
5
+ import { createContext } from "./context";
6
+ export { createStore, Store, Model, mount, unmount, updateStore, onSnapshot, onSnapshotDiff, toSnapshot, applySnapshot, createContext, };
7
+ export { observable, computed, source, reportChanged, reportObserved, getSignal, isObservable, reaction, Signal, ReadonlySignal, batch, untracked, effect, Observable, signal, } from "./observables";
6
8
  export * from "./decorators";
7
9
  export type { Configuration, Snapshot, IdType, SnapshotDiff } from "./types";
10
+ export type { Context } from "./context";
@@ -1,13 +1,17 @@
1
- import { Snapshot } from "../types";
1
+ import { ModelConfiguration, Snapshot } from "../types";
2
+ type ExtractModelDidInitArgs<T extends Model> = T extends {
3
+ modelDidInit(...args: infer Args): unknown;
4
+ } ? Args extends [infer Snapshot, ...infer Rest] ? Rest : [] : [];
2
5
  export default class Model {
3
- static types: object;
6
+ static get types(): ModelConfiguration<unknown>;
4
7
  static childTypes: object;
5
8
  static create<T extends Model = Model>(this: {
6
9
  new (...args: unknown[]): T;
7
- }, snapshot?: Snapshot<T>, ...args: unknown[]): T;
10
+ }, snapshot?: Snapshot<T>, ...args: ExtractModelDidInitArgs<T>): T;
8
11
  constructor();
9
12
  get parent(): Model | null;
10
13
  modelDidInit(snapshot?: Snapshot<this>, ...args: unknown[]): void;
11
14
  modelDidAttach(): void;
12
15
  modelWillDetach(): void;
13
16
  }
17
+ export {};
@@ -5,8 +5,9 @@ export declare function getConfigurationFromSnapshot(snapshot: object): ModelCon
5
5
  export declare function getModelAdm<T extends Model>(model: T): ModelAdministration;
6
6
  export declare class ModelAdministration extends PreactObjectAdministration<any> {
7
7
  static proxyTraps: ProxyHandler<object>;
8
- configuration: ModelConfiguration<any>;
9
- parent: ModelAdministration | null;
8
+ private configurationGetter?;
9
+ private _parent;
10
+ private parentAtom;
10
11
  referencedAtoms: Map<PropertyKey, AtomNode>;
11
12
  referencedModels: Map<PropertyKey, ComputedNode<Model[]>>;
12
13
  activeModels: Set<PropertyKey>;
@@ -15,21 +16,25 @@ export declare class ModelAdministration extends PreactObjectAdministration<any>
15
16
  private writeInProgress;
16
17
  private computedSnapshot;
17
18
  private snapshotMap;
19
+ private contextCache;
18
20
  parentName: PropertyKey | null;
19
- setConfiguration(configuration: ModelConfiguration<any>): void;
21
+ get parent(): ModelAdministration | null;
22
+ set parent(value: ModelAdministration | null);
23
+ setConfiguration(configurationGetter: () => ModelConfiguration<any>): void;
24
+ private get configuration();
20
25
  private getReferencedAtom;
21
26
  private setState;
22
27
  private setId;
23
28
  private setModel;
24
29
  private setModels;
25
- private getModel;
26
- private getModels;
27
30
  private getModelRef;
28
31
  private getModelRefs;
29
32
  private setModelRef;
30
33
  private setModelRefs;
31
34
  private attach;
32
35
  private detach;
36
+ getContextValue<T>(contextId: symbol, provideSymbol: symbol, defaultValue: T | undefined, hasDefault: boolean): T;
37
+ private lookupContextValue;
33
38
  private toJSON;
34
39
  onSnapshotChange(onChange: SnapshotChange<any>): () => void;
35
40
  loadSnapshot(snapshot: Snapshot<any>): void;
@@ -3,4 +3,4 @@ export { ArrayAdministration } from "./array";
3
3
  export { CollectionAdministration } from "./collection";
4
4
  export { DateAdministration } from "./date";
5
5
  export { ObjectAdministration } from "./object";
6
- export { AtomNode, createReaction, SignalNode, createAtom, runInBatch, createComputed, createSignal, runInUntracked, ListenerNode, createListener, ComputedNode, PreactObjectAdministration, getSignal, source, reportChanged, reportObserved, observable, createEffect, Observable, } from "./preact";
6
+ export { AtomNode, reaction, SignalNode, createAtom, batch, createComputed, createSignal, untracked, ListenerNode, createListener, ComputedNode, PreactObjectAdministration, getSignal, source, reportChanged, reportObserved, observable, computed, Signal, ReadonlySignal, effect, signal, Observable, } from "./preact";
@@ -3,7 +3,7 @@ export declare function defaultEquals<T>(a: T, b: T): boolean;
3
3
  export declare function isNonPrimitive(val: unknown): val is object;
4
4
  export declare function isPropertyKey(val: unknown): val is string | number | symbol;
5
5
  export type PropertyType = "action" | "computed" | "observable";
6
- export declare function getPropertyType(key: PropertyKey, obj: object): PropertyType;
6
+ export declare function getPropertyType(key: PropertyKey, obj: object): PropertyType | null;
7
7
  export declare function getPropertyDescriptor(obj: object, key: PropertyKey): PropertyDescriptor | undefined;
8
8
  export declare function isPlainObject(value: unknown): value is object;
9
9
  export declare function resolveNode(node: SignalNode<unknown> | AtomNode | ComputedNode<unknown>): unknown;
@@ -7,7 +7,7 @@ export declare class ObjectAdministration<T extends object> extends Administrati
7
7
  hasMap: AtomMap<PropertyKey>;
8
8
  valuesMap: SignalMap<PropertyKey>;
9
9
  computedMap: Map<PropertyKey, ComputedNode<T[keyof T]>>;
10
- types: Map<PropertyKey, PropertyType>;
10
+ types: Map<PropertyKey, PropertyType | null>;
11
11
  static proxyTraps: ProxyHandler<object>;
12
12
  constructor(source?: T);
13
13
  private get;
@@ -1,4 +1,4 @@
1
- import { Signal, ReadonlySignal } from "@preact/signals-core";
1
+ import { signal, Signal, ReadonlySignal, batch, effect, untracked } from "@preact/signals-core";
2
2
  import { ObjectAdministration } from "./object";
3
3
  export { isObservable } from "./index";
4
4
  export declare class PreactObjectAdministration<T extends object> extends ObjectAdministration<T> {
@@ -39,9 +39,8 @@ export declare function createObservedAtom(): {
39
39
  };
40
40
  export declare function createSignal<T>(initialValue: T): SignalNode<T>;
41
41
  export declare function createAtom(): AtomNode;
42
- export declare function createEffect(fn: () => void): () => void;
43
- export declare function runInUntracked<T>(fn: () => T): T;
44
- export declare function createReaction<T>(fn: () => T, callback: (value: T) => void): () => void;
42
+ export { effect, signal, batch, untracked, Signal, ReadonlySignal };
43
+ export declare function reaction<T>(fn: () => T, callback: (value: T) => void): () => void;
45
44
  export type Listener = {
46
45
  dispose: () => void;
47
46
  track: <T>(trackFn: () => T) => T;
@@ -56,8 +55,10 @@ export type PreactObservable<T> = T extends Function ? T : T extends Map<infer K
56
55
  readonly [key in keyof T as T[key] extends object ? never : `$${string & key}`]?: Signal<T[key]>;
57
56
  };
58
57
  export declare function observable<T>(obj: T): PreactObservable<T>;
58
+ export declare function observable(value: undefined, context: ClassFieldDecoratorContext): void;
59
+ export declare function computed<T>(value: () => T, context: ClassGetterDecoratorContext): void;
60
+ export declare function computed<T>(fn: () => T): ReadonlySignal<T>;
59
61
  export declare function source<T>(obj: PreactObservable<T> | T): T;
60
- export declare function runInBatch<T>(fn: () => T): T;
61
62
  export declare class Observable {
62
63
  constructor();
63
64
  }