-
Notifications
You must be signed in to change notification settings - Fork 909
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: support drag-and-drop when importing opml (#2001)
- Loading branch information
Showing
2 changed files
with
74 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import type { DragEvent, ReactNode } from "react" | ||
import { useCallback, useRef, useState } from "react" | ||
|
||
// Ported from https://github.com/react-dropzone/react-dropzone/issues/753#issuecomment-774782919 | ||
const useDragAndDrop = ({ callback }: { callback: (file: FileList) => void | Promise<void> }) => { | ||
const [isDragging, setIsDragging] = useState(false) | ||
const dragCounter = useRef(0) | ||
|
||
const onDrop = useCallback( | ||
async (event: DragEvent<HTMLLabelElement>) => { | ||
event.preventDefault() | ||
setIsDragging(false) | ||
if (event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files.length > 0) { | ||
dragCounter.current = 0 | ||
await callback(event.dataTransfer.files) | ||
event.dataTransfer.clearData() | ||
} | ||
}, | ||
[callback], | ||
) | ||
|
||
const onDragEnter = useCallback((event: DragEvent) => { | ||
event.preventDefault() | ||
dragCounter.current++ | ||
setIsDragging(true) | ||
}, []) | ||
|
||
const onDragOver = useCallback((event: DragEvent) => { | ||
event.preventDefault() | ||
}, []) | ||
|
||
const onDragLeave = useCallback((event: DragEvent) => { | ||
event.preventDefault() | ||
dragCounter.current-- | ||
if (dragCounter.current > 0) return | ||
setIsDragging(false) | ||
}, []) | ||
|
||
return { | ||
isDragging, | ||
|
||
dragHandlers: { | ||
onDrop, | ||
onDragOver, | ||
onDragEnter, | ||
onDragLeave, | ||
}, | ||
} | ||
} | ||
|
||
export const DropZone = ({ | ||
onDrop, | ||
children, | ||
}: { | ||
onDrop: (file: FileList) => void | Promise<void> | ||
children?: ReactNode | ||
}) => { | ||
const { isDragging, dragHandlers } = useDragAndDrop({ callback: onDrop }) | ||
|
||
return ( | ||
<label | ||
className={`center flex h-[100px] w-full rounded-md border border-dashed ${ | ||
isDragging ? "border-blue-500 bg-blue-100" : "" | ||
}`} | ||
htmlFor="upload-file" | ||
{...dragHandlers} | ||
> | ||
{children} | ||
</label> | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters