markdown-link-util.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { EditorView } from '@codemirror/view';
  2. import Linker from './Linker';
  3. const curPos = (editor: EditorView) => {
  4. return editor.state.selection.main.head;
  5. };
  6. const doc = (editor: EditorView) => {
  7. return editor.state.doc;
  8. };
  9. const getCursorLine = (editor: EditorView) => {
  10. return doc(editor).lineAt(curPos(editor));
  11. };
  12. export const isInLink = (editor: EditorView): boolean => {
  13. const cursorLine = getCursorLine(editor);
  14. const startPos = curPos(editor) - cursorLine.from;
  15. const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(cursorLine.text, startPos);
  16. return beginningOfLink >= 0 && endOfLink >= 0;
  17. };
  18. export const getMarkdownLink = (editor: EditorView): Linker => {
  19. if (!isInLink(editor)) {
  20. const selection = editor?.state.sliceDoc(
  21. editor?.state.selection.main.from,
  22. editor?.state.selection.main.to,
  23. );
  24. return Linker.fromMarkdownString(selection);
  25. }
  26. const cursorLine = getCursorLine(editor);
  27. const startPos = curPos(editor) - cursorLine.from;
  28. return Linker.fromLineWithIndex(cursorLine.text, startPos);
  29. };
  30. export const replaceFocusedMarkdownLinkWithEditor = (editor: EditorView, linkText: string): void => {
  31. editor.dispatch(editor.state.replaceSelection(linkText));
  32. // if (!isInLink(editor)) {
  33. // console.log('!isInLink');
  34. // editor.dispatch(editor.state.replaceSelection(linkText));
  35. // }
  36. // else {
  37. // // editor.dispatch(editor.state.replaceSelection(linkText));
  38. // // console.log('isInLink');
  39. // // const cursorLine = getCursorLine(editor);
  40. // // const startPos = curPos(editor) - cursorLine.from;
  41. // // const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(cursorLine.text, startPos);
  42. // // editor.dispatch({
  43. // // changes: {
  44. // // from: { line: cursorLine.number, ch: beginningOfLink },
  45. // // to: endOfLink,
  46. // // insert: linkText,
  47. // // },
  48. // // });
  49. // }
  50. };