diff --git a/src/components/DragAndDrop.tsx b/src/components/DragAndDrop.tsx new file mode 100644 index 0000000..5b66d7d --- /dev/null +++ b/src/components/DragAndDrop.tsx @@ -0,0 +1,80 @@ +import React from "react" +import { useState } from "react" +import { useEffect } from "react" +import style from "./../style/DragAndDrop.module.scss" + +interface Props { + onDrop?: ()=>void + onEnter?: (event: DragEvent)=>void + onLeave?: (event: DragEvent)=>void + onDragOver?: (event: DragEvent)=>void + handleDrop?: (files: FileList)=>void +} + +const DragAndDrop: React.FC = (props) => { + const dropRef = React.createRef() + const [hover,setHover] = useState(false) + + function handleDragEnter(event: DragEvent) { + // console.debug("dragenter",event) + event.preventDefault() + event.stopPropagation() + setHover(true) + props.onEnter?.(event) + } + + function handleDragLeave(event: DragEvent) { + // console.debug("dragleave",event) + event.preventDefault() + event.stopPropagation() + setHover(false) + props.onLeave?.(event) + } + + function handleDragOver(event:DragEvent) { + event.preventDefault() + event.stopPropagation() + setHover(true) + props.onDragOver?.(event) + } + + function handleDrop(event: DragEvent) { + console.debug("drop",event) + event.preventDefault() + event.stopPropagation() + setHover(false) + props.onDrop?.() + if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) { + props.handleDrop?.(event.dataTransfer.files) + // event.dataTransfer.clearData() + } + } + + useEffect(()=>{ + if(dropRef.current){ + console.debug("Add drag event listner") + dropRef.current.addEventListener("dragenter",handleDragEnter) + dropRef.current.addEventListener("dragleave",handleDragLeave) + dropRef.current.addEventListener("dragover",handleDragOver) + dropRef.current.addEventListener("drop",handleDrop) + + return ()=>{ + if (dropRef.current){ + console.debug("Remove drag event listner") + dropRef.current.removeEventListener("dragenter",handleDragEnter) + dropRef.current.removeEventListener("dragleave",handleDragLeave) + dropRef.current.removeEventListener("dragover",handleDragOver) + dropRef.current.removeEventListener("drop",handleDrop) + } + } + } + },[]) + + return ( +
+ {props.children} +
+ ) +} + +export default DragAndDrop \ No newline at end of file diff --git a/src/style/DragAndDrop.module.scss b/src/style/DragAndDrop.module.scss new file mode 100644 index 0000000..5c32f1d --- /dev/null +++ b/src/style/DragAndDrop.module.scss @@ -0,0 +1,21 @@ +.active{ + border: dashed grey 4px; + background-color: rgba(255,255,255,.8); + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + z-index: 2; +} + +.dragAndDrop{ + top: 0; + bottom: 0; + left: 0; + right: 0; + width: 100%; + height: 100%; + position: absolute; + z-index: 2; +} \ No newline at end of file