You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@answer.apache.org by ro...@apache.org on 2024/04/03 10:03:14 UTC

(incubator-answer) 04/04: refactor(ui): Migrate CodeMirror 5 to 6

This is an automated email from the ASF dual-hosted git repository.

robin0716 pushed a commit to branch refactor/editor
in repository https://gitbox.apache.org/repos/asf/incubator-answer.git

commit d421681ddbd932a9d496fc89a77c32188d8013c9
Author: robin <ro...@rnode.me>
AuthorDate: Wed Apr 3 18:02:58 2024 +0800

    refactor(ui): Migrate CodeMirror 5 to 6
---
 ui/src/components/Editor/utils/index.ts | 412 +++++++++++++++++++++-----------
 1 file changed, 278 insertions(+), 134 deletions(-)

diff --git a/ui/src/components/Editor/utils/index.ts b/ui/src/components/Editor/utils/index.ts
index 4930c768..6debb3dc 100644
--- a/ui/src/components/Editor/utils/index.ts
+++ b/ui/src/components/Editor/utils/index.ts
@@ -1,3 +1,4 @@
+/* eslint-disable */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
@@ -17,87 +18,15 @@
  * under the License.
  */
 
-import { useEffect, useState, useRef } from 'react';
+import { useEffect, useState } from 'react';
 
-import type { Editor, Position } from 'codemirror';
+import type { Position } from 'codemirror';
+import { EditorSelection, EditorState, StateEffect } from '@codemirror/state';
+import { EditorView, keymap, KeyBinding, Command } from '@codemirror/view';
+import { markdown } from '@codemirror/lang-markdown';
 import type CodeMirror from 'codemirror';
 import 'codemirror/lib/codemirror.css';
 
-export function createEditorUtils(
-  codemirror: typeof CodeMirror,
-  editor: Editor,
-) {
-  editor.wrapText = (before: string, after = before, defaultText) => {
-    const range = editor.somethingSelected()
-      ? editor.listSelections()[0]
-      : editor.findWordAt(editor.getCursor());
-
-    const from = range.from();
-    const to = range.to();
-    const text = editor.getRange(from, to) || defaultText;
-    const fromBefore = codemirror.Pos(from.line, from.ch - before.length);
-    const toAfter = codemirror.Pos(to.line, to.ch + after.length);
-
-    if (
-      editor.getRange(fromBefore, from) === before &&
-      editor.getRange(to, toAfter) === after
-    ) {
-      editor.replaceRange(text, fromBefore, toAfter);
-      editor.setSelection(
-        fromBefore,
-        codemirror.Pos(fromBefore.line, fromBefore.ch + text.length),
-      );
-    } else {
-      editor.replaceRange(before + text + after, from, to);
-      const cursor = editor.getCursor();
-
-      editor.setSelection(
-        codemirror.Pos(cursor.line, cursor.ch - after.length - text.length),
-        codemirror.Pos(cursor.line, cursor.ch - after.length),
-      );
-    }
-  };
-  editor.replaceLines = (
-    replace: Parameters<Array<string>['map']>[0],
-    symbolLen = 0,
-  ) => {
-    const [selection] = editor.listSelections();
-
-    const range = [
-      codemirror.Pos(selection.from().line, 0),
-      codemirror.Pos(selection.to().line),
-    ] as const;
-    const lines = editor.getRange(...range).split('\n');
-
-    editor.replaceRange(lines.map(replace).join('\n'), ...range);
-    const newRange = range;
-
-    if (symbolLen > 0) {
-      newRange[0].ch = symbolLen;
-    }
-    editor.setSelection(...newRange);
-  };
-  editor.appendBlock = (content: string): Position => {
-    const cursor = editor.getCursor();
-
-    let emptyLine = -1;
-
-    for (let i = cursor.line; i < editor.lineCount(); i += 1) {
-      if (!editor.getLine(i).trim()) {
-        emptyLine = i;
-        break;
-      }
-    }
-    if (emptyLine === -1) {
-      editor.replaceRange('\n', codemirror.Pos(editor.lineCount()));
-      emptyLine = editor.lineCount();
-    }
-
-    editor.replaceRange(`\n${content}`, codemirror.Pos(emptyLine));
-    return codemirror.Pos(emptyLine + 1, 0);
-  };
-}
-
 export function htmlRender(el: HTMLElement | null) {
   if (!el) return;
   // Replace all br tags with newlines
@@ -137,7 +66,243 @@ export function htmlRender(el: HTMLElement | null) {
     }
   });
 }
+export interface ExtendEditor {
+  addKeyMap: (keyMap: Record<string, Command>) => void;
+  on: (
+    event:
+      | 'change'
+      | 'focus'
+      | 'blur'
+      | 'dragenter'
+      | 'dragover'
+      | 'drop'
+      | 'paste',
+    callback: (e?) => void,
+  ) => void;
+  getValue: () => string;
+  setValue: (value: string) => void;
+  off: (
+    event:
+      | 'change'
+      | 'focus'
+      | 'blur'
+      | 'dragenter'
+      | 'dragover'
+      | 'drop'
+      | 'paste',
+    callback: (e?) => void,
+  ) => void;
+  getSelection: () => string;
+  replaceSelection: (value: string) => void;
+  focus: () => void;
+  wrapText: (before: string, after?: string, defaultText?: string) => void;
+  replaceLines: (
+    replace: Parameters<Array<string>['map']>[0],
+    symbolLen?: number,
+  ) => void;
+  appendBlock: (content: string) => Position;
+  getCursor: () => Position;
+  replaceRange: (value: string, from: Position, to: Position) => void;
+}
+
+const createEditorUtils = (editor: EditorView & ExtendEditor) => {
+  editor.focus = () => {
+    editor.contentDOM.focus();
+  };
+
+  editor.getCursor = () => {
+    const range = editor.state.selection.ranges[0];
+    const line = editor.state.doc.lineAt(range.from).number;
+    const from = editor.state.doc.line(line).from;
+    const to = editor.state.doc.line(line).to;
+    return { from, to, ch: range.from - from };
+  };
+
+  editor.addKeyMap = (keyMap) => {
+    const array = Object.entries(keyMap).map(([key, value]) => {
+      const keyBinding: KeyBinding = {
+        key,
+        preventDefault: true,
+        run: value,
+      };
+      return keyBinding;
+    });
+
+    editor.dispatch({
+      effects: StateEffect.appendConfig.of(keymap.of(array)),
+    });
+  };
+
+  editor.getSelection = () => {
+    return editor.state.sliceDoc(
+      editor.state.selection.main.from,
+      editor.state.selection.main.to,
+    );
+  };
+
+  editor.replaceSelection = (value: string) => {
+    editor.dispatch({
+      changes: [
+        {
+          from: editor.state.selection.main.from,
+          to: editor.state.selection.main.to,
+          insert: value,
+        },
+      ],
+      selection: EditorSelection.cursor(
+        editor.state.selection.main.from + value.length,
+      ),
+    });
+  };
+
+  editor.on = (event, callback) => {
+    if (event === 'change') {
+      const change = EditorView.updateListener.of((update) => {
+        if (update.docChanged) {
+          callback();
+        }
+      });
+
+      editor.dispatch({
+        effects: StateEffect.appendConfig.of(change),
+      });
+    }
+    if (event === 'focus') {
+      editor.contentDOM.addEventListener('focus', callback);
+    }
+    if (event === 'blur') {
+      editor.contentDOM.addEventListener('blur', callback);
+    }
+
+    if (event === 'dragenter') {
+      editor.contentDOM.addEventListener('dragenter', callback);
+    }
+
+    if (event === 'dragover') {
+      editor.contentDOM.addEventListener('dragover', callback);
+    }
+
+    if (event === 'drop') {
+      editor.contentDOM.addEventListener('drop', callback);
+    }
+
+    if (event === 'paste') {
+      editor.contentDOM.addEventListener('paste', callback);
+    }
+  };
+
+  editor.off = (event, callback) => {
+    if (event === 'focus') {
+      editor.contentDOM.removeEventListener('focus', callback);
+    }
+
+    if (event === 'blur') {
+      editor.contentDOM.removeEventListener('blur', callback);
+    }
+
+    if (event === 'dragenter') {
+      editor.contentDOM.removeEventListener('dragenter', callback);
+    }
+
+    if (event === 'dragover') {
+      editor.contentDOM.removeEventListener('dragover', callback);
+    }
+
+    if (event === 'drop') {
+      editor.contentDOM.removeEventListener('drop', callback);
+    }
+
+    if (event === 'paste') {
+      editor.contentDOM.removeEventListener('paste', callback);
+    }
+  };
+
+  editor.getValue = () => {
+    return editor.state.doc.toString();
+  };
+
+  editor.setValue = (value: string) => {
+    editor.dispatch({
+      changes: { from: 0, to: editor.state.doc.length, insert: value },
+    });
+  };
+
+  editor.wrapText = (before: string, after = before, defaultText) => {
+    const range = editor.state.selection.ranges[0];
+    const selection = editor.state.sliceDoc(range.from, range.to);
+    if (selection) {
+      editor.replaceSelection(`${before}${selection}${after}`);
+    } else {
+      editor.replaceSelection(`${before}${defaultText}${after}`);
+    }
+  };
+  editor.replaceLines = (replace: Parameters<Array<string>['map']>[0]) => {
+    const range = editor.state.selection.ranges[0];
+    const line = editor.state.doc.lineAt(range.from).number;
+    const from = editor.state.doc.line(line).from;
+    const to = editor.state.doc.line(line).to;
+    const lines = editor.state.sliceDoc(from, to).split('\n');
+
+    const insert = lines.map(replace).join('\n');
+    const selectionStart = from;
+    const selectionEnd = from + insert.length;
+
+    editor.dispatch({
+      changes: [
+        {
+          from,
+          to,
+          insert,
+        },
+      ],
+      selection: EditorSelection.single(selectionStart, selectionEnd),
+    });
+  };
+
+  editor.appendBlock = (content: string): Position => {
+    const range = editor.state.selection.ranges[0];
+    const line = editor.state.doc.lineAt(range.from).number;
+    const from = editor.state.doc.line(line).from;
+    const to = editor.state.doc.line(line).to;
+    let insert = `\n\n${content}`;
+    let selection = EditorSelection.single(to, to + content.length);
+    if (from === to) {
+      insert = `${content}\n`;
+      selection = EditorSelection.single(from, from + content.length);
+    }
+
+    editor.dispatch({
+      changes: [
+        {
+          from: to,
+          insert,
+        },
+      ],
+      selection,
+    });
+  };
 
+  editor.replaceRange = (
+    value: string,
+    selectionStart: Position,
+    selectionEnd: Position,
+  ) => {
+    const from = selectionStart.from;
+    const to = selectionEnd.to + selectionEnd.ch;
+    editor.dispatch({
+      changes: [
+        {
+          from,
+          to,
+          insert: value,
+        },
+      ],
+      selection: EditorSelection.cursor(from + value.length),
+    });
+  };
+
+  return editor;
+};
 export const useEditor = ({
   editorRef,
   placeholder,
@@ -148,78 +313,58 @@ export const useEditor = ({
 }) => {
   const [editor, setEditor] = useState<CodeMirror.Editor | null>(null);
   const [value, setValue] = useState<string>('');
-  const isMountedRef = useRef(false);
-
-  const onEnter = (cm) => {
-    const cursor = cm.getCursor();
-    const text = cm.getLine(cursor.line);
-    const doc = cm.getDoc();
-
-    const olRegexData = text.match(/^(\s{0,})(\d+)\.\s/);
-    const ulRegexData = text.match(/^(\s{0,})(-|\*)\s/);
-    const blockquoteData = text.match(/^>\s+?/g);
-
-    if (olRegexData && text !== olRegexData[0]) {
-      const num = olRegexData[2];
-
-      doc.replaceSelection(`\n${olRegexData[1]}${Number(num) + 1}. `);
-    } else if (ulRegexData && text !== ulRegexData[0]) {
-      doc.replaceSelection(`\n${ulRegexData[1]}${ulRegexData[2]} `);
-    } else if (blockquoteData && text !== blockquoteData[0]) {
-      doc.replaceSelection(`\n> `);
-    } else if (
-      text.trim() === '>' ||
-      text.trim().match(/^\d{1,}\.$/) ||
-      text.trim().match(/^(\*|-)$/)
-    ) {
-      doc.replaceRange(`\n`, { ...cursor, ch: 0 }, cursor);
-    } else {
-      doc.replaceSelection(`\n`);
-    }
-  };
-
   const init = async () => {
-    if (isMountedRef.current) {
-      return false;
-    }
-    isMountedRef.current = true;
-
-    const { default: codeMirror } = await import('codemirror');
-    await import('codemirror/mode/markdown/markdown');
-    await import('codemirror/addon/display/placeholder');
+    const theme = EditorView.theme({
+      '&': {
+        width: '100%',
+        height: '100%',
+      },
+      '&.cm-focused': {
+        outline: 'none',
+      },
+      '.cm-content': {
+        width: '100%',
+        padding: '1rem',
+      },
+      '.cm-line': {
+        whiteSpace: 'pre-wrap',
+        wordWrap: 'break-word',
+        wordBreak: 'break-all',
+      },
+    });
+    let startState = EditorState.create({
+      extensions: [markdown(), theme],
+    });
 
-    const cm = codeMirror(editorRef?.current, {
-      mode: 'markdown',
-      lineWrapping: true,
-      placeholder,
+    const view = new EditorView({
+      parent: editorRef.current,
+      state: startState,
     });
 
+    const editor = createEditorUtils(view as EditorView & ExtendEditor);
+
     if (autoFocus) {
       setTimeout(() => {
-        cm.focus();
+        editor.focus();
       }, 10);
     }
 
-    cm.on('change', (e) => {
-      const newValue = e.getValue();
+    editor.on('change', () => {
+      const newValue = editor.getValue();
       setValue(newValue);
     });
 
-    cm.on('focus', () => {
+    editor.on('focus', () => {
       onFocus?.();
     });
-    cm.on('blur', () => {
+
+    editor.on('blur', () => {
       onBlur?.();
     });
 
-    setEditor(cm);
-    createEditorUtils(codeMirror, cm);
+    setEditor(editor);
 
-    cm.setSize('100%', '100%');
-    cm.addKeyMap({
-      Enter: onEnter,
-    });
-    return cm;
+    return editor;
   };
 
   useEffect(() => {
@@ -227,11 +372,10 @@ export const useEditor = ({
   }, [value]);
 
   useEffect(() => {
-    if (!(editorRef.current instanceof HTMLElement)) {
+    if (!(editorRef.current instanceof HTMLElement) || editor) {
       return;
     }
     init();
-  }, [editorRef]);
-
+  }, [editor]);
   return editor;
 };