Просмотр исходного кода

Reimplemented MarkdownLinkUtil for CodeMirror v6

Shun Miyazawa 2 лет назад
Родитель
Сommit
21cff07463
1 измененных файлов с 59 добавлено и 0 удалено
  1. 59 0
      packages/editor/src/services/link-util/markdown-link-util.ts

+ 59 - 0
packages/editor/src/services/link-util/markdown-link-util.ts

@@ -0,0 +1,59 @@
+import type { EditorView } from '@codemirror/view';
+
+import Linker from './Linker';
+
+const curPos = (editor: EditorView) => {
+  return editor.state.selection.main.head;
+};
+
+const doc = (editor: EditorView) => {
+  return editor.state.doc;
+};
+
+const getCursorLine = (editor: EditorView) => {
+  return doc(editor).lineAt(curPos(editor));
+
+};
+
+export const isInLink = (editor: EditorView): boolean => {
+  const cursorLine = getCursorLine(editor);
+  const startPos = curPos(editor) - cursorLine.from;
+
+  const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(cursorLine.text, startPos);
+  return beginningOfLink >= 0 && endOfLink >= 0;
+};
+export const getMarkdownLink = (editor: EditorView): Linker => {
+  if (!isInLink(editor)) {
+    const selection = editor?.state.sliceDoc(
+      editor?.state.selection.main.from,
+      editor?.state.selection.main.to,
+    );
+    return Linker.fromMarkdownString(selection);
+  }
+
+  const cursorLine = getCursorLine(editor);
+  const startPos = curPos(editor) - cursorLine.from;
+  return Linker.fromLineWithIndex(cursorLine.text, startPos);
+};
+
+export const replaceFocusedMarkdownLinkWithEditor = (editor: EditorView, linkText: string): void => {
+  editor.dispatch(editor.state.replaceSelection(linkText));
+  // if (!isInLink(editor)) {
+  //   console.log('!isInLink');
+  //   editor.dispatch(editor.state.replaceSelection(linkText));
+  // }
+  // else {
+  //   // editor.dispatch(editor.state.replaceSelection(linkText));
+  //   // console.log('isInLink');
+  //   // const cursorLine = getCursorLine(editor);
+  //   // const startPos = curPos(editor) - cursorLine.from;
+  //   // const { beginningOfLink, endOfLink } = Linker.getBeginningAndEndIndexOfLink(cursorLine.text, startPos);
+  //   // editor.dispatch({
+  //   //   changes: {
+  //   //     from:  { line: cursorLine.number, ch: beginningOfLink },
+  //   //     to: endOfLink,
+  //   //     insert: linkText,
+  //   //   },
+  //   // });
+  // }
+};