Files
med-notes/.pnpm-store/v10/files/c0/9c382a01febeec55226fcc21d4c5b52dafc67706cd2f6da2db1919b8039a40b4b86dbebdcfc43e6b7e1d9be4313caa5116d59300cd52b99dc69e8682303f6c
2025-05-09 05:30:08 +02:00

108 lines
3.0 KiB
Plaintext

import { Derived } from "./derived.js";
const __storeToDerived = /* @__PURE__ */ new WeakMap();
const __derivedToStore = /* @__PURE__ */ new WeakMap();
const __depsThatHaveWrittenThisTick = {
current: []
};
let __isFlushing = false;
let __batchDepth = 0;
const __pendingUpdates = /* @__PURE__ */ new Set();
const __initialBatchValues = /* @__PURE__ */ new Map();
function __flush_internals(relatedVals) {
const sorted = Array.from(relatedVals).sort((a, b) => {
if (a instanceof Derived && a.options.deps.includes(b)) return 1;
if (b instanceof Derived && b.options.deps.includes(a)) return -1;
return 0;
});
for (const derived of sorted) {
if (__depsThatHaveWrittenThisTick.current.includes(derived)) {
continue;
}
__depsThatHaveWrittenThisTick.current.push(derived);
derived.recompute();
const stores = __derivedToStore.get(derived);
if (stores) {
for (const store of stores) {
const relatedLinkedDerivedVals = __storeToDerived.get(store);
if (!relatedLinkedDerivedVals) continue;
__flush_internals(relatedLinkedDerivedVals);
}
}
}
}
function __notifyListeners(store) {
store.listeners.forEach(
(listener) => listener({
prevVal: store.prevState,
currentVal: store.state
})
);
}
function __notifyDerivedListeners(derived) {
derived.listeners.forEach(
(listener) => listener({
prevVal: derived.prevState,
currentVal: derived.state
})
);
}
function __flush(store) {
if (__batchDepth > 0 && !__initialBatchValues.has(store)) {
__initialBatchValues.set(store, store.prevState);
}
__pendingUpdates.add(store);
if (__batchDepth > 0) return;
if (__isFlushing) return;
try {
__isFlushing = true;
while (__pendingUpdates.size > 0) {
const stores = Array.from(__pendingUpdates);
__pendingUpdates.clear();
for (const store2 of stores) {
const prevState = __initialBatchValues.get(store2) ?? store2.prevState;
store2.prevState = prevState;
__notifyListeners(store2);
}
for (const store2 of stores) {
const derivedVals = __storeToDerived.get(store2);
if (!derivedVals) continue;
__depsThatHaveWrittenThisTick.current.push(store2);
__flush_internals(derivedVals);
}
for (const store2 of stores) {
const derivedVals = __storeToDerived.get(store2);
if (!derivedVals) continue;
for (const derived of derivedVals) {
__notifyDerivedListeners(derived);
}
}
}
} finally {
__isFlushing = false;
__depsThatHaveWrittenThisTick.current = [];
__initialBatchValues.clear();
}
}
function batch(fn) {
__batchDepth++;
try {
fn();
} finally {
__batchDepth--;
if (__batchDepth === 0) {
const pendingUpdateToFlush = Array.from(__pendingUpdates)[0];
if (pendingUpdateToFlush) {
__flush(pendingUpdateToFlush);
}
}
}
}
export {
__depsThatHaveWrittenThisTick,
__derivedToStore,
__flush,
__storeToDerived,
batch
};
//# sourceMappingURL=scheduler.js.map