markdown-table.js 4.7 KB

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