overmind
Version:
Frictionless state management
67 lines (65 loc) • 2.18 kB
JavaScript
import { EventType } from "./internalTypes.js";
import { IS_PROXY, TrackStateTree } from "proxy-state-tree";
//#region src/derived.ts
const IS_DERIVED = Symbol("IS_DERIVED");
const IS_DERIVED_CONSTRUCTOR = Symbol("IS_DERIVED_CONSTRUCTOR");
var Derived = class {
constructor(cb) {
this.cb = cb;
this.isDirty = true;
this.updateCount = 0;
const boundEvaluate = this.evaluate.bind(this);
if (process.env.NODE_ENV === "development") boundEvaluate.dispose = () => {
this.disposeOnMutation();
};
boundEvaluate[IS_DERIVED] = true;
return boundEvaluate;
}
runScope(tree, path) {
const parent = path.slice(0, path.length - 1).reduce((curr, key) => curr[key], tree.state);
return this.cb(parent, tree.state);
}
evaluate(eventHub, tree, proxyStateTree, path) {
if (!this.disposeOnMutation) this.disposeOnMutation = proxyStateTree.onMutation((_, paths, flushId) => {
if (typeof path.reduce((aggr, key) => aggr && aggr[key], proxyStateTree.sourceState) !== "function") {
this.disposeOnMutation();
return;
}
if (this.isDirty) return;
for (const mutationPath of paths) if (this.paths.has(mutationPath)) {
this.isDirty = true;
eventHub.emitAsync(EventType.DERIVED_DIRTY, {
derivedPath: path,
path: mutationPath,
flushId
});
return;
}
});
if (this.isDirty || this.previousProxifier !== tree.proxifier) {
const getPaths = tree.trackPaths();
this.value = this.runScope(tree, path);
this.isDirty = false;
this.paths = getPaths();
if (process.env.NODE_ENV === "development") {
eventHub.emitAsync(EventType.DERIVED, {
path,
paths: Array.from(this.paths),
updateCount: this.updateCount,
value: this.value
});
this.updateCount++;
}
}
if (tree instanceof TrackStateTree) for (const path$1 of this.paths) {
tree.addTrackingPath(path$1);
tree.trackPathListeners.forEach((cb) => cb(path$1));
}
this.previousProxifier = tree.proxifier;
if (this.value && this.value[IS_PROXY]) return proxyStateTree.rescope(this.value, tree);
return this.value;
}
};
//#endregion
export { Derived, IS_DERIVED, IS_DERIVED_CONSTRUCTOR };
//# sourceMappingURL=derived.js.map