/
ChordLabels.tsx
117 lines (110 loc) · 3.33 KB
/
ChordLabels.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { memo, useMemo } from 'react'
import { useTransition, animated, to } from '@react-spring/web'
import {
// @ts-ignore
midAngle,
// @ts-ignore
getPolarLabelProps,
useTheme,
} from '@nivo/core'
import { useMotionConfig } from '@nivo/core'
import { ArcDatum, ChordCommonProps } from './types'
import { useInheritedColor } from '@nivo/colors'
interface ChordLabelsProps {
arcs: ArcDatum[]
radius: number
rotation: number
color: ChordCommonProps['labelTextColor']
}
export const ChordLabels = memo(({ arcs, radius, rotation, color }: ChordLabelsProps) => {
const { animate, config: springConfig } = useMotionConfig()
const theme = useTheme()
const getColor = useInheritedColor(color, theme)
const labels = useMemo(
() =>
arcs.map(arc => {
const angle = midAngle(arc)
const textProps = getPolarLabelProps(radius, angle, rotation)
return {
id: arc.id,
label: arc.label,
x: textProps.x,
y: textProps.y,
rotation: textProps.rotate,
color: getColor(arc),
textAnchor: textProps.align,
dominantBaseline: textProps.baseline,
}
}),
[arcs, radius, radius, rotation, getColor]
)
const transition = useTransition<
typeof labels[number],
{
x: number
y: number
rotation: number
color: string
}
>(labels, {
keys: label => label.id,
initial: label => {
return {
x: label.x,
y: label.y,
rotation: label.rotation,
color: label.color,
}
},
from: label => {
return {
x: label.x,
y: label.y,
rotation: label.rotation,
color: label.color,
}
},
enter: label => {
return {
x: label.x,
y: label.y,
rotation: label.rotation,
color: label.color,
}
},
update: label => {
return {
x: label.x,
y: label.y,
rotation: label.rotation,
color: label.color,
}
},
expires: true,
config: springConfig,
immediate: !animate,
})
return (
<>
{transition((transitionProps, label) => (
<animated.text
key={label.id}
data-testid={`label.${label.id}`}
style={{
...theme.labels.text,
pointerEvents: 'none',
fill: transitionProps.color,
}}
transform={to(
[transitionProps.x, transitionProps.y, transitionProps.rotation],
(x, y, rotation) => `translate(${x}, ${y}) rotate(${rotation})`
)}
textAnchor={label.textAnchor}
dominantBaseline={label.dominantBaseline}
>
{label.label}
</animated.text>
))}
</>
)
})