withsubclocks.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. // Public interface
  2. var S = function S(fn, value) {
  3. var owner = Owner, clock = RunningClock === null ? RootClock : RunningClock, running = RunningNode;
  4. if (owner === null)
  5. console.warn("computations created without a root or parent will never be disposed");
  6. var node = new ComputationNode(clock, fn, value);
  7. Owner = RunningNode = node;
  8. if (RunningClock === null) {
  9. toplevelComputation(node);
  10. }
  11. else {
  12. node.value = node.fn(node.value);
  13. }
  14. if (owner && owner !== UNOWNED) {
  15. if (owner.owned === null)
  16. owner.owned = [node];
  17. else
  18. owner.owned.push(node);
  19. }
  20. Owner = owner;
  21. RunningNode = running;
  22. return function computation() {
  23. if (RunningNode !== null) {
  24. var rclock = RunningClock, sclock = node.clock;
  25. while (rclock.depth > sclock.depth + 1)
  26. rclock = rclock.parent;
  27. if (rclock === sclock || rclock.parent === sclock) {
  28. if (node.preclocks !== null) {
  29. for (var i = 0; i < node.preclocks.count; i++) {
  30. var preclock = node.preclocks.clocks[i];
  31. updateClock(preclock);
  32. }
  33. }
  34. if (node.age === node.clock.time()) {
  35. if (node.state === RUNNING)
  36. throw new Error("circular dependency");
  37. else
  38. updateNode(node); // checks for state === STALE internally, so don't need to check here
  39. }
  40. if (node.preclocks !== null) {
  41. for (var i = 0; i < node.preclocks.count; i++) {
  42. var preclock = node.preclocks.clocks[i];
  43. if (rclock === sclock)
  44. logNodePreClock(preclock, RunningNode);
  45. else
  46. logClockPreClock(preclock, rclock, RunningNode);
  47. }
  48. }
  49. }
  50. else {
  51. if (rclock.depth > sclock.depth)
  52. rclock = rclock.parent;
  53. while (sclock.depth > rclock.depth + 1)
  54. sclock = sclock.parent;
  55. if (sclock.parent === rclock) {
  56. logNodePreClock(sclock, RunningNode);
  57. }
  58. else {
  59. if (sclock.depth > rclock.depth)
  60. sclock = sclock.parent;
  61. while (rclock.parent !== sclock.parent)
  62. rclock = rclock.parent, sclock = sclock.parent;
  63. logClockPreClock(sclock, rclock, RunningNode);
  64. }
  65. updateClock(sclock);
  66. }
  67. logComputationRead(node, RunningNode);
  68. }
  69. return node.value;
  70. };
  71. };
  72. // compatibility with commonjs systems that expect default export to be at require('s.js').default rather than just require('s-js')
  73. Object.defineProperty(S, 'default', { value: S });
  74. export default S;
  75. S.root = function root(fn) {
  76. var owner = Owner, root = fn.length === 0 ? UNOWNED : new ComputationNode(RunningClock || RootClock, null, null), result = undefined, disposer = fn.length === 0 ? null : function _dispose() {
  77. if (RunningClock !== null) {
  78. markClockStale(root.clock);
  79. root.clock.disposes.add(root);
  80. }
  81. else {
  82. dispose(root);
  83. }
  84. };
  85. Owner = root;
  86. if (RunningClock === null) {
  87. result = topLevelRoot(fn, disposer, owner);
  88. }
  89. else {
  90. result = disposer === null ? fn() : fn(disposer);
  91. Owner = owner;
  92. }
  93. return result;
  94. };
  95. function topLevelRoot(fn, disposer, owner) {
  96. try {
  97. return disposer === null ? fn() : fn(disposer);
  98. }
  99. finally {
  100. Owner = owner;
  101. }
  102. }
  103. S.on = function on(ev, fn, seed, onchanges) {
  104. if (Array.isArray(ev))
  105. ev = callAll(ev);
  106. onchanges = !!onchanges;
  107. return S(on, seed);
  108. function on(value) {
  109. var running = RunningNode;
  110. ev();
  111. if (onchanges)
  112. onchanges = false;
  113. else {
  114. RunningNode = null;
  115. value = fn(value);
  116. RunningNode = running;
  117. }
  118. return value;
  119. }
  120. };
  121. function callAll(ss) {
  122. return function all() {
  123. for (var i = 0; i < ss.length; i++)
  124. ss[i]();
  125. };
  126. }
  127. S.data = function data(value) {
  128. var node = new DataNode(RunningClock === null ? RootClock : RunningClock, value);
  129. return function data(value) {
  130. var rclock = RunningClock, sclock = node.clock;
  131. if (RunningClock !== null) {
  132. while (rclock.depth > sclock.depth)
  133. rclock = rclock.parent;
  134. while (sclock.depth > rclock.depth && sclock.parent !== rclock)
  135. sclock = sclock.parent;
  136. if (sclock.parent !== rclock)
  137. while (rclock.parent !== sclock.parent)
  138. rclock = rclock.parent, sclock = sclock.parent;
  139. if (rclock !== sclock) {
  140. updateClock(sclock);
  141. }
  142. }
  143. var cclock = rclock === sclock ? sclock : sclock.parent;
  144. if (arguments.length > 0) {
  145. if (RunningClock !== null) {
  146. if (node.pending !== NOTPENDING) { // value has already been set once, check for conflicts
  147. if (value !== node.pending) {
  148. throw new Error("conflicting changes: " + value + " !== " + node.pending);
  149. }
  150. }
  151. else { // add to list of changes
  152. markClockStale(cclock);
  153. node.pending = value;
  154. cclock.changes.add(node);
  155. }
  156. }
  157. else { // not batching, respond to change now
  158. if (node.log !== null) {
  159. node.pending = value;
  160. RootClock.changes.add(node);
  161. event();
  162. }
  163. else {
  164. node.value = value;
  165. }
  166. }
  167. return value;
  168. }
  169. else {
  170. if (RunningNode !== null) {
  171. logDataRead(node, RunningNode);
  172. if (sclock.parent === rclock)
  173. logNodePreClock(sclock, RunningNode);
  174. else if (sclock !== rclock)
  175. logClockPreClock(sclock, rclock, RunningNode);
  176. }
  177. return node.value;
  178. }
  179. };
  180. };
  181. S.value = function value(current, eq) {
  182. var data = S.data(current), clock = RunningClock || RootClock, age = -1;
  183. return function value(update) {
  184. if (arguments.length === 0) {
  185. return data();
  186. }
  187. else {
  188. var same = eq ? eq(current, update) : current === update;
  189. if (!same) {
  190. var time = clock.time();
  191. if (age === time)
  192. throw new Error("conflicting values: " + update + " is not the same as " + current);
  193. age = time;
  194. current = update;
  195. data(update);
  196. }
  197. return update;
  198. }
  199. };
  200. };
  201. S.freeze = function freeze(fn) {
  202. var result = undefined;
  203. if (RunningClock !== null) {
  204. result = fn();
  205. }
  206. else {
  207. RunningClock = RootClock;
  208. RunningClock.changes.reset();
  209. try {
  210. result = fn();
  211. event();
  212. }
  213. finally {
  214. RunningClock = null;
  215. }
  216. }
  217. return result;
  218. };
  219. S.sample = function sample(fn) {
  220. var result, running = RunningNode;
  221. if (running !== null) {
  222. RunningNode = null;
  223. result = fn();
  224. RunningNode = running;
  225. }
  226. else {
  227. result = fn();
  228. }
  229. return result;
  230. };
  231. S.cleanup = function cleanup(fn) {
  232. if (Owner !== null) {
  233. if (Owner.cleanups === null)
  234. Owner.cleanups = [fn];
  235. else
  236. Owner.cleanups.push(fn);
  237. }
  238. else {
  239. console.warn("cleanups created without a root or parent will never be run");
  240. }
  241. };
  242. S.subclock = function subclock(fn) {
  243. var clock = new Clock(RunningClock || RootClock);
  244. return fn === undefined ? subclock : subclock(fn);
  245. function subclock(fn) {
  246. var result = null, running = RunningClock;
  247. RunningClock = clock;
  248. clock.state = STALE;
  249. try {
  250. result = fn();
  251. clock.subtime++;
  252. run(clock);
  253. }
  254. finally {
  255. RunningClock = running;
  256. }
  257. // if we were run from top level, have to flush any changes in RootClock
  258. if (RunningClock === null)
  259. event();
  260. return result;
  261. }
  262. };
  263. // Internal implementation
  264. /// Graph classes and operations
  265. var Clock = /** @class */ (function () {
  266. function Clock(parent) {
  267. this.parent = parent;
  268. this.id = Clock.count++;
  269. this.state = CURRENT;
  270. this.subtime = 0;
  271. this.preclocks = null;
  272. this.changes = new Queue(); // batched changes to data nodes
  273. this.subclocks = new Queue(); // subclocks that need to be updated
  274. this.updates = new Queue(); // computations to update
  275. this.disposes = new Queue(); // disposals to run after current batch of updates finishes
  276. if (parent !== null) {
  277. this.age = parent.time();
  278. this.depth = parent.depth + 1;
  279. }
  280. else {
  281. this.age = 0;
  282. this.depth = 0;
  283. }
  284. }
  285. Clock.prototype.time = function () {
  286. var time = this.subtime, p = this;
  287. while ((p = p.parent) !== null)
  288. time += p.subtime;
  289. return time;
  290. };
  291. Clock.count = 0;
  292. return Clock;
  293. }());
  294. var DataNode = /** @class */ (function () {
  295. function DataNode(clock, value) {
  296. this.clock = clock;
  297. this.value = value;
  298. this.pending = NOTPENDING;
  299. this.log = null;
  300. }
  301. return DataNode;
  302. }());
  303. var ComputationNode = /** @class */ (function () {
  304. function ComputationNode(clock, fn, value) {
  305. this.clock = clock;
  306. this.fn = fn;
  307. this.value = value;
  308. this.state = CURRENT;
  309. this.source1 = null;
  310. this.source1slot = 0;
  311. this.sources = null;
  312. this.sourceslots = null;
  313. this.log = null;
  314. this.preclocks = null;
  315. this.owned = null;
  316. this.cleanups = null;
  317. this.age = this.clock.time();
  318. }
  319. return ComputationNode;
  320. }());
  321. var Log = /** @class */ (function () {
  322. function Log() {
  323. this.node1 = null;
  324. this.node1slot = 0;
  325. this.nodes = null;
  326. this.nodeslots = null;
  327. }
  328. return Log;
  329. }());
  330. var NodePreClockLog = /** @class */ (function () {
  331. function NodePreClockLog() {
  332. this.count = 0;
  333. this.clocks = []; // [clock], where clock.parent === node.clock
  334. this.ages = []; // clock.id -> node.age
  335. this.ucount = 0; // number of ancestor clocks with preclocks from this node
  336. this.uclocks = [];
  337. this.uclockids = [];
  338. }
  339. return NodePreClockLog;
  340. }());
  341. var ClockPreClockLog = /** @class */ (function () {
  342. function ClockPreClockLog() {
  343. this.count = 0;
  344. this.clockcounts = []; // clock.id -> ref count
  345. this.clocks = []; // clock.id -> clock
  346. this.ids = []; // [clock.id]
  347. }
  348. return ClockPreClockLog;
  349. }());
  350. var Queue = /** @class */ (function () {
  351. function Queue() {
  352. this.items = [];
  353. this.count = 0;
  354. }
  355. Queue.prototype.reset = function () {
  356. this.count = 0;
  357. };
  358. Queue.prototype.add = function (item) {
  359. this.items[this.count++] = item;
  360. };
  361. Queue.prototype.run = function (fn) {
  362. var items = this.items;
  363. for (var i = 0; i < this.count; i++) {
  364. fn(items[i]);
  365. items[i] = null;
  366. }
  367. this.count = 0;
  368. };
  369. return Queue;
  370. }());
  371. // Constants
  372. var NOTPENDING = {}, CURRENT = 0, STALE = 1, RUNNING = 2;
  373. // "Globals" used to keep track of current system state
  374. var RootClock = new Clock(null), RunningClock = null, // currently running clock
  375. RunningNode = null, // currently running computation
  376. Owner = null, // owner for new computations
  377. UNOWNED = new ComputationNode(RootClock, null, null);
  378. // Functions
  379. function logRead(from, to) {
  380. var fromslot, toslot = to.source1 === null ? -1 : to.sources === null ? 0 : to.sources.length;
  381. if (from.node1 === null) {
  382. from.node1 = to;
  383. from.node1slot = toslot;
  384. fromslot = -1;
  385. }
  386. else if (from.nodes === null) {
  387. from.nodes = [to];
  388. from.nodeslots = [toslot];
  389. fromslot = 0;
  390. }
  391. else {
  392. fromslot = from.nodes.length;
  393. from.nodes.push(to);
  394. from.nodeslots.push(toslot);
  395. }
  396. if (to.source1 === null) {
  397. to.source1 = from;
  398. to.source1slot = fromslot;
  399. }
  400. else if (to.sources === null) {
  401. to.sources = [from];
  402. to.sourceslots = [fromslot];
  403. }
  404. else {
  405. to.sources.push(from);
  406. to.sourceslots.push(fromslot);
  407. }
  408. }
  409. function logDataRead(data, to) {
  410. if (data.log === null)
  411. data.log = new Log();
  412. logRead(data.log, to);
  413. }
  414. function logComputationRead(node, to) {
  415. if (node.log === null)
  416. node.log = new Log();
  417. logRead(node.log, to);
  418. }
  419. function logNodePreClock(clock, to) {
  420. if (to.preclocks === null)
  421. to.preclocks = new NodePreClockLog();
  422. else if (to.preclocks.ages[clock.id] === to.age)
  423. return;
  424. to.preclocks.ages[clock.id] = to.age;
  425. to.preclocks.clocks[to.preclocks.count++] = clock;
  426. }
  427. function logClockPreClock(sclock, rclock, rnode) {
  428. var clocklog = rclock.preclocks === null ? (rclock.preclocks = new ClockPreClockLog()) : rclock.preclocks, nodelog = rnode.preclocks === null ? (rnode.preclocks = new NodePreClockLog()) : rnode.preclocks;
  429. if (nodelog.ages[sclock.id] === rnode.age)
  430. return;
  431. nodelog.ages[sclock.id] = rnode.age;
  432. nodelog.uclocks[nodelog.ucount] = rclock;
  433. nodelog.uclockids[nodelog.ucount++] = sclock.id;
  434. var clockcount = clocklog.clockcounts[sclock.id];
  435. if (clockcount === undefined) {
  436. clocklog.ids[clocklog.count++] = sclock.id;
  437. clocklog.clockcounts[sclock.id] = 1;
  438. clocklog.clocks[sclock.id] = sclock;
  439. }
  440. else if (clockcount === 0) {
  441. clocklog.clockcounts[sclock.id] = 1;
  442. clocklog.clocks[sclock.id] = sclock;
  443. }
  444. else {
  445. clocklog.clockcounts[sclock.id]++;
  446. }
  447. }
  448. function event() {
  449. // b/c we might be under a top level S.root(), have to preserve current root
  450. var owner = Owner;
  451. RootClock.subclocks.reset();
  452. RootClock.updates.reset();
  453. RootClock.subtime++;
  454. try {
  455. run(RootClock);
  456. }
  457. finally {
  458. RunningClock = RunningNode = null;
  459. Owner = owner;
  460. }
  461. }
  462. function toplevelComputation(node) {
  463. RunningClock = RootClock;
  464. RootClock.changes.reset();
  465. RootClock.subclocks.reset();
  466. RootClock.updates.reset();
  467. try {
  468. node.value = node.fn(node.value);
  469. if (RootClock.changes.count > 0 || RootClock.subclocks.count > 0 || RootClock.updates.count > 0) {
  470. RootClock.subtime++;
  471. run(RootClock);
  472. }
  473. }
  474. finally {
  475. RunningClock = Owner = RunningNode = null;
  476. }
  477. }
  478. function run(clock) {
  479. var running = RunningClock, count = 0;
  480. RunningClock = clock;
  481. clock.disposes.reset();
  482. // for each batch ...
  483. while (clock.changes.count !== 0 || clock.subclocks.count !== 0 || clock.updates.count !== 0 || clock.disposes.count !== 0) {
  484. if (count > 0) // don't tick on first run, or else we expire already scheduled updates
  485. clock.subtime++;
  486. clock.changes.run(applyDataChange);
  487. clock.subclocks.run(updateClock);
  488. clock.updates.run(updateNode);
  489. clock.disposes.run(dispose);
  490. // if there are still changes after excessive batches, assume runaway
  491. if (count++ > 1e5) {
  492. throw new Error("Runaway clock detected");
  493. }
  494. }
  495. RunningClock = running;
  496. }
  497. function applyDataChange(data) {
  498. data.value = data.pending;
  499. data.pending = NOTPENDING;
  500. if (data.log)
  501. markComputationsStale(data.log);
  502. }
  503. function markComputationsStale(log) {
  504. var node1 = log.node1, nodes = log.nodes;
  505. // mark all downstream nodes stale which haven't been already
  506. if (node1 !== null)
  507. markNodeStale(node1);
  508. if (nodes !== null) {
  509. for (var i = 0, len = nodes.length; i < len; i++) {
  510. markNodeStale(nodes[i]);
  511. }
  512. }
  513. }
  514. function markNodeStale(node) {
  515. var time = node.clock.time();
  516. if (node.age < time) {
  517. markClockStale(node.clock);
  518. node.age = time;
  519. node.state = STALE;
  520. node.clock.updates.add(node);
  521. if (node.owned !== null)
  522. markOwnedNodesForDisposal(node.owned);
  523. if (node.log !== null)
  524. markComputationsStale(node.log);
  525. }
  526. }
  527. function markOwnedNodesForDisposal(owned) {
  528. for (var i = 0; i < owned.length; i++) {
  529. var child = owned[i];
  530. child.age = child.clock.time();
  531. child.state = CURRENT;
  532. if (child.owned !== null)
  533. markOwnedNodesForDisposal(child.owned);
  534. }
  535. }
  536. function markClockStale(clock) {
  537. var time = 0;
  538. if ((clock.parent !== null && clock.age < (time = clock.parent.time())) || clock.state === CURRENT) {
  539. if (clock.parent !== null) {
  540. clock.age = time;
  541. markClockStale(clock.parent);
  542. clock.parent.subclocks.add(clock);
  543. }
  544. clock.changes.reset();
  545. clock.subclocks.reset();
  546. clock.updates.reset();
  547. clock.state = STALE;
  548. }
  549. }
  550. function updateClock(clock) {
  551. var time = clock.parent.time();
  552. if (clock.age < time || clock.state === STALE) {
  553. if (clock.age < time)
  554. clock.state = CURRENT;
  555. if (clock.preclocks !== null) {
  556. for (var i = 0; i < clock.preclocks.ids.length; i++) {
  557. var preclock = clock.preclocks.clocks[clock.preclocks.ids[i]];
  558. if (preclock)
  559. updateClock(preclock);
  560. }
  561. }
  562. clock.age = time;
  563. }
  564. if (clock.state === RUNNING) {
  565. throw new Error("clock circular reference");
  566. }
  567. else if (clock.state === STALE) {
  568. clock.state = RUNNING;
  569. run(clock);
  570. clock.state = CURRENT;
  571. }
  572. }
  573. function updateNode(node) {
  574. if (node.state === STALE) {
  575. var owner = Owner, running = RunningNode, clock = RunningClock;
  576. Owner = RunningNode = node;
  577. RunningClock = node.clock;
  578. node.state = RUNNING;
  579. cleanup(node, false);
  580. node.value = node.fn(node.value);
  581. node.state = CURRENT;
  582. Owner = owner;
  583. RunningNode = running;
  584. RunningClock = clock;
  585. }
  586. }
  587. function cleanup(node, final) {
  588. var source1 = node.source1, sources = node.sources, sourceslots = node.sourceslots, cleanups = node.cleanups, owned = node.owned, preclocks = node.preclocks, i, len;
  589. if (cleanups !== null) {
  590. for (i = 0; i < cleanups.length; i++) {
  591. cleanups[i](final);
  592. }
  593. node.cleanups = null;
  594. }
  595. if (owned !== null) {
  596. for (i = 0; i < owned.length; i++) {
  597. dispose(owned[i]);
  598. }
  599. node.owned = null;
  600. }
  601. if (source1 !== null) {
  602. cleanupSource(source1, node.source1slot);
  603. node.source1 = null;
  604. }
  605. if (sources !== null) {
  606. for (i = 0, len = sources.length; i < len; i++) {
  607. cleanupSource(sources.pop(), sourceslots.pop());
  608. }
  609. }
  610. if (preclocks !== null) {
  611. for (i = 0; i < preclocks.count; i++) {
  612. preclocks.clocks[i] = null;
  613. }
  614. preclocks.count = 0;
  615. for (i = 0; i < preclocks.ucount; i++) {
  616. var upreclocks = preclocks.uclocks[i].preclocks, uclockid = preclocks.uclockids[i];
  617. if (--upreclocks.clockcounts[uclockid] === 0) {
  618. upreclocks.clocks[uclockid] = null;
  619. }
  620. }
  621. preclocks.ucount = 0;
  622. }
  623. }
  624. function cleanupSource(source, slot) {
  625. var nodes = source.nodes, nodeslots = source.nodeslots, last, lastslot;
  626. if (slot === -1) {
  627. source.node1 = null;
  628. }
  629. else {
  630. last = nodes.pop();
  631. lastslot = nodeslots.pop();
  632. if (slot !== nodes.length) {
  633. nodes[slot] = last;
  634. nodeslots[slot] = lastslot;
  635. if (lastslot === -1) {
  636. last.source1slot = slot;
  637. }
  638. else {
  639. last.sourceslots[lastslot] = slot;
  640. }
  641. }
  642. }
  643. }
  644. function dispose(node) {
  645. node.clock = null;
  646. node.fn = null;
  647. node.log = null;
  648. node.preclocks = null;
  649. cleanup(node, true);
  650. }