GridEditorUtil.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Utility for grid editor
  3. */
  4. class GridEditorUtil {
  5. constructor() {
  6. // TODO url
  7. this.lineBeginPartOfGridRE = /(<[^/].*>)/;
  8. this.lineEndPartOfGridRE = /(<\/.*>)/;
  9. this.linePartOfGridRE = /(<.*>)[\s\S]*<\/.*>$/;
  10. this.replaceGridWithHtmlWithEditor = this.replaceGridWithHtmlWithEditor.bind(this);
  11. }
  12. /**
  13. * return the postion of the BOD(beginning of grid)
  14. */
  15. getBog(editor) {
  16. const curPos = editor.getCursor();
  17. const firstLine = editor.getDoc().firstLine();
  18. let line = curPos.line - 1;
  19. let isFound = false;
  20. for (; line >= firstLine; line--) {
  21. const strLine = editor.getDoc().getLine(line);
  22. if (this.linePartOfGridRE.test(strLine)) {
  23. isFound = true;
  24. break;
  25. }
  26. if (this.linePartOfGridRE.test(strLine)) {
  27. isFound = false;
  28. break;
  29. }
  30. }
  31. if (!isFound) {
  32. return { line: curPos.line, ch: curPos.ch };
  33. }
  34. const bodLine = Math.max(firstLine, line);
  35. return { line: bodLine, ch: 0 };
  36. }
  37. /**
  38. * return the postion of the EOD(end of grid)
  39. */
  40. getEog(editor) {
  41. const curPos = editor.getCursor();
  42. const lastLine = editor.getDoc().lastLine();
  43. let line = curPos.line + 1;
  44. let isFound = false;
  45. for (; line <= lastLine; line++) {
  46. const strLine = editor.getDoc().getLine(line);
  47. if (this.linePartOfGridRE.test(strLine)) {
  48. isFound = true;
  49. break;
  50. }
  51. if (this.lineBeginPartOfDrawioRE.test(strLine)) {
  52. isFound = false;
  53. break;
  54. }
  55. }
  56. if (!isFound) {
  57. return { line: curPos.line, ch: curPos.ch };
  58. }
  59. const eodLine = Math.min(line, lastLine);
  60. const lineLength = editor.getDoc().getLine(eodLine).length;
  61. return { line: eodLine, ch: lineLength };
  62. // return { line: lastLine, ch: curPos.ch };
  63. }
  64. replaceGridWithHtmlWithEditor(editor, grid) {
  65. const curPos = editor.getCursor();
  66. console.log('getBog');
  67. console.log(this.getBog(editor));
  68. console.log('getEog');
  69. console.log(this.getEog(editor));
  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;