-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathAnimatedLineGraph.tsx
More file actions
565 lines (502 loc) · 14.7 KB
/
AnimatedLineGraph.tsx
File metadata and controls
565 lines (502 loc) · 14.7 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { View, StyleSheet, LayoutChangeEvent } from 'react-native'
import Reanimated, {
runOnJS,
useAnimatedReaction,
useSharedValue,
useDerivedValue,
cancelAnimation,
withRepeat,
withSequence,
withTiming,
withDelay,
withSpring,
} from 'react-native-reanimated'
import { GestureDetector } from 'react-native-gesture-handler'
import {
Canvas,
SkPath,
LinearGradient,
Path,
Skia,
vec,
Group,
PathCommand,
mix,
Circle,
Shadow,
} from '@shopify/react-native-skia'
import type { AnimatedLineGraphProps } from './LineGraphProps'
import { SelectionDot as DefaultSelectionDot } from './SelectionDot'
import {
createGraphPath,
createGraphPathWithGradient,
getGraphPathRange,
GraphPathRange,
getXInRange,
getPointsInRange,
} from './CreateGraphPath'
import { getSixDigitHex } from './utils/getSixDigitHex'
import { usePanGesture } from './hooks/usePanGesture'
import { getYForX } from './GetYForX'
import { hexToRgba } from './utils/hexToRgba'
const INDICATOR_RADIUS = 7
const INDICATOR_BORDER_MULTIPLIER = 1.3
const INDICATOR_PULSE_BLUR_RADIUS_SMALL =
INDICATOR_RADIUS * INDICATOR_BORDER_MULTIPLIER
const INDICATOR_PULSE_BLUR_RADIUS_BIG =
INDICATOR_RADIUS * INDICATOR_BORDER_MULTIPLIER + 20
export function AnimatedLineGraph({
points: allPoints,
color,
gradientFillColors,
lineThickness = 3,
range,
enableFadeInMask,
enablePanGesture = false,
onPointSelected,
onGestureStart,
onGestureEnd,
panGestureDelay = 300,
SelectionDot = DefaultSelectionDot,
enableIndicator = false,
indicatorPulsating = false,
horizontalPadding = enableIndicator
? Math.ceil(INDICATOR_RADIUS * INDICATOR_BORDER_MULTIPLIER)
: 0,
verticalPadding = lineThickness,
TopAxisLabel,
BottomAxisLabel,
...props
}: AnimatedLineGraphProps): React.ReactElement {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
const interpolateProgress = useSharedValue(0)
const { gesture, isActive, x } = usePanGesture({
enabled: enablePanGesture,
holdDuration: panGestureDelay,
})
const circleX = useSharedValue(0)
const circleY = useSharedValue(0)
const pathEnd = useSharedValue(0)
const indicatorRadius = useSharedValue(enableIndicator ? INDICATOR_RADIUS : 0)
const indicatorBorderRadius = useDerivedValue(
() => indicatorRadius.value * INDICATOR_BORDER_MULTIPLIER
)
const pulseTrigger = useDerivedValue(() => (isActive.value ? 1 : 0))
const indicatorPulseAnimation = useSharedValue(0)
const indicatorPulseRadius = useDerivedValue(() => {
if (pulseTrigger.value === 0) {
return mix(
indicatorPulseAnimation.value,
INDICATOR_PULSE_BLUR_RADIUS_SMALL,
INDICATOR_PULSE_BLUR_RADIUS_BIG
)
}
return 0
})
const indicatorPulseOpacity = useDerivedValue(() => {
if (pulseTrigger.value === 0) {
return mix(indicatorPulseAnimation.value, 1, 0)
}
return 0
})
const positions = useDerivedValue(() => [
0,
Math.min(0.15, pathEnd.value),
pathEnd.value,
pathEnd.value,
1,
])
const onLayout = useCallback(
({ nativeEvent: { layout } }: LayoutChangeEvent) => {
setWidth(Math.round(layout.width))
setHeight(Math.round(layout.height))
},
[]
)
const straightLine = useMemo(() => {
const path = Skia.Path.Make()
path.moveTo(0, height / 2)
for (let i = 0; i < width - 1; i += 2) {
const x = i
const y = height / 2
path.cubicTo(x, y, x, y, x, y)
}
return path
}, [height, width])
const paths = useSharedValue<{ from?: SkPath; to?: SkPath }>({})
const gradientPaths = useSharedValue<{ from?: SkPath; to?: SkPath }>({})
const commands = useSharedValue<PathCommand[]>([])
const [commandsChanged, setCommandsChanged] = useState(0)
const pointSelectedIndex = useRef<number | undefined>(undefined)
const pathRange: GraphPathRange = useMemo(
() => getGraphPathRange(allPoints, range),
[allPoints, range]
)
const pointsInRange = useMemo(
() => getPointsInRange(allPoints, pathRange),
[allPoints, pathRange]
)
const drawingWidth = useMemo(
() => width - 2 * horizontalPadding,
[horizontalPadding, width]
)
const lineWidth = useMemo(() => {
const lastPoint = pointsInRange[pointsInRange.length - 1]
if (lastPoint == null) return drawingWidth
return Math.max(getXInRange(drawingWidth, lastPoint.date, pathRange.x), 0)
}, [drawingWidth, pathRange.x, pointsInRange])
const indicatorX = useDerivedValue(
() => Math.floor(lineWidth) + horizontalPadding
)
const indicatorY = useDerivedValue(
() => getYForX(commands.value, indicatorX.value) || 0
)
const indicatorPulseColor = useMemo(() => hexToRgba(color, 0.4), [color])
const shouldFillGradient = gradientFillColors != null
useEffect(() => {
if (height < 1 || width < 1) {
// view is not yet measured!
return
}
if (pointsInRange.length < 1) {
// points are still empty!
return
}
let path
let gradientPath
const createGraphPathProps = {
pointsInRange,
range: pathRange,
horizontalPadding,
verticalPadding,
canvasHeight: height,
canvasWidth: width,
}
if (shouldFillGradient) {
const { path: pathNew, gradientPath: gradientPathNew } =
createGraphPathWithGradient(createGraphPathProps)
path = pathNew
gradientPath = gradientPathNew
} else {
path = createGraphPath(createGraphPathProps)
}
commands.value = path.toCmds()
if (gradientPath != null) {
const previous = gradientPaths.value
let from: SkPath = previous.to ?? straightLine
if (previous.from != null && interpolateProgress.value < 1)
from =
from.interpolate(previous.from, interpolateProgress.value) ?? from
if (gradientPath.isInterpolatable(from)) {
gradientPaths.value = {
from,
to: gradientPath,
}
} else {
gradientPaths.value = {
from: gradientPath,
to: gradientPath,
}
}
}
const previous = paths.value
let from: SkPath = previous.to ?? straightLine
if (previous.from != null && interpolateProgress.value < 1)
from = from.interpolate(previous.from, interpolateProgress.value) ?? from
if (path.isInterpolatable(from)) {
paths.value = {
from,
to: path,
}
} else {
paths.value = {
from: path,
to: path,
}
}
setCommandsChanged(commandsChanged + 1)
interpolateProgress.value = withSpring(1, {
mass: 1,
stiffness: 500,
damping: 400,
velocity: 0,
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
height,
horizontalPadding,
interpolateProgress,
pathRange,
paths,
shouldFillGradient,
gradientPaths,
pointsInRange,
range,
straightLine,
verticalPadding,
width,
])
const gradientColors = useMemo(() => {
if (enableFadeInMask) {
return [
`${getSixDigitHex(color)}00`,
`${getSixDigitHex(color)}ff`,
`${getSixDigitHex(color)}ff`,
`${getSixDigitHex(color)}33`,
`${getSixDigitHex(color)}33`,
]
}
return [
color,
color,
color,
`${getSixDigitHex(color)}33`,
`${getSixDigitHex(color)}33`,
]
}, [color, enableFadeInMask])
const path = useDerivedValue(
() => {
const from = paths.value.from ?? straightLine
const to = paths.value.to ?? straightLine
return to.interpolate(from, interpolateProgress.value)
},
// RN Skia deals with deps differently. They are actually the required SkiaValues that the derived value listens to, not react values.
[interpolateProgress]
)
const gradientPath = useDerivedValue(
() => {
const from = gradientPaths.value.from ?? straightLine
const to = gradientPaths.value.to ?? straightLine
return to.interpolate(from, interpolateProgress.value)
},
// RN Skia deals with deps differently. They are actually the required SkiaValues that the derived value listens to, not react values.
[interpolateProgress]
)
const stopPulsating = useCallback(() => {
cancelAnimation(indicatorPulseAnimation)
indicatorPulseAnimation.value = 0
}, [indicatorPulseAnimation])
const startPulsating = useCallback(() => {
indicatorPulseAnimation.value = withRepeat(
withDelay(
1000,
withSequence(
withTiming(1, { duration: 1100 }),
withTiming(0, { duration: 0 }), // revert to 0
withTiming(0, { duration: 1200 }), // delay between pulses
withTiming(1, { duration: 1100 }),
withTiming(1, { duration: 2000 }) // delay after both pulses
)
),
-1
)
}, [indicatorPulseAnimation])
const setFingerPoint = useCallback(
(fingerX: number) => {
const fingerXInRange = Math.max(fingerX - horizontalPadding, 0)
const index = Math.round(
(fingerXInRange /
getXInRange(
drawingWidth,
pointsInRange[pointsInRange.length - 1]!.date,
pathRange.x
)) *
(pointsInRange.length - 1)
)
const pointIndex = Math.min(Math.max(index, 0), pointsInRange.length - 1)
if (pointSelectedIndex.current !== pointIndex) {
const dataPoint = pointsInRange[pointIndex]
pointSelectedIndex.current = pointIndex
if (dataPoint != null && isActive.value) {
onPointSelected?.(dataPoint)
}
}
},
[
drawingWidth,
horizontalPadding,
onPointSelected,
pathRange.x,
pointsInRange,
isActive,
]
)
const setFingerX = useCallback(
(fingerX: number) => {
'worklet'
const y = getYForX(commands.value, fingerX)
if (y != null) {
circleX.value = fingerX
circleY.value = y
}
if (isActive.value) pathEnd.value = fingerX / width
},
// pathRange.x must be extra included in deps otherwise onPointSelected doesn't work, IDK why
// eslint-disable-next-line react-hooks/exhaustive-deps
[circleX, circleY, isActive, pathEnd, pathRange.x, width, commands]
)
const setIsActive = useCallback(
(active: boolean) => {
indicatorRadius.value = withSpring(!active ? INDICATOR_RADIUS : 0, {
mass: 1,
stiffness: 1000,
damping: 50,
velocity: 0,
})
if (active) {
onGestureStart?.()
stopPulsating()
} else {
onGestureEnd?.()
pointSelectedIndex.current = undefined
pathEnd.value = 1
startPulsating()
}
},
[
indicatorRadius,
onGestureEnd,
onGestureStart,
pathEnd,
startPulsating,
stopPulsating,
]
)
useAnimatedReaction(
() => x.value,
(fingerX) => {
if (isActive.value || fingerX) {
setFingerX(fingerX)
runOnJS(setFingerPoint)(fingerX)
}
},
[isActive, setFingerX, width, x]
)
useAnimatedReaction(
() => isActive.value,
(active) => {
runOnJS(setIsActive)(active)
},
[isActive, setIsActive]
)
useEffect(() => {
if (pointsInRange.length !== 0 && commands.value.length !== 0)
pathEnd.value = 1
}, [commands, pathEnd, pointsInRange.length])
useEffect(() => {
if (indicatorPulsating) {
startPulsating()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [indicatorPulsating])
const axisLabelContainerStyle = {
paddingTop: TopAxisLabel != null ? 20 : 0,
paddingBottom: BottomAxisLabel != null ? 20 : 0,
}
const indicatorVisible = enableIndicator && commandsChanged > 0
return (
<View {...props}>
<GestureDetector gesture={gesture}>
<Reanimated.View style={[styles.container, axisLabelContainerStyle]}>
{/* Top Label (max price) */}
{TopAxisLabel != null && (
<View style={styles.axisRow}>
<TopAxisLabel />
</View>
)}
{/* Actual Skia Graph */}
<View style={styles.container} onLayout={onLayout}>
{/* Fix for react-native-skia's incorrect type declarations */}
<Canvas style={styles.svg}>
<Group>
<Path
// @ts-expect-error
path={path}
strokeWidth={lineThickness}
style="stroke"
strokeJoin="round"
strokeCap="round"
>
<LinearGradient
start={vec(0, 0)}
end={vec(width, 0)}
colors={gradientColors}
positions={positions}
/>
</Path>
{shouldFillGradient && (
<Path
// @ts-expect-error
path={gradientPath}
>
<LinearGradient
start={vec(0, 0)}
end={vec(0, height)}
colors={gradientFillColors}
/>
</Path>
)}
</Group>
{SelectionDot != null && (
<SelectionDot
isActive={isActive}
color={color}
lineThickness={lineThickness}
circleX={circleX}
circleY={circleY}
/>
)}
{indicatorVisible && (
<Group>
{indicatorPulsating && (
<Circle
cx={indicatorX}
cy={indicatorY}
r={indicatorPulseRadius}
opacity={indicatorPulseOpacity}
color={indicatorPulseColor}
style="fill"
/>
)}
<Circle
cx={indicatorX}
cy={indicatorY}
r={indicatorBorderRadius}
color="#ffffff"
>
<Shadow dx={2} dy={2} color="rgba(0,0,0,0.2)" blur={4} />
</Circle>
<Circle
cx={indicatorX}
cy={indicatorY}
r={indicatorRadius}
color={color}
/>
</Group>
)}
</Canvas>
</View>
{/* Bottom Label (min price) */}
{BottomAxisLabel != null && (
<View style={styles.axisRow}>
<BottomAxisLabel />
</View>
)}
</Reanimated.View>
</GestureDetector>
</View>
)
}
const styles = StyleSheet.create({
svg: {
flex: 1,
},
container: {
flex: 1,
},
axisRow: {
height: 17,
},
})