MarkdownTableInterceptor.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { BasicInterceptor } from 'crowi-pluginkit';
  2. import mtu from './MarkdownTableUtil';
  3. /**
  4. * Interceptor for markdown table
  5. */
  6. export default class MarkdownTableInterceptor extends BasicInterceptor {
  7. constructor() {
  8. super();
  9. }
  10. /**
  11. * @inheritdoc
  12. */
  13. isInterceptWhen(contextName) {
  14. return (
  15. contextName === 'preHandleEnter'
  16. );
  17. }
  18. /**
  19. * return boolean value whether processable parallel
  20. */
  21. isProcessableParallel() {
  22. return false;
  23. }
  24. /**
  25. * @inheritdoc
  26. */
  27. process(contextName, ...args) {
  28. const context = Object.assign(args[0]); // clone
  29. const editor = context.editor;
  30. // get strings from BOL(beginning of line) to current position
  31. const strFromBol = mtu.getStrFromBol(editor);
  32. if (mtu.isEndOfLine(editor) && mtu.linePartOfTableRE.test(strFromBol)) {
  33. // get lines all of table from current position to beginning of table
  34. const strTableLines = mtu.getStrFromBot(editor);
  35. let table = mtu.parseFromTableStringToMarkdownTable(editor, mtu.getBot(editor), editor.getCursor());
  36. mtu.addRowToMarkdownTable(table);
  37. const curPos = editor.getCursor();
  38. const nextLineHead = { line: curPos.line + 1, ch: 0 };
  39. const tableBottom = mtu.parseFromTableStringToMarkdownTable(editor, nextLineHead, mtu.getEot(editor));
  40. if (tableBottom.table.length > 0) {
  41. table = mtu.mergeMarkdownTable([table, tableBottom]);
  42. }
  43. // replace the lines to strTableLinesFormated
  44. const strTableLinesFormated = table.toString();
  45. editor.getDoc().replaceRange(strTableLinesFormated, mtu.getBot(editor), mtu.getEot(editor));
  46. editor.getDoc().setCursor(curPos.line + 1, 2);
  47. // report to manager that handling was done
  48. context.handlers.push(this.className);
  49. }
  50. // resolve
  51. return Promise.resolve(context);
  52. }
  53. }