UNPKG

table

Version:

Formats data into a string table.

415 lines • 15.5 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCellInRange = exports.areCellEqual = exports.calculateRangeCoordinate = exports.flatten = exports.extractTruncates = exports.sumArray = exports.sequence = exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = exports.sliceAnsi = exports.stringWidth = exports.stripAnsi = exports.calculateSliceLength = exports.splitGraphemes = exports.isSingleColumn = void 0; const slice_ansi_1 = __importDefault(require("slice-ansi")); const string_width_1 = __importDefault(require("string-width")); const strip_ansi_1 = __importDefault(require("strip-ansi")); const getBorderCharacters_1 = require("./getBorderCharacters"); /** * A user-perceived character: a code point together with the combining marks, variation selectors, * emoji modifiers and tag characters attached to it, including zero-width joiner emoji sequences; * or a pair of regional indicators, which is rendered as a flag. */ const graphemeRegex = /\p{Regional_Indicator}{2}|[\s\S][\p{M}\p{Emoji_Modifier}\u{E0020}-\u{E007F}]*(?:\u200D[\s\S][\p{M}\p{Emoji_Modifier}\u{E0020}-\u{E007F}]*)*/gu; /** * Printable ASCII, printable Latin-1, the IPA and spacing modifier letters, and the dashes, quotes and * ellipsis of General Punctuation. None of these is an escape code, a combining mark, an emoji or a * full-width character, so each is one grapheme, one terminal column and one slice-ansi position. */ const singleColumnRegex = /^[\u0020-\u007E\u00A0-\u02FF\u2010-\u2027]+$/u; const printableAsciiRegex = /^[\u0020-\u007E]+$/u; /** * Tests whether a string is non-empty single-column text. Printable ASCII, the most common content, is * tested first, because its expression is faster than the one of the whole set. */ const testSingleColumn = (subject) => { return printableAsciiRegex.test(subject) || singleColumnRegex.test(subject); }; /** * Tests whether a string is non-empty single-column text: no escape codes, and one grapheme, one * terminal column and one slice-ansi position per character. * * @internal */ const isSingleColumn = (subject) => { return testSingleColumn(subject); }; exports.isSingleColumn = isSingleColumn; /** * slice-ansi positions are not terminal columns: it advances one position per code point and two for * full-width BMP characters, but only one for astral characters such as emoji. Asking slice-ansi * directly keeps the computed boundaries aligned with how it slices. */ const countSlicePositions = (grapheme) => { let positions = 0; for (const codePoint of grapheme) { positions += (0, slice_ansi_1.default)(codePoint, 0, 1) === '' ? 2 : 1; } return positions; }; /** * The characters that start an escape code or a terminal hyperlink. A string without them is left as it * is by strip-ansi and is sliced by slice-ansi only by counting positions. */ // eslint-disable-next-line no-control-regex const escapeRegex = /[\u001B\u009B\u009D]/u; /** * Like strip-ansi, but returns a string without escape codes as it is. */ const stripEscapes = (input) => { return escapeRegex.test(input) ? (0, strip_ansi_1.default)(input) : input; }; const graphemeCache = new Map(); /** * Measures a grapheme in terminal columns and in slice-ansi positions. Measurements are cached, and the * cache is emptied whenever it grows large so that its memory use stays bounded. */ const measureGrapheme = (value) => { let grapheme = graphemeCache.get(value); if (!grapheme) { if (graphemeCache.size >= 10000) { graphemeCache.clear(); } grapheme = { positions: countSlicePositions(value), value, width: (0, string_width_1.default)(value), }; graphemeCache.set(value, grapheme); } return grapheme; }; /** * Splits a string without ANSI escape codes into graphemes, measured in terminal columns and in * slice-ansi positions. * * @internal */ const splitGraphemes = (subject) => { var _a; // Single-column text, the most common content, is one column and one slice-ansi position per character. if (testSingleColumn(subject)) { return Array.from(subject, (value) => { return { positions: 1, value, width: 1, }; }); } return ((_a = subject.match(graphemeRegex)) !== null && _a !== void 0 ? _a : []).map(measureGrapheme); }; exports.splitGraphemes = splitGraphemes; /** * Calculates the slice-ansi length of the longest run of whole graphemes at the start of a string * without ANSI escape codes that fits within the given width. At least one grapheme is included, so * that callers always make progress. * * @internal */ const calculateSliceLength = (subject, maximumWidth) => { // Single-column text is one column and one position per character. The character after the cut is // checked as well, so that a combining mark or modifier is never separated from the one before it. if (maximumWidth >= 1 && testSingleColumn(subject.slice(0, maximumWidth + 1))) { return Math.min(subject.length, maximumWidth); } // A copy, so that this loop has its own lastIndex. const regex = new RegExp(graphemeRegex); let width = 0; let positions = 0; for (let match = regex.exec(subject); match; match = regex.exec(subject)) { const grapheme = measureGrapheme(match[0]); if (positions > 0 && width + grapheme.width > maximumWidth) { break; } width += grapheme.width; positions += grapheme.positions; } return positions; }; exports.calculateSliceLength = calculateSliceLength; /** * A terminal hyperlink (OSC 8) sequence. An opening sequence carries the parameters and the URI of the * link that the text after it belongs to; a closing sequence has an empty URI. */ // eslint-disable-next-line no-control-regex const hyperlinkRegex = /(\u001B\]|\u009D)8;[^\u0007\u001B\u009C;]*;([^\u0007\u001B\u009C]*)(\u0007|\u001B\\|\u009C)/gu; const containsHyperlink = (input) => { return input.includes(']8;') || input.includes('\u009D8;'); }; const removeHyperlinks = (input) => { return containsHyperlink(input) ? input.replace(hyperlinkRegex, '') : input; }; /** * Like strip-ansi, but also removes terminal hyperlinks, whatever their URI and terminator. * * @internal */ const stripAnsi = (input) => { // Single-column text has no escape codes to remove. if (testSingleColumn(input)) { return input; } return stripEscapes(removeHyperlinks(input)); }; exports.stripAnsi = stripAnsi; /** * Like string-width, but also ignores terminal hyperlinks, whatever their URI and terminator. * * @internal */ const stringWidth = (input) => { // Single-column text is one column per character. if (testSingleColumn(input)) { return input.length; } return (0, string_width_1.default)(removeHyperlinks(input)); }; exports.stringWidth = stringWidth; /** * Separates the terminal hyperlinks from the rest of the input, and divides its text into runs, measured * in slice-ansi positions, that each belong to one hyperlink or to none. */ const splitHyperlinks = (input) => { // A copy, so that this loop has its own lastIndex. const regex = new RegExp(hyperlinkRegex); const runs = []; let plain = ''; let position = 0; let start = 0; let link; let lastIndex = 0; const appendText = (text) => { plain += text; position += (0, exports.calculateSliceLength)(stripEscapes(text), Number.POSITIVE_INFINITY); if (position > start) { runs.push({ end: position, link, start }); start = position; } }; for (let match = regex.exec(input); match; match = regex.exec(input)) { appendText(input.slice(lastIndex, match.index)); const [escapeSequence, introducer, uri, terminator] = match; link = uri ? { close: introducer + '8;;' + terminator, open: escapeSequence } : undefined; lastIndex = regex.lastIndex; } appendText(input.slice(lastIndex)); return { plain, runs }; }; const codePointPositionCache = new Map(); /** * The number of slice-ansi positions of one code point: two for a full-width BMP character, one * otherwise. Measurements are cached, and the cache is emptied whenever it grows large. */ const measureCodePoint = (codePoint) => { let positions = codePointPositionCache.get(codePoint); if (positions === undefined) { if (codePointPositionCache.size >= 10000) { codePointPositionCache.clear(); } positions = (0, slice_ansi_1.default)(codePoint, 0, 1) === '' ? 2 : 1; codePointPositionCache.set(codePoint, positions); } return positions; }; /** * Slices a string without escape codes exactly as slice-ansi does: each code point advances one * position, or two if it is full-width, and is kept if the position it reaches is within the range. */ const slicePlain = (input, begin, end) => { const stringEnd = typeof end === 'number' ? end : Number.POSITIVE_INFINITY; let output = ''; let visible = 0; for (const codePoint of input) { visible += codePoint.charCodeAt(0) < 0x7F ? 1 : measureCodePoint(codePoint); if (visible > begin && visible <= stringEnd) { output += codePoint; } else if (visible >= stringEnd) { break; } } return output; }; /** * Like slice-ansi, but keeps terminal hyperlinks: each part of the result that belongs to a hyperlink is * wrapped in its own opening and closing sequences. * * @internal */ const sliceAnsi = (input, begin, end) => { // Single-column text has no escape codes and is one slice-ansi position per character. if (begin >= 0 && (end === undefined || end >= 0) && testSingleColumn(input)) { return input.slice(begin, end); } // Without escape codes, slice-ansi only counts positions. if (!escapeRegex.test(input)) { return slicePlain(input, begin, end); } if (!containsHyperlink(input)) { return (0, slice_ansi_1.default)(input, begin, end); } const { plain, runs } = splitHyperlinks(input); if (!runs.some(({ link }) => { return link; })) { return (0, slice_ansi_1.default)(plain, begin, end); } return runs.map(({ end: runEnd, link, start }) => { const from = Math.max(begin, start); const to = Math.min(end !== null && end !== void 0 ? end : Number.POSITIVE_INFINITY, runEnd); if (from >= to) { return ''; } const text = (0, slice_ansi_1.default)(plain, from, to); return link ? link.open + text + link.close : text; }).join(''); }; exports.sliceAnsi = sliceAnsi; /** * Converts Windows-style newline to Unix-style * * @internal */ const normalizeString = (input) => { return input.replace(/\r\n/g, '\n'); }; exports.normalizeString = normalizeString; /** * Splits ansi string by newlines * * @internal */ const splitAnsi = (input) => { const lines = input.split('\n'); // Lines of single-column text have no escape codes and are one slice-ansi position per character, so // slicing the input gives back each line as it is. if (lines.every((line) => { return line === '' || testSingleColumn(line); })) { return lines; } // Line lengths in slice-ansi positions, which differ from display widths for emoji. const lengths = (0, exports.stripAnsi)(input).split('\n').map((line) => { return (0, exports.calculateSliceLength)(line, Number.POSITIVE_INFINITY); }); const result = []; let startIndex = 0; lengths.forEach((length) => { result.push(length === 0 ? '' : (0, exports.sliceAnsi)(input, startIndex, startIndex + length)); // Plus 1 for the newline character itself startIndex += length + 1; }); return result; }; exports.splitAnsi = splitAnsi; /** * Merges user provided border characters with the default border ("honeywell") characters. * * @internal */ const makeBorderConfig = (border) => { return { ...(0, getBorderCharacters_1.getBorderCharacters)('honeywell'), ...border, }; }; exports.makeBorderConfig = makeBorderConfig; /** * Groups the array into sub-arrays by sizes. * * @internal * @example * groupBySizes(['a', 'b', 'c', 'd', 'e'], [2, 1, 2]) = [ ['a', 'b'], ['c'], ['d', 'e'] ] */ const groupBySizes = (array, sizes) => { let startIndex = 0; return sizes.map((size) => { const group = array.slice(startIndex, startIndex + size); startIndex += size; return group; }); }; exports.groupBySizes = groupBySizes; /** * Counts the number of continuous spaces in a string * * @internal * @example * countGroupSpaces('a bc de f') = 3 */ const countSpaceSequence = (input) => { var _a, _b; return (_b = (_a = input.match(/\s+/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0; }; exports.countSpaceSequence = countSpaceSequence; /** * Creates the non-increasing number array given sum and length * whose the difference between maximum and minimum is not greater than 1 * * @internal * @example * distributeUnevenly(6, 3) = [2, 2, 2] * distributeUnevenly(8, 3) = [3, 3, 2] */ const distributeUnevenly = (sum, length) => { const result = Array.from({ length }).fill(Math.floor(sum / length)); return result.map((element, index) => { return element + (index < sum % length ? 1 : 0); }); }; exports.distributeUnevenly = distributeUnevenly; const sequence = (start, end) => { return Array.from({ length: end - start + 1 }, (_, index) => { return index + start; }); }; exports.sequence = sequence; const sumArray = (array) => { return array.reduce((accumulator, element) => { return accumulator + element; }, 0); }; exports.sumArray = sumArray; const extractTruncates = (config) => { return config.columns.map(({ truncate }) => { return truncate; }); }; exports.extractTruncates = extractTruncates; const flatten = (array) => { const destination = []; const arrayLength = array.length; for (let index = 0; index < arrayLength; index++) { destination.push(...array[index]); } return destination; }; exports.flatten = flatten; const calculateRangeCoordinate = (spanningCellConfig) => { const { row, col, colSpan = 1, rowSpan = 1 } = spanningCellConfig; return { bottomRight: { col: col + colSpan - 1, row: row + rowSpan - 1 }, topLeft: { col, row } }; }; exports.calculateRangeCoordinate = calculateRangeCoordinate; const areCellEqual = (cell1, cell2) => { return cell1.row === cell2.row && cell1.col === cell2.col; }; exports.areCellEqual = areCellEqual; const isCellInRange = (cell, { topLeft, bottomRight }) => { return (topLeft.row <= cell.row && cell.row <= bottomRight.row && topLeft.col <= cell.col && cell.col <= bottomRight.col); }; exports.isCellInRange = isCellInRange; //# sourceMappingURL=utils.js.map