@react-native-ohos/victory-native-xl 41.17.5-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ The MIT License (MIT)
2
+ Copyright © 2024 <copyright holders>
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,11 @@
1
+ [
2
+ {
3
+ "Name": "victory-native-xl",
4
+ "License": "MIT License",
5
+ "License File": " LICENSE ",
6
+ "Version Number": "41.17.4",
7
+ "Owner" : "xiafeng@huawei.com",
8
+ "Upstream URL": "https://github.com/FormidableLabs/victory-native-xl",
9
+ "Description": "A charting library for React Native with a focus on performance and customization."
10
+ }
11
+ ]
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @react-native-oh-tpl/victory-native-xl
2
+
3
+ 本项目基于 [victory-native-xl](https://github.com/FormidableLabs/victory-native-xl)
4
+
5
+ ## 文档地址 / Documentation URL
6
+
7
+ [中文 / Chinese](https://gitee.com/react-native-oh-library/usage-docs/blob/master/zh-cn/victory-native-xl.md)
8
+
9
+ [英文 / English](https://gitee.com/react-native-oh-library/usage-docs/blob/master/zh-en/victory-native-xl.md)
10
+
11
+ ## 请悉知 / Acknowledgements
12
+
13
+ 本项目基于 [The MIT License (MIT)](https://www.mit-license.org/) ,请自由地享受和参与开源。
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@react-native-ohos/victory-native-xl",
3
+ "version": "41.17.5-rc.1",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/FormidableLabs/victory-native-xl"
9
+ },
10
+ "harmony": {
11
+ "alias": "victory-native-xl"
12
+ },
13
+ "main": "src/index.ts",
14
+ "files": [
15
+ "src"
16
+ ],
17
+ "scripts": {
18
+ "build": "rm -rf dist && tsc -p ./tsconfig.build.json",
19
+ "dev": "tsc --watch",
20
+ "typecheck": "tsc --noEmit",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest"
23
+ },
24
+ "dependencies": {
25
+ "d3-scale": "^4.0.2",
26
+ "d3-shape": "^3.2.0",
27
+ "its-fine": "^1.2.5",
28
+ "react-fast-compare": "^3.2.2",
29
+ "react-native-reanimated": "^3.18.0"
30
+ },
31
+ "peerDependencies": {
32
+ "@shopify/react-native-skia": "^1.3.7",
33
+ "react": "18.3.1",
34
+ "victory-native": "^41.17.4",
35
+ "react-native": "0.77.1"
36
+ },
37
+ "devDependencies": {
38
+ "@types/d3-scale": "^4.0.3",
39
+ "@types/d3-shape": "^3.1.1",
40
+ "@types/react": "~18.2.14",
41
+ "typescript": "^5.1.6",
42
+ "vitest": "^0.34.2"
43
+ }
44
+ }
@@ -0,0 +1,709 @@
1
+ import * as React from "react";
2
+ import { type LayoutChangeEvent, Button, View } from "react-native";
3
+ import { Canvas, Group, rect, Path } from "@shopify/react-native-skia";
4
+ import { useSharedValue } from "react-native-reanimated";
5
+ import {
6
+ type ComposedGesture,
7
+ Gesture,
8
+ GestureDetector,
9
+ GestureHandlerRootView,
10
+ type TouchData,
11
+ } from "react-native-gesture-handler";
12
+ import { type MutableRefObject } from "react";
13
+ import type { ScaleLinear } from "d3-scale";
14
+ import type {
15
+ AxisProps,
16
+ CartesianChartRenderArg,
17
+ InputFields,
18
+ NumericalFields,
19
+ SidedNumber,
20
+ TransformedData,
21
+ ChartBounds,
22
+ Viewport,
23
+ ChartPressPanConfig,
24
+ YAxisInputProps,
25
+ FrameInputProps,
26
+ XAxisInputProps,
27
+ GestureHandlerConfig
28
+ } from "victory-native/src/types";
29
+ import { transformInputData } from "victory-native/src/cartesian/utils/transformInputData";
30
+ import { findClosestPoint } from "victory-native/src/utils/findClosestPoint";
31
+ import { valueFromSidedNumber } from "victory-native/src/utils/valueFromSidedNumber";
32
+ import {
33
+ CartesianAxis,
34
+ CartesianAxisDefaultProps,
35
+ } from "victory-native/src/cartesian/components/CartesianAxis";
36
+ import { asNumber } from "victory-native/src/utils/asNumber";
37
+ import type { ChartPressState,
38
+ ChartPressStateInit, } from "victory-native/src/cartesian/hooks/useChartPressState";
39
+ import { useFunctionRef } from "victory-native/src/hooks/useFunctionRef";
40
+ import { CartesianChartProvider } from "victory-native/src/cartesian/contexts/CartesianChartContext";
41
+ import { XAxis } from "victory-native/src/cartesian/components/XAxis";
42
+ import { YAxis } from "victory-native/src/cartesian/components/YAxis";
43
+ import { Frame } from "victory-native/src/cartesian/components/Frame";
44
+ import { useBuildChartAxis } from "victory-native/src/cartesian/hooks/useBuildChartAxis";
45
+ import { type ChartTransformState } from "victory-native/src/cartesian/hooks/useChartTransformState";
46
+ import {
47
+ panTransformGesture,
48
+ type PanTransformGestureConfig,
49
+ pinchTransformGesture,
50
+ type PinchTransformGestureConfig,
51
+ } from "victory-native/src/cartesian/utils/transformGestures";
52
+ import {
53
+ CartesianTransformProvider,
54
+ useCartesianTransformContext,
55
+ } from "victory-native/src/cartesian/contexts/CartesianTransformContext";
56
+ import { downsampleTicks } from "victory-native/src/utils/tickHelpers";
57
+ import { GestureHandler } from "victory-native/src/shared/GestureHandler";
58
+ import { boundsToClip } from "victory-native/src/utils/boundsToClip";
59
+ import { normalizeYAxisTicks } from "victory-native/src/utils/normalizeYAxisTicks";
60
+ import { createFallbackChartState } from "victory-native/src/cartesian/utils/createFallbackChartState";
61
+ import { ZoomTransform } from "d3-zoom";
62
+ import isEqual from "react-fast-compare";
63
+ export type CartesianActionsHandle<T = undefined> =
64
+ T extends ChartPressState<infer S>
65
+ ? S extends ChartPressStateInit
66
+ ? {
67
+ handleTouch: (v: T, x: number, y: number) => void;
68
+ }
69
+ : never
70
+ : never;
71
+
72
+ type CartesianChartProps<
73
+ RawData extends Record<string, unknown>,
74
+ XK extends keyof InputFields<RawData>,
75
+ YK extends keyof NumericalFields<RawData>,
76
+ > = {
77
+ data: RawData[];
78
+ xKey: XK;
79
+ yKeys: YK[];
80
+ padding?: SidedNumber;
81
+ domainPadding?: SidedNumber;
82
+ domain?: { x?: [number] | [number, number]; y?: [number] | [number, number] };
83
+ viewport?: Viewport;
84
+ chartPressState?:
85
+ | ChartPressState<{ x: InputFields<RawData>[XK]; y: Record<YK, number> }>
86
+ | ChartPressState<{ x: InputFields<RawData>[XK]; y: Record<YK, number> }>[];
87
+ chartPressConfig?: {
88
+ pan?: ChartPressPanConfig;
89
+ };
90
+ gestureHandlerConfig?: GestureHandlerConfig;
91
+ children: (args: CartesianChartRenderArg<RawData, YK>) => React.ReactNode;
92
+ renderOutside?: (
93
+ args: CartesianChartRenderArg<RawData, YK>,
94
+ ) => React.ReactNode;
95
+ axisOptions?: Partial<Omit<AxisProps<RawData, XK, YK>, "xScale" | "yScale">>;
96
+
97
+ onChartBoundsChange?: (bounds: ChartBounds) => void;
98
+ onScaleChange?: (
99
+ xScale: ScaleLinear<number, number>,
100
+ yScale: ScaleLinear<number, number>,
101
+ ) => void;
102
+ /**
103
+ * @deprecated This prop will eventually be replaced by the new `chartPressConfig`. For now it's being kept around for backwards compatibility sake.
104
+ */
105
+ gestureLongPressDelay?: number;
106
+ xAxis?: XAxisInputProps<RawData, XK>;
107
+ yAxis?: YAxisInputProps<RawData, YK>[];
108
+ frame?: FrameInputProps;
109
+ transformState?: ChartTransformState;
110
+ transformConfig?: {
111
+ pan?: PanTransformGestureConfig;
112
+ pinch?: PinchTransformGestureConfig;
113
+ };
114
+ customGestures?: ComposedGesture;
115
+ actionsRef?: MutableRefObject<CartesianActionsHandle<
116
+ | ChartPressState<{
117
+ x: InputFields<RawData>[XK];
118
+ y: Record<YK, number>;
119
+ }>
120
+ | undefined
121
+ > | null>;
122
+ };
123
+
124
+ export function CartesianChart<
125
+ RawData extends Record<string, unknown>,
126
+ XK extends keyof InputFields<RawData>,
127
+ YK extends keyof NumericalFields<RawData>,
128
+ >({ transformState, children, ...rest }: CartesianChartProps<RawData, XK, YK>) {
129
+ return (
130
+ <CartesianTransformProvider transformState={transformState}>
131
+ <CartesianChartContent {...{ ...rest, transformState }}>
132
+ {children}
133
+ </CartesianChartContent>
134
+ </CartesianTransformProvider>
135
+ );
136
+ }
137
+
138
+ function CartesianChartContent<
139
+ RawData extends Record<string, unknown>,
140
+ XK extends keyof InputFields<RawData>,
141
+ YK extends keyof NumericalFields<RawData>,
142
+ >({
143
+ data,
144
+ xKey,
145
+ yKeys,
146
+ padding,
147
+ domainPadding,
148
+ children,
149
+ renderOutside = () => null,
150
+ axisOptions,
151
+ domain,
152
+ chartPressState,
153
+ chartPressConfig,
154
+ gestureHandlerConfig,
155
+ onChartBoundsChange,
156
+ onScaleChange,
157
+ gestureLongPressDelay = 100,
158
+ xAxis,
159
+ yAxis,
160
+ frame,
161
+ transformState,
162
+ transformConfig,
163
+ customGestures,
164
+ actionsRef,
165
+ viewport,
166
+ }: CartesianChartProps<RawData, XK, YK>) {
167
+ const [size, setSize] = React.useState({ width: 0, height: 0 });
168
+ const chartBoundsRef = React.useRef<ChartBounds | undefined>(undefined);
169
+ const xScaleRef = React.useRef<ScaleLinear<number, number> | undefined>(
170
+ undefined,
171
+ );
172
+ const yScaleRef = React.useRef<ScaleLinear<number, number> | undefined>(
173
+ undefined,
174
+ );
175
+ const [hasMeasuredLayoutSize, setHasMeasuredLayoutSize] =
176
+ React.useState(false);
177
+ const onLayout = React.useCallback(
178
+ ({ nativeEvent: { layout } }: LayoutChangeEvent) => {
179
+ setHasMeasuredLayoutSize(true);
180
+ setSize(layout);
181
+ },
182
+ [],
183
+ );
184
+ const normalizedAxisProps = useBuildChartAxis({
185
+ xAxis,
186
+ yAxis,
187
+ frame,
188
+ yKeys,
189
+ axisOptions,
190
+ });
191
+
192
+ // create a d3-zoom transform object based on the current transform state. This
193
+ // is used for rescaling the X and Y axes.
194
+ const transform = useCartesianTransformContext();
195
+ const zoomX = React.useMemo(
196
+ () => new ZoomTransform(transform.k, transform.tx, transform.ty),
197
+ [transform.k, transform.tx, transform.ty],
198
+ );
199
+ const zoomY = React.useMemo(
200
+ () => new ZoomTransform(transform.ky, transform.tx, transform.ty),
201
+ [transform.ky, transform.tx, transform.ty],
202
+ );
203
+
204
+ const tData = useSharedValue<TransformedData<RawData, XK, YK>>({
205
+ ix: [],
206
+ ox: [],
207
+ y: yKeys.reduce(
208
+ (acc, key) => {
209
+ acc[key] = { i: [], o: [] };
210
+ return acc;
211
+ },
212
+ {} as TransformedData<RawData, XK, YK>["y"],
213
+ ),
214
+ });
215
+
216
+ const {
217
+ yAxes,
218
+ xScale,
219
+ chartBounds,
220
+ isNumericalData,
221
+ xTicksNormalized,
222
+ _tData,
223
+ } = React.useMemo(() => {
224
+ if (!data.length) {
225
+ return createFallbackChartState<RawData, XK, YK>(yKeys);
226
+ }
227
+ const { xScale, yAxes, isNumericalData, xTicksNormalized, ..._tData } =
228
+ transformInputData({
229
+ data,
230
+ xKey,
231
+ yKeys,
232
+ outputWindow: {
233
+ xMin: valueFromSidedNumber(padding, "left"),
234
+ xMax: size.width - valueFromSidedNumber(padding, "right"),
235
+ yMin: valueFromSidedNumber(padding, "top"),
236
+ yMax: size.height - valueFromSidedNumber(padding, "bottom"),
237
+ },
238
+ domain,
239
+ domainPadding,
240
+ xAxis: normalizedAxisProps.xAxis,
241
+ yAxes: normalizedAxisProps.yAxes,
242
+ viewport,
243
+ labelRotate: normalizedAxisProps.xAxis.labelRotate,
244
+ });
245
+
246
+ const primaryYAxis = yAxes[0];
247
+ const primaryYScale = primaryYAxis.yScale;
248
+ const chartBounds = {
249
+ left: xScale(viewport?.x?.[0] ?? xScale.domain().at(0) ?? 0),
250
+ right: xScale(viewport?.x?.[1] ?? xScale.domain().at(-1) ?? 0),
251
+ top: primaryYScale(
252
+ viewport?.y?.[1] ?? (primaryYScale.domain().at(0) || 0),
253
+ ),
254
+ bottom: primaryYScale(
255
+ viewport?.y?.[0] ?? (primaryYScale.domain().at(-1) || 0),
256
+ ),
257
+ };
258
+
259
+ return {
260
+ xTicksNormalized,
261
+ yAxes,
262
+ xScale,
263
+ chartBounds,
264
+ isNumericalData,
265
+ _tData,
266
+ };
267
+ }, [
268
+ data,
269
+ xKey,
270
+ yKeys,
271
+ padding,
272
+ size.width,
273
+ size.height,
274
+ domain,
275
+ domainPadding,
276
+ normalizedAxisProps,
277
+ viewport,
278
+ ]);
279
+
280
+ React.useEffect(() => {
281
+ tData.value = _tData;
282
+ }, [_tData, tData]);
283
+
284
+ const primaryYAxis = yAxes[0];
285
+ const primaryYScale = primaryYAxis.yScale;
286
+
287
+ // stacked bar values
288
+ const chartHeight = chartBounds.bottom;
289
+ const yScaleTop = primaryYAxis.yScale.domain().at(0);
290
+ const yScaleBottom = primaryYAxis.yScale.domain().at(-1);
291
+ // end stacked bar values
292
+
293
+ /**
294
+ * Pan gesture handling
295
+ */
296
+ const lastIdx = useSharedValue(null as null | number);
297
+ /**
298
+ * Take a "press value" and an x-value and update the shared values accordingly.
299
+ */
300
+ const handleTouch = (
301
+ v: ChartPressState<{ x: InputFields<RawData>[XK]; y: Record<YK, number> }>,
302
+ x: number,
303
+ y: number,
304
+ ) => {
305
+ "worklet";
306
+ const idx = findClosestPoint(tData.value.ox, x);
307
+
308
+ if (typeof idx !== "number") return;
309
+
310
+ const isInYs = (yk: string): yk is YK & string => yKeys.includes(yk as YK);
311
+
312
+ // begin stacked bar handling:
313
+ // store the heights of each bar segment
314
+ const barHeights: number[] = [];
315
+ for (const yk in v.y) {
316
+ if (isInYs(yk)) {
317
+ const height = asNumber(tData.value.y[yk].i[idx]);
318
+ barHeights.push(height);
319
+ }
320
+ }
321
+
322
+ const chartYPressed = chartHeight - y; // Invert y-coordinate, since RNGH gives us the absolute Y, and we want to know where in the chart they clicked
323
+ // Calculate the actual yValue of the touch within the domain of the yScale
324
+ const yDomainValue =
325
+ (chartYPressed / chartHeight) * (yScaleTop! - yScaleBottom!);
326
+
327
+ // track the cumulative height and the y-index of the touched segment
328
+ let cumulativeHeight = 0;
329
+ let yIndex = -1;
330
+
331
+ // loop through the bar heights to find which bar was touched
332
+ for (let i = 0; i < barHeights.length; i++) {
333
+ // Accumulate the height as we go along
334
+ cumulativeHeight += barHeights[i]!;
335
+ // Check if the y-value touched falls within the current segment
336
+ if (yDomainValue <= cumulativeHeight) {
337
+ // If it does, set yIndex to the current segment index and break
338
+ yIndex = i;
339
+ break;
340
+ }
341
+ }
342
+
343
+ // Update the yIndex value in the state or context
344
+ v.yIndex.value = yIndex;
345
+ // end stacked bar handling
346
+
347
+ if (v) {
348
+ try {
349
+ v.matchedIndex.value = idx;
350
+ v.x.value.value = tData.value.ix[idx]!;
351
+ v.x.position.value = asNumber(tData.value.ox[idx]);
352
+ for (const yk in v.y) {
353
+ if (isInYs(yk)) {
354
+ v.y[yk].value.value = asNumber(tData.value.y[yk].i[idx]);
355
+ v.y[yk].position.value = asNumber(tData.value.y[yk].o[idx]);
356
+ }
357
+ }
358
+ } catch (err) {
359
+ // no-op
360
+ }
361
+ }
362
+
363
+ lastIdx.value = idx;
364
+ };
365
+
366
+ if (actionsRef) {
367
+ actionsRef.current = {
368
+ handleTouch,
369
+ };
370
+ }
371
+
372
+ /**
373
+ * Touch gesture is a modified Pan gesture handler that allows for multiple presses:
374
+ * - Using Pan Gesture handler effectively _just_ for the .activateAfterLongPress functionality.
375
+ * - Tracking the finger is handled with .onTouchesMove instead of .onUpdate, because
376
+ * .onTouchesMove gives us access to each individual finger.
377
+ * - The activation gets a bit complicated because we want to wait til "start" state before updating Press Value
378
+ * which gives time for the gesture to get cancelled before we start updating the shared values.
379
+ * Therefore we use gestureState.bootstrap to store some "bootstrap" information if gesture isn't active when finger goes down.
380
+ */
381
+ // touch ID -> value index mapping to keep track of which finger updates which value
382
+ const touchMap = useSharedValue({} as Record<number, number | undefined>);
383
+ const activePressSharedValues = Array.isArray(chartPressState)
384
+ ? chartPressState
385
+ : [chartPressState];
386
+ const gestureState = useSharedValue({
387
+ isGestureActive: false,
388
+ bootstrap: [] as [
389
+ ChartPressState<{ x: InputFields<RawData>[XK]; y: Record<YK, number> }>,
390
+ TouchData,
391
+ ][],
392
+ });
393
+
394
+ const panGesture = Gesture.Pan()
395
+ /**
396
+ * When a finger goes down, either update the state or store in the bootstrap array.
397
+ */
398
+ .onTouchesDown((e) => {
399
+ const vals = activePressSharedValues || [];
400
+ if (!vals.length || e.numberOfTouches === 0) return;
401
+
402
+ for (let i = 0; i < Math.min(e.allTouches.length, vals.length); i++) {
403
+ const touch = e.allTouches[i];
404
+ const v = vals[i];
405
+ if (!v || !touch) continue;
406
+
407
+ if (gestureState.value.isGestureActive) {
408
+ // Update the mapping
409
+ if (typeof touchMap.value[touch.id] !== "number")
410
+ touchMap.value[touch.id] = i;
411
+
412
+ v.isActive.value = true;
413
+ handleTouch(v, touch.x, touch.y);
414
+ } else {
415
+ gestureState.value.bootstrap.push([v, touch]);
416
+ }
417
+ }
418
+ })
419
+ /**
420
+ * On start, check if we have any bootstrapped updates we need to apply.
421
+ */
422
+ .onStart(() => {
423
+ gestureState.value.isGestureActive = true;
424
+
425
+ for (let i = 0; i < gestureState.value.bootstrap.length; i++) {
426
+ const [v, touch] = gestureState.value.bootstrap[i]!;
427
+ // Update the mapping
428
+ if (typeof touchMap.value[touch.id] !== "number")
429
+ touchMap.value[touch.id] = i;
430
+
431
+ v.isActive.value = true;
432
+ handleTouch(v, touch.x, touch.y);
433
+ }
434
+ })
435
+ /**
436
+ * Clear gesture state on gesture end.
437
+ */
438
+ .onFinalize(() => {
439
+ gestureState.value.isGestureActive = false;
440
+ gestureState.value.bootstrap = [];
441
+ })
442
+ /**
443
+ * As fingers move, update the shared values accordingly.
444
+ */
445
+ .onTouchesMove((e) => {
446
+ const vals = activePressSharedValues || [];
447
+ if (!vals.length || e.numberOfTouches === 0) return;
448
+
449
+ for (let i = 0; i < Math.min(e.allTouches.length, vals.length); i++) {
450
+ const touch = e.allTouches[i];
451
+ const touchId = touch?.id;
452
+ const idx = typeof touchId === "number" && touchMap.value[touchId];
453
+ const v = typeof idx === "number" && vals?.[idx];
454
+
455
+ if (!v || !touch) continue;
456
+ if (!v.isActive.value) v.isActive.value = true;
457
+ handleTouch(v, touch.x, touch.y);
458
+ }
459
+ })
460
+ /**
461
+ * On each finger up, start to update values and "free up" the touch map.
462
+ */
463
+ .onTouchesUp((e) => {
464
+ for (const touch of e.changedTouches) {
465
+ const vals = activePressSharedValues || [];
466
+
467
+ // Set active state to false
468
+ const touchId = touch?.id;
469
+ const idx = typeof touchId === "number" && touchMap.value[touchId];
470
+ const val = typeof idx === "number" && vals[idx];
471
+ if (val) {
472
+ val.isActive.value = false;
473
+ }
474
+
475
+ // Free up touch map for this touch
476
+ touchMap.value[touch.id] = undefined;
477
+ }
478
+ })
479
+ /**
480
+ * Once the gesture ends, ensure all active values are falsified.
481
+ */
482
+ .onEnd(() => {
483
+ const vals = activePressSharedValues || [];
484
+ // Set active state to false for all vals
485
+ for (const val of vals) {
486
+ if (val) {
487
+ val.isActive.value = false;
488
+ }
489
+ }
490
+ });
491
+
492
+ if (!chartPressConfig?.pan) {
493
+ /**
494
+ * Activate after a long press, which helps with preventing all touch hijacking.
495
+ * This is important if this chart is inside of some sort of scrollable container.
496
+ */
497
+ panGesture.activateAfterLongPress(gestureLongPressDelay);
498
+ }
499
+
500
+ if (chartPressConfig?.pan?.activateAfterLongPress) {
501
+ panGesture.activateAfterLongPress(
502
+ chartPressConfig.pan?.activateAfterLongPress,
503
+ );
504
+ }
505
+ if (chartPressConfig?.pan?.activeOffsetX) {
506
+ panGesture.activeOffsetX(chartPressConfig.pan.activeOffsetX);
507
+ }
508
+ if (chartPressConfig?.pan?.activeOffsetY) {
509
+ panGesture.activeOffsetX(chartPressConfig.pan.activeOffsetY);
510
+ }
511
+ if (chartPressConfig?.pan?.failOffsetX) {
512
+ panGesture.failOffsetX(chartPressConfig.pan.failOffsetX);
513
+ }
514
+ if (chartPressConfig?.pan?.failOffsetY) {
515
+ panGesture.failOffsetX(chartPressConfig.pan.failOffsetY);
516
+ }
517
+
518
+ /**
519
+ * Allow end-user to request "raw-ish" data for a given yKey.
520
+ * Generate this on demand using a proxy.
521
+ */
522
+ type PointsArg = CartesianChartRenderArg<RawData, YK>["points"];
523
+ const points = React.useMemo<PointsArg>(() => {
524
+ const cache = {} as Record<YK, PointsArg[keyof PointsArg]>;
525
+ return new Proxy(
526
+ {},
527
+ {
528
+ get(_, property: string): PointsArg[keyof PointsArg] | undefined {
529
+ const key = property as YK;
530
+ if (!yKeys.includes(key)) return undefined;
531
+ if (cache[key]) return cache[key];
532
+
533
+ cache[key] = _tData.ix.map((x, i) => ({
534
+ x: asNumber(_tData.ox[i]),
535
+ xValue: x,
536
+ y: _tData.y[key].o[i],
537
+ yValue: _tData.y[key].i[i],
538
+ }));
539
+
540
+ return cache[key];
541
+ },
542
+ },
543
+ ) as PointsArg;
544
+ }, [_tData, yKeys]);
545
+
546
+ // On bounds change, emit
547
+ const onChartBoundsRef = useFunctionRef(onChartBoundsChange);
548
+ React.useEffect(() => {
549
+ if (!isEqual(chartBounds, chartBoundsRef.current)) {
550
+ chartBoundsRef.current = chartBounds;
551
+ onChartBoundsRef.current?.(chartBounds);
552
+ }
553
+ }, [chartBounds, onChartBoundsRef]);
554
+
555
+ const onScaleRef = useFunctionRef(onScaleChange);
556
+ React.useEffect(() => {
557
+ const rescaledX = zoomX.rescaleX(xScale);
558
+ const rescaledY = zoomY.rescaleY(primaryYScale);
559
+ if (
560
+ !isEqual(xScaleRef.current?.domain(), rescaledX.domain()) ||
561
+ !isEqual(yScaleRef.current?.domain(), rescaledY.domain()) ||
562
+ !isEqual(xScaleRef.current?.range(), rescaledX.range()) ||
563
+ !isEqual(yScaleRef.current?.range(), rescaledY.range())
564
+ ) {
565
+ xScaleRef.current = xScale;
566
+ yScaleRef.current = primaryYScale;
567
+ onScaleRef.current?.(rescaledX, rescaledY);
568
+ }
569
+ }, [onScaleChange, onScaleRef, xScale, zoomX, zoomY, primaryYScale]);
570
+
571
+ const renderArg: CartesianChartRenderArg<RawData, YK> = {
572
+ xScale,
573
+ xTicks: xTicksNormalized,
574
+ yScale: primaryYScale,
575
+ yTicks: primaryYAxis.yTicksNormalized,
576
+ chartBounds,
577
+ canvasSize: size,
578
+ points,
579
+ };
580
+
581
+ const clipRect = boundsToClip(chartBounds);
582
+ const YAxisComponents =
583
+ hasMeasuredLayoutSize && (axisOptions || yAxes)
584
+ ? normalizedAxisProps.yAxes?.map((axis, index) => {
585
+ const yAxis = yAxes[index];
586
+
587
+ if (!yAxis) return null;
588
+
589
+ const primaryAxisProps = normalizedAxisProps.yAxes[0]!;
590
+ const primaryRescaled = zoomY.rescaleY(primaryYScale);
591
+ const rescaled = zoomY.rescaleY(yAxis.yScale);
592
+
593
+ const rescaledTicks = axis.tickValues
594
+ ? downsampleTicks(axis.tickValues, axis.tickCount)
595
+ : axis.enableRescaling
596
+ ? rescaled.ticks(axis.tickCount)
597
+ : yAxis.yScale.ticks(axis.tickCount);
598
+
599
+ const primaryTicksRescaled = primaryAxisProps.tickValues
600
+ ? downsampleTicks(
601
+ primaryAxisProps.tickValues,
602
+ primaryAxisProps.tickCount,
603
+ )
604
+ : primaryAxisProps.enableRescaling
605
+ ? primaryRescaled.ticks(primaryAxisProps.tickCount)
606
+ : primaryYScale.ticks(primaryAxisProps.tickCount);
607
+
608
+ return (
609
+ <YAxis
610
+ key={index}
611
+ {...axis}
612
+ xScale={zoomX.rescaleX(xScale)}
613
+ yScale={rescaled}
614
+ yTicksNormalized={
615
+ index > 0 && !axis.tickValues
616
+ ? normalizeYAxisTicks(
617
+ primaryTicksRescaled,
618
+ primaryRescaled,
619
+ rescaled,
620
+ )
621
+ : rescaledTicks
622
+ }
623
+ chartBounds={chartBounds}
624
+ />
625
+ );
626
+ })
627
+ : null;
628
+
629
+ const XAxisComponents =
630
+ hasMeasuredLayoutSize && (axisOptions || xAxis) ? (
631
+ <XAxis
632
+ {...normalizedAxisProps.xAxis}
633
+ xScale={xScale}
634
+ yScale={zoomY.rescaleY(primaryYScale)}
635
+ ix={_tData.ix}
636
+ isNumericalData={isNumericalData}
637
+ chartBounds={chartBounds}
638
+ zoom={zoomX}
639
+ />
640
+ ) : null;
641
+
642
+ const FrameComponent =
643
+ hasMeasuredLayoutSize && (axisOptions || frame) ? (
644
+ <Frame
645
+ {...normalizedAxisProps.frame}
646
+ xScale={xScale}
647
+ yScale={primaryYScale}
648
+ />
649
+ ) : null;
650
+
651
+ // Body of the chart.
652
+ const body = (
653
+ <Canvas style={{ flex: 1 }} onLayout={onLayout}>
654
+ {YAxisComponents}
655
+ {XAxisComponents}
656
+ {FrameComponent}
657
+ <CartesianChartProvider yScale={primaryYScale} xScale={xScale}>
658
+ <Group clip={clipRect}>
659
+ <Group matrix={transformState?.matrix}>
660
+ {hasMeasuredLayoutSize && children(renderArg)}
661
+ </Group>
662
+ </Group>
663
+ </CartesianChartProvider>
664
+ {hasMeasuredLayoutSize && renderOutside?.(renderArg)}
665
+ </Canvas>
666
+ );
667
+
668
+ let composed = customGestures ?? Gesture.Race();
669
+ if (transformState) {
670
+ let gestures = Gesture.Simultaneous();
671
+
672
+ if (transformConfig?.pinch?.enabled ?? true) {
673
+ gestures = Gesture.Simultaneous(
674
+ gestures,
675
+ pinchTransformGesture(transformState, transformConfig?.pinch),
676
+ );
677
+ }
678
+
679
+ if (transformConfig?.pan?.enabled ?? true) {
680
+ gestures = Gesture.Simultaneous(
681
+ gestures,
682
+ panTransformGesture(transformState, transformConfig?.pan),
683
+ );
684
+ }
685
+
686
+ composed = Gesture.Race(composed, Gesture.Simultaneous(gestures));
687
+ }
688
+ if (chartPressState) {
689
+ composed = Gesture.Race(composed, panGesture);
690
+ }
691
+
692
+ return (
693
+ <GestureHandlerRootView style={{ flex: 1, overflow: "hidden" }}>
694
+ {body}
695
+ <GestureHandler
696
+ config={gestureHandlerConfig}
697
+ gesture={composed}
698
+ transformState={transformState}
699
+ dimensions={{
700
+ x: Math.min(xScale.range()[0]!, 0),
701
+ y: Math.min(primaryYScale.range()[0]!, 0),
702
+ width: xScale.range()[1]! - Math.min(xScale.range()[0]!, 0),
703
+ height:
704
+ primaryYScale.range()[1]! - Math.min(primaryYScale.range()[0]!, 0),
705
+ }}
706
+ />
707
+ </GestureHandlerRootView>
708
+ );
709
+ }
package/src/index.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Cartesian chart exports (including useful types)
3
+ */
4
+ export { CartesianChart } from "./cartesian/CartesianChart";
5
+ export { PolarChart } from "./polar/PolarChart";
6
+
7
+
8
+ export { type CurveType } from "victory-native";
9
+ export { type RoundedCorners } from "victory-native";
10
+
11
+ export { useAnimatedPath } from "victory-native";
12
+ export { AnimatedPath } from "victory-native";
13
+ export { usePrevious } from "victory-native";
14
+ export {
15
+ useChartPressState,
16
+ type ChartPressState,
17
+ } from "victory-native";
18
+
19
+ // Line
20
+ export { useLinePath } from "victory-native";
21
+ export { Line } from "victory-native";
22
+
23
+ // Bar
24
+ export { useBarPath } from "victory-native";
25
+ export { Bar } from "victory-native";
26
+
27
+ // Bar group
28
+ export { useBarGroupPaths } from "victory-native";
29
+ export { BarGroup } from "victory-native";
30
+
31
+ // Area
32
+ export { useAreaPath } from "victory-native";
33
+ export { Area } from "victory-native";
34
+
35
+ // Scatter
36
+ export { Scatter, type ScatterShape } from "victory-native";
37
+
38
+ // Grid and Axis
39
+ export { CartesianAxis } from "victory-native";
40
+
41
+ /**
42
+ * Polar chart exports
43
+ */
44
+
45
+ /**
46
+ * Pie chart exports (including useful types)
47
+ */
48
+ export { Pie, type PieSliceData } from "victory-native";
49
+
50
+ export { useSlicePath } from "victory-native";
51
+ export { useSliceAngularInsetPath } from "victory-native";
52
+ export { useChartTransformState } from "victory-native";
@@ -0,0 +1,144 @@
1
+ import * as React from "react";
2
+
3
+ import { Canvas } from "@shopify/react-native-skia";
4
+ import { useContextBridge, FiberProvider } from "its-fine";
5
+ import {
6
+ StyleSheet,
7
+ View,
8
+ type ViewStyle,
9
+ type LayoutChangeEvent,
10
+ type StyleProp,
11
+ } from "react-native";
12
+ import {
13
+ PolarChartProvider,
14
+ usePolarChartContext,
15
+ } from "victory-native/src/polar/contexts/PolarChartContext";
16
+ import type {
17
+ ColorFields,
18
+ InputFields,
19
+ NumericalFields,
20
+ StringKeyOf,
21
+ } from "victory-native/src/types";
22
+
23
+ type PolarChartBaseProps = {
24
+ onLayout: ({ nativeEvent: { layout } }: LayoutChangeEvent) => void;
25
+ hasMeasuredLayoutSize: boolean;
26
+ canvasSize: { width: number; height: number };
27
+ containerStyle?: StyleProp<ViewStyle>;
28
+ canvasStyle?: StyleProp<ViewStyle>;
29
+ };
30
+
31
+ interface PolarChartContext {
32
+ data: Record<string, unknown>[];
33
+ canvasSize: { width: number; height: number };
34
+ labelKey: string;
35
+ valueKey: string;
36
+ colorKey: string;
37
+ }
38
+
39
+ const PolarChartBase = (
40
+ props: React.PropsWithChildren<PolarChartBaseProps>,
41
+ ) => {
42
+ const {
43
+ containerStyle,
44
+ canvasStyle,
45
+ children,
46
+ onLayout,
47
+ hasMeasuredLayoutSize,
48
+ canvasSize,
49
+ } = props;
50
+ const { width, height } = canvasSize;
51
+
52
+ const ctx = usePolarChartContext();
53
+ const ContextBridge = useContextBridge();
54
+ return (
55
+ <View style={[styles.baseContainer, containerStyle]}>
56
+ <Canvas
57
+ onLayout={onLayout}
58
+ style={StyleSheet.flatten([
59
+ styles.canvasContainer,
60
+ hasMeasuredLayoutSize ? { width, height } : null,
61
+ canvasStyle,
62
+ ])}
63
+ >
64
+ {/* https://shopify.github.io/react-native-skia/docs/canvas/contexts/
65
+ we have to re-inject our context to make it available in the skia renderer
66
+ */}
67
+ <ContextBridge {...ctx}>
68
+ {children}
69
+ </ContextBridge>
70
+ {/* <PolarChartProvider {...ctx} canvasSize={canvasSize}>
71
+ {children}
72
+ </PolarChartProvider> */}
73
+ </Canvas>
74
+ </View>
75
+ );
76
+ };
77
+
78
+ type PolarChartProps<
79
+ RawData extends Record<string, unknown>,
80
+ LabelKey extends StringKeyOf<InputFields<RawData>>,
81
+ ValueKey extends StringKeyOf<NumericalFields<RawData>>,
82
+ ColorKey extends StringKeyOf<ColorFields<RawData>>,
83
+ > = {
84
+ data: RawData[];
85
+ colorKey: ColorKey;
86
+ labelKey: LabelKey;
87
+ valueKey: ValueKey;
88
+ } & Omit<
89
+ PolarChartBaseProps,
90
+ "canvasSize" | "onLayout" | "hasMeasuredLayoutSize" // omit exposing internal props for calculating canvas layout/size
91
+ >;
92
+ export const PolarChart = <
93
+ RawData extends Record<string, unknown>,
94
+ LabelKey extends StringKeyOf<InputFields<RawData>>,
95
+ ValueKey extends StringKeyOf<NumericalFields<RawData>>,
96
+ ColorKey extends StringKeyOf<ColorFields<RawData>>,
97
+ >(
98
+ props: React.PropsWithChildren<
99
+ PolarChartProps<RawData, LabelKey, ValueKey, ColorKey>
100
+ >,
101
+ ) => {
102
+ const { data, labelKey, colorKey, valueKey } = props;
103
+
104
+ const [canvasSize, setCanvasSize] = React.useState({ width: 0, height: 0 });
105
+
106
+ const [hasMeasuredLayoutSize, setHasMeasuredLayoutSize] =
107
+ React.useState(false);
108
+
109
+ const onLayout = React.useCallback(
110
+ ({ nativeEvent: { layout } }: LayoutChangeEvent) => {
111
+ setHasMeasuredLayoutSize(true);
112
+ setCanvasSize(layout);
113
+ },
114
+ [],
115
+ );
116
+
117
+ return (
118
+ <FiberProvider>
119
+ <PolarChartProvider
120
+ data={data}
121
+ labelKey={labelKey.toString()}
122
+ colorKey={colorKey.toString()}
123
+ valueKey={valueKey.toString()}
124
+ canvasSize={canvasSize}
125
+ >
126
+ <PolarChartBase
127
+ {...props}
128
+ onLayout={onLayout}
129
+ hasMeasuredLayoutSize={hasMeasuredLayoutSize}
130
+ canvasSize={canvasSize}
131
+ />
132
+ </PolarChartProvider>
133
+ </FiberProvider>
134
+ );
135
+ };
136
+
137
+ const styles = StyleSheet.create({
138
+ baseContainer: {
139
+ flex: 1,
140
+ },
141
+ canvasContainer: {
142
+ flex: 1,
143
+ },
144
+ });