Kaynağa Gözat

mod Enter call onSave and enable defaultKeymap

reiji-h 2 yıl önce
ebeveyn
işleme
598166ff8f

+ 34 - 2
packages/editor/src/components/CodeMirrorEditor/CodeMirrorEditor.tsx

@@ -1,7 +1,10 @@
 import {
-  forwardRef, useMemo, useRef,
+  forwardRef, useMemo, useRef, useEffect,
 } from 'react';
 
+
+import { defaultKeymap } from '@codemirror/commands';
+import { keymap } from '@codemirror/view';
 import type { ReactCodeMirrorProps } from '@uiw/react-codemirror';
 
 import { GlobalCodeMirrorEditorKey } from '../../consts';
@@ -21,12 +24,14 @@ const CodeMirrorEditorContainer = forwardRef<HTMLDivElement>((props, ref) => {
 type Props = {
   editorKey: string | GlobalCodeMirrorEditorKey,
   onChange?: (value: string) => void,
+  onSave?: () => void,
 }
 
 export const CodeMirrorEditor = (props: Props): JSX.Element => {
   const {
     editorKey,
     onChange,
+    onSave,
   } = props;
 
   const containerRef = useRef(null);
@@ -36,7 +41,34 @@ export const CodeMirrorEditor = (props: Props): JSX.Element => {
       onChange,
     };
   }, [onChange]);
-  useCodeMirrorEditorIsolated(editorKey, containerRef.current, cmProps);
+
+  const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(editorKey, containerRef.current, cmProps);
+
+  // set handler to save with ctrl/cmd + Enter key
+  useEffect(() => {
+    if (onSave == null) {
+      return;
+    }
+
+    const extension = keymap.of([
+      {
+        key: 'Mod-Enter',
+        preventDefault: true,
+        run: () => {
+          const doc = codeMirrorEditor?.getDoc();
+          if (doc != null) {
+            onSave();
+          }
+          return true;
+        },
+      },
+      ...defaultKeymap,
+    ]);
+
+    const cleanupFunction = codeMirrorEditor?.appendExtensions?.(extension);
+
+    return cleanupFunction;
+  }, [codeMirrorEditor, onSave]);
 
   return (
     <div className="flex-expand-vert">