MarkdownLinkUtil.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import Linker from '../../models/Linker';
  2. /**
  3. * Utility for markdown link
  4. */
  5. class MarkdownLinkUtil {
  6. constructor() {
  7. this.getMarkdownLink = this.getMarkdownLink.bind(this);
  8. this.isInLink = this.isInLink.bind(this);
  9. this.replaceFocusedMarkdownLinkWithEditor = this.replaceFocusedMarkdownLinkWithEditor.bind(this);
  10. }
  11. // return an instance of Linker from cursor position or selected text.
  12. getMarkdownLink(editor) {
  13. if (!this.isInLink(editor)) {
  14. return Linker.fromMarkdownString(editor.getDoc().getSelection());
  15. }
  16. const curPos = editor.getCursor();
  17. return Linker.fromLineWithIndex(editor.getDoc().getLine(curPos.line), curPos.ch);
  18. }
  19. isInLink(editor) {
  20. const curPos = editor.getCursor();
  21. const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(editor.getDoc().getLine(curPos.line), curPos.ch);
  22. return beginningOfLink >= 0 && endOfLink >= 0;
  23. }
  24. // replace link(link is an instance of Linker)
  25. replaceFocusedMarkdownLinkWithEditor(editor, link) {
  26. const curPos = editor.getCursor();
  27. const linkStr = link.generateMarkdownText();
  28. if (!this.isInLink(editor)) {
  29. editor.getDoc().replaceSelection(linkStr);
  30. }
  31. else {
  32. const line = editor.getDoc().getLine(curPos.line);
  33. const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(line, curPos.ch);
  34. editor.getDoc().replaceRange(linkStr, { line: curPos.line, ch: beginningOfLink }, { line: curPos.line, ch: endOfLink });
  35. }
  36. }
  37. }
  38. // singleton pattern
  39. const instance = new MarkdownLinkUtil();
  40. Object.freeze(instance);
  41. export default instance;