MarkdownTableInterceptor.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { BasicInterceptor } from '@growi/core';
  2. import MarkdownTable from '~/client/models/MarkdownTable';
  3. import mtu from './MarkdownTableUtil';
  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. // "autoFormatMarkdownTable" may be undefined, so it is compared to true and converted to bool.
  49. const noIntercept = (context.autoFormatMarkdownTable === false);
  50. // do nothing if editor is not a CodeMirrorEditor or no intercept
  51. if (editor == null || editor.getCodeMirror() == null || noIntercept) {
  52. return context;
  53. }
  54. const cm = editor.getCodeMirror();
  55. const isInTable = mtu.isInTable(cm);
  56. const isLastRow = mtu.getStrToEot(cm) === editor.getStrToEol();
  57. if (isInTable) {
  58. // at EOL in the table
  59. if (mtu.isEndOfLine(cm)) {
  60. this.addRow(cm);
  61. }
  62. // last empty row
  63. else if (isLastRow && mtu.emptyLineOfTableRE.test(editor.getStrFromBol() + editor.getStrToEol())) {
  64. this.removeRow(editor);
  65. }
  66. else {
  67. this.reformTable(cm);
  68. }
  69. // report to manager that handling was done
  70. context.handlers.push(this.className);
  71. return context;
  72. }
  73. }
  74. }