UNPKG

@tldraw/state

Version:

tldraw infinite canvas SDK (state).

72 lines (71 loc) 2.05 kB
import { ArraySet } from "./ArraySet.mjs"; import { HistoryBuffer } from "./HistoryBuffer.mjs"; import { maybeCaptureParent } from "./capture.mjs"; import { EMPTY_ARRAY, equals, singleton } from "./helpers.mjs"; import { advanceGlobalEpoch, atomDidChange, getGlobalEpoch } from "./transactions.mjs"; import { RESET_VALUE } from "./types.mjs"; class __Atom__ { constructor(name, current, options) { this.name = name; this.current = current; this.isEqual = options?.isEqual ?? null; if (!options) return; if (options.historyLength) { this.historyBuffer = new HistoryBuffer(options.historyLength); } this.computeDiff = options.computeDiff; } isEqual; computeDiff; lastChangedEpoch = getGlobalEpoch(); children = new ArraySet(); historyBuffer; __unsafe__getWithoutCapture(_ignoreErrors) { return this.current; } get() { maybeCaptureParent(this); return this.current; } set(value, diff) { if (this.isEqual?.(this.current, value) ?? equals(this.current, value)) { return this.current; } advanceGlobalEpoch(); if (this.historyBuffer) { this.historyBuffer.pushEntry( this.lastChangedEpoch, getGlobalEpoch(), diff ?? this.computeDiff?.(this.current, value, this.lastChangedEpoch, getGlobalEpoch()) ?? RESET_VALUE ); } this.lastChangedEpoch = getGlobalEpoch(); const oldValue = this.current; this.current = value; atomDidChange(this, oldValue); return value; } update(updater) { return this.set(updater(this.current)); } getDiffSince(epoch) { maybeCaptureParent(this); if (epoch >= this.lastChangedEpoch) { return EMPTY_ARRAY; } return this.historyBuffer?.getChangesSince(epoch) ?? RESET_VALUE; } } const _Atom = singleton("Atom", () => __Atom__); function atom(name, initialValue, options) { return new _Atom(name, initialValue, options); } function isAtom(value) { return value instanceof _Atom; } export { _Atom, atom, isAtom }; //# sourceMappingURL=Atom.mjs.map