MarkdownTableHelper.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. console.log(performance.now() + ': ReformMarkdownTableInterceptor.process is started');
  35. const orgContext = args[0];
  36. const editor = orgContext.editor;
  37. const curPos = editor.getCursor();
  38. const isEndOfLine = (curPos.ch == editor.getDoc().getLine(curPos.line).length);
  39. console.log(performance.now() + ': curPos.ch=' + curPos.ch + ', curPos.line=' + curPos.line);
  40. // get strings from BOL(beginning of line) to current position
  41. const strFromBol = mtu.getStrFromBol(editor);
  42. if (isEndOfLine && this.linePartOfTableRE.test(strFromBol)) {
  43. const context = Object.assign(args[0]); // clone
  44. const editor = context.editor;
  45. console.log('MarkdownTableHelper.process');
  46. // get lines all of table from current position to beginning of table
  47. const strTableLines = mtu.getStrFromBot(editor);
  48. console.log('strTableLines: ' + strTableLines);
  49. const table = mtu.parseFromTableStringToJSON(editor, mtu.getBot(editor), editor.getCursor());
  50. console.log('table: ' + JSON.stringify(table));
  51. const strTableLinesFormated = table;
  52. console.log('strTableLinesFormated: ' + strTableLinesFormated);
  53. // replace the lines to strFormatedTableLines
  54. editor.getDoc().replaceRange(strTableLinesFormated, mtu.getBot(editor), editor.getCursor());
  55. codemirror.commands.newlineAndIndent(editor);
  56. // report to manager that handling was done
  57. context.handlers.push(this.className);
  58. }
  59. console.log(performance.now() + ': ReformMarkdownTableInterceptor.process is finished');
  60. // resolve
  61. // return Promise.resolve(context);
  62. return Promise.resolve(orgContext);
  63. }
  64. }