MarkdownTableHelper.js 2.3 KB

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