Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lazy type for lazy importing of models #1722

Merged
merged 14 commits into from
Aug 5, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions docs/API/index.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/mobx-state-tree/__tests__/core/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ const TYPES = stringToArray(`
identifier,
identifierNumber,
late,
lazy,
undefined,
null,
snapshotProcessor
Expand Down
111 changes: 111 additions & 0 deletions packages/mobx-state-tree/__tests__/core/lazy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import { when } from "mobx"
import { getRoot, types } from "../../src"

interface IRootModel {
shouldLoad: boolean
}

test("it should load the correct type", async () => {
const LazyModel = types
.model("LazyModel", {
width: types.number,
height: types.number
})
.views((self) => ({
get area() {
return self.height * self.width
}
}))

const Root = types
.model("Root", {
shouldLoad: types.optional(types.boolean, false),
lazyModel: types.lazy<typeof LazyModel, IRootModel>("lazy", {
loadType: () => Promise.resolve(LazyModel),
shouldLoadPredicate: (parent) => parent.shouldLoad == true
})
})
.actions((self) => ({
load: () => {
self.shouldLoad = true
}
}))

const store = Root.create({
lazyModel: {
width: 3,
height: 2
}
})

expect(store.lazyModel.width).toBe(3)
expect(store.lazyModel.height).toBe(2)
expect(store.lazyModel.area).toBeUndefined()
store.load()
const promise = new Promise<number>((resolve, reject) => {
when(
() => store.lazyModel && store.lazyModel.area !== undefined,
() => resolve(store.lazyModel.area)
)

setTimeout(reject, 2000)
})

await expect(promise).resolves.toBe(6)
})

test("maintains the tree structure when loaded", async () => {
const LazyModel = types
.model("LazyModel", {
width: types.number,
height: types.number
})
.views((self) => ({
get area() {
const root = getRoot<{ rootValue: number }>(self)
return self.height * self.width * root.rootValue
}
}))

const Root = types
.model("Root", {
shouldLoad: types.optional(types.boolean, false),
lazyModel: types.lazy<typeof LazyModel, IRootModel>("lazy", {
loadType: () => Promise.resolve(LazyModel),
shouldLoadPredicate: (parent) => parent.shouldLoad == true
})
})
.views(() => ({
get rootValue() {
return 5
}
}))
.actions((self) => ({
load: () => {
self.shouldLoad = true
}
}))

const store = Root.create({
lazyModel: {
width: 3,
height: 2
}
})

expect(store.lazyModel.width).toBe(3)
expect(store.lazyModel.height).toBe(2)
expect(store.rootValue).toEqual(5)
expect(store.lazyModel.area).toBeUndefined()
store.load()
const promise = new Promise<number>((resolve, reject) => {
when(
() => store.lazyModel && store.lazyModel.area !== undefined,
() => resolve(store.lazyModel.area)
)

setTimeout(reject, 2000)
})

await expect(promise).resolves.toBe(30)
})
3 changes: 2 additions & 1 deletion packages/mobx-state-tree/src/core/type/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ export enum TypeFlags {
Undefined = 1 << 16,
Integer = 1 << 17,
Custom = 1 << 18,
SnapshotProcessor = 1 << 19
SnapshotProcessor = 1 << 19,
Lazy = 1 << 20
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/mobx-state-tree/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export * from "./types/utility-types/union"
export * from "./types/utility-types/optional"
export * from "./types/utility-types/maybe"
export * from "./types/utility-types/late"
export * from "./types/utility-types/lazy"
export * from "./types/utility-types/frozen"
export * from "./types/utility-types/reference"
export * from "./types/utility-types/identifier"
Expand Down
4 changes: 3 additions & 1 deletion packages/mobx-state-tree/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
identifier,
identifierNumber,
late,
lazy,
undefinedType,
nullType,
snapshotProcessor
Expand Down Expand Up @@ -54,5 +55,6 @@ export const types = {
late,
undefined: undefinedType,
null: nullType,
snapshotProcessor
snapshotProcessor,
lazy
clgeoio marked this conversation as resolved.
Show resolved Hide resolved
}
120 changes: 120 additions & 0 deletions packages/mobx-state-tree/src/types/utility-types/lazy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { action, IObservableArray, observable, when } from "mobx"
import { AnyNode } from "../../core/node/BaseNode"
import { IType } from "../../core/type/type"
import {
IValidationContext,
IValidationResult,
TypeFlags,
typeCheckSuccess,
AnyObjectNode,
SimpleType,
createScalarNode,
deepFreeze,
isSerializable,
typeCheckFailure
} from "../../internal"

interface LazyOptions<T extends IType<any, any, any>, U> {
loadType: () => Promise<T>
shouldLoadPredicate: (parent: U) => boolean
}

export function lazy<T extends IType<any, any, any>, U>(
name: string,
options: LazyOptions<T, U>
): T {
// TODO: fix this unknown casting to be stricter
return (new Lazy(name, options) as unknown) as T
}

/**
* @internal
* @hidden
*/
export class Lazy<T extends IType<any, any, any>, U> extends SimpleType<T, T, T> {
flags = TypeFlags.Lazy

private loadedType: T | null = null
private pendingNodeList: IObservableArray<AnyNode> = observable.array()

constructor(name: string, private readonly options: LazyOptions<T, U>) {
super(name)

when(
() =>
this.pendingNodeList.length > 0 &&
this.pendingNodeList.some(
(node) =>
node.isAlive &&
this.options.shouldLoadPredicate(node.parent ? node.parent.value : null)
),
() => {
this.options.loadType().then(
action((type: T) => {
this.loadedType = type
this.pendingNodeList.forEach((node) => {
if (!node.parent) return
if (!this.loadedType) return

node.parent.applyPatches([
{
op: "replace",
path: `/${node.subpath}`,
value: node.snapshot
}
])
})
})
)
}
)
}

describe() {
return `<lazy ${this.name}>`
}

instantiate(
parent: AnyObjectNode | null,
subpath: string,
environment: any,
value: this["C"]
): this["N"] {
if (this.loadedType) {
return this.loadedType.instantiate(parent, subpath, environment, value) as this["N"]
}

const node = createScalarNode(this, parent, subpath, environment, deepFreeze(value))
this.pendingNodeList.push(node)

when(
() => !node.isAlive,
() => this.pendingNodeList.splice(this.pendingNodeList.indexOf(node), 1)
)

return node
}

isValidSnapshot(value: this["C"], context: IValidationContext): IValidationResult {
if (this.loadedType) {
return this.loadedType.validate(value, context)
}
if (!isSerializable(value)) {
return typeCheckFailure(context, value, "Value is not serializable and cannot be lazy")
}
return typeCheckSuccess()
}

reconcile(current: this["N"], value: T, parent: AnyObjectNode, subpath: string): this["N"] {
if (this.loadedType) {
current.die()
return this.loadedType.instantiate(
parent,
subpath,
parent.environment,
value
) as this["N"]
}
return super.reconcile(current, value, parent, subpath)
}
}