npmc
Version:
a package manager for JavaScript
40 lines (33 loc) • 1.21 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _dom = require("./dom");
// Squashing text nodes allows to combine multiple text nodes into one and write
// to `Output` instance only once. For example, <Text>hello{' '}world</Text>
// is actually 3 text nodes, which would result 3 writes to `Output`.
//
// Also, this is necessary for libraries like ink-link (https://github.com/sindresorhus/ink-link),
// which need to wrap all children at once, instead of wrapping 3 text nodes separately.
const squashTextNodes = node => {
if (!Array.isArray(node.childNodes) || node.childNodes.length === 0) {
return node;
}
const childNodes = node.childNodes.map(squashTextNodes);
const isAllTextNodes = childNodes.every(node => {
return Boolean(node.nodeValue) || node.nodeName === 'SPAN' && Boolean(node.textContent);
});
if (isAllTextNodes) {
let text = '';
childNodes.forEach(node => {
text += node.nodeValue || node.textContent;
});
node.childNodes = [(0, _dom.createTextNode)(text)];
} else {
node.childNodes = childNodes;
}
return node;
};
var _default = squashTextNodes;
exports.default = _default;
;