Răsfoiți Sursa

Merge pull request #8124 from weseek/imprv/126527-131252-file-paste

imprv: Support Ctrl+V file paste.
reiji-h 2 ani în urmă
părinte
comite
61301aab43

+ 44 - 0
packages/editor/src/components/CodeMirrorEditor/CodeMirrorEditor.tsx

@@ -3,6 +3,7 @@ import {
 } from 'react';
 
 import { indentUnit } from '@codemirror/language';
+import { EditorView } from '@codemirror/view';
 import type { ReactCodeMirrorProps } from '@uiw/react-codemirror';
 
 import { GlobalCodeMirrorEditorKey } from '../../consts';
@@ -54,6 +55,49 @@ export const CodeMirrorEditor = (props: Props): JSX.Element => {
 
   }, [codeMirrorEditor, indentSize]);
 
+  useEffect(() => {
+    const handlePaste = (event: ClipboardEvent) => {
+      event.preventDefault();
+
+      if (event.clipboardData == null) {
+        return;
+      }
+
+      if (onUpload != null && event.clipboardData.types.includes('Files')) {
+        onUpload(Array.from(event.clipboardData.files));
+      }
+
+      if (event.clipboardData.types.includes('text/plain')) {
+        const textData = event.clipboardData.getData('text/plain');
+        codeMirrorEditor?.replaceText(textData);
+      }
+    };
+
+    const extension = EditorView.domEventHandlers({
+      paste: handlePaste,
+    });
+
+    const cleanupFunction = codeMirrorEditor?.appendExtensions(extension);
+    return cleanupFunction;
+
+  }, [codeMirrorEditor, onUpload]);
+
+  useEffect(() => {
+
+    const handleDrop = (event: DragEvent) => {
+      // prevents conflicts between codemirror and react-dropzone during file drops.
+      event.preventDefault();
+    };
+
+    const extension = EditorView.domEventHandlers({
+      drop: handleDrop,
+    });
+
+    const cleanupFunction = codeMirrorEditor?.appendExtensions(extension);
+    return cleanupFunction;
+
+  }, [codeMirrorEditor]);
+
   const { getRootProps, open } = useFileDropzone({ onUpload });
 
   return (

+ 7 - 1
packages/editor/src/services/codemirror-editor/use-codemirror-editor/use-codemirror-editor.ts

@@ -45,11 +45,17 @@ export const useCodeMirrorEditor = (props?: UseCodeMirror): UseCodeMirrorEditor
       {
         extensions: defaultExtensions,
         // Reset settings of react-codemirror.
-        // The extension defined first will be used, so it must be disabled here.
+        // Extensions are defined first will be used if they have the same priority.
+        // If extensions conflict, disable them here.
+        // And add them to defaultExtensions: Extension[] with a lower priority.
+        // ref: https://codemirror.net/examples/config/
+        // ------- Start -------
         indentWithTab: false,
         basicSetup: {
           defaultKeymap: false,
+          dropCursor: false,
         },
+        // ------- End -------
       },
     );
   }, [props]);