Yuki Takei 2 лет назад
Родитель
Сommit
8c3331f412

+ 13 - 4
packages/editor/src/components/playground/PlaygroundController.tsx

@@ -29,15 +29,23 @@ export const InitEditorValueRow = (): JSX.Element => {
 };
 
 type SetCursorRowFormData = {
-  lineNumber: number;
+  lineNumber: number | string;
 };
 
 export const SetCursorRow = (): JSX.Element => {
 
-  // const { data } = useCodeMirrorEditorMain();
+  const { data } = useCodeMirrorEditorMain();
+  const { register, handleSubmit } = useForm<SetCursorRowFormData>({
+    defaultValues: {
+      lineNumber: 1,
+    },
+  });
 
-  const { register, handleSubmit } = useForm<SetCursorRowFormData>();
-  const onSubmit = handleSubmit(data => console.log(data));
+  const setCursor = data?.setCursor;
+  const onSubmit = handleSubmit((submitData) => {
+    const lineNumber = Number(submitData.lineNumber) || 1;
+    setCursor?.(lineNumber);
+  });
 
   return (
     <form className="row mt-3" onSubmit={onSubmit}>
@@ -45,6 +53,7 @@ export const SetCursorRow = (): JSX.Element => {
         <div className="input-group">
           <input
             {...register('lineNumber')}
+            type="number"
             className="form-control"
             placeholder="Input line number"
             aria-label="line number"

+ 20 - 0
packages/editor/src/services/codemirror-editor/use-codemirror-editor.ts

@@ -12,6 +12,7 @@ export type UseCodeMirrorEditor = UseCodeMirror;
 type UseCodeMirrorEditorUtils = {
   initState: (config?: EditorStateConfig) => void,
   initDoc: (doc?: string) => void,
+  setCursor: (lineNumber?: number) => void,
 }
 
 export type UseCodeMirrorEditorResponse = UseCodeMirrorEditorStates & UseCodeMirrorEditorUtils;
@@ -56,6 +57,24 @@ export const useCodeMirrorEditor = (props?: UseCodeMirrorEditor): UseCodeMirrorE
     initState({ doc });
   }, [initState]);
 
+  // implement setCursor method
+  const setCursor = useCallback((lineNumber?: number): void => {
+    if (view == null) {
+      return;
+    }
+
+    const posOfLineEnd = view.state.doc.line(lineNumber ?? 1).to;
+    view.dispatch({
+      selection: {
+        anchor: posOfLineEnd,
+        head: posOfLineEnd,
+      },
+    });
+    // focus
+    view.focus();
+
+  }, [view]);
+
   useEffect(() => {
     if (props?.container != null) {
       setContainer(props.container);
@@ -66,5 +85,6 @@ export const useCodeMirrorEditor = (props?: UseCodeMirrorEditor): UseCodeMirrorE
     ...codemirror,
     initState,
     initDoc,
+    setCursor,
   };
 };