UNPKG

@prodo/core

Version:

Core package for [Prodo](https://prodo.dev). See [documentation](https://docs.prodo.dev) for more info.

105 lines 3.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var react_dom_1 = require("react-dom"); var logger_1 = require("./logger"); var utils_1 = require("./utils"); exports.subscribe = function (store, path, node) { // root tree var tree = store.watchTree; tree.subs.add(node); // watching the entire state if (path.length === 0) { tree.esubs.add(node); return; } // add node to subs of all child trees path.forEach(function (key) { if (!tree.children[key]) { tree.children[key] = { subs: new Set(), esubs: new Set(), children: {}, }; } tree = tree.children[key]; tree.subs.add(node); }); // add node to esubs of exact part of state tree that was subscribed tree.esubs.add(node); }; exports.unsubscribe = function (store, path, node) { var tree = store.watchTree; tree.subs.delete(node); if (path.length === 0) { tree.esubs.delete(node); return; } for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var pathKey = path_1[_i]; var prev = tree; tree = tree.children[pathKey]; if (node.unsubscribe) { node.unsubscribe({ name: node.name, compId: node.compId, }); } tree.subs.delete(node); // there are no more subscribers to children of this tree // cut the branch if (tree.subs.size === 0) { delete prev.children[pathKey]; break; } } tree.esubs.delete(node); }; exports.get = function (universe, pathKey) { return utils_1.splitPath(pathKey).reduce(function (x, y) { return x && x[y]; }, universe); }; exports.submitPatches = function (store, universe, event) { var callbacksSet = new Set(); var patches = event.patches; patches.forEach(function (_a) { var path = _a.path; var subtree = store.watchTree; // tslint:disable-next-line:prefer-for-of for (var i = 0; i < path.length; i += 1) { var key = path[i]; if (!subtree.children[key]) { break; } subtree = subtree.children[key]; Array.from(i === path.length - 1 ? subtree.subs : subtree.esubs).forEach(function (x) { return callbacksSet.add(x); }); } }); var comps = {}; var compIds = []; Array.from(callbacksSet) .sort(function (x, y) { return x.compId - y.compId; }) .forEach(function (x) { if (!comps[x.compId]) { compIds.push(x.compId); comps[x.compId] = { setState: x.setState, status: x.status, name: x.name, newValues: {}, }; } comps[x.compId.toString()].newValues[x.pathKey] = exports.get(universe, x.pathKey); }); logger_1.default.info("[update cycle]", comps); event.rerender = {}; react_dom_1.unstable_batchedUpdates(function () { return Object.keys(comps).forEach(function (compId) { var _a = comps[compId], setState = _a.setState, name = _a.name, newValues = _a.newValues, status = _a.status; if (!status.unmounted) { event.rerender[comps[compId].name] = true; logger_1.default.info("[upcoming state update] " + name, newValues, status); setState(newValues); } }); }); }; //# sourceMappingURL=watch.js.map