@adpt/core
Version:
AdaptJS core library
85 lines • 2.95 kB
JavaScript
;
/*
* Copyright 2019 Unbounded Systems, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const jsx_1 = require("./jsx");
function domForEach(dom, f) {
if (dom == null)
return;
f(dom);
jsx_1.childrenToArray(dom.props.children)
.forEach((c) => jsx_1.isMountedElement(c) && domForEach(c, f));
}
exports.domForEach = domForEach;
function domMap(dom, f) {
const ret = [];
domForEach(dom, (el) => ret.push(f(el)));
return ret;
}
exports.domMap = domMap;
exports.defaultDomDiffId = (el) => el.id;
function domDiff(oldDom, newDom, idFunc = exports.defaultDomDiffId) {
const byId = new Map();
const added = new Set();
const deleted = new Set();
const commonOld = new Set();
const commonNew = new Set();
domForEach(oldDom, (el) => byId.set(idFunc(el), el));
domForEach(newDom, (el) => {
const id = idFunc(el);
const old = byId.get(id);
if (old) {
commonOld.add(old);
commonNew.add(el);
byId.delete(id);
}
else {
added.add(el);
}
});
byId.forEach((el) => deleted.add(el));
return { added, deleted, commonOld, commonNew };
}
exports.domDiff = domDiff;
/**
* Given a DomDiff, generated from an old and new DOM, returns an Array of
* the Elements that will be active if this DomDiff is deployed. That means
* all of the Elements in the new DOM plus the deleted Elements from the
* old DOM.
*/
function domActiveElems(diff) {
// This implementation (with Array.from & concat) may seem slightly
// odd to look at, but if we have really large DOMs, it avoids the
// JS arg length hard limits that could happen when using the spread
// operator or apply.
const a = [];
return a.concat(Array.from(diff.added), Array.from(diff.commonNew), Array.from(diff.deleted));
}
exports.domActiveElems = domActiveElems;
function logElements(msg, elements, logger) {
const els = elements.map((el) => {
let path = "[not mounted]";
let id = "[not mounted]";
if (jsx_1.isMountedElement(el)) {
path = el.path;
id = el.id;
}
return `${el.componentName} (key=${el.props.key})\n path: ${path}\n ID: ${id}`;
});
logger(msg + els.join("\n"));
}
exports.logElements = logElements;
//# sourceMappingURL=dom_utils.js.map