MarkdownTableInterceptor.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { BasicInterceptor } from 'growi-commons';
  2. import mtu from './MarkdownTableUtil';
  3. import MarkdownTable from '../../models/MarkdownTable';
  4. /**
  5. * Interceptor for markdown table
  6. */
  7. export default class MarkdownTableInterceptor extends BasicInterceptor {
  8. /**
  9. * @inheritdoc
  10. */
  11. isInterceptWhen(contextName) {
  12. return (
  13. contextName === 'preHandleEnter'
  14. );
  15. }
  16. /**
  17. * return boolean value whether processable parallel
  18. */
  19. isProcessableParallel() {
  20. return false;
  21. }
  22. addRow(cm) {
  23. // get lines all of table from current position to beginning of table
  24. const strFromBot = mtu.getStrFromBot(cm);
  25. let table = MarkdownTable.fromMarkdownString(strFromBot);
  26. mtu.addRowToMarkdownTable(table);
  27. const strToEot = mtu.getStrToEot(cm);
  28. const tableBottom = MarkdownTable.fromMarkdownString(strToEot);
  29. if (tableBottom.table.length > 0) {
  30. table = mtu.mergeMarkdownTable([table, tableBottom]);
  31. }
  32. mtu.replaceMarkdownTableWithReformed(cm, table);
  33. }
  34. reformTable(cm) {
  35. const tableStr = mtu.getStrFromBot(cm) + mtu.getStrToEot(cm);
  36. const table = MarkdownTable.fromMarkdownString(tableStr);
  37. mtu.replaceMarkdownTableWithReformed(cm, table);
  38. }
  39. removeRow(editor) {
  40. editor.replaceLine('\n');
  41. }
  42. /**
  43. * @inheritdoc
  44. */
  45. async process(contextName, ...args) {
  46. const context = Object.assign(args[0]); // clone
  47. const editor = context.editor; // AbstractEditor instance
  48. // do nothing if editor is not a CodeMirrorEditor
  49. if (editor == null || editor.getCodeMirror() == null) {
  50. return context;
  51. }
  52. const cm = editor.getCodeMirror();
  53. const isInTable = mtu.isInTable(cm);
  54. const isLastRow = mtu.getStrToEot(cm) === editor.getStrToEol();
  55. if (isInTable) {
  56. // at EOL in the table
  57. if (mtu.isEndOfLine(cm)) {
  58. this.addRow(cm);
  59. }
  60. // last empty row
  61. else if (isLastRow && mtu.emptyLineOfTableRE.test(editor.getStrFromBol() + editor.getStrToEol())) {
  62. this.removeRow(editor);
  63. }
  64. else {
  65. this.reformTable(cm);
  66. }
  67. // report to manager that handling was done
  68. context.handlers.push(this.className);
  69. return context;
  70. }
  71. }
  72. }