MarkdownTableHelper.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { BasicInterceptor } from 'crowi-pluginkit';
  2. import * as codemirror from 'codemirror';
  3. import markdownTable from 'markdown-table';
  4. import mtu from '../../util/interceptor/MarkdownTableUtil';
  5. /**
  6. * Utility for markdown table
  7. */
  8. export default class MarkdownTableUtil extends BasicInterceptor {
  9. constructor() {
  10. super();
  11. // https://github.com/markdown-it/markdown-it/blob/d29f421927e93e88daf75f22089a3e732e195bd2/lib/rules_block/table.js#L83
  12. // https://regex101.com/r/7BN2fR/7
  13. this.tableAlignmentLineRE = /^[-:|][-:|\s]*$/;
  14. this.linePartOfTableRE = /^\|[^\r\n]*|[^\r\n]*\|$|([^\|\r\n]+\|[^\|\r\n]*)+/; // own idea
  15. }
  16. /**
  17. * @inheritdoc
  18. */
  19. isInterceptWhen(contextName) {
  20. return (
  21. contextName === 'preHandleEnter'
  22. );
  23. }
  24. /**
  25. * return boolean value whether processable parallel
  26. */
  27. isProcessableParallel() {
  28. return false;
  29. }
  30. /**
  31. * @inheritdoc
  32. */
  33. process(contextName, ...args) {
  34. const context = Object.assign(args[0]); // clone
  35. const editor = context.editor;
  36. const curPos = editor.getCursor();
  37. const isEndOfLine = (curPos.ch == editor.getDoc().getLine(curPos.line).length);
  38. // get strings from BOL(beginning of line) to current position
  39. const strFromBol = mtu.getStrFromBol(editor);
  40. if (isEndOfLine && this.linePartOfTableRE.test(strFromBol)) {
  41. // get lines all of table from current position to beginning of table
  42. const strTableLines = mtu.getStrFromBot(editor);
  43. const table = mtu.parseFromTableStringToJSON(editor, mtu.getBot(editor), editor.getCursor());
  44. let newRow = [];
  45. table.table[0].forEach(() => { newRow.push('') });
  46. table.table.push(newRow);
  47. const curPos = editor.getCursor();
  48. const nextLineHead = { line: curPos.line + 1, ch: 0 };
  49. const tableBottom = mtu.parseFromTableStringToJSON(editor, nextLineHead, mtu.getEot(editor));
  50. if (tableBottom.table.length > 0) {
  51. table.table = table.table.concat(tableBottom.table);
  52. }
  53. // replace the lines to strTableLinesFormated
  54. const strTableLinesFormated = markdownTable(table.table, { align: table.align });
  55. editor.getDoc().replaceRange(strTableLinesFormated, mtu.getBot(editor), mtu.getEot(editor));
  56. editor.getDoc().setCursor(curPos.line + 1, 2);
  57. // report to manager that handling was done
  58. context.handlers.push(this.className);
  59. }
  60. // resolve
  61. return Promise.resolve(context);
  62. }
  63. }