-
Notifications
You must be signed in to change notification settings - Fork 2k
/
SourceBox.tsx
77 lines (70 loc) · 1.51 KB
/
SourceBox.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
71
72
73
74
75
76
77
import {
CSSProperties,
FC,
useState,
useCallback,
useMemo,
memo,
ReactNode,
} from 'react'
import { useDrag, DragSourceMonitor } from 'react-dnd'
import { Colors } from './Colors'
const style: CSSProperties = {
border: '1px dashed gray',
padding: '0.5rem',
margin: '0.5rem',
}
export interface SourceBoxProps {
color: string
onToggleForbidDrag?: () => void
children?: ReactNode
}
export const SourceBox: FC<SourceBoxProps> = memo(function SourceBox({
color,
children,
}) {
const [forbidDrag, setForbidDrag] = useState(false)
const [{ isDragging }, drag] = useDrag(
() => ({
type: color,
canDrag: !forbidDrag,
collect: (monitor: DragSourceMonitor) => ({
isDragging: monitor.isDragging(),
}),
}),
[forbidDrag, color],
)
const onToggleForbidDrag = useCallback(() => {
setForbidDrag(!forbidDrag)
}, [forbidDrag, setForbidDrag])
const backgroundColor = useMemo(() => {
switch (color) {
case Colors.YELLOW:
return 'lightgoldenrodyellow'
case Colors.BLUE:
return 'lightblue'
default:
return 'lightgoldenrodyellow'
}
}, [color])
const containerStyle = useMemo(
() => ({
...style,
backgroundColor,
opacity: isDragging ? 0.4 : 1,
cursor: forbidDrag ? 'default' : 'move',
}),
[isDragging, forbidDrag, backgroundColor],
)
return (
<div ref={drag} style={containerStyle} role="SourceBox" data-color={color}>
<input
type="checkbox"
checked={forbidDrag}
onChange={onToggleForbidDrag}
/>
<small>Forbid drag</small>
{children}
</div>
)
})