2021-06-23 05:37:08 -04:00
|
|
|
import { useRef } from 'react'
|
2020-11-26 09:22:30 -05:00
|
|
|
import PropTypes from 'prop-types'
|
|
|
|
import { useDragLayer } from 'react-dnd'
|
|
|
|
import classNames from 'classnames'
|
|
|
|
|
|
|
|
// a custom component rendered on top of a draggable area that renders the
|
|
|
|
// dragged item. See
|
|
|
|
// https://react-dnd.github.io/react-dnd/examples/drag-around/custom-drag-layer
|
|
|
|
// for more details.
|
|
|
|
// Also used to display a container border when hovered.
|
|
|
|
function FileTreeDraggablePreviewLayer({ isOver }) {
|
|
|
|
const { isDragging, item, clientOffset } = useDragLayer(monitor => ({
|
|
|
|
isDragging: monitor.isDragging(),
|
|
|
|
item: monitor.getItem(),
|
2021-04-27 03:52:58 -04:00
|
|
|
clientOffset: monitor.getClientOffset(),
|
2020-11-26 09:22:30 -05:00
|
|
|
}))
|
|
|
|
const ref = useRef()
|
|
|
|
|
|
|
|
const containerOffset = ref.current
|
|
|
|
? ref.current.getBoundingClientRect()
|
|
|
|
: null
|
|
|
|
|
2022-07-21 04:32:34 -04:00
|
|
|
if (!isDragging || !item.title) {
|
2020-11-26 09:22:30 -05:00
|
|
|
return null
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div
|
|
|
|
ref={ref}
|
|
|
|
className={classNames('dnd-draggable-preview-layer', {
|
2021-04-27 03:52:58 -04:00
|
|
|
'dnd-droppable-hover': isOver,
|
2020-11-26 09:22:30 -05:00
|
|
|
})}
|
|
|
|
>
|
|
|
|
<div style={getItemStyle(clientOffset, containerOffset)}>
|
|
|
|
<DraggablePreviewItem title={item.title} />
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
FileTreeDraggablePreviewLayer.propTypes = {
|
2021-04-27 03:52:58 -04:00
|
|
|
isOver: PropTypes.bool.isRequired,
|
2020-11-26 09:22:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function DraggablePreviewItem({ title }) {
|
|
|
|
return <div className="dnd-draggable-preview-item">{title}</div>
|
|
|
|
}
|
|
|
|
|
|
|
|
DraggablePreviewItem.propTypes = {
|
2021-04-27 03:52:58 -04:00
|
|
|
title: PropTypes.string.isRequired,
|
2020-11-26 09:22:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// makes the preview item follow the cursor.
|
|
|
|
// See https://react-dnd.github.io/react-dnd/docs/api/drag-layer-monitor
|
|
|
|
function getItemStyle(clientOffset, containerOffset) {
|
|
|
|
if (!containerOffset || !clientOffset) {
|
|
|
|
return {
|
2021-04-27 03:52:58 -04:00
|
|
|
display: 'none',
|
2020-11-26 09:22:30 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
const { x: containerX, y: containerY } = containerOffset
|
|
|
|
const { x: clientX, y: clientY } = clientOffset
|
|
|
|
const posX = clientX - containerX - 15
|
|
|
|
const posY = clientY - containerY - 15
|
|
|
|
const transform = `translate(${posX}px, ${posY}px)`
|
|
|
|
return {
|
|
|
|
transform,
|
2021-04-27 03:52:58 -04:00
|
|
|
WebkitTransform: transform,
|
2020-11-26 09:22:30 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default FileTreeDraggablePreviewLayer
|