UNPKG

1.97 kBJavaScriptView Raw
1import { dep } from "optimism";
2import { Slot } from "@wry/context";
3export var cacheSlot = new Slot();
4var cacheInfoMap = new WeakMap();
5function getCacheInfo(cache) {
6 var info = cacheInfoMap.get(cache);
7 if (!info) {
8 cacheInfoMap.set(cache, info = {
9 vars: new Set,
10 dep: dep(),
11 });
12 }
13 return info;
14}
15export function forgetCache(cache) {
16 getCacheInfo(cache).vars.forEach(function (rv) { return rv.forgetCache(cache); });
17}
18export function recallCache(cache) {
19 getCacheInfo(cache).vars.forEach(function (rv) { return rv.attachCache(cache); });
20}
21export function makeVar(value) {
22 var caches = new Set();
23 var listeners = new Set();
24 var rv = function (newValue) {
25 if (arguments.length > 0) {
26 if (value !== newValue) {
27 value = newValue;
28 caches.forEach(function (cache) {
29 getCacheInfo(cache).dep.dirty(rv);
30 broadcast(cache);
31 });
32 var oldListeners = Array.from(listeners);
33 listeners.clear();
34 oldListeners.forEach(function (listener) { return listener(value); });
35 }
36 }
37 else {
38 var cache = cacheSlot.getValue();
39 if (cache) {
40 attach(cache);
41 getCacheInfo(cache).dep(rv);
42 }
43 }
44 return value;
45 };
46 rv.onNextChange = function (listener) {
47 listeners.add(listener);
48 return function () {
49 listeners.delete(listener);
50 };
51 };
52 var attach = rv.attachCache = function (cache) {
53 caches.add(cache);
54 getCacheInfo(cache).vars.add(rv);
55 return rv;
56 };
57 rv.forgetCache = function (cache) { return caches.delete(cache); };
58 return rv;
59}
60function broadcast(cache) {
61 if (cache.broadcastWatches) {
62 cache.broadcastWatches();
63 }
64}
65//# sourceMappingURL=reactiveVars.js.map
\No newline at end of file