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

shuai pushed a commit to branch feat/1.2.1/ui
in repository https://gitbox.apache.org/repos/asf/incubator-answer.git

commit 615d90f7c85b002d94295ca6412ab7dcf50baf99
Author: shuai <[email protected]>
AuthorDate: Fri Nov 24 11:09:02 2023 +0800

    fix: editor auto focus
---
 ui/src/components/Editor/utils/index.ts | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/ui/src/components/Editor/utils/index.ts 
b/ui/src/components/Editor/utils/index.ts
index ca46dc99..4930c768 100644
--- a/ui/src/components/Editor/utils/index.ts
+++ b/ui/src/components/Editor/utils/index.ts
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-import { useEffect, useState } from 'react';
+import { useEffect, useState, useRef } from 'react';
 
 import type { Editor, Position } from 'codemirror';
 import type CodeMirror from 'codemirror';
@@ -148,6 +148,7 @@ 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();
@@ -178,6 +179,11 @@ export const useEditor = ({
   };
 
   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');
@@ -186,11 +192,13 @@ export const useEditor = ({
       mode: 'markdown',
       lineWrapping: true,
       placeholder,
-      focus: autoFocus,
     });
 
-    setEditor(cm);
-    createEditorUtils(codeMirror, cm);
+    if (autoFocus) {
+      setTimeout(() => {
+        cm.focus();
+      }, 10);
+    }
 
     cm.on('change', (e) => {
       const newValue = e.getValue();
@@ -203,6 +211,10 @@ export const useEditor = ({
     cm.on('blur', () => {
       onBlur?.();
     });
+
+    setEditor(cm);
+    createEditorUtils(codeMirror, cm);
+
     cm.setSize('100%', '100%');
     cm.addKeyMap({
       Enter: onEnter,

Reply via email to