UNPKG

proxy-state-tree

Version:

An implementation of the Mobx/Vue state tracking approach, for library authors

77 lines 2.36 kB
import { Proxifier } from './Proxyfier'; export class MutationTree { mutationCallbacks = []; root; state; proxifier; mutations = []; objectChanges = new Set(); isTracking = false; isBlocking = false; trackPathListeners = []; constructor(root, proxifier) { this.isTracking = true; this.root = root; this.proxifier = proxifier || new Proxifier(this); this.state = this.proxifier.proxify(root.sourceState, ''); } trackPaths() { const paths = new Set(); const listener = (path) => { paths.add(path); }; this.trackPathListeners.push(listener); return () => { this.trackPathListeners.splice(this.trackPathListeners.indexOf(listener), 1); return paths; }; } getMutations() { const mutations = this.mutations.slice(); this.mutations.length = 0; return mutations; } getObjectChanges() { const objectChanges = new Set([...this.objectChanges]); this.objectChanges.clear(); return objectChanges; } addMutation(mutation, objectChangePath) { const currentFlushId = this.root.currentFlushId; this.mutations.push(mutation); if (objectChangePath) { this.objectChanges.add(objectChangePath); } for (const cb of this.root.mutationCallbacks) { cb(mutation, new Set(objectChangePath ? [mutation.path, objectChangePath] : [mutation.path]), currentFlushId); } for (const callback of this.mutationCallbacks) { callback(mutation, new Set(objectChangePath ? [mutation.path, objectChangePath] : [mutation.path]), currentFlushId); } } flush(isAsync = false) { return this.root.flush(this, isAsync); } onMutation(callback) { this.mutationCallbacks.push(callback); } canMutate() { return this.isTracking && !this.isBlocking; } canTrack() { return false; } blockMutations() { this.isBlocking = true; } enableMutations() { this.isBlocking = false; } dispose() { this.isTracking = false; this.mutationCallbacks.length = 0; this.proxifier = this.root.proxifier; return this; } } //# sourceMappingURL=MutationTree.js.map