62 lines
2.0 KiB
JavaScript
62 lines
2.0 KiB
JavaScript
|
"use strict";
|
||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||
|
exports.Computed = void 0;
|
||
|
exports.computed = computed;
|
||
|
const system_js_1 = require("./system.js");
|
||
|
function computed(getter) {
|
||
|
return new Computed(getter);
|
||
|
}
|
||
|
class Computed {
|
||
|
constructor(getter) {
|
||
|
this.getter = getter;
|
||
|
this.cachedValue = undefined;
|
||
|
// Dependency
|
||
|
this.subs = undefined;
|
||
|
this.subsTail = undefined;
|
||
|
this.linkedTrackId = -1;
|
||
|
// Subscriber
|
||
|
this.deps = undefined;
|
||
|
this.depsTail = undefined;
|
||
|
this.trackId = 0;
|
||
|
this.dirtyLevel = 3 /* DirtyLevels.Dirty */;
|
||
|
this.canPropagate = false;
|
||
|
}
|
||
|
get() {
|
||
|
const dirtyLevel = this.dirtyLevel;
|
||
|
if (dirtyLevel === 2 /* DirtyLevels.MaybeDirty */) {
|
||
|
system_js_1.Subscriber.resolveMaybeDirty(this);
|
||
|
if (this.dirtyLevel === 3 /* DirtyLevels.Dirty */) {
|
||
|
this.update();
|
||
|
}
|
||
|
}
|
||
|
else if (dirtyLevel === 3 /* DirtyLevels.Dirty */ || dirtyLevel === 4 /* DirtyLevels.Released */) {
|
||
|
this.update();
|
||
|
}
|
||
|
const activeTrackId = system_js_1.System.activeTrackId;
|
||
|
if (activeTrackId !== 0 && this.linkedTrackId !== activeTrackId) {
|
||
|
this.linkedTrackId = activeTrackId;
|
||
|
system_js_1.Dependency.linkSubscriber(this, system_js_1.System.activeSub);
|
||
|
}
|
||
|
return this.cachedValue;
|
||
|
}
|
||
|
update() {
|
||
|
const prevSub = system_js_1.Subscriber.startTrackDependencies(this);
|
||
|
const oldValue = this.cachedValue;
|
||
|
let newValue;
|
||
|
try {
|
||
|
newValue = this.getter(oldValue);
|
||
|
}
|
||
|
finally {
|
||
|
system_js_1.Subscriber.endTrackDependencies(this, prevSub);
|
||
|
}
|
||
|
if (oldValue !== newValue) {
|
||
|
this.cachedValue = newValue;
|
||
|
const subs = this.subs;
|
||
|
if (subs !== undefined) {
|
||
|
system_js_1.Dependency.propagate(subs);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
exports.Computed = Computed;
|