-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Dustbin.tsx
70 lines (61 loc) · 1.58 KB
/
Dustbin.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
60
61
62
63
64
65
66
67
68
69
70
import { CSSProperties, FC, ReactNode, useState } from 'react'
import { useDrop } from 'react-dnd'
import { ItemTypes } from './ItemTypes'
function getStyle(backgroundColor: string): CSSProperties {
return {
border: '1px solid rgba(0,0,0,0.2)',
minHeight: '8rem',
minWidth: '8rem',
color: 'white',
backgroundColor,
padding: '2rem',
paddingTop: '1rem',
margin: '1rem',
textAlign: 'center',
float: 'left',
fontSize: '1rem',
}
}
export interface DustbinProps {
greedy?: boolean
children?: ReactNode
}
export interface DustbinState {
hasDropped: boolean
hasDroppedOnChild: boolean
}
export const Dustbin: FC<DustbinProps> = ({ greedy, children }) => {
const [hasDropped, setHasDropped] = useState(false)
const [hasDroppedOnChild, setHasDroppedOnChild] = useState(false)
const [{ isOver, isOverCurrent }, drop] = useDrop(
() => ({
accept: ItemTypes.BOX,
drop(_item: unknown, monitor) {
const didDrop = monitor.didDrop()
if (didDrop && !greedy) {
return
}
setHasDropped(true)
setHasDroppedOnChild(didDrop)
},
collect: (monitor) => ({
isOver: monitor.isOver(),
isOverCurrent: monitor.isOver({ shallow: true }),
}),
}),
[greedy, setHasDropped, setHasDroppedOnChild],
)
const text = greedy ? 'greedy' : 'not greedy'
let backgroundColor = 'rgba(0, 0, 0, .5)'
if (isOverCurrent || (isOver && greedy)) {
backgroundColor = 'darkgreen'
}
return (
<div ref={drop} style={getStyle(backgroundColor)}>
{text}
<br />
{hasDropped && <span>dropped {hasDroppedOnChild && ' on child'}</span>}
<div>{children}</div>
</div>
)
}