Added drag and drop support to map upload

This commit is contained in:
Mitchell McCaffrey 2020-04-15 21:15:16 +10:00
parent 64f284ebb7
commit 279d83122f
2 changed files with 69 additions and 9 deletions

View File

@ -18,8 +18,7 @@ function AddMapButton({ onMapChanged }) {
const mapDataRef = useRef(null); const mapDataRef = useRef(null);
const [mapSource, setMapSource] = useState(null); const [mapSource, setMapSource] = useState(null);
function handleImageUpload(event) { function handleImageUpload(file) {
const file = event.target.files[0];
const url = URL.createObjectURL(file); const url = URL.createObjectURL(file);
let image = new Image(); let image = new Image();
image.onload = function () { image.onload = function () {

View File

@ -1,5 +1,13 @@
import React, { useRef } from "react"; import React, { useRef, useState } from "react";
import { Box, Button, Image as UIImage, Flex, Label, Input } from "theme-ui"; import {
Box,
Button,
Image as UIImage,
Flex,
Label,
Input,
Text,
} from "theme-ui";
import Modal from "../components/Modal"; import Modal from "../components/Modal";
@ -22,6 +30,30 @@ function AddMapModal({
fileInputRef.current.click(); fileInputRef.current.click();
} }
} }
const [dragging, setDragging] = useState(false);
function handleImageDragEnter(event) {
event.preventDefault();
event.stopPropagation();
setDragging(true);
}
function handleImageDragLeave(event) {
event.preventDefault();
event.stopPropagation();
setDragging(false);
}
function handleImageDrop(event) {
event.preventDefault();
event.stopPropagation();
const file = event.dataTransfer.files[0];
if (file.type.startsWith("image")) {
onImageUpload(file);
}
setDragging(false);
}
return ( return (
<Modal isOpen={isOpen} onRequestClose={onRequestClose}> <Modal isOpen={isOpen} onRequestClose={onRequestClose}>
<Box <Box
@ -30,19 +62,24 @@ function AddMapModal({
e.preventDefault(); e.preventDefault();
onDone(); onDone();
}} }}
onDragEnter={handleImageDragEnter}
> >
<Label pt={2} pb={1}>
Add map
</Label>
<input <input
onChange={onImageUpload} onChange={(event) => onImageUpload(event.target.files[0])}
type="file" type="file"
accept="image/*" accept="image/*"
style={{ display: "none" }} style={{ display: "none" }}
ref={fileInputRef} ref={fileInputRef}
/> />
<Flex sx={{ flexDirection: "column" }}> <Flex
sx={{
flexDirection: "column",
}}
>
<Label pt={2} pb={1}>
Add map
</Label>
<UIImage <UIImage
my={2} my={2}
sx={{ sx={{
@ -91,6 +128,30 @@ function AddMapModal({
Select Image Select Image
</Button> </Button>
)} )}
{dragging && (
<Flex
bg="muted"
sx={{
position: "absolute",
top: 0,
right: 0,
left: 0,
bottom: 0,
justifyContent: "center",
alignItems: "center",
cursor: "copy",
}}
onDragLeave={handleImageDragLeave}
onDragOver={(e) => {
e.preventDefault();
e.stopPropagation();
e.dataTransfer.dropEffect = "copy";
}}
onDrop={handleImageDrop}
>
<Text sx={{ pointerEvents: "none" }}>Drop map to upload</Text>
</Flex>
)}
</Flex> </Flex>
</Box> </Box>
</Modal> </Modal>