Tsv2Table.js 1.7 KB

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