react-markdown-table-ts 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -8,6 +8,52 @@ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'defau
8
8
 
9
9
  var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
10
10
 
11
+ /******************************************************************************
12
+ Copyright (c) Microsoft Corporation.
13
+
14
+ Permission to use, copy, modify, and/or distribute this software for any
15
+ purpose with or without fee is hereby granted.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
18
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
19
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
20
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
21
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
22
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
23
+ PERFORMANCE OF THIS SOFTWARE.
24
+ ***************************************************************************** */
25
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
26
+
27
+ var extendStatics = function(d, b) {
28
+ extendStatics = Object.setPrototypeOf ||
29
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
30
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
31
+ return extendStatics(d, b);
32
+ };
33
+
34
+ function __extends(d, b) {
35
+ if (typeof b !== "function" && b !== null)
36
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
37
+ extendStatics(d, b);
38
+ function __() { this.constructor = d; }
39
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
40
+ }
41
+
42
+ function __spreadArray(to, from, pack) {
43
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
44
+ if (ar || !(i in from)) {
45
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
46
+ ar[i] = from[i];
47
+ }
48
+ }
49
+ return to.concat(ar || Array.prototype.slice.call(from));
50
+ }
51
+
52
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
53
+ var e = new Error(message);
54
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
55
+ };
56
+
11
57
  var jsxRuntime = {exports: {}};
12
58
 
13
59
  var reactJsxRuntime_production_min = {};
@@ -1381,61 +1427,21 @@ if (process.env.NODE_ENV === 'production') {
1381
1427
 
1382
1428
  var jsxRuntimeExports = jsxRuntime.exports;
1383
1429
 
1384
- /******************************************************************************
1385
- Copyright (c) Microsoft Corporation.
1386
-
1387
- Permission to use, copy, modify, and/or distribute this software for any
1388
- purpose with or without fee is hereby granted.
1389
-
1390
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1391
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1392
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1393
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1394
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1395
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1396
- PERFORMANCE OF THIS SOFTWARE.
1397
- ***************************************************************************** */
1398
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
1399
-
1400
- var extendStatics = function(d, b) {
1401
- extendStatics = Object.setPrototypeOf ||
1402
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1403
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1404
- return extendStatics(d, b);
1405
- };
1406
-
1407
- function __extends(d, b) {
1408
- if (typeof b !== "function" && b !== null)
1409
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1410
- extendStatics(d, b);
1411
- function __() { this.constructor = d; }
1412
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1413
- }
1414
-
1415
- function __spreadArray(to, from, pack) {
1416
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1417
- if (ar || !(i in from)) {
1418
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1419
- ar[i] = from[i];
1420
- }
1421
- }
1422
- return to.concat(ar || Array.prototype.slice.call(from));
1423
- }
1424
-
1425
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1426
- var e = new Error(message);
1427
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1428
- };
1429
-
1430
- // src/utils.ts
1431
- /**
1432
- * Calculates the maximum width for each column based on the content.
1433
- * @param allRows - All rows (header and body) of the table.
1434
- * @param maxColumnCount - The maximum number of columns in the table.
1435
- * @returns An array of maximum widths for each column.
1436
- */
1430
+ // Error class
1431
+ var MarkdownTableError = /** @class */ (function (_super) {
1432
+ __extends(MarkdownTableError, _super);
1433
+ function MarkdownTableError(message) {
1434
+ var _this = _super.call(this, message) || this;
1435
+ _this.name = 'MarkdownTableError';
1436
+ return _this;
1437
+ }
1438
+ return MarkdownTableError;
1439
+ }(Error));
1440
+ // Styles
1441
+ var prismStyles = "\n code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}\n code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}\n code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}\n @media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}\n pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}\n :not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}\n :not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}\n .token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}\n .token.punctuation{color:#999}\n .token.namespace{opacity:.7}\n .token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}\n .token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}\n .language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}\n .token.atrule,.token.attr-value,.token.keyword{color:#07a}\n .token.class-name,.token.function{color:#dd4a68}\n .token.important,.token.regex,.token.variable{color:#e90}\n .token.bold,.token.important{font-weight:700}\n .token.italic{font-style:italic}\n .token.entity{cursor:help}\n \n /* Line Numbers */\n pre[class*=\"language-\"].line-numbers {\n position: relative;\n padding-left: 3.8em;\n counter-reset: linenumber;\n }\n\n pre[class*=\"language-\"].line-numbers > code {\n position: relative;\n white-space: inherit;\n }\n\n .line-numbers .line-numbers-rows {\n position: absolute;\n pointer-events: none;\n top: 0;\n font-size: 100%;\n left: -3.8em;\n width: 3em; /* works for line-numbers below 1000 lines */\n letter-spacing: -1px;\n border-right: 1px solid #999;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n }\n\n .line-numbers-rows > span {\n display: block;\n counter-increment: linenumber;\n }\n\n .line-numbers-rows > span:before {\n content: counter(linenumber);\n color: #999;\n display: block;\n padding-right: 0.8em;\n text-align: right;\n }\n";
1442
+ // Helper functions
1437
1443
  function calculateColumnWidths(allRows, maxColumnCount) {
1438
- var widths = new Array(maxColumnCount).fill(3); // Minimum width of 3 for each column.
1444
+ var widths = new Array(maxColumnCount).fill(3);
1439
1445
  allRows.forEach(function (row) {
1440
1446
  var _a;
1441
1447
  for (var i = 0; i < maxColumnCount; i++) {
@@ -1445,24 +1451,9 @@ function calculateColumnWidths(allRows, maxColumnCount) {
1445
1451
  });
1446
1452
  return widths;
1447
1453
  }
1448
- /**
1449
- * Replaces newline characters in a string with <br> tags.
1450
- * @param cell - The cell content to process.
1451
- * @returns The processed cell content with newlines replaced.
1452
- */
1453
1454
  function replaceNewlinesInCell(cell) {
1454
1455
  return cell.replace(/\n/g, '<br>');
1455
1456
  }
1456
- /**
1457
- * Formats a single row into a Markdown-formatted string.
1458
- * @param columnCount - The number of columns in the table.
1459
- * @param row - The data of the current row.
1460
- * @param columnAlignments - Alignment settings for each column.
1461
- * @param columnWidths - Widths of each column.
1462
- * @param useTabs - Flag to use tabs between columns.
1463
- * @param replaceNewlines - Flag to replace newlines with <br> tags.
1464
- * @returns The Markdown string for the row.
1465
- */
1466
1457
  function formatMarkdownRow(columnCount, row, columnAlignments, columnWidths, useTabs, replaceNewlines) {
1467
1458
  var _a, _b;
1468
1459
  if (useTabs === void 0) { useTabs = false; }
@@ -1488,20 +1479,11 @@ function formatMarkdownRow(columnCount, row, columnAlignments, columnWidths, use
1488
1479
  markdownRow += "".concat(useTabs ? '\t' : ' ').concat(' '.repeat(paddingLeft)).concat(cell).concat(' '.repeat(paddingRight)).concat(useTabs ? '\t' : ' ', "|");
1489
1480
  }
1490
1481
  else {
1491
- // Left alignment or default
1492
1482
  markdownRow += "".concat(useTabs ? '\t' : ' ').concat(cell.padEnd(targetWidth)).concat(useTabs ? '\t' : ' ', "|");
1493
1483
  }
1494
1484
  }
1495
1485
  return markdownRow;
1496
1486
  }
1497
- /**
1498
- * Generates the alignment row for the Markdown table syntax.
1499
- * @param columnCount - The number of columns in the table.
1500
- * @param columnAlignments - Alignment settings for each column.
1501
- * @param columnWidths - Widths of each column.
1502
- * @param useTabs - Flag to use tabs between columns.
1503
- * @returns The Markdown string for the alignment row.
1504
- */
1505
1487
  function formatAlignmentRow(columnCount, columnAlignments, columnWidths, useTabs) {
1506
1488
  var _a;
1507
1489
  if (useTabs === void 0) { useTabs = false; }
@@ -1531,15 +1513,6 @@ function formatAlignmentRow(columnCount, columnAlignments, columnWidths, useTabs
1531
1513
  }
1532
1514
  return alignmentRow;
1533
1515
  }
1534
- /**
1535
- * Generates a complete Markdown table string from the provided data.
1536
- * @param tableData - The table data including headers and rows.
1537
- * @param columnAlignments - Alignment settings for each column.
1538
- * @param adjustColumnWidths - Flag to adjust column widths based on content.
1539
- * @param useTabs - Flag to use tabs between columns.
1540
- * @param replaceNewlines - Flag to replace newlines with <br> tags.
1541
- * @returns The complete Markdown table string.
1542
- */
1543
1516
  function generateMarkdownTableString(tableData, columnAlignments, adjustColumnWidths, useTabs, replaceNewlines) {
1544
1517
  if (adjustColumnWidths === void 0) { adjustColumnWidths = true; }
1545
1518
  if (useTabs === void 0) { useTabs = false; }
@@ -1557,109 +1530,46 @@ function generateMarkdownTableString(tableData, columnAlignments, adjustColumnWi
1557
1530
  return formatMarkdownRow(maxColumnCount, row, columnAlignments, columnWidths, useTabs, replaceNewlines);
1558
1531
  })
1559
1532
  .join('\n');
1560
- return "".concat(markdownHeaderRow, "\n").concat(markdownAlignmentRow, "\n").concat(markdownBodyRows).trimEnd();
1561
- }
1562
-
1563
- // src/errors.ts
1564
- /**
1565
- * Custom error class for handling Markdown table generation errors.
1566
- */
1567
- var MarkdownTableError = /** @class */ (function (_super) {
1568
- __extends(MarkdownTableError, _super);
1569
- function MarkdownTableError(message) {
1570
- var _this = _super.call(this, message) || this;
1571
- _this.name = 'MarkdownTableError';
1572
- Object.setPrototypeOf(_this, MarkdownTableError.prototype);
1573
- return _this;
1574
- }
1575
- return MarkdownTableError;
1576
- }(Error));
1577
-
1578
- // src/validation.ts
1579
- /**
1580
- * Validates the structure of the table data based on the `hasHeader` flag.
1581
- * Throws an error if validation fails.
1582
- * @param props - The props to validate.
1583
- */
1584
- function validateMarkdownTableProps(props) {
1585
- var data = props.data, _a = props.hasHeader, hasHeader = _a === void 0 ? true : _a, columnAlignments = props.columnAlignments, _b = props.isCompact, isCompact = _b === void 0 ? false : _b, _c = props.hasTabs, hasTabs = _c === void 0 ? false : _c, _d = props.canReplaceNewlines, canReplaceNewlines = _d === void 0 ? false : _d;
1586
- if (!data || !Array.isArray(data)) {
1587
- throw new MarkdownTableError("The 'data' prop must be a non-empty two-dimensional array.");
1588
- }
1589
- if (data.length === 0) {
1590
- throw new MarkdownTableError("The 'data' array must contain at least one row.");
1591
- }
1592
- // If hasHeader is true, ensure the first row exists and is valid
1593
- if (hasHeader) {
1594
- var header = data[0];
1595
- if (!Array.isArray(header) || header.length === 0) {
1596
- throw new MarkdownTableError("The first row of 'data' must be a non-empty array representing the header.");
1597
- }
1598
- // Validate each header cell is a string
1599
- header.forEach(function (cell, index) {
1600
- if (typeof cell !== 'string') {
1601
- throw new MarkdownTableError("Header cell at index ".concat(index, " must be a string."));
1602
- }
1603
- });
1604
- }
1605
- // Validate each row
1606
- data.forEach(function (row, rowIndex) {
1607
- if (!Array.isArray(row)) {
1608
- throw new MarkdownTableError("Row ".concat(rowIndex + 1, " in 'data' must be an array of strings."));
1609
- }
1610
- row.forEach(function (cell, cellIndex) {
1611
- if (typeof cell !== 'string') {
1612
- throw new MarkdownTableError("Cell at row ".concat(rowIndex + 1, ", column ").concat(cellIndex + 1, " must be a string."));
1613
- }
1614
- });
1533
+ var lines = "".concat(markdownHeaderRow, "\n").concat(markdownAlignmentRow, "\n").concat(markdownBodyRows)
1534
+ .trimEnd()
1535
+ .split('\n');
1536
+ var lineNumbers = lines.map(function (_, index) { return "".concat(index + 1); });
1537
+ var maxLineNumberWidth = lineNumbers[lineNumbers.length - 1].length;
1538
+ var numberedLines = lines.map(function (line, index) {
1539
+ var paddedLineNumber = lineNumbers[index].padStart(maxLineNumberWidth, ' ');
1540
+ return "".concat(paddedLineNumber, " | ").concat(line);
1615
1541
  });
1616
- // Validate columnAlignments if provided
1617
- if (columnAlignments) {
1618
- if (!Array.isArray(columnAlignments)) {
1619
- throw new MarkdownTableError("'columnAlignments' must be an array of alignment strings.");
1620
- }
1621
- var validAlignments_1 = ['left', 'center', 'right', 'none'];
1622
- columnAlignments.forEach(function (alignment, index) {
1623
- if (!validAlignments_1.includes(alignment)) {
1624
- throw new MarkdownTableError("Invalid alignment '".concat(alignment, "' at index ").concat(index, ". Valid options are 'left', 'center', 'right', 'none'."));
1625
- }
1626
- });
1627
- }
1628
- // Validate isCompact
1629
- if (typeof isCompact !== 'boolean') {
1630
- throw new MarkdownTableError("'isCompact' must be a boolean.");
1631
- }
1632
- // Validate hasTabs
1633
- if (typeof hasTabs !== 'boolean') {
1634
- throw new MarkdownTableError("'hasTabs' must be a boolean.");
1542
+ return numberedLines.join('\n');
1543
+ }
1544
+ function generateAlphabetHeaders(columnCount) {
1545
+ var headers = [];
1546
+ for (var i = 0; i < columnCount; i++) {
1547
+ headers.push(getColumnName(i));
1635
1548
  }
1636
- // Validate canReplaceNewlines
1637
- if (typeof canReplaceNewlines !== 'boolean') {
1638
- throw new MarkdownTableError("'canReplaceNewlines' must be a boolean.");
1549
+ return headers;
1550
+ }
1551
+ function getColumnName(index) {
1552
+ var name = '';
1553
+ var currentIndex = index;
1554
+ while (currentIndex >= 0) {
1555
+ name = String.fromCharCode((currentIndex % 26) + 65) + name;
1556
+ currentIndex = Math.floor(currentIndex / 26) - 1;
1639
1557
  }
1558
+ return name;
1640
1559
  }
1641
-
1642
- /**
1643
- * React component that generates and displays Markdown table syntax.
1644
- * @param props - The input parameters for table generation.
1645
- * @returns A <pre> element containing the Markdown table syntax or an error message.
1646
- */
1560
+ // Main component
1647
1561
  var MarkdownTable = function (_a) {
1648
- var data = _a.data, _b = _a.hasHeader, hasHeader = _b === void 0 ? true : _b, _c = _a.columnAlignments, columnAlignments = _c === void 0 ? [] : _c, _d = _a.isCompact, isCompact = _d === void 0 ? false : _d, _e = _a.hasTabs, hasTabs = _e === void 0 ? false : _e, _f = _a.canReplaceNewlines, canReplaceNewlines = _f === void 0 ? false : _f, className = _a.className, onTableCreate = _a.onTableCreate;
1649
- // Invert isCompact to get adjustColumnWidths
1562
+ var _b = _a.data, data = _b === void 0 ? null : _b, _c = _a.hasHeader, hasHeader = _c === void 0 ? true : _c, _d = _a.columnAlignments, columnAlignments = _d === void 0 ? [] : _d, _e = _a.isCompact, isCompact = _e === void 0 ? false : _e, _f = _a.hasTabs, hasTabs = _f === void 0 ? false : _f, _g = _a.canReplaceNewlines, canReplaceNewlines = _g === void 0 ? false : _g, className = _a.className, onTableCreate = _a.onTableCreate;
1650
1563
  var adjustColumnWidths = !isCompact;
1651
- // Generate Markdown table
1564
+ var preRef = require$$0.useRef(null);
1652
1565
  var markdownSyntax = require$$0.useMemo(function () {
1566
+ if (data === null) {
1567
+ return 'Error: No data provided for the table.';
1568
+ }
1653
1569
  try {
1654
- validateMarkdownTableProps({
1655
- data: data,
1656
- hasHeader: hasHeader,
1657
- columnAlignments: columnAlignments,
1658
- isCompact: isCompact,
1659
- hasTabs: hasTabs,
1660
- canReplaceNewlines: canReplaceNewlines,
1661
- });
1662
- // Determine header and rows based on hasHeader
1570
+ if (!Array.isArray(data) || data.length === 0) {
1571
+ throw new MarkdownTableError("The 'data' prop must be a non-empty two-dimensional array.");
1572
+ }
1663
1573
  var tableData = hasHeader
1664
1574
  ? {
1665
1575
  header: data[0],
@@ -1692,36 +1602,13 @@ var MarkdownTable = function (_a) {
1692
1602
  onTableCreate(markdownSyntax);
1693
1603
  }
1694
1604
  }, [markdownSyntax, onTableCreate]);
1695
- return jsxRuntimeExports.jsx("pre", { className: className, children: markdownSyntax });
1605
+ require$$0.useEffect(function () {
1606
+ if (preRef.current && window.Prism) {
1607
+ window.Prism.highlightElement(preRef.current.querySelector('code'));
1608
+ }
1609
+ }, [markdownSyntax]);
1610
+ return (jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [jsxRuntimeExports.jsx("style", { children: prismStyles }), jsxRuntimeExports.jsx("pre", { ref: preRef, className: "".concat(className, " language-markdown line-numbers"), children: jsxRuntimeExports.jsx("code", { children: markdownSyntax }) })] }));
1696
1611
  };
1697
- /**
1698
- * Generates alphabetical headers (A, B, C, ...) based on the number of columns.
1699
- * @param columnCount - The number of columns.
1700
- * @returns An array of alphabetical headers.
1701
- */
1702
- function generateAlphabetHeaders(columnCount) {
1703
- var headers = [];
1704
- for (var i = 0; i < columnCount; i++) {
1705
- headers.push(getColumnName(i));
1706
- }
1707
- return headers;
1708
- }
1709
- /**
1710
- * Converts a zero-based column index to its corresponding alphabetical representation.
1711
- * For example, 0 -> 'A', 1 -> 'B', ..., 25 -> 'Z', 26 -> 'AA', etc.
1712
- * @param index - The zero-based column index.
1713
- * @returns The alphabetical column name.
1714
- */
1715
- function getColumnName(index) {
1716
- var name = '';
1717
- var currentIndex = index;
1718
- while (currentIndex >= 0) {
1719
- name = String.fromCharCode((currentIndex % 26) + 65) + name;
1720
- currentIndex = Math.floor(currentIndex / 26) - 1;
1721
- }
1722
- return name;
1723
- }
1724
1612
 
1725
1613
  exports.MarkdownTable = MarkdownTable;
1726
- exports.MarkdownTableError = MarkdownTableError;
1727
1614
  //# sourceMappingURL=index.cjs.js.map