UNPKG

ink

Version:
47 lines • 2.16 kB
import wrapAnsi from 'wrap-ansi'; import sanitizeAnsi from './sanitize-ansi.js'; // 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) => { let text = ''; for (const childNode of node.childNodes) { let nodeText = ''; if (childNode.nodeName === '#text') { nodeText = childNode.nodeValue; } else { if (childNode.isHidden) { continue; } if (childNode.nodeName === 'ink-text' || childNode.nodeName === 'ink-virtual-text') { nodeText = squashTextNodes(childNode); } // Since these text nodes are being concatenated, `Output` instance won't be able to // apply children transform, so we have to do it manually here for each text node if (nodeText.length > 0 && typeof childNode.internal_transform === 'function') { const transform = childNode.internal_transform; nodeText = nodeText .split('\n') .map((line, lineIndex) => transform(line, lineIndex)) .join('\n'); } } text += nodeText; } text = sanitizeAnsi(text.replaceAll('\r\n', '\n')); // Measurement and styling dependencies understand the ESC forms of these C1 controls. text = text.replaceAll('›', '[').replaceAll('', ']').replaceAll('œ', '\\'); // Expand tabs after combining nested text so measurement and rendering use the same columns. if (node.nodeName === 'ink-text' && text.includes('\t')) { text = wrapAnsi(text, Infinity, { trim: false }); } return text; }; export default squashTextNodes; //# sourceMappingURL=squash-text-nodes.js.map