MarkdownLinkUtil.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Linker from '~/client/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, linkText) {
  26. const curPos = editor.getCursor();
  27. if (!this.isInLink(editor)) {
  28. editor.getDoc().replaceSelection(linkText);
  29. }
  30. else {
  31. const line = editor.getDoc().getLine(curPos.line);
  32. const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(line, curPos.ch);
  33. editor.getDoc().replaceRange(linkText, { line: curPos.line, ch: beginningOfLink }, { line: curPos.line, ch: endOfLink });
  34. }
  35. }
  36. }
  37. // singleton pattern
  38. const instance = new MarkdownLinkUtil();
  39. Object.freeze(instance);
  40. export default instance;