MarkdownTable.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import markdownTable from 'markdown-table';
  2. import stringWidth from 'string-width';
  3. import csvToMarkdown from 'csv-to-markdown-table';
  4. // https://github.com/markdown-it/markdown-it/blob/d29f421927e93e88daf75f22089a3e732e195bd2/lib/rules_block/table.js#L83
  5. // https://regex101.com/r/7BN2fR/7
  6. const tableAlignmentLineRE = /^[-:|][-:|\s]*$/;
  7. const tableAlignmentLineNegRE = /^[^-:]*$/; // it is need to check to ignore empty row which is matched above RE
  8. const linePartOfTableRE = /^\|[^\r\n]*|[^\r\n]*\|$|([^|\r\n]+\|[^|\r\n]*)+/; // own idea
  9. // set up DOMParser
  10. const domParser = new (window.DOMParser)();
  11. /**
  12. * markdown table class for markdown-table module
  13. * ref. https://github.com/wooorm/markdown-table
  14. */
  15. export default class MarkdownTable {
  16. constructor(table, options) {
  17. this.table = table || [];
  18. this.options = options || {};
  19. this.toString = this.toString.bind(this);
  20. }
  21. toString() {
  22. return markdownTable(this.table, this.options);
  23. }
  24. /**
  25. * returns cloned Markdowntable instance
  26. * (This method clones only the table field.)
  27. */
  28. clone() {
  29. const newTable = [];
  30. for (let i = 0; i < this.table.length; i++) {
  31. newTable.push([].concat(this.table[i]));
  32. }
  33. return new MarkdownTable(newTable, this.options);
  34. }
  35. /**
  36. * normalize all cell data(trim & convert the newline character to space or pad '' if cell data is null)
  37. */
  38. normalizeCells() {
  39. for (let i = 0; i < this.table.length; i++) {
  40. for (let j = 0; j < this.table[i].length; j++) {
  41. if (this.table[i][j] != null) {
  42. this.table[i][j] = this.table[i][j].trim().replace(/\r?\n/g, ' ');
  43. }
  44. else {
  45. this.table[i][j] = '';
  46. }
  47. }
  48. }
  49. return this;
  50. }
  51. /**
  52. * return a MarkdownTable instance made from a string of HTML table tag
  53. *
  54. * If a parser error occurs, an error object with an error message is thrown.
  55. * The error message is a innerHTML, so must not assign it into element.innerHTML because it can lead to Mutation-based XSS
  56. */
  57. static fromHTMLTableTag(str) {
  58. // use DOMParser to prevent DOM based XSS (https://developer.mozilla.org/en-US/docs/Web/API/DOMParser)
  59. const dom = domParser.parseFromString(str, 'application/xml');
  60. if (dom.querySelector('parsererror')) {
  61. throw new Error(dom.documentElement.innerHTML);
  62. }
  63. const tableElement = dom.querySelector('table');
  64. const trElements = tableElement.querySelectorAll('tr');
  65. const table = [];
  66. let maxRowSize = 0;
  67. for (let i = 0; i < trElements.length; i++) {
  68. const row = [];
  69. const cellElements = trElements[i].querySelectorAll('th,td');
  70. for (let j = 0; j < cellElements.length; j++) {
  71. row.push(cellElements[j].innerHTML);
  72. }
  73. table.push(row);
  74. if (maxRowSize < row.length) maxRowSize = row.length;
  75. }
  76. const align = [];
  77. for (let i = 0; i < maxRowSize; i++) {
  78. align.push('');
  79. }
  80. return new MarkdownTable(table, { align });
  81. }
  82. /**
  83. * return a MarkdownTable instance made from a string of delimiter-separated values
  84. */
  85. static fromDSV(str, delimiter) {
  86. return MarkdownTable.fromMarkdownString(csvToMarkdown(str, delimiter, true));
  87. }
  88. /**
  89. * return a MarkdownTable instance
  90. * ref. https://github.com/wooorm/markdown-table
  91. * @param {string} str markdown string
  92. */
  93. static fromMarkdownString(str) {
  94. const arrMDTableLines = str.split(/(\r\n|\r|\n)/);
  95. const contents = [];
  96. let aligns = [];
  97. for (let n = 0; n < arrMDTableLines.length; n++) {
  98. const line = arrMDTableLines[n];
  99. if (tableAlignmentLineRE.test(line) && !tableAlignmentLineNegRE.test(line)) {
  100. // parse line which described alignment
  101. const alignRuleRE = [
  102. { align: 'c', regex: /^:-+:$/ },
  103. { align: 'l', regex: /^:-+$/ },
  104. { align: 'r', regex: /^-+:$/ },
  105. ];
  106. let lineText = '';
  107. lineText = line.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  108. lineText = lineText.replace(/\s*/g, '');
  109. aligns = lineText.split(/\|/).map((col) => {
  110. const rule = alignRuleRE.find((rule) => { return col.match(rule.regex) });
  111. return (rule != null) ? rule.align : '';
  112. });
  113. }
  114. else if (linePartOfTableRE.test(line)) {
  115. // parse line whether header or body
  116. let lineText = '';
  117. lineText = line.replace(/\s*\|\s*/g, '|');
  118. lineText = lineText.replace(/^\||\|$/g, ''); // strip off pipe charactor which is placed head of line and last of line.
  119. const row = lineText.split(/\|/);
  120. contents.push(row);
  121. }
  122. }
  123. return (new MarkdownTable(contents, { align: aligns, stringLength: stringWidth }));
  124. }
  125. }