react-markdown-table-ts 0.2.1 → 0.2.3

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.esm.js CHANGED
@@ -1,4 +1,50 @@
1
- import require$$0, { useMemo, useEffect } from 'react';
1
+ import require$$0, { useRef, useMemo, useEffect } from 'react';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
18
+
19
+ var extendStatics = function(d, b) {
20
+ extendStatics = Object.setPrototypeOf ||
21
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
22
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
23
+ return extendStatics(d, b);
24
+ };
25
+
26
+ function __extends(d, b) {
27
+ if (typeof b !== "function" && b !== null)
28
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
29
+ extendStatics(d, b);
30
+ function __() { this.constructor = d; }
31
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
32
+ }
33
+
34
+ function __spreadArray(to, from, pack) {
35
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
36
+ if (ar || !(i in from)) {
37
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
38
+ ar[i] = from[i];
39
+ }
40
+ }
41
+ return to.concat(ar || Array.prototype.slice.call(from));
42
+ }
43
+
44
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
45
+ var e = new Error(message);
46
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
+ };
2
48
 
3
49
  var jsxRuntime = {exports: {}};
4
50
 
@@ -1373,61 +1419,21 @@ if (process.env.NODE_ENV === 'production') {
1373
1419
 
1374
1420
  var jsxRuntimeExports = jsxRuntime.exports;
1375
1421
 
1376
- /******************************************************************************
1377
- Copyright (c) Microsoft Corporation.
1378
-
1379
- Permission to use, copy, modify, and/or distribute this software for any
1380
- purpose with or without fee is hereby granted.
1381
-
1382
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1383
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1384
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1385
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1386
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1387
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1388
- PERFORMANCE OF THIS SOFTWARE.
1389
- ***************************************************************************** */
1390
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
1391
-
1392
- var extendStatics = function(d, b) {
1393
- extendStatics = Object.setPrototypeOf ||
1394
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1395
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1396
- return extendStatics(d, b);
1397
- };
1398
-
1399
- function __extends(d, b) {
1400
- if (typeof b !== "function" && b !== null)
1401
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1402
- extendStatics(d, b);
1403
- function __() { this.constructor = d; }
1404
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1405
- }
1406
-
1407
- function __spreadArray(to, from, pack) {
1408
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1409
- if (ar || !(i in from)) {
1410
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1411
- ar[i] = from[i];
1412
- }
1413
- }
1414
- return to.concat(ar || Array.prototype.slice.call(from));
1415
- }
1416
-
1417
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1418
- var e = new Error(message);
1419
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1420
- };
1421
-
1422
- // src/utils.ts
1423
- /**
1424
- * Calculates the maximum width for each column based on the content.
1425
- * @param allRows - All rows (header and body) of the table.
1426
- * @param maxColumnCount - The maximum number of columns in the table.
1427
- * @returns An array of maximum widths for each column.
1428
- */
1422
+ // Error class
1423
+ var MarkdownTableError = /** @class */ (function (_super) {
1424
+ __extends(MarkdownTableError, _super);
1425
+ function MarkdownTableError(message) {
1426
+ var _this = _super.call(this, message) || this;
1427
+ _this.name = 'MarkdownTableError';
1428
+ return _this;
1429
+ }
1430
+ return MarkdownTableError;
1431
+ }(Error));
1432
+ // Styles
1433
+ 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";
1434
+ // Helper functions
1429
1435
  function calculateColumnWidths(allRows, maxColumnCount) {
1430
- var widths = new Array(maxColumnCount).fill(3); // Minimum width of 3 for each column.
1436
+ var widths = new Array(maxColumnCount).fill(3);
1431
1437
  allRows.forEach(function (row) {
1432
1438
  var _a;
1433
1439
  for (var i = 0; i < maxColumnCount; i++) {
@@ -1437,24 +1443,9 @@ function calculateColumnWidths(allRows, maxColumnCount) {
1437
1443
  });
1438
1444
  return widths;
1439
1445
  }
1440
- /**
1441
- * Replaces newline characters in a string with <br> tags.
1442
- * @param cell - The cell content to process.
1443
- * @returns The processed cell content with newlines replaced.
1444
- */
1445
1446
  function replaceNewlinesInCell(cell) {
1446
1447
  return cell.replace(/\n/g, '<br>');
1447
1448
  }
1448
- /**
1449
- * Formats a single row into a Markdown-formatted string.
1450
- * @param columnCount - The number of columns in the table.
1451
- * @param row - The data of the current row.
1452
- * @param columnAlignments - Alignment settings for each column.
1453
- * @param columnWidths - Widths of each column.
1454
- * @param useTabs - Flag to use tabs between columns.
1455
- * @param replaceNewlines - Flag to replace newlines with <br> tags.
1456
- * @returns The Markdown string for the row.
1457
- */
1458
1449
  function formatMarkdownRow(columnCount, row, columnAlignments, columnWidths, useTabs, replaceNewlines) {
1459
1450
  var _a, _b;
1460
1451
  if (useTabs === void 0) { useTabs = false; }
@@ -1480,20 +1471,11 @@ function formatMarkdownRow(columnCount, row, columnAlignments, columnWidths, use
1480
1471
  markdownRow += "".concat(useTabs ? '\t' : ' ').concat(' '.repeat(paddingLeft)).concat(cell).concat(' '.repeat(paddingRight)).concat(useTabs ? '\t' : ' ', "|");
1481
1472
  }
1482
1473
  else {
1483
- // Left alignment or default
1484
1474
  markdownRow += "".concat(useTabs ? '\t' : ' ').concat(cell.padEnd(targetWidth)).concat(useTabs ? '\t' : ' ', "|");
1485
1475
  }
1486
1476
  }
1487
1477
  return markdownRow;
1488
1478
  }
1489
- /**
1490
- * Generates the alignment row for the Markdown table syntax.
1491
- * @param columnCount - The number of columns in the table.
1492
- * @param columnAlignments - Alignment settings for each column.
1493
- * @param columnWidths - Widths of each column.
1494
- * @param useTabs - Flag to use tabs between columns.
1495
- * @returns The Markdown string for the alignment row.
1496
- */
1497
1479
  function formatAlignmentRow(columnCount, columnAlignments, columnWidths, useTabs) {
1498
1480
  var _a;
1499
1481
  if (useTabs === void 0) { useTabs = false; }
@@ -1523,15 +1505,6 @@ function formatAlignmentRow(columnCount, columnAlignments, columnWidths, useTabs
1523
1505
  }
1524
1506
  return alignmentRow;
1525
1507
  }
1526
- /**
1527
- * Generates a complete Markdown table string from the provided data.
1528
- * @param tableData - The table data including headers and rows.
1529
- * @param columnAlignments - Alignment settings for each column.
1530
- * @param adjustColumnWidths - Flag to adjust column widths based on content.
1531
- * @param useTabs - Flag to use tabs between columns.
1532
- * @param replaceNewlines - Flag to replace newlines with <br> tags.
1533
- * @returns The complete Markdown table string.
1534
- */
1535
1508
  function generateMarkdownTableString(tableData, columnAlignments, adjustColumnWidths, useTabs, replaceNewlines) {
1536
1509
  if (adjustColumnWidths === void 0) { adjustColumnWidths = true; }
1537
1510
  if (useTabs === void 0) { useTabs = false; }
@@ -1549,112 +1522,44 @@ function generateMarkdownTableString(tableData, columnAlignments, adjustColumnWi
1549
1522
  return formatMarkdownRow(maxColumnCount, row, columnAlignments, columnWidths, useTabs, replaceNewlines);
1550
1523
  })
1551
1524
  .join('\n');
1552
- return "".concat(markdownHeaderRow, "\n").concat(markdownAlignmentRow, "\n").concat(markdownBodyRows).trimEnd();
1553
- }
1554
-
1555
- // src/errors.ts
1556
- /**
1557
- * Custom error class for handling Markdown table generation errors.
1558
- */
1559
- var MarkdownTableError = /** @class */ (function (_super) {
1560
- __extends(MarkdownTableError, _super);
1561
- function MarkdownTableError(message) {
1562
- var _this = _super.call(this, message) || this;
1563
- _this.name = 'MarkdownTableError';
1564
- Object.setPrototypeOf(_this, MarkdownTableError.prototype);
1565
- return _this;
1566
- }
1567
- return MarkdownTableError;
1568
- }(Error));
1569
-
1570
- // src/validation.ts
1571
- /**
1572
- * Validates the structure of the table data based on the `hasHeader` flag.
1573
- * Throws an error if validation fails.
1574
- * @param props - The props to validate.
1575
- */
1576
- function validateMarkdownTableProps(props) {
1577
- 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;
1578
- if (!Array.isArray(data)) {
1579
- throw new MarkdownTableError("The 'data' prop must be a two-dimensional array.");
1580
- }
1581
- if (data.length === 0) {
1582
- throw new MarkdownTableError("The 'data' array must contain at least one row.");
1583
- }
1584
- // If hasHeader is true, ensure the first row exists and is valid
1585
- if (hasHeader) {
1586
- var header = data[0];
1587
- if (!Array.isArray(header) || header.length === 0) {
1588
- throw new MarkdownTableError("The first row of 'data' must be a non-empty array representing the header.");
1589
- }
1590
- // Validate each header cell is a string
1591
- header.forEach(function (cell, index) {
1592
- if (typeof cell !== 'string') {
1593
- throw new MarkdownTableError("Header cell at index ".concat(index, " must be a string."));
1594
- }
1595
- });
1596
- }
1597
- // Validate each row
1598
- data.forEach(function (row, rowIndex) {
1599
- if (!Array.isArray(row)) {
1600
- throw new MarkdownTableError("Row ".concat(rowIndex + 1, " in 'data' must be an array of strings."));
1601
- }
1602
- row.forEach(function (cell, cellIndex) {
1603
- if (typeof cell !== 'string') {
1604
- throw new MarkdownTableError("Cell at row ".concat(rowIndex + 1, ", column ").concat(cellIndex + 1, " must be a string."));
1605
- }
1606
- });
1525
+ var lines = "".concat(markdownHeaderRow, "\n").concat(markdownAlignmentRow, "\n").concat(markdownBodyRows).trimEnd().split('\n');
1526
+ var lineNumbers = lines.map(function (_, index) { return "".concat(index + 1); });
1527
+ var maxLineNumberWidth = lineNumbers[lineNumbers.length - 1].length;
1528
+ var numberedLines = lines.map(function (line, index) {
1529
+ var paddedLineNumber = lineNumbers[index].padStart(maxLineNumberWidth, ' ');
1530
+ return "".concat(paddedLineNumber, " | ").concat(line);
1607
1531
  });
1608
- // Validate columnAlignments if provided
1609
- if (columnAlignments) {
1610
- if (!Array.isArray(columnAlignments)) {
1611
- throw new MarkdownTableError("'columnAlignments' must be an array of alignment strings.");
1612
- }
1613
- var validAlignments_1 = ['left', 'center', 'right', 'none'];
1614
- columnAlignments.forEach(function (alignment, index) {
1615
- if (!validAlignments_1.includes(alignment)) {
1616
- throw new MarkdownTableError("Invalid alignment '".concat(alignment, "' at index ").concat(index, ". Valid options are 'left', 'center', 'right', 'none'."));
1617
- }
1618
- });
1619
- }
1620
- // Validate isCompact
1621
- if (typeof isCompact !== 'boolean') {
1622
- throw new MarkdownTableError("'isCompact' must be a boolean.");
1623
- }
1624
- // Validate hasTabs
1625
- if (typeof hasTabs !== 'boolean') {
1626
- throw new MarkdownTableError("'hasTabs' must be a boolean.");
1532
+ return numberedLines.join('\n');
1533
+ }
1534
+ function generateAlphabetHeaders(columnCount) {
1535
+ var headers = [];
1536
+ for (var i = 0; i < columnCount; i++) {
1537
+ headers.push(getColumnName(i));
1627
1538
  }
1628
- // Validate canReplaceNewlines
1629
- if (typeof canReplaceNewlines !== 'boolean') {
1630
- throw new MarkdownTableError("'canReplaceNewlines' must be a boolean.");
1539
+ return headers;
1540
+ }
1541
+ function getColumnName(index) {
1542
+ var name = '';
1543
+ var currentIndex = index;
1544
+ while (currentIndex >= 0) {
1545
+ name = String.fromCharCode((currentIndex % 26) + 65) + name;
1546
+ currentIndex = Math.floor(currentIndex / 26) - 1;
1631
1547
  }
1548
+ return name;
1632
1549
  }
1633
-
1634
- /**
1635
- * React component that generates and displays Markdown table syntax.
1636
- * @param props - The input parameters for table generation.
1637
- * @returns A <pre> element containing the Markdown table syntax or an error message.
1638
- */
1550
+ // Main component
1639
1551
  var MarkdownTable = function (_a) {
1640
1552
  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;
1641
- // Invert isCompact to get adjustColumnWidths
1642
1553
  var adjustColumnWidths = !isCompact;
1643
- // Generate Markdown table
1554
+ var preRef = useRef(null);
1644
1555
  var markdownSyntax = useMemo(function () {
1645
1556
  if (data === null) {
1646
1557
  return 'Error: No data provided for the table.';
1647
1558
  }
1648
1559
  try {
1649
- validateMarkdownTableProps({
1650
- data: data,
1651
- hasHeader: hasHeader,
1652
- columnAlignments: columnAlignments,
1653
- isCompact: isCompact,
1654
- hasTabs: hasTabs,
1655
- canReplaceNewlines: canReplaceNewlines,
1656
- });
1657
- // Determine header and rows based on hasHeader
1560
+ if (!Array.isArray(data) || data.length === 0) {
1561
+ throw new MarkdownTableError("The 'data' prop must be a non-empty two-dimensional array.");
1562
+ }
1658
1563
  var tableData = hasHeader
1659
1564
  ? {
1660
1565
  header: data[0],
@@ -1687,35 +1592,13 @@ var MarkdownTable = function (_a) {
1687
1592
  onTableCreate(markdownSyntax);
1688
1593
  }
1689
1594
  }, [markdownSyntax, onTableCreate]);
1690
- return jsxRuntimeExports.jsx("pre", { className: className, children: markdownSyntax });
1595
+ useEffect(function () {
1596
+ if (preRef.current && window.Prism) {
1597
+ window.Prism.highlightElement(preRef.current.querySelector('code'));
1598
+ }
1599
+ }, [markdownSyntax]);
1600
+ 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 }) })] }));
1691
1601
  };
1692
- /**
1693
- * Generates alphabetical headers (A, B, C, ...) based on the number of columns.
1694
- * @param columnCount - The number of columns.
1695
- * @returns An array of alphabetical headers.
1696
- */
1697
- function generateAlphabetHeaders(columnCount) {
1698
- var headers = [];
1699
- for (var i = 0; i < columnCount; i++) {
1700
- headers.push(getColumnName(i));
1701
- }
1702
- return headers;
1703
- }
1704
- /**
1705
- * Converts a zero-based column index to its corresponding alphabetical representation.
1706
- * For example, 0 -> 'A', 1 -> 'B', ..., 25 -> 'Z', 26 -> 'AA', etc.
1707
- * @param index - The zero-based column index.
1708
- * @returns The alphabetical column name.
1709
- */
1710
- function getColumnName(index) {
1711
- var name = '';
1712
- var currentIndex = index;
1713
- while (currentIndex >= 0) {
1714
- name = String.fromCharCode((currentIndex % 26) + 65) + name;
1715
- currentIndex = Math.floor(currentIndex / 26) - 1;
1716
- }
1717
- return name;
1718
- }
1719
1602
 
1720
- export { MarkdownTable, MarkdownTableError };
1603
+ export { MarkdownTable };
1721
1604
  //# sourceMappingURL=index.esm.js.map