MarkdownLinkUtil.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import MarkdownTable from '../../models/MarkdownTable';
  2. /**
  3. * Utility for markdown link
  4. */
  5. class MarkdownLinkUtil {
  6. constructor() {
  7. // TODO Regular expression for link /^([^\r\n|]*)\|(([^\r\n|]*\|)+)$/
  8. this.linePartOfLink = /^\[/;
  9. this.isInTable = this.isInTable.bind(this);
  10. }
  11. getBot(editor) {
  12. const curPos = editor.getCursor();
  13. if (!this.isInTable(editor)) {
  14. return { line: curPos.line, ch: curPos.ch };
  15. }
  16. const firstLine = editor.getDoc().firstLine();
  17. let line = curPos.line - 1;
  18. for (; line >= firstLine; line--) {
  19. const strLine = editor.getDoc().getLine(line);
  20. if (!this.linePartOfTableRE.test(strLine)) {
  21. break;
  22. }
  23. }
  24. const botLine = Math.max(firstLine, line + 1);
  25. return { line: botLine, ch: 0 };
  26. }
  27. /**
  28. * return the postion of the EOT(end of table)
  29. * (If the cursor is not in a table, return its position)
  30. */
  31. getEot(editor) {
  32. const curPos = editor.getCursor();
  33. if (!this.isInTable(editor)) {
  34. return { line: curPos.line, ch: curPos.ch };
  35. }
  36. const lastLine = editor.getDoc().lastLine();
  37. let line = curPos.line + 1;
  38. for (; line <= lastLine; line++) {
  39. const strLine = editor.getDoc().getLine(line);
  40. if (!this.linePartOfTableRE.test(strLine)) {
  41. break;
  42. }
  43. }
  44. const eotLine = Math.min(line - 1, lastLine);
  45. const lineLength = editor.getDoc().getLine(eotLine).length;
  46. return { line: eotLine, ch: lineLength };
  47. }
  48. getMarkdownLink(editor) {
  49. if (!this.isInTable(editor)) {
  50. return null;
  51. }
  52. const strFromBotToEot = editor.getDoc().getRange(this.getBot(editor), this.getEot(editor));
  53. return MarkdownTable.fromMarkdownString(strFromBotToEot);
  54. }
  55. getSelectedTextInEditor(editor) {
  56. return editor.getDoc().getSelection();
  57. }
  58. replaceFocusedMarkdownLinkWithEditor(editor, link) {
  59. editor.getDoc().replaceSelection(link);
  60. }
  61. isInTable(editor) {
  62. const curPos = editor.getCursor();
  63. return this.linePartOfLink.test(editor.getDoc().getLine(curPos.line));
  64. }
  65. }
  66. // singleton pattern
  67. const instance = new MarkdownLinkUtil();
  68. Object.freeze(instance);
  69. export default instance;