-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathStaticLineGraph.tsx
92 lines (84 loc) · 2.36 KB
/
StaticLineGraph.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
import { Canvas, LinearGradient, Path, vec } from '@shopify/react-native-skia'
import { getSixDigitHex } from './utils/getSixDigitHex'
import React, { useCallback, useMemo, useState } from 'react'
import { View, StyleSheet, LayoutChangeEvent } from 'react-native'
import {
createGraphPath,
getGraphPathRange,
getPointsInRange,
GraphPathRange,
} from './CreateGraphPath'
import type { StaticLineGraphProps } from './LineGraphProps'
export function StaticLineGraph({
points: allPoints,
range,
color,
lineThickness = 3,
enableFadeInMask,
style,
...props
}: StaticLineGraphProps): React.ReactElement {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const onLayout = useCallback(
({ nativeEvent: { layout } }: LayoutChangeEvent) => {
setWidth(Math.round(layout.width))
setHeight(Math.round(layout.height))
},
[]
)
const pathRange: GraphPathRange = useMemo(
() => getGraphPathRange(allPoints, range),
[allPoints, range]
)
const pointsInRange = useMemo(
() => getPointsInRange(allPoints, pathRange),
[allPoints, pathRange]
)
const path = useMemo(
() =>
createGraphPath({
pointsInRange: pointsInRange,
range: pathRange,
canvasHeight: height,
canvasWidth: width,
horizontalPadding: lineThickness,
verticalPadding: lineThickness,
}),
[height, lineThickness, pathRange, pointsInRange, width]
)
const gradientColors = useMemo(
() => [`${getSixDigitHex(color)}00`, `${getSixDigitHex(color)}ff`],
[color]
)
const gradientFrom = useMemo(() => vec(0, 0), [])
const gradientTo = useMemo(() => vec(width * 0.15, 0), [width])
return (
<View {...props} style={style} onLayout={onLayout}>
{/* Fix for react-native-skia's incorrect type declarations */}
<Canvas style={styles.svg}>
<Path
path={path}
strokeWidth={lineThickness}
color={enableFadeInMask ? undefined : color}
style="stroke"
strokeJoin="round"
strokeCap="round"
>
{enableFadeInMask && (
<LinearGradient
start={gradientFrom}
end={gradientTo}
colors={gradientColors}
/>
)}
</Path>
</Canvas>
</View>
)
}
const styles = StyleSheet.create({
svg: {
flex: 1,
},
})