mobx-keystone
Version:
A MobX powered state management solution based on data trees with first class support for TypeScript, snapshots, patches and much more
66 lines (56 loc) • 1.51 kB
text/typescript
import { createAtom, IAtom } from "mobx"
import { isModel } from "../model/utils"
import { getOrCreate } from "../utils/mapUtils"
import type { ParentPath } from "./path"
/**
* @internal
*/
export const objectParents = new WeakMap<object, ParentPath<object> | undefined>()
const objectParentsAtoms = new WeakMap<object, IAtom>()
/**
* @internal
*/
export function parentPathEquals(
parentPath1: ParentPath<any> | undefined,
parentPath2: ParentPath<any> | undefined
) {
if (!(parentPath1 || parentPath2)) {
return true
}
if (!(parentPath1 && parentPath2)) {
return false
}
return parentPath1.parent === parentPath2.parent && parentPath1.path === parentPath2.path
}
function createParentPathAtom() {
return createAtom("parentAtom")
}
/**
* @internal
*/
export function reportParentPathObserved(node: object) {
getOrCreate(objectParentsAtoms, node, createParentPathAtom).reportObserved()
}
/**
* @internal
*/
export function reportParentPathChanged(node: object) {
objectParentsAtoms.get(node)?.reportChanged()
}
/**
* @internal
*/
export const dataObjectParent = new WeakMap<object, object>()
/**
* @internal
*/
export function dataToModelNode<T extends object>(node: T): T {
const modelNode = dataObjectParent.get(node)
return (modelNode as T | undefined) ?? node
}
/**
* @internal
*/
export function modelToDataNode<T extends object>(node: T): T {
return isModel(node) ? node.$ : node
}