MarkdownTableInterceptor.js 2.1 KB

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