UNPKG

markdown-table-prettify

Version:

Transforms markdown tables to be more readable.

58 lines (57 loc) 3.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TableValidator = void 0; var TableValidator = /** @class */ (function () { function TableValidator(_selectionInterpreter) { this._selectionInterpreter = _selectionInterpreter; } TableValidator.prototype.isValid = function (selection) { if (selection == null || selection === undefined) return false; var rawRows = this._selectionInterpreter.allRows(selection); var sizeValid = rawRows.length > 2 && // at least two rows are required (besides the separator) rawRows[0].length > 1 && // at least two columns are required rawRows.every(function (r) { return r.length == rawRows[0].length; }); // all rows of a column must match the length of the first row of that column return sizeValid && this.hasValidSeparators(this._selectionInterpreter.separator(selection)); }; TableValidator.prototype.lineIsValidSeparator = function (separatorLine) { return this.hasValidSeparators(this._selectionInterpreter.splitLine(separatorLine)); }; TableValidator.prototype.hasValidSeparators = function (separator) { var _this = this; if (!separator || separator.length < 1 || !separator[1]) return false; // if all columns are dashes, then it is valid var allCellsDash = separator.every(function (cell) { return _this.validSeparator(cell); }); if (allCellsDash) return true; // now it can only be valid of the table starts or ends with a border and the middle columns are dashes return this.allDashesWithBorder(separator); }; TableValidator.prototype.validSeparator = function (cellValue) { var trimmedSpace = cellValue.trim(); // alignment options with dash are allowed if (trimmedSpace[0] == ":") trimmedSpace = trimmedSpace.slice(1); if (trimmedSpace[trimmedSpace.length - 1] == ":") trimmedSpace = trimmedSpace.slice(0, -1); var firstDash = trimmedSpace.replace(/(?!^)-/g, ""); if (firstDash === "-") return true; return false; }; TableValidator.prototype.allDashesWithBorder = function (secondRow) { var _this = this; var hasStartingBorder = secondRow.length >= 3 && secondRow[0].trim() === ""; var hasEndingBorder = secondRow.length >= 3 && secondRow[secondRow.length - 1].trim() === ""; var startIndex = hasStartingBorder ? 1 : 0; var endIndex = hasEndingBorder ? secondRow.length - 2 : secondRow.length - 1; var middleColumns = secondRow.filter(function (v, i) { return i >= startIndex && i <= endIndex; }); var middleColumnsAllDash = middleColumns.every(function (cell) { return _this.validSeparator(cell); }); if (middleColumnsAllDash && (hasStartingBorder || hasEndingBorder)) return true; return false; }; return TableValidator; }()); exports.TableValidator = TableValidator;