Tsv2Table.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. export default class Tsv2Table {
  2. constructor(option) {
  3. if (!option) {
  4. option = {};
  5. }
  6. this.option = option;
  7. this.option.header = this.option.header || false;
  8. }
  9. getCols(codeLines) {
  10. let max = 0;
  11. for (let i = 0; i < codeLines ; i++) {
  12. if (max < codeLines.length) {
  13. max = codeLines.length;
  14. }
  15. }
  16. return max;
  17. }
  18. splitColums(line) {
  19. // \t is replaced to ' ' by Lexer.lex(), so split by 4 spaces
  20. return line.split(/\s{4}/g);
  21. }
  22. getTableHeader(codeLines, option) {
  23. let headers = [];
  24. let headLine = (codeLines[0] || '');
  25. //console.log('head', headLine);
  26. headers = this.splitColums(headLine).map(col => {
  27. return `<th>${Crowi.escape(col)}</th>`;
  28. });
  29. if (headers.length < option.cols) {
  30. headers.concat(new Array(option.cols - headers.length));
  31. }
  32. return `<tr>
  33. ${headers.join('\n')}
  34. </tr>`;
  35. }
  36. getTableBody(codeLines, option) {
  37. let rows;
  38. if (this.option.header) {
  39. codeLines.shift();
  40. }
  41. rows = codeLines.map(row => {
  42. const cols = this.splitColums(row).map(col => {
  43. return `<td>${Crowi.escape(col)}</td>`;
  44. }).join('');
  45. return `<tr>${cols}</tr>`;
  46. });
  47. return rows.join('\n');
  48. }
  49. process(code) {
  50. let option = {};
  51. const codeLines = code.split(/\n|\r/);
  52. option.cols = this.getCols(codeLines);
  53. let header = '';
  54. if (this.option.header) {
  55. header = `<thead>
  56. ${this.getTableHeader(codeLines, option)}
  57. </thead>`;
  58. }
  59. return `<table>
  60. ${header}
  61. <tbody>
  62. ${this.getTableBody(codeLines, option)}
  63. </tbody>
  64. </table>`;
  65. }
  66. }