Skip to content

Commit 0eae80c

Browse files
committed
Add functionality for caching view values in the snapshot for fast
readonly access [no-changelog-required]
1 parent c7c5442 commit 0eae80c

13 files changed

+620
-52
lines changed

README.md

Lines changed: 87 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,11 @@
1313

1414
## Why?
1515

16-
[`mobx-state-tree`](https://mobx-state-tree.js.org/) is great for modeling data and observing changes to it, but it adds a lot of runtime overhead! Raw `mobx` itself adds substantial overhead over plain old JS objects or ES6 classes, and `mobx-state-tree` adds more on top of that. If you want to use your MST data models in a non-reactive or non-observing context, all that runtime overhead for observability is just wasted, as nothing is ever changing.
16+
[`mobx-state-tree`](https://mobx-state-tree.js.org/) is great for modeling data and observing changes to it, but it adds a lot of runtime overhead! Raw `mobx` itself adds substantial overhead over plain old JS objects or ES6 classes, and `mobx-state-tree` adds more on top of that. If you want to use your MST data models in a non-reactive or non-observing context, all that runtime overhead for observability is just wasted, as nothing is ever-changing.
1717

1818
`mobx-quick-tree` implements the same API as MST and exposes the same useful observable instances for use in observable contexts, but adds a second option for instantiating a read-only instance that is 100x faster.
1919

20-
If `mobx-state-tree` instances are great for modeling within an "editor" part of an app where nodes and properties are changed all over the place, the performant, read-only instances constructed by `mobx-quick-tree` are great for using within a "read" part of an app that displays data in the tree without ever changing it. For a website builder for example, you might use MST in the page builder area where someone arranges components within a page, and then use MQT in the part of the app that needs to render those webpages frequently.
20+
If `mobx-state-tree` instances are great for modeling within an "editor" part of an app where nodes and properties are changed all over the place, the performant, read-only instances constructed by `mobx-quick-tree` are great for use within a "read" part of an app that displays data in the tree without ever changing it. For a website builder for example, you might use MST in the page builder area where someone arranges components within a page, and then use MQT in the part of the app that needs to render those web pages frequently.
2121

2222
### Two APIs
2323

@@ -164,7 +164,7 @@ class Car extends ClassModel({
164164
}
165165
```
166166

167-
Each Class Model **must** be registered with the system using the `@register` decorator in order to be instantiated.
167+
Each Class Model **must** be registered with the system using the `@register` decorator to be instantiated.
168168
`@register` is necessary for setting up the internal state of the class and generating the observable MST type.
169169

170170
Within Class Model class bodies, refer to the current instance using the standard ES6/JS `this` keyword. `mobx-state-tree` users tend to use `self` within view or action blocks, but Class Models return to using standard JS `this` for performance.
@@ -284,11 +284,11 @@ class Car extends ClassModel({
284284
}
285285
```
286286

287-
Explicit decoration of views is exactly equivalent to implicit declaration of views without a decorator.
287+
Explicit decoration of views is exactly equivalent to an implicit declaration of views without a decorator.
288288

289289
#### Defining actions with `@action`
290290

291-
Class Models support actions on instances, which are functions that change state on the instance or it's children. Class Model actions are exactly the same as `mobx-state-tree` actions defined using the `.actions()` API on a `types.model`. See the [`mobx-state-tree` actions docs](https://mobx-state-tree.js.org/concepts/actions) for more information.
291+
Class Models support actions on instances, which are functions that change the state of the instance or its children. Class Model actions are exactly the same as `mobx-state-tree` actions defined using the `.actions()` API on a `types.model`. See the [`mobx-state-tree` actions docs](https://mobx-state-tree.js.org/concepts/actions) for more information.
292292

293293
To define an action on a Class Model, define a function within a Class Model body, and register it as an action with `@action`.
294294

@@ -433,6 +433,85 @@ watch.stop();
433433

434434
**Note**: Volatile actions will _not_ trigger observers on readonly instances. Readonly instances are not observable because they are readonly (and for performance), and so volatiles aren't observable, and so volatile actions that change them won't fire observers. This makes volatile actions appropriate for reference tracking and implementation that syncs with external systems, but not for general state management. If you need to be able to observe state, use an observable instance.
435435

436+
#### Caching view values in snapshots with `snapshottedView`
437+
438+
For expensive views, `mobx-quick-tree` supports caching the computed value of the view from an observable instance in the snapshot. This allows the read-only instance to skip re-computing the cached value, and instead return a cached value from the snapshot quickly.
439+
440+
To cache a view's value in the snapshot, define a view with the `@snapshottedView` decorator. Each `getSnapshot` call of your observable instance will include the view's result in the snapshot under the view's key.
441+
442+
```typescript
443+
import { ClassModel, register, view, snapshottedView } from "@gadgetinc/mobx-quick-tree";
444+
445+
@register
446+
class Car extends ClassModel({
447+
make: types.string,
448+
model: types.string,
449+
year: types.number,
450+
}) {
451+
@snapshottedView
452+
get name() {
453+
return `${this.year} ${this.model} ${this.make}`;
454+
}
455+
}
456+
457+
// create an observable instance
458+
const car = Car.create({ make: "Toyota", model: "Prius", year: 2008 });
459+
460+
// get a snapshot of the observable instance
461+
const snapshot = getSnapshot(car);
462+
463+
// the snapshot will include the cached view value
464+
snapshot.name; // => "2008 Toyota Prius"
465+
```
466+
467+
Snapshotted views can also transform the value of the view before it is cached in the snapshot. To transform the value of a snapshotted view, pass a function to the `@snapshottedView` decorator that takes the view's value and returns the transformed value.
468+
469+
For example, for a view that returns a rich type like a `URL`, we can store the view's value as a string in the snapshot, and re-create the rich type when a read-only instance is created::
470+
471+
```typescript
472+
@register
473+
class TransformExample extends ClassModel({ url: types.string }) {
474+
@snapshottedView<URL>({
475+
getSnapshot(value, snapshot, node) {
476+
return value.toString();
477+
},
478+
createReadOnly(value, snapshot, node) {
479+
return value ? new URL(value) : undefined;
480+
},
481+
})
482+
get withoutParams() {
483+
const url = new URL(this.url);
484+
for (const [key] of url.searchParams.entries()) {
485+
url.searchParams.delete(key);
486+
}
487+
return url;
488+
}
489+
490+
@action
491+
setURL(url: string) {
492+
this.url = url;
493+
}
494+
}
495+
```
496+
497+
##### Snapshotted view semantics
498+
499+
Snapshotted views are a complicated beast, and are best avoided until your performance demands less computation on readonly instances.
500+
501+
On observable instances, snapshotted views go through the following lifecycle:
502+
503+
- when an observable instance is created, any view values in the snapshot are _ignored_
504+
- like mobx-state-tree, view values aren't computed until the first time they are accessed. On observable instances, snapshotted views will _always_ be recomputed when accessed the first time
505+
- once a snapshotted view is computed, it will follow the standard mobx-state-tree rules for recomputation, recomputing when any of its dependencies change, and only observing dependencies if it has one or more observers of it's own
506+
- when the observable instance is snapshotted via `getSnapshot` or an observer of the snapshot, the view will always be computed, and the view's value will be JSON serialized into the snapshot
507+
508+
On readonly instances, snapshotted views go through the following lifecycle:
509+
510+
- when a readonly instance is created, any snapshotted view values in the snapshot are memoized and stored in the readonly instance
511+
- snapshotted views are never re-computed on readonly instances, and their value is always returned from the snapshot if present
512+
- if the incoming snapshot does not have a value for the view, then the view is lazily computed on first access like a normal `@view`, and memoized forever after that
513+
- when a readonly instance is snapshotted via `getSnapshot` or an observer of the snapshot, the view will be computed if it hasn't been already, and the view's value will be JSON serialized into the snapshot
514+
436515
#### References to and from class models
437516

438517
Class Models support `types.references` within their properties as well as being the target of `types.reference`s on other models or class models.
@@ -588,7 +667,7 @@ const buildClass = () => {
588667
someView: view,
589668
someAction: action,
590669
},
591-
"Example"
670+
"Example",
592671
);
593672
};
594673

@@ -728,7 +807,7 @@ class Student extends addName(
728807
firstName: types.string,
729808
lastName: types.string,
730809
homeroom: types.string,
731-
})
810+
}),
732811
) {}
733812

734813
@register
@@ -737,7 +816,7 @@ class Teacher extends addName(
737816
firstName: types.string,
738817
lastName: types.string,
739818
email: types.string,
740-
})
819+
}),
741820
) {}
742821
```
743822

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`class model snapshotted views references references to models with snapshotted views can be instantiated 1`] = `
4+
{
5+
"examples": {
6+
"1": {
7+
"key": "1",
8+
"name": "Alice",
9+
"slug": "alice",
10+
},
11+
"2": {
12+
"key": "2",
13+
"name": "Bob",
14+
"slug": "bob",
15+
},
16+
},
17+
"referrers": {
18+
"a": {
19+
"example": "1",
20+
"id": "a",
21+
},
22+
"b": {
23+
"example": "2",
24+
"id": "b",
25+
},
26+
},
27+
}
28+
`;

spec/class-model-mixins.spec.ts

Lines changed: 55 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { IsExact } from "conditional-type-checks";
22
import { assert } from "conditional-type-checks";
33
import type { Constructor } from "../src";
4-
import { isType } from "../src";
4+
import { isType, snapshottedView } from "../src";
55
import { IAnyClassModelType, IAnyStateTreeNode, extend } from "../src";
66
import { getSnapshot } from "../src";
77
import { ClassModel, action, register, types } from "../src";
@@ -69,6 +69,17 @@ const AddViewMixin = <T extends Constructor<{ name: string }>>(Klass: T) => {
6969
return MixedIn;
7070
};
7171

72+
const AddSnapshottedViewMixin = <T extends Constructor<{ name: string }>>(Klass: T) => {
73+
class MixedIn extends Klass {
74+
@snapshottedView()
75+
get snapshottedMixinGetter() {
76+
return this.name.toUpperCase();
77+
}
78+
}
79+
80+
return MixedIn;
81+
};
82+
7283
const AddActionMixin = <T extends Constructor<{ name: string }>>(Klass: T) => {
7384
class MixedIn extends Klass {
7485
@action
@@ -97,21 +108,25 @@ const AddVolatileMixin = <T extends Constructor<{ name: string }>>(Klass: T) =>
97108
@register
98109
class ChainedA extends AddVolatileMixin(
99110
AddViewMixin(
100-
AddActionMixin(
101-
ClassModel({
102-
name: types.string,
103-
}),
111+
AddSnapshottedViewMixin(
112+
AddActionMixin(
113+
ClassModel({
114+
name: types.string,
115+
}),
116+
),
104117
),
105118
),
106119
) {}
107120

108121
@register
109122
class ChainedB extends AddActionMixin(
110-
AddViewMixin(
111-
AddVolatileMixin(
112-
ClassModel({
113-
name: types.string,
114-
}),
123+
AddSnapshottedViewMixin(
124+
AddViewMixin(
125+
AddVolatileMixin(
126+
ClassModel({
127+
name: types.string,
128+
}),
129+
),
115130
),
116131
),
117132
) {}
@@ -120,9 +135,24 @@ class ChainedB extends AddActionMixin(
120135
class ChainedC extends AddActionMixin(
121136
AddVolatileMixin(
122137
AddViewMixin(
123-
ClassModel({
124-
name: types.string,
125-
}),
138+
AddSnapshottedViewMixin(
139+
ClassModel({
140+
name: types.string,
141+
}),
142+
),
143+
),
144+
),
145+
) {}
146+
147+
@register
148+
class ChainedD extends AddSnapshottedViewMixin(
149+
AddActionMixin(
150+
AddVolatileMixin(
151+
AddViewMixin(
152+
ClassModel({
153+
name: types.string,
154+
}),
155+
),
126156
),
127157
),
128158
) {}
@@ -132,6 +162,7 @@ describe("class model mixins", () => {
132162
["Chain A", ChainedA],
133163
["Chain B", ChainedB],
134164
["Chain C", ChainedC],
165+
["Chain D", ChainedD],
135166
])("%s", (_name, Klass) => {
136167
test("function views can be added to classes by mixins", () => {
137168
let instance = Klass.createReadOnly({ name: "Test" });
@@ -149,6 +180,17 @@ describe("class model mixins", () => {
149180
expect(instance.mixinGetter).toBe("TEST");
150181
});
151182

183+
test("snapshotted views can be added to classes by mixins", () => {
184+
let instance = Klass.createReadOnly({ name: "Test" });
185+
expect(instance.snapshottedMixinGetter).toBe("TEST");
186+
187+
const snapshot = getSnapshot(instance);
188+
expect((snapshot as any).snapshottedMixinGetter).toBe("TEST");
189+
190+
instance = Klass.createReadOnly({ name: "Test", snapshottedMixinGetter: "foobar" } as any);
191+
expect(instance.snapshottedMixinGetter).toBe("foobar");
192+
});
193+
152194
test("actions can be added to classes by mixins", () => {
153195
const instance = Klass.create({ name: "Test" });
154196
instance.mixinSetName("another test");

0 commit comments

Comments
 (0)