-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Box.tsx
59 lines (53 loc) · 1.42 KB
/
Box.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { CSSProperties, FC } from 'react'
import { ItemTypes } from './ItemTypes'
import { useDrag, DragSourceMonitor } from 'react-dnd'
const style: CSSProperties = {
border: '1px dashed gray',
backgroundColor: 'white',
padding: '0.5rem 1rem',
marginRight: '1.5rem',
marginBottom: '1.5rem',
float: 'left',
}
export interface BoxProps {
name: string
}
interface DropResult {
allowedDropEffect: string
dropEffect: string
name: string
}
export const Box: FC<BoxProps> = ({ name }) => {
const [{ opacity }, drag] = useDrag(
() => ({
type: ItemTypes.BOX,
item: { name },
end(item, monitor) {
const dropResult = monitor.getDropResult() as DropResult
if (item && dropResult) {
let alertMessage = ''
const isDropAllowed =
dropResult.allowedDropEffect === 'any' ||
dropResult.allowedDropEffect === dropResult.dropEffect
if (isDropAllowed) {
const isCopyAction = dropResult.dropEffect === 'copy'
const actionName = isCopyAction ? 'copied' : 'moved'
alertMessage = `You ${actionName} ${item.name} into ${dropResult.name}!`
} else {
alertMessage = `You cannot ${dropResult.dropEffect} an item into the ${dropResult.name}`
}
alert(alertMessage)
}
},
collect: (monitor: DragSourceMonitor) => ({
opacity: monitor.isDragging() ? 0.4 : 1,
}),
}),
[name],
)
return (
<div ref={drag} style={{ ...style, opacity }}>
{name}
</div>
)
}