Socket
Socket
Sign inDemoInstall

table

Package Overview
Dependencies
17
Maintainers
2
Versions
86
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 6.7.6 to 6.8.0

dist/src/alignSpanningCell.d.ts

8

dist/src/alignTableData.js

@@ -6,5 +6,11 @@ "use strict";

const alignTableData = (rows, config) => {
return rows.map((row) => {
return rows.map((row, rowIndex) => {
return row.map((cell, cellIndex) => {
var _a;
const { width, alignment } = config.columns[cellIndex];
const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex,
row: rowIndex }, { mapped: true });
if (containingRange) {
return cell;
}
return (0, alignString_1.alignString)(cell, width, alignment);

@@ -11,0 +17,0 @@ });

@@ -5,2 +5,3 @@ "use strict";

const calculateCellHeight_1 = require("./calculateCellHeight");
const utils_1 = require("./utils");
/**

@@ -10,12 +11,34 @@ * Produces an array of values that describe the largest value length (height) in every row.

const calculateRowHeights = (rows, config) => {
return rows.map((row) => {
const rowHeights = [];
for (const [rowIndex, row] of rows.entries()) {
let rowHeight = 1;
row.forEach((cell, cellIndex) => {
const cellHeight = (0, calculateCellHeight_1.calculateCellHeight)(cell, config.columns[cellIndex].width, config.columns[cellIndex].wrapWord);
rowHeight = Math.max(rowHeight, cellHeight);
var _a;
const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex,
row: rowIndex });
if (!containingRange) {
const cellHeight = (0, calculateCellHeight_1.calculateCellHeight)(cell, config.columns[cellIndex].width, config.columns[cellIndex].wrapWord);
rowHeight = Math.max(rowHeight, cellHeight);
return;
}
const { topLeft, bottomRight, height } = containingRange;
// bottom-most cell of a range needs to contain all remain lines of spanning cells
if (rowIndex === bottomRight.row) {
const totalOccupiedSpanningCellHeight = (0, utils_1.sumArray)(rowHeights.slice(topLeft.row));
const totalHorizontalBorderHeight = bottomRight.row - topLeft.row;
const totalHiddenHorizontalBorderHeight = (0, utils_1.sequence)(topLeft.row + 1, bottomRight.row).filter((horizontalBorderIndex) => {
var _a;
/* istanbul ignore next */
return !((_a = config.drawHorizontalLine) === null || _a === void 0 ? void 0 : _a.call(config, horizontalBorderIndex, rows.length));
}).length;
const cellHeight = height - totalOccupiedSpanningCellHeight - totalHorizontalBorderHeight + totalHiddenHorizontalBorderHeight;
rowHeight = Math.max(rowHeight, cellHeight);
}
// otherwise, just depend on other sibling cell heights in the row
});
return rowHeight;
});
rowHeights.push(rowHeight);
}
return rowHeights;
};
exports.calculateRowHeights = calculateRowHeights;
//# sourceMappingURL=calculateRowHeights.js.map

3

dist/src/createStream.js

@@ -13,5 +13,6 @@ "use strict";

const truncateTableData_1 = require("./truncateTableData");
const utils_1 = require("./utils");
const prepareData = (data, config) => {
let rows = (0, stringifyTableData_1.stringifyTableData)(data);
rows = (0, truncateTableData_1.truncateTableData)(rows, config);
rows = (0, truncateTableData_1.truncateTableData)(rows, (0, utils_1.extractTruncates)(config));
const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config);

@@ -18,0 +19,0 @@ rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config);

@@ -1,26 +0,34 @@

import type { DrawVerticalLine } from './types/api';
import type { TableConfig, SeparatorGetter, TopBorderConfig, JoinBorderConfig, BottomBorderConfig } from './types/internal';
import type { SpanningCellManager } from './spanningCellManager';
import type { BorderConfig, DrawVerticalLine } from './types/api';
import type { SeparatorGetter } from './types/internal';
declare type Separator = {
readonly left: string;
readonly right: string;
readonly body: string;
readonly bodyJoinOuter?: string;
readonly bodyJoinInner?: string;
readonly join: string;
readonly left: string;
readonly right: string;
readonly joinUp?: string;
readonly joinDown?: string;
readonly joinLeft?: string;
readonly joinRight?: string;
};
declare const drawBorder: (columnWidths: number[], config: {
drawVerticalLine: DrawVerticalLine;
export declare const drawBorderSegments: (columnWidths: number[], parameters: Parameters<typeof drawBorder>[1]) => string[];
export declare const createSeparatorGetter: (dependencies: Parameters<typeof drawBorder>[1]) => (verticalBorderIndex: number, columnCount: number) => string;
export declare const drawBorder: (columnWidths: number[], parameters: Omit<DrawBorderParameters, 'border'> & {
separator: Separator;
}) => string;
declare const drawBorderTop: (columnWidths: number[], config: {
border: TopBorderConfig;
export declare const drawBorderTop: (columnWidths: number[], parameters: DrawBorderParameters) => string;
export declare const drawBorderJoin: (columnWidths: number[], parameters: DrawBorderParameters) => string;
export declare const drawBorderBottom: (columnWidths: number[], parameters: DrawBorderParameters) => string;
export declare type BorderGetterParameters = {
border: BorderConfig;
drawVerticalLine: DrawVerticalLine;
}) => string;
declare const drawBorderJoin: (columnWidths: number[], config: {
border: JoinBorderConfig;
drawVerticalLine: DrawVerticalLine;
}) => string;
declare const drawBorderBottom: (columnWidths: number[], config: {
border: BottomBorderConfig;
drawVerticalLine: DrawVerticalLine;
}) => string;
export declare const createTableBorderGetter: (columnWidths: number[], config: TableConfig) => SeparatorGetter;
export { drawBorder, drawBorderBottom, drawBorderJoin, drawBorderTop, };
spanningCellManager?: SpanningCellManager;
rowCount?: number;
};
export declare type DrawBorderParameters = Omit<BorderGetterParameters, 'outputColumnWidths'> & {
horizontalBorderIndex?: number;
};
export declare const createTableBorderGetter: (columnWidths: number[], parameters: BorderGetterParameters) => SeparatorGetter;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.drawBorderTop = exports.drawBorderJoin = exports.drawBorderBottom = exports.drawBorder = exports.createTableBorderGetter = void 0;
exports.createTableBorderGetter = exports.drawBorderBottom = exports.drawBorderJoin = exports.drawBorderTop = exports.drawBorder = exports.createSeparatorGetter = exports.drawBorderSegments = void 0;
const drawContent_1 = require("./drawContent");
const drawBorder = (columnWidths, config) => {
const { separator, drawVerticalLine } = config;
const columns = columnWidths.map((size) => {
return config.separator.body.repeat(size);
const drawBorderSegments = (columnWidths, parameters) => {
const { separator, horizontalBorderIndex, spanningCellManager } = parameters;
return columnWidths.map((columnWidth, columnIndex) => {
const normalSegment = separator.body.repeat(columnWidth);
if (horizontalBorderIndex === undefined) {
return normalSegment;
}
/* istanbul ignore next */
const range = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ col: columnIndex,
row: horizontalBorderIndex });
if (!range) {
return normalSegment;
}
const { topLeft } = range;
// draw border segments as usual for top border of spanning cell
if (horizontalBorderIndex === topLeft.row) {
return normalSegment;
}
// if for first column/row of spanning cell, just skip
if (columnIndex !== topLeft.col) {
return '';
}
return range.extractBorderContent(horizontalBorderIndex);
});
return (0, drawContent_1.drawContent)(columns, {
drawSeparator: drawVerticalLine,
separatorGetter: (index, columnCount) => {
if (index === 0) {
};
exports.drawBorderSegments = drawBorderSegments;
const createSeparatorGetter = (dependencies) => {
const { separator, spanningCellManager, horizontalBorderIndex, rowCount } = dependencies;
// eslint-disable-next-line complexity
return (verticalBorderIndex, columnCount) => {
const inSameRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.inSameRange;
if (horizontalBorderIndex !== undefined && inSameRange) {
const topCell = { col: verticalBorderIndex,
row: horizontalBorderIndex - 1 };
const leftCell = { col: verticalBorderIndex - 1,
row: horizontalBorderIndex };
const oppositeCell = { col: verticalBorderIndex - 1,
row: horizontalBorderIndex - 1 };
const currentCell = { col: verticalBorderIndex,
row: horizontalBorderIndex };
const pairs = [
[oppositeCell, topCell],
[topCell, currentCell],
[currentCell, leftCell],
[leftCell, oppositeCell],
];
// left side of horizontal border
if (verticalBorderIndex === 0) {
if (inSameRange(currentCell, topCell) && separator.bodyJoinOuter) {
return separator.bodyJoinOuter;
}
return separator.left;
}
if (index === columnCount) {
// right side of horizontal border
if (verticalBorderIndex === columnCount) {
if (inSameRange(oppositeCell, leftCell) && separator.bodyJoinOuter) {
return separator.bodyJoinOuter;
}
return separator.right;
}
return separator.join;
},
// top horizontal border
if (horizontalBorderIndex === 0) {
if (inSameRange(currentCell, leftCell)) {
return separator.body;
}
return separator.join;
}
// bottom horizontal border
if (horizontalBorderIndex === rowCount) {
if (inSameRange(topCell, oppositeCell)) {
return separator.body;
}
return separator.join;
}
const sameRangeCount = pairs.map((pair) => {
return inSameRange(...pair);
}).filter(Boolean).length;
// four cells are belongs to different spanning cells
if (sameRangeCount === 0) {
return separator.join;
}
// belong to one spanning cell
if (sameRangeCount === 4) {
return '';
}
// belongs to two spanning cell
if (sameRangeCount === 2) {
if (inSameRange(...pairs[1]) && inSameRange(...pairs[3]) && separator.bodyJoinInner) {
return separator.bodyJoinInner;
}
return separator.body;
}
/* istanbul ignore next */
if (sameRangeCount === 1) {
if (!separator.joinRight || !separator.joinLeft || !separator.joinUp || !separator.joinDown) {
throw new Error(`Can not get border separator for position [${horizontalBorderIndex}, ${verticalBorderIndex}]`);
}
if (inSameRange(...pairs[0])) {
return separator.joinDown;
}
if (inSameRange(...pairs[1])) {
return separator.joinLeft;
}
if (inSameRange(...pairs[2])) {
return separator.joinUp;
}
return separator.joinRight;
}
/* istanbul ignore next */
throw new Error('Invalid case');
}
if (verticalBorderIndex === 0) {
return separator.left;
}
if (verticalBorderIndex === columnCount) {
return separator.right;
}
return separator.join;
};
};
exports.createSeparatorGetter = createSeparatorGetter;
const drawBorder = (columnWidths, parameters) => {
const borderSegments = (0, exports.drawBorderSegments)(columnWidths, parameters);
const { drawVerticalLine, horizontalBorderIndex, spanningCellManager } = parameters;
return (0, drawContent_1.drawContent)({
contents: borderSegments,
drawSeparator: drawVerticalLine,
elementType: 'border',
rowIndex: horizontalBorderIndex,
separatorGetter: (0, exports.createSeparatorGetter)(parameters),
spanningCellManager,
}) + '\n';
};
exports.drawBorder = drawBorder;
const drawBorderTop = (columnWidths, config) => {
const result = drawBorder(columnWidths, {
...config,
const drawBorderTop = (columnWidths, parameters) => {
const { border } = parameters;
const result = (0, exports.drawBorder)(columnWidths, {
...parameters,
separator: {
body: config.border.topBody,
join: config.border.topJoin,
left: config.border.topLeft,
right: config.border.topRight,
body: border.topBody,
join: border.topJoin,
left: border.topLeft,
right: border.topRight,
},

@@ -40,10 +156,17 @@ });

exports.drawBorderTop = drawBorderTop;
const drawBorderJoin = (columnWidths, config) => {
return drawBorder(columnWidths, {
...config,
const drawBorderJoin = (columnWidths, parameters) => {
const { border } = parameters;
return (0, exports.drawBorder)(columnWidths, {
...parameters,
separator: {
body: config.border.joinBody,
join: config.border.joinJoin,
left: config.border.joinLeft,
right: config.border.joinRight,
body: border.joinBody,
bodyJoinInner: border.bodyJoin,
bodyJoinOuter: border.bodyLeft,
join: border.joinJoin,
joinDown: border.joinMiddleDown,
joinLeft: border.joinMiddleLeft,
joinRight: border.joinMiddleRight,
joinUp: border.joinMiddleUp,
left: border.joinLeft,
right: border.joinRight,
},

@@ -53,10 +176,11 @@ });

exports.drawBorderJoin = drawBorderJoin;
const drawBorderBottom = (columnWidths, config) => {
return drawBorder(columnWidths, {
...config,
const drawBorderBottom = (columnWidths, parameters) => {
const { border } = parameters;
return (0, exports.drawBorder)(columnWidths, {
...parameters,
separator: {
body: config.border.bottomBody,
join: config.border.bottomJoin,
left: config.border.bottomLeft,
right: config.border.bottomRight,
body: border.bottomBody,
join: border.bottomJoin,
left: border.bottomLeft,
right: border.bottomRight,
},

@@ -66,36 +190,13 @@ });

exports.drawBorderBottom = drawBorderBottom;
const createTableBorderGetter = (columnWidths, config) => {
const createTableBorderGetter = (columnWidths, parameters) => {
return (index, size) => {
if (!config.header) {
if (index === 0) {
return drawBorderTop(columnWidths, config);
}
if (index === size) {
return drawBorderBottom(columnWidths, config);
}
return drawBorderJoin(columnWidths, config);
}
// Deal with the header
const drawBorderParameters = { ...parameters,
horizontalBorderIndex: index };
if (index === 0) {
return drawBorderTop(columnWidths, {
...config,
border: {
...config.border,
topJoin: config.border.topBody,
},
});
return (0, exports.drawBorderTop)(columnWidths, drawBorderParameters);
}
if (index === 1) {
return drawBorderJoin(columnWidths, {
...config,
border: {
...config.border,
joinJoin: config.border.headerJoin,
},
});
else if (index === size) {
return (0, exports.drawBorderBottom)(columnWidths, drawBorderParameters);
}
if (index === size) {
return drawBorderBottom(columnWidths, config);
}
return drawBorderJoin(columnWidths, config);
return (0, exports.drawBorderJoin)(columnWidths, drawBorderParameters);
};

@@ -102,0 +203,0 @@ };

@@ -1,9 +0,14 @@

declare type SeparatorConfig = {
import type { SpanningCellManager } from './spanningCellManager';
/**
* Shared function to draw horizontal borders, rows or the entire table
*/
declare type DrawContentParameters = {
contents: string[];
drawSeparator: (index: number, size: number) => boolean;
separatorGetter: (index: number, size: number) => string;
spanningCellManager?: SpanningCellManager;
rowIndex?: number;
elementType?: 'border' | 'cell' | 'row';
};
/**
* Shared function to draw horizontal borders, rows or the entire table
*/
export declare const drawContent: (contents: string[], separatorConfig: SeparatorConfig) => string;
export declare const drawContent: (parameters: DrawContentParameters) => string;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.drawContent = void 0;
/**
* Shared function to draw horizontal borders, rows or the entire table
*/
const drawContent = (contents, separatorConfig) => {
const { separatorGetter, drawSeparator } = separatorConfig;
const drawContent = (parameters) => {
const { contents, separatorGetter, drawSeparator, spanningCellManager, rowIndex, elementType } = parameters;
const contentSize = contents.length;

@@ -15,6 +12,33 @@ const result = [];

contents.forEach((content, contentIndex) => {
result.push(content);
if (!elementType || elementType === 'border' || elementType === 'row') {
result.push(content);
}
if (elementType === 'cell' && rowIndex === undefined) {
result.push(content);
}
if (elementType === 'cell' && rowIndex !== undefined) {
/* istanbul ignore next */
const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange({ col: contentIndex,
row: rowIndex });
// when drawing content row, just add a cell when it is a normal cell
// or belongs to first column of spanning cell
if (!containingRange || contentIndex === containingRange.topLeft.col) {
result.push(content);
}
}
// Only append the middle separator if the content is not the last
if (contentIndex + 1 < contentSize && drawSeparator(contentIndex + 1, contentSize)) {
result.push(separatorGetter(contentIndex + 1, contentSize));
const separator = separatorGetter(contentIndex + 1, contentSize);
if (elementType === 'cell' && rowIndex !== undefined) {
const currentCell = { col: contentIndex + 1,
row: rowIndex };
/* istanbul ignore next */
const containingRange = spanningCellManager === null || spanningCellManager === void 0 ? void 0 : spanningCellManager.getContainingRange(currentCell);
if (!containingRange || containingRange.topLeft.col === currentCell.col) {
result.push(separator);
}
}
else {
result.push(separator);
}
}

@@ -21,0 +45,0 @@ });

@@ -0,6 +1,10 @@

import type { SpanningCellManager } from './spanningCellManager';
import type { DrawVerticalLine } from './types/api';
import type { BodyBorderConfig, Row } from './types/internal';
export declare const drawRow: (row: Row, config: {
export declare type DrawRowConfig = {
border: BodyBorderConfig;
drawVerticalLine: DrawVerticalLine;
}) => string;
spanningCellManager?: SpanningCellManager;
rowIndex?: number;
};
export declare const drawRow: (row: Row, config: DrawRowConfig) => string;

@@ -6,5 +6,8 @@ "use strict";

const drawRow = (row, config) => {
const { border, drawVerticalLine } = config;
return (0, drawContent_1.drawContent)(row, {
const { border, drawVerticalLine, rowIndex, spanningCellManager } = config;
return (0, drawContent_1.drawContent)({
contents: row,
drawSeparator: drawVerticalLine,
elementType: 'cell',
rowIndex,
separatorGetter: (index, columnCount) => {

@@ -19,2 +22,3 @@ if (index === 0) {

},
spanningCellManager,
}) + '\n';

@@ -21,0 +25,0 @@ };

import type { TableConfig, Row } from './types/internal';
export declare const drawTable: (rows: Row[], columnWidths: number[], rowHeights: number[], config: TableConfig) => string;
export declare const drawTable: (rows: Row[], outputColumnWidths: number[], rowHeights: number[], config: TableConfig) => string;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.drawTable = void 0;
const string_width_1 = __importDefault(require("string-width"));
const drawBorder_1 = require("./drawBorder");
const drawContent_1 = require("./drawContent");
const drawHeader_1 = require("./drawHeader");
const drawRow_1 = require("./drawRow");
const utils_1 = require("./utils");
const drawTable = (rows, columnWidths, rowHeights, config) => {
const drawTable = (rows, outputColumnWidths, rowHeights, config) => {
const { drawHorizontalLine, singleLine, } = config;
const contents = (0, utils_1.groupBySizes)(rows, rowHeights).map((group) => {
const contents = (0, utils_1.groupBySizes)(rows, rowHeights).map((group, groupIndex) => {
return group.map((row) => {
return (0, drawRow_1.drawRow)(row, config);
return (0, drawRow_1.drawRow)(row, { ...config,
rowIndex: groupIndex });
}).join('');
});
if (config.header) {
// assume that topLeft/right border have width = 1
const headerWidth = (0, string_width_1.default)((0, drawRow_1.drawRow)(rows[0], config)) - 2 -
config.header.paddingLeft - config.header.paddingRight;
const header = (0, drawHeader_1.drawHeader)(headerWidth, config);
contents.unshift(header);
}
return (0, drawContent_1.drawContent)(contents, {
return (0, drawContent_1.drawContent)({ contents,
drawSeparator: (index, size) => {

@@ -35,6 +24,9 @@ // Top/bottom border

},
separatorGetter: (0, drawBorder_1.createTableBorderGetter)(columnWidths, config),
});
elementType: 'row',
rowIndex: -1,
separatorGetter: (0, drawBorder_1.createTableBorderGetter)(outputColumnWidths, { ...config,
rowCount: contents.length }),
spanningCellManager: config.spanningCellManager });
};
exports.drawTable = drawTable;
//# sourceMappingURL=drawTable.js.map

@@ -7,3 +7,3 @@ declare function validate43(data: any, { instancePath, parentData, parentDataProperty, rootData }?: {

}): boolean;
declare function validate76(data: any, { instancePath, parentData, parentDataProperty, rootData }?: {
declare function validate86(data: any, { instancePath, parentData, parentDataProperty, rootData }?: {
instancePath?: string | undefined;

@@ -14,2 +14,2 @@ parentData: any;

}): boolean;
export { validate43 as _config_json, validate76 as _streamConfig_json };
export { validate43 as _config_json, validate86 as _streamConfig_json };

@@ -24,2 +24,6 @@ "use strict";

joinJoin: '┼',
joinMiddleDown: '┬',
joinMiddleUp: '┴',
joinMiddleLeft: '┤',
joinMiddleRight: '├',
};

@@ -45,2 +49,6 @@ }

joinJoin: '┼',
joinMiddleDown: '┬',
joinMiddleUp: '┴',
joinMiddleLeft: '┤',
joinMiddleRight: '├',
};

@@ -66,2 +74,6 @@ }

joinJoin: '|',
joinMiddleDown: '+',
joinMiddleUp: '+',
joinMiddleLeft: '+',
joinMiddleRight: '+',
};

@@ -87,2 +99,6 @@ }

joinJoin: '',
joinMiddleDown: '',
joinMiddleUp: '',
joinMiddleLeft: '',
joinMiddleRight: '',
};

@@ -89,0 +105,0 @@ }

@@ -1,2 +0,2 @@

import type { TableUserConfig } from './types/api';
import type { SpanningCellConfig, TableUserConfig } from './types/api';
import type { Row, TableConfig } from './types/internal';

@@ -7,2 +7,2 @@ /**

*/
export declare const makeTableConfig: (rows: Row[], config?: TableUserConfig) => TableConfig;
export declare const makeTableConfig: (rows: Row[], config?: TableUserConfig, injectedSpanningCellConfig?: SpanningCellConfig[] | undefined) => TableConfig;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeTableConfig = void 0;
const calculateColumnWidths_1 = __importDefault(require("./calculateColumnWidths"));
const calculateMaximumColumnWidths_1 = require("./calculateMaximumColumnWidths");
const spanningCellManager_1 = require("./spanningCellManager");
const utils_1 = require("./utils");
const validateConfig_1 = require("./validateConfig");
const validateSpanningCellConfig_1 = require("./validateSpanningCellConfig");
/**

@@ -14,4 +13,4 @@ * Creates a configuration for every column using default

*/
const makeColumnsConfig = (rows, columns, columnDefault) => {
const columnWidths = (0, calculateColumnWidths_1.default)(rows);
const makeColumnsConfig = (rows, columns, columnDefault, spanningCellConfigs) => {
const columnWidths = (0, calculateMaximumColumnWidths_1.calculateMaximumColumnWidths)(rows, spanningCellConfigs);
return rows[0].map((_, columnIndex) => {

@@ -31,15 +30,2 @@ return {

};
const makeHeaderConfig = (config) => {
if (!config.header) {
return undefined;
}
return {
alignment: 'center',
paddingLeft: 1,
paddingRight: 1,
truncate: Number.POSITIVE_INFINITY,
wrapWord: false,
...config.header,
};
};
/**

@@ -49,17 +35,28 @@ * Makes a new configuration object out of the userConfig object

*/
const makeTableConfig = (rows, config = {}) => {
var _a, _b, _c;
const makeTableConfig = (rows, config = {}, injectedSpanningCellConfig) => {
var _a, _b, _c, _d, _e;
(0, validateConfig_1.validateConfig)('config.json', config);
(0, validateSpanningCellConfig_1.validateSpanningCellConfig)(rows, (_a = config.spanningCells) !== null && _a !== void 0 ? _a : []);
const spanningCellConfigs = (_b = injectedSpanningCellConfig !== null && injectedSpanningCellConfig !== void 0 ? injectedSpanningCellConfig : config.spanningCells) !== null && _b !== void 0 ? _b : [];
const columnsConfig = makeColumnsConfig(rows, config.columns, config.columnDefault, spanningCellConfigs);
const drawVerticalLine = (_c = config.drawVerticalLine) !== null && _c !== void 0 ? _c : (() => {
return true;
});
const drawHorizontalLine = (_d = config.drawHorizontalLine) !== null && _d !== void 0 ? _d : (() => {
return true;
});
return {
...config,
border: (0, utils_1.makeBorderConfig)(config.border),
columns: makeColumnsConfig(rows, config.columns, config.columnDefault),
drawHorizontalLine: (_a = config.drawHorizontalLine) !== null && _a !== void 0 ? _a : (() => {
return true;
columns: columnsConfig,
drawHorizontalLine,
drawVerticalLine,
singleLine: (_e = config.singleLine) !== null && _e !== void 0 ? _e : false,
spanningCellManager: (0, spanningCellManager_1.createSpanningCellManager)({
columnsConfig,
drawHorizontalLine,
drawVerticalLine,
rows,
spanningCellConfigs,
}),
drawVerticalLine: (_b = config.drawVerticalLine) !== null && _b !== void 0 ? _b : (() => {
return true;
}),
header: makeHeaderConfig(config),
singleLine: (_c = config.singleLine) !== null && _c !== void 0 ? _c : false,
};

@@ -66,0 +63,0 @@ };

@@ -0,2 +1,4 @@

import type { VerticalAlignment } from './types/api';
import type { BaseConfig, Row } from './types/internal';
export declare const padCellVertically: (lines: string[], rowHeight: number, verticalAlignment: VerticalAlignment) => string[];
export declare const mapDataUsingRowHeights: (unmappedRows: Row[], rowHeights: number[], config: BaseConfig) => Row[];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapDataUsingRowHeights = void 0;
exports.mapDataUsingRowHeights = exports.padCellVertically = void 0;
const utils_1 = require("./utils");
const wrapCell_1 = require("./wrapCell");

@@ -8,4 +9,3 @@ const createEmptyStrings = (length) => {

};
const padCellVertically = (lines, rowHeight, columnConfig) => {
const { verticalAlignment } = columnConfig;
const padCellVertically = (lines, rowHeight, verticalAlignment) => {
const availableLines = rowHeight - lines.length;

@@ -24,15 +24,22 @@ if (verticalAlignment === 'top') {

};
const flatten = (array) => {
return [].concat(...array);
};
exports.padCellVertically = padCellVertically;
const mapDataUsingRowHeights = (unmappedRows, rowHeights, config) => {
const tableWidth = unmappedRows[0].length;
const nColumns = unmappedRows[0].length;
const mappedRows = unmappedRows.map((unmappedRow, unmappedRowIndex) => {
const outputRowHeight = rowHeights[unmappedRowIndex];
const outputRow = Array.from({ length: outputRowHeight }, () => {
return new Array(tableWidth).fill('');
return new Array(nColumns).fill('');
});
unmappedRow.forEach((cell, cellIndex) => {
var _a;
const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex,
row: unmappedRowIndex });
if (containingRange) {
containingRange.extractCellContent(unmappedRowIndex).forEach((cellLine, cellLineIndex) => {
outputRow[cellLineIndex][cellIndex] = cellLine;
});
return;
}
const cellLines = (0, wrapCell_1.wrapCell)(cell, config.columns[cellIndex].width, config.columns[cellIndex].wrapWord);
const paddedCellLines = padCellVertically(cellLines, outputRowHeight, config.columns[cellIndex]);
const paddedCellLines = (0, exports.padCellVertically)(cellLines, outputRowHeight, config.columns[cellIndex].verticalAlignment);
paddedCellLines.forEach((cellLine, cellLineIndex) => {

@@ -44,5 +51,5 @@ outputRow[cellLineIndex][cellIndex] = cellLine;

});
return flatten(mappedRows);
return (0, utils_1.flatten)(mappedRows);
};
exports.mapDataUsingRowHeights = mapDataUsingRowHeights;
//# sourceMappingURL=mapDataUsingRowHeights.js.map

@@ -9,4 +9,10 @@ "use strict";

const padTableData = (rows, config) => {
return rows.map((cells) => {
return rows.map((cells, rowIndex) => {
return cells.map((cell, cellIndex) => {
var _a;
const containingRange = (_a = config.spanningCellManager) === null || _a === void 0 ? void 0 : _a.getContainingRange({ col: cellIndex,
row: rowIndex }, { mapped: true });
if (containingRange) {
return cell;
}
const { paddingLeft, paddingRight } = config.columns[cellIndex];

@@ -13,0 +19,0 @@ return (0, exports.padString)(cell, paddingLeft, paddingRight);

@@ -48,2 +48,46 @@ {

"typeof": "boolean"
},
"spanningCells": {
"type": "array",
"items": {
"type": "object",
"properties": {
"col": {
"type": "integer",
"minimum": 0
},
"row": {
"type": "integer",
"minimum": 0
},
"colSpan": {
"type": "integer",
"minimum": 1
},
"rowSpan": {
"type": "integer",
"minimum": 1
},
"alignment": {
"$ref": "shared.json#/definitions/alignment"
},
"verticalAlignment": {
"$ref": "shared.json#/definitions/verticalAlignment"
},
"wrapWord": {
"type": "boolean"
},
"truncate": {
"type": "integer"
},
"paddingLeft": {
"type": "integer"
},
"paddingRight": {
"type": "integer"
}
},
"required": ["row", "col"],
"additionalProperties": false
}
}

@@ -50,0 +94,0 @@ },

@@ -31,8 +31,3 @@ {

"verticalAlignment": {
"type": "string",
"enum": [
"top",
"middle",
"bottom"
]
"$ref": "#/definitions/verticalAlignment"
},

@@ -108,2 +103,14 @@ "width": {

"$ref": "#/definitions/border"
},
"joinMiddleUp": {
"$ref": "#/definitions/border"
},
"joinMiddleDown": {
"$ref": "#/definitions/border"
},
"joinMiddleLeft": {
"$ref": "#/definitions/border"
},
"joinMiddleRight": {
"$ref": "#/definitions/border"
}

@@ -124,4 +131,12 @@ },

]
},
"verticalAlignment": {
"type": "string",
"enum": [
"top",
"middle",
"bottom"
]
}
}
}

@@ -5,5 +5,6 @@ "use strict";

const alignTableData_1 = require("./alignTableData");
const calculateCellWidths_1 = require("./calculateCellWidths");
const calculateOutputColumnWidths_1 = require("./calculateOutputColumnWidths");
const calculateRowHeights_1 = require("./calculateRowHeights");
const drawTable_1 = require("./drawTable");
const injectHeaderConfig_1 = require("./injectHeaderConfig");
const makeTableConfig_1 = require("./makeTableConfig");

@@ -14,2 +15,3 @@ const mapDataUsingRowHeights_1 = require("./mapDataUsingRowHeights");

const truncateTableData_1 = require("./truncateTableData");
const utils_1 = require("./utils");
const validateTableData_1 = require("./validateTableData");

@@ -19,12 +21,14 @@ const table = (data, userConfig = {}) => {

let rows = (0, stringifyTableData_1.stringifyTableData)(data);
const config = (0, makeTableConfig_1.makeTableConfig)(rows, userConfig);
rows = (0, truncateTableData_1.truncateTableData)(rows, config);
const [injectedRows, injectedSpanningCellConfig] = (0, injectHeaderConfig_1.injectHeaderConfig)(rows, userConfig);
const config = (0, makeTableConfig_1.makeTableConfig)(injectedRows, userConfig, injectedSpanningCellConfig);
rows = (0, truncateTableData_1.truncateTableData)(injectedRows, (0, utils_1.extractTruncates)(config));
const rowHeights = (0, calculateRowHeights_1.calculateRowHeights)(rows, config);
config.spanningCellManager.setRowHeights(rowHeights);
rows = (0, mapDataUsingRowHeights_1.mapDataUsingRowHeights)(rows, rowHeights, config);
rows = (0, alignTableData_1.alignTableData)(rows, config);
rows = (0, padTableData_1.padTableData)(rows, config);
const cellWidths = (0, calculateCellWidths_1.calculateCellWidths)(rows[0]);
return (0, drawTable_1.drawTable)(rows, cellWidths, rowHeights, config);
const outputColumnWidths = (0, calculateOutputColumnWidths_1.calculateOutputColumnWidths)(config);
return (0, drawTable_1.drawTable)(rows, outputColumnWidths, rowHeights, config);
};
exports.table = table;
//# sourceMappingURL=table.js.map

@@ -1,2 +0,2 @@

import type { BaseConfig, Row } from './types/internal';
import type { Row } from './types/internal';
export declare const truncateString: (input: string, length: number) => string;

@@ -6,2 +6,2 @@ /**

*/
export declare const truncateTableData: (rows: Row[], config: BaseConfig) => Row[];
export declare const truncateTableData: (rows: Row[], truncates: number[]) => Row[];

@@ -16,6 +16,6 @@ "use strict";

*/
const truncateTableData = (rows, config) => {
const truncateTableData = (rows, truncates) => {
return rows.map((cells) => {
return cells.map((cell, cellIndex) => {
return (0, exports.truncateString)(cell, config.columns[cellIndex].truncate);
return (0, exports.truncateString)(cell, truncates[cellIndex]);
});

@@ -22,0 +22,0 @@ });

@@ -17,2 +17,6 @@ export declare type DrawLinePredicate = (index: number, size: number) => boolean;

readonly joinJoin?: string;
readonly joinMiddleUp?: string;
readonly joinMiddleDown?: string;
readonly joinMiddleLeft?: string;
readonly joinMiddleRight?: string;
readonly headerJoin?: string;

@@ -26,3 +30,3 @@ readonly bodyRight?: string;

export declare type VerticalAlignment = 'bottom' | 'middle' | 'top';
export declare type ColumnUserConfig = {
export declare type CellUserConfig = {
/**

@@ -37,6 +41,2 @@ * Cell content horizontal alignment (default: left)

/**
* Column width (default: auto calculation based on the cell content)
*/
readonly width?: number;
/**
* Number of characters are which the content will be truncated (default: Infinity)

@@ -58,2 +58,11 @@ */

};
export declare type ColumnUserConfig = CellUserConfig & {
/**
* Column width (default: auto calculation based on the cell content)
*/
readonly width?: number;
};
/**
* @deprecated Use spanning cell API instead
*/
export declare type HeaderUserConfig = Omit<ColumnUserConfig, 'verticalAlignment' | 'width'> & {

@@ -97,3 +106,10 @@ readonly content: string;

readonly singleLine?: boolean;
readonly spanningCells?: SpanningCellConfig[];
};
export declare type SpanningCellConfig = CellUserConfig & {
readonly row: number;
readonly col: number;
readonly rowSpan?: number;
readonly colSpan?: number;
};
export declare type StreamUserConfig = BaseUserConfig & {

@@ -100,0 +116,0 @@ /**

@@ -1,1 +0,10 @@

export {};
import type { SpanningCellConfig } from './types/api';
import type { BaseConfig, CellCoordinates, RangeCoordinate } from './types/internal';
export declare const sequence: (start: number, end: number) => number[];
export declare const sumArray: (array: number[]) => number;
export declare const extractTruncates: (config: BaseConfig) => number[];
export declare const flatten: <T>(array: T[][]) => T[];
export declare const findOriginalRowIndex: (mappedRowHeights: number[], mappedRowIndex: number) => number;
export declare const calculateRangeCoordinate: (spanningCellConfig: SpanningCellConfig) => RangeCoordinate;
export declare const areCellEqual: (cell1: CellCoordinates, cell2: CellCoordinates) => boolean;
export declare const isCellInRange: (cell: CellCoordinates, { topLeft, bottomRight }: RangeCoordinate) => boolean;

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0;
exports.isCellInRange = exports.areCellEqual = exports.calculateRangeCoordinate = exports.findOriginalRowIndex = exports.flatten = exports.extractTruncates = exports.sumArray = exports.sequence = exports.distributeUnevenly = exports.countSpaceSequence = exports.groupBySizes = exports.makeBorderConfig = exports.splitAnsi = exports.normalizeString = void 0;
const slice_ansi_1 = __importDefault(require("slice-ansi"));

@@ -94,2 +94,52 @@ const string_width_1 = __importDefault(require("string-width"));

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) => {
return [].concat(...array);
};
exports.flatten = flatten;
const findOriginalRowIndex = (mappedRowHeights, mappedRowIndex) => {
const rowIndexMapping = (0, exports.flatten)(mappedRowHeights.map((height, index) => {
return Array.from({ length: height }, () => {
return index;
});
}));
return rowIndexMapping[mappedRowIndex];
};
exports.findOriginalRowIndex = findOriginalRowIndex;
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

@@ -13,3 +13,3 @@ "use strict";

// https://regex101.com/r/gY5kZ1/1
const re = new RegExp('(^.{1,' + String(Math.max(size, 1)) + '}(\\s+|$))|(^.{1,' + String(Math.max(2, size - 1) - 1) + '}(\\\\|/|_|\\.|,|;|-))');
const re = new RegExp('(^.{1,' + String(Math.max(size, 1)) + '}(\\s+|$))|(^.{1,' + String(Math.max(size - 1, 1)) + '}(\\\\|/|_|\\.|,|;|-))');
do {

@@ -36,3 +36,3 @@ let chunk;

let startIndex = 0;
calculateStringLengths(input, Math.max(size, 1)).forEach(([length, offset]) => {
calculateStringLengths(input, size).forEach(([length, offset]) => {
result.push((0, slice_ansi_1.default)(input, startIndex, startIndex + length));

@@ -39,0 +39,0 @@ startIndex += length + offset;

@@ -76,3 +76,3 @@ {

},
"version": "6.7.6"
"version": "6.8.0"
}

@@ -551,2 +551,4 @@ <a name="table"></a>

*Deprecated in favor of the new spanning cells API.*
The header configuration inherits the most of the column's, except:

@@ -593,2 +595,78 @@ - `content` **{string}**: the header content.

<a name="table-api-table-1-config-spanningcells"></a>
##### config.spanningCells
Type: `SpanningCellConfig[]`
Spanning cells configuration.
The configuration should be straightforward: just specify an array of minimal cell configurations including the position of top-left cell
and the number of columns and/or rows will be expanded from it.
The content of overlap cells will be ignored to make the `data` shape be consistent.
By default, the configuration of column that the top-left cell belongs to will be applied to the whole spanning cell, except:
* The `width` will be summed up of all spanning columns.
* The `paddingRight` will be received from the right-most column intentionally.
Advances customized column-like styles can be configurable to each spanning cell to overwrite the default behavior.
```js
const data = [
['Test Coverage Report', '', '', '', '', ''],
['Module', 'Component', 'Test Cases', 'Failures', 'Durations', 'Success Rate'],
['Services', 'User', '50', '30', '3m 7s', '60.0%'],
['', 'Payment', '100', '80', '7m 15s', '80.0%'],
['Subtotal', '', '150', '110', '10m 22s', '73.3%'],
['Controllers', 'User', '24', '18', '1m 30s', '75.0%'],
['', 'Payment', '30', '24', '50s', '80.0%'],
['Subtotal', '', '54', '42', '2m 20s', '77.8%'],
['Total', '', '204', '152', '12m 42s', '74.5%'],
];
const config = {
columns: [
{ alignment: 'center', width: 12 },
{ alignment: 'center', width: 10 },
{ alignment: 'right' },
{ alignment: 'right' },
{ alignment: 'right' },
{ alignment: 'right' }
],
spanningCells: [
{ col: 0, row: 0, colSpan: 6 },
{ col: 0, row: 2, rowSpan: 2, verticalAlignment: 'middle'},
{ col: 0, row: 4, colSpan: 2, alignment: 'right'},
{ col: 0, row: 5, rowSpan: 2, verticalAlignment: 'middle'},
{ col: 0, row: 7, colSpan: 2, alignment: 'right' },
{ col: 0, row: 8, colSpan: 2, alignment: 'right' }
],
};
console.log(table(data, config));
```
```
╔══════════════════════════════════════════════════════════════════════════════╗
║ Test Coverage Report ║
╟──────────────┬────────────┬────────────┬──────────┬───────────┬──────────────╢
║ Module │ Component │ Test Cases │ Failures │ Durations │ Success Rate ║
╟──────────────┼────────────┼────────────┼──────────┼───────────┼──────────────╢
║ │ User │ 50 │ 30 │ 3m 7s │ 60.0% ║
║ Services ├────────────┼────────────┼──────────┼───────────┼──────────────╢
║ │ Payment │ 100 │ 80 │ 7m 15s │ 80.0% ║
╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢
║ Subtotal │ 150 │ 110 │ 10m 22s │ 73.3% ║
╟──────────────┬────────────┼────────────┼──────────┼───────────┼──────────────╢
║ │ User │ 24 │ 18 │ 1m 30s │ 75.0% ║
║ Controllers ├────────────┼────────────┼──────────┼───────────┼──────────────╢
║ │ Payment │ 30 │ 24 │ 50s │ 80.0% ║
╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢
║ Subtotal │ 54 │ 42 │ 2m 20s │ 77.8% ║
╟───────────────────────────┼────────────┼──────────┼───────────┼──────────────╢
║ Total │ 204 │ 152 │ 12m 42s │ 74.5% ║
╚═══════════════════════════╧════════════╧══════════╧═══════════╧══════════════╝
```
<a name="table-api-createstream"></a>

@@ -595,0 +673,0 @@ ### createStream

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc