GridEditorUtil.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Utility for grid editor
  3. */
  4. class GridEditorUtil {
  5. constructor() {
  6. // https://regex101.com/r/7BN2fR/11
  7. this.lineBeginPartOfGridRE = /^:::(\s.*)editable-row$/;
  8. this.lineEndPartOfGridRE = /^:::$/;
  9. this.replaceGridWithHtmlWithEditor = this.replaceGridWithHtmlWithEditor.bind(this);
  10. }
  11. /**
  12. * return the postion of the BOD(beginning of grid)
  13. */
  14. getBog(editor) {
  15. const curPos = editor.getCursor();
  16. const firstLine = editor.getDoc().firstLine();
  17. if (this.lineBeginPartOfGridRE.test(editor.getDoc().getLine(curPos.line))) {
  18. return { line: curPos.line, ch: 0 };
  19. }
  20. let line = curPos.line - 1;
  21. let isFound = false;
  22. for (; line >= firstLine; line--) {
  23. const strLine = editor.getDoc().getLine(line);
  24. if (this.lineBeginPartOfGridRE.test(strLine)) {
  25. isFound = true;
  26. break;
  27. }
  28. if (this.lineEndPartOfGridRE.test(strLine)) {
  29. isFound = false;
  30. break;
  31. }
  32. }
  33. if (!isFound) {
  34. return { line: curPos.line, ch: curPos.ch };
  35. }
  36. const bodLine = Math.max(firstLine, line);
  37. return { line: bodLine, ch: 0 };
  38. }
  39. /**
  40. * return the postion of the EOD(end of grid)
  41. */
  42. getEog(editor) {
  43. const curPos = editor.getCursor();
  44. const lastLine = editor.getDoc().lastLine();
  45. if (this.lineEndPartOfGridRE.test(editor.getDoc().getLine(curPos.line))) {
  46. return { line: curPos.line, ch: editor.getDoc().getLine(curPos.line).length };
  47. }
  48. let line = curPos.line + 1;
  49. let isFound = false;
  50. for (; line <= lastLine; line++) {
  51. const strLine = editor.getDoc().getLine(line);
  52. if (this.lineEndPartOfGridRE.test(strLine)) {
  53. isFound = true;
  54. break;
  55. }
  56. if (this.lineBeginPartOfGridRE.test(strLine)) {
  57. isFound = false;
  58. break;
  59. }
  60. }
  61. if (!isFound) {
  62. return { line: curPos.line, ch: curPos.ch };
  63. }
  64. const eodLine = Math.min(line, lastLine);
  65. const lineLength = editor.getDoc().getLine(eodLine).length;
  66. return { line: eodLine, ch: lineLength };
  67. }
  68. replaceGridWithHtmlWithEditor(editor, grid) {
  69. const curPos = editor.getCursor();
  70. editor.getDoc().replaceRange(grid.toString(), this.getBog(editor), this.getEog(editor));
  71. editor.getDoc().setCursor(curPos.line + 1, 2);
  72. }
  73. }
  74. // singleton pattern
  75. const instance = new GridEditorUtil();
  76. Object.freeze(instance);
  77. export default instance;