Skip to content

Commit

Permalink
fix: cross-browser upload drag and drop
Browse files Browse the repository at this point in the history
  • Loading branch information
jmikrut committed Dec 29, 2021
1 parent c54da71 commit 4119eec
Showing 1 changed file with 9 additions and 16 deletions.
25 changes: 9 additions & 16 deletions src/admin/components/views/collections/Edit/Upload/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ const validate = (value) => {
const Upload: React.FC<Props> = (props) => {
const inputRef = useRef(null);
const dropRef = useRef(null);
const [fileList, setFileList] = useState(undefined);
const [selectingFile, setSelectingFile] = useState(false);
const [dragging, setDragging] = useState(false);
const [dragCounter, setDragCounter] = useState(0);
Expand All @@ -53,16 +52,16 @@ const Upload: React.FC<Props> = (props) => {
const handleDragIn = useCallback((e) => {
e.preventDefault();
e.stopPropagation();
setDragCounter(dragCounter + 1);
setDragCounter((count) => count + 1);
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
setDragging(true);
}
}, [dragCounter]);
}, []);

const handleDragOut = useCallback((e) => {
e.preventDefault();
e.stopPropagation();
setDragCounter(dragCounter - 1);
setDragCounter((count) => count - 1);
if (dragCounter > 1) return;
setDragging(false);
}, [dragCounter]);
Expand All @@ -73,19 +72,21 @@ const Upload: React.FC<Props> = (props) => {
setDragging(false);

if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
setFileList(e.dataTransfer.files);
setValue(e.dataTransfer.files[0]);
setDragging(false);

e.dataTransfer.clearData();
setDragCounter(0);
} else {
setDragging(false);
}
}, []);
}, [setValue]);

// Only called when input is interacted with directly
// Not called when drag + drop is used
// Or when input is cleared
const handleInputChange = useCallback(() => {
setSelectingFile(false);
setFileList(inputRef?.current?.files || null);
setValue(inputRef?.current?.files?.[0] || null);
}, [inputRef, setValue]);

Expand Down Expand Up @@ -113,13 +114,7 @@ const Upload: React.FC<Props> = (props) => {
}

return () => null;
}, [handleDragIn, handleDragOut, handleDrop, dropRef]);

useEffect(() => {
if (inputRef.current && fileList !== undefined) {
inputRef.current.files = fileList;
}
}, [fileList]);
}, [handleDragIn, handleDragOut, handleDrop, value]);

useEffect(() => {
setReplacingFile(false);
Expand All @@ -143,7 +138,6 @@ const Upload: React.FC<Props> = (props) => {
collection={collection}
handleRemove={() => {
setReplacingFile(true);
setFileList(null);
setValue(null);
}}
/>
Expand All @@ -163,7 +157,6 @@ const Upload: React.FC<Props> = (props) => {
buttonStyle="icon-label"
iconStyle="with-border"
onClick={() => {
setFileList(null);
setValue(null);
}}
/>
Expand Down

0 comments on commit 4119eec

Please sign in to comment.