-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.tsx
More file actions
379 lines (320 loc) · 8.86 KB
/
App.tsx
File metadata and controls
379 lines (320 loc) · 8.86 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
import {scaleLinear} from 'd3-scale';
import * as shape from 'd3-shape';
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import {Button, Platform, StyleSheet, View} from 'react-native';
import {LongPressGestureHandler} from 'react-native-gesture-handler';
import Animated, {
cancelAnimation,
runOnUI,
useAnimatedGestureHandler,
useAnimatedProps,
useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
useWorkletCallback,
withSpring,
withTiming,
} from 'react-native-reanimated';
import {useVector} from 'react-native-redash';
import Svg, {Defs, LinearGradient, Path, Stop} from 'react-native-svg';
import {data1, data2, data3} from './datas';
import {requireOnUI} from './requireOnUI';
import {SIZE} from './src/Model';
interface ChartProps {
// gestureRef: React.Ref<LongPressGestureHandler>;
}
const AnimatedPath = Animated.createAnimatedComponent(Path);
const ChartsStackContext = React.createContext(null);
const CURSOR = 50;
const styles = StyleSheet.create({
cursor: {
width: CURSOR,
height: CURSOR,
borderRadius: CURSOR / 2,
backgroundColor: 'rgba(0, 0, 0, 0.1)',
justifyContent: 'center',
alignItems: 'center',
},
cursorBody: {
width: 15,
height: 15,
borderRadius: 7.5,
backgroundColor: 'red',
},
});
// shares all the gesture stuff between charts
function ChartsStack({children, width, height}) {
const isActive = useSharedValue(false);
const translation = useVector();
const onGestureEvent = useAnimatedGestureHandler({
onStart: () => {
isActive.value = true;
console.log('start');
},
onActive: event => {
isActive.value = true;
translation.x.value = event.x < 0 ? 0 : event.x > width ? width : event.x;
translation.y.value = event.y;
console.log('active', event.x, event.y);
},
onFail: () => {
isActive.value = false;
},
onCancel: () => {
isActive.value = false;
},
onEnd: () => {
isActive.value = false;
},
});
return (
<ChartsStackContext.Provider value={{isActive, translation, width, height}}>
<View style={{width, height}}>
<LongPressGestureHandler
{...{onGestureEvent}}
maxDist={100000}
minDurationMs={0}
shouldCancelWhenOutside={false}>
<Animated.View style={{width, height}}>{children}</Animated.View>
</LongPressGestureHandler>
</View>
</ChartsStackContext.Provider>
);
}
interface CursorData {
x: Animated.SharedValue<number>;
y: Animated.SharedValue<number>;
isActive: Animated.SharedValue<boolean>;
strokeColor: string;
}
interface ChartContext extends CursorData {}
const ChartContext = React.createContext<ChartContext>(null);
interface Point {
x: number;
y: number;
}
interface ChartProps {
data: Point[];
name: string;
children: React.ReactElement;
stroke?: string;
}
interface DataPoints {
// percent_change: number;
prices: PriceList;
}
type PriceList = {x: number; y: number}[];
const POINTS = 60;
function useUIValue() {
const idRef = useRef();
if (!idRef.current) {
// use some uuid here
idRef.current = Date.now() + Math.floor(Math.random() * 10000);
}
const {current} = idRef;
return useWorkletCallback(() => {
'worklet';
if (!global.remoteValues) {
global.remoteValues = {};
}
return {
get value() {
return global.remoteValues[current];
},
set value(value) {
global.remoteValues[current] = value;
},
};
});
}
function Chart({children, data, stroke}: ChartProps) {
const {isActive, translation, width, height} = useContext(ChartsStackContext);
// const gestureRef = useRef<LongPressGestureHandler>();
const interpolatorUI = useUIValue();
const pathPropertiesUI = useUIValue();
//////////////////////
const createPath = useCallback(({data, width, height}) => {
const x = data.map(item => item.x);
const y = data.map(item => item.y);
const scaleX = scaleLinear()
.domain([Math.min(...x), Math.max(...x)])
.range([0, width]);
const scaleY = scaleLinear()
.domain([Math.min(...y), Math.max(...y)])
.range([height, 0]);
const path = shape
.line()
.x(item => scaleX(item.x))
.y(item => scaleY(item.y)) // Y position of top line breaks
// .x(item => scaleX(item.x))
// .y1(item => scaleY(item.y)) // Y position of top line breaks
// .y0(height)
.curve(shape.curveBasis)(data);
return path;
}, []);
const initialPath = useMemo(() => createPath({data, width, height}), []);
const [paths, setPaths] = useState(() => [initialPath, initialPath]);
const transition = useSharedValue(0);
useEffect(() => {
setPaths(([_, curr]) => [curr, createPath({data, width, height})]);
}, [data]);
const timeout = useSharedValue(0);
useEffect(() => {
runOnUI(() => {
'worklet';
if (transition.value !== 0 && transition.value !== 1) {
cancelAnimation(translation);
cancelAnimation(timeout);
}
transition.value = 0;
interpolatorUI().value = requireOnUI(
'd3-interpolate-path',
).interpolatePath(paths[0], paths[1]);
pathPropertiesUI().value = requireOnUI('svg-path-properties')(paths[1]);
timeout.value = withTiming(
timeout.value === 1 ? 0 : 1,
{
duration: 100,
},
() => {
transition.value = withTiming(1);
},
);
})();
}, [paths]);
const x = useSharedValue(0);
const y = useSharedValue(0);
useAnimatedReaction(
() => translation.x.value,
value => {
if (!pathPropertiesUI().value) {
return 0;
}
const totalLength = pathPropertiesUI().value.getTotalLength();
const values = pathPropertiesUI().value.getPointAtLength(
totalLength * (value / width),
);
x.value = values.x;
y.value = values.y;
},
[paths],
);
const animatedProps = useAnimatedProps(() => {
const d = interpolatorUI().value
? interpolatorUI().value(transition.value)
: '';
return {
d: d,
};
}, [paths]);
const contextValue = useMemo<ChartContext>(
() => ({
x,
y,
isActive,
strokeColor: stroke,
}),
[],
);
const gradientY1Position = Platform.OS === 'android' ? '-700%' : '-130%';
return (
<ChartContext.Provider value={contextValue}>
<Animated.View style={{position: 'absolute', width, height}}>
<Svg
viewBox={`0 0 ${width} ${height}`}
width={width - 1}
height={height}>
<AnimatedPath
animatedProps={animatedProps}
fill="url(#prefix__paint0_linear)"
stroke={stroke}
strokeWidth={2}
/>
<Defs>
<LinearGradient
id="prefix__paint0_linear"
x1="100%"
y1={gradientY1Position}
x2="100%"
y2="120%">
<Stop stopColor={stroke} />
<Stop offset="100%" stopColor={'#FFFFFF'} stopOpacity={0} />
</LinearGradient>
</Defs>
</Svg>
</Animated.View>
{children}
</ChartContext.Provider>
);
}
function useChartData() {
return useContext(ChartContext);
}
function useCursor(): CursorData {
const {x, y, isActive, strokeColor} = useChartData();
return {x, y, isActive, strokeColor};
}
function Cursor({name}) {
const cursor = useCursor();
const style = useAnimatedStyle(() => {
const translateX = cursor.x.value - CURSOR / 2;
const translateY = cursor.y.value - CURSOR / 2;
return {
transform: [
{translateX},
{translateY},
{scale: withSpring(cursor.isActive.value ? 1 : 0)},
],
};
});
return (
<Animated.View style={[StyleSheet.absoluteFill]}>
<Animated.View style={[styles.cursor, style]}>
<View
style={[styles.cursorBody, {backgroundColor: cursor.strokeColor}]}
/>
</Animated.View>
</Animated.View>
);
}
function Rainbow() {
const [data, setData] = useState(false);
function swapData() {
setData(v => !v);
}
return (
<View
style={[
{
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
]}>
<ChartsStack width={SIZE - 50} height={SIZE / 3}>
<Chart data={data ? data1 : data3} stroke={'black'}>
<Cursor name="1" />
</Chart>
<Chart data={data ? data2 : data1} stroke={'red'}>
<Cursor name="1" />
</Chart>
{/* <Chart data={graph2} stroke={'black'}>
<Cursor name="2" />
</Chart> */}
{/* <Chart data={data2} name="third" stroke={'green'}>
<Cursor name="2" />
</Chart> */}
</ChartsStack>
<Button title="Swap data" onPress={swapData} />
</View>
);
}
export default Rainbow;