forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLineChartContent.tsx
More file actions
307 lines (271 loc) · 12 KB
/
LineChartContent.tsx
File metadata and controls
307 lines (271 loc) · 12 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
import {useFont} from '@shopify/react-native-skia';
import React, {useState} from 'react';
import type {LayoutChangeEvent} from 'react-native';
import {View} from 'react-native';
import {GestureDetector} from 'react-native-gesture-handler';
import {useSharedValue} from 'react-native-reanimated';
import type {CartesianChartRenderArg, ChartBounds, Scale} from 'victory-native';
import {CartesianChart, Line} from 'victory-native';
import ActivityIndicator from '@components/ActivityIndicator';
import ChartTooltip from '@components/Charts/components/ChartTooltip';
import ChartXAxisLabels from '@components/Charts/components/ChartXAxisLabels';
import LeftFrameLine from '@components/Charts/components/LeftFrameLine';
import ScatterPoints from '@components/Charts/components/ScatterPoints';
import {
AXIS_LABEL_GAP,
CHART_CONTENT_MIN_HEIGHT,
CHART_PADDING,
DIAGONAL_ANGLE_RADIAN_THRESHOLD,
X_AXIS_LINE_WIDTH,
Y_AXIS_LINE_WIDTH,
Y_AXIS_TICK_COUNT,
} from '@components/Charts/constants';
import fontSource from '@components/Charts/font';
import type {ComputeGeometryFn, HitTestArgs} from '@components/Charts/hooks';
import {useChartInteractions, useChartLabelFormats, useChartLabelLayout, useDynamicYDomain, useLabelHitTesting, useTooltipData} from '@components/Charts/hooks';
import type {CartesianChartProps, ChartDataPoint} from '@components/Charts/types';
import {calculateMinDomainPadding, DEFAULT_CHART_COLOR, measureTextWidth, rotatedLabelYOffset} from '@components/Charts/utils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan';
import variables from '@styles/variables';
/** Inner dot radius for line chart data points */
const DOT_RADIUS = 6;
/** Extra hover area beyond the dot radius for easier touch targeting */
const DOT_HOVER_EXTRA_RADIUS = 2;
/** Minimum safe padding to avoid clipping labels/points */
const MIN_SAFE_PADDING = DOT_RADIUS + DOT_HOVER_EXTRA_RADIUS;
/** Base domain padding applied to all sides */
const BASE_DOMAIN_PADDING = {top: 16, bottom: 16, left: 0, right: 0};
/**
* Line chart geometry for label hit-testing.
* Labels are start-anchored at the tick: the 45° parallelogram's upper-right corner is
* offset by (iconSize/3 * sinA) left and down, placing the box just below the axis line.
*/
const computeLineLabelGeometry: ComputeGeometryFn = ({ascent, descent, sinA, angleRad, labelWidths, padding}) => {
const iconThirdSin = (variables.iconSizeExtraSmall / 3) * sinA;
let additionalOffset = 0;
if (angleRad > 0 && angleRad < DIAGONAL_ANGLE_RADIAN_THRESHOLD) {
additionalOffset = variables.iconSizeExtraSmall / 1.5;
} else if (angleRad > 1) {
additionalOffset = variables.iconSizeExtraSmall / 3;
}
return {
labelYOffset: AXIS_LABEL_GAP + rotatedLabelYOffset(ascent, descent, angleRad) - additionalOffset,
iconSin: variables.iconSizeExtraSmall * sinA,
labelSins: labelWidths.map((w) => w * sinA),
halfWidths: labelWidths.map((w) => w / 2),
cornerAnchorDX: labelWidths.map(() => -iconThirdSin),
cornerAnchorDY: labelWidths.map(() => iconThirdSin),
yMin90Offsets: labelWidths.map(() => padding),
yMax90Offsets: labelWidths.map((w) => w + padding),
};
};
type LineChartProps = CartesianChartProps & {
/** Callback when a data point is pressed */
onPointPress?: (dataPoint: ChartDataPoint, index: number) => void;
};
function LineChartContent({data, isLoading, yAxisUnit, yAxisUnitPosition = 'left', onPointPress}: LineChartProps) {
const theme = useTheme();
const styles = useThemeStyles();
const font = useFont(fontSource, variables.iconSizeExtraSmall);
const [chartWidth, setChartWidth] = useState(0);
const [plotAreaWidth, setPlotAreaWidth] = useState(0);
const [boundsLeft, setBoundsLeft] = useState(0);
const [boundsRight, setBoundsRight] = useState(0);
const yAxisDomain = useDynamicYDomain(data);
const chartData = data.map((point, index) => ({
x: index,
y: point.total,
}));
const handlePointPress = (index: number) => {
if (index < 0 || index >= data.length) {
return;
}
const dataPoint = data.at(index);
if (dataPoint && onPointPress) {
onPointPress(dataPoint, index);
}
};
const handleLayout = (event: LayoutChangeEvent) => {
setChartWidth(event.nativeEvent.layout.width);
};
const chartBottom = useSharedValue(0);
const domainPadding = (() => {
if (chartWidth === 0 || data.length === 0) {
return BASE_DOMAIN_PADDING;
}
const geometricPadding = calculateMinDomainPadding(chartWidth, data.length);
if (!font) {
return {...BASE_DOMAIN_PADDING, left: geometricPadding, right: geometricPadding};
}
const firstLabelWidth = measureTextWidth(data.at(0)?.label ?? '', font);
const lastLabelWidth = measureTextWidth(data.at(-1)?.label ?? '', font);
const firstLabelNeeds = firstLabelWidth / 2;
const lastLabelNeeds = lastLabelWidth / 2;
const wastedLeft = geometricPadding - firstLabelNeeds;
const wastedRight = geometricPadding - lastLabelNeeds;
const reclaimablePadding = Math.min(wastedLeft, wastedRight);
if (reclaimablePadding <= 0) {
return {...BASE_DOMAIN_PADDING, left: geometricPadding, right: geometricPadding};
}
const horizontalPadding = Math.max(geometricPadding - reclaimablePadding, MIN_SAFE_PADDING);
return {...BASE_DOMAIN_PADDING, left: horizontalPadding, right: horizontalPadding};
})();
const tickSpacing = plotAreaWidth > 0 && data.length > 0 ? plotAreaWidth / data.length : 0;
const totalDomainPadding = domainPadding.left + domainPadding.right;
const paddingScale = plotAreaWidth > 0 ? plotAreaWidth / (plotAreaWidth + totalDomainPadding) : 0;
const {labelRotation, labelSkipInterval, truncatedLabels, xAxisLabelHeight} = useChartLabelLayout({
data,
font,
tickSpacing,
labelAreaWidth: plotAreaWidth,
firstTickLeftSpace: boundsLeft + domainPadding.left * paddingScale,
lastTickRightSpace: chartWidth > 0 ? chartWidth - boundsRight + domainPadding.right * paddingScale : 0,
allowTightDiagonalPacking: true,
});
const {formatValue} = useChartLabelFormats({
data,
font,
unit: yAxisUnit,
unitPosition: yAxisUnitPosition,
});
const {isCursorOverLabel, findLabelCursorX, updateTickPositions} = useLabelHitTesting({
font,
truncatedLabels,
labelRotation,
labelSkipInterval,
chartBottom,
computeGeometry: computeLineLabelGeometry,
});
const handleChartBoundsChange = (bounds: ChartBounds) => {
setPlotAreaWidth(bounds.right - bounds.left);
setBoundsLeft(bounds.left);
setBoundsRight(bounds.right);
chartBottom.set(bounds.bottom);
};
const checkIsOverDot = (args: HitTestArgs) => {
'worklet';
const dx = args.cursorX - args.targetX;
const dy = args.cursorY - args.targetY;
return Math.sqrt(dx * dx + dy * dy) <= DOT_RADIUS + DOT_HOVER_EXTRA_RADIUS;
};
const {customGestures, setPointPositions, activeDataIndex, isTooltipActive, isOverClickableTarget, initialTooltipPosition} = useChartInteractions({
handlePress: handlePointPress,
checkIsOver: checkIsOverDot,
isCursorOverLabel,
resolveLabelTouchX: findLabelCursorX,
chartBottom,
});
const handleScaleChange = (xScale: Scale, yScale: Scale) => {
updateTickPositions(xScale, data.length);
setPointPositions(
chartData.map((point) => xScale(point.x)),
chartData.map((point) => yScale(point.y)),
);
};
const tooltipData = useTooltipData(activeDataIndex, data, formatValue);
const renderOutside = (args: CartesianChartRenderArg<{x: number; y: number}, 'y'>) => {
return (
<>
<LeftFrameLine
chartBounds={args.chartBounds}
yTicks={args.yTicks}
yScale={args.yScale}
color={theme.border}
/>
<ScatterPoints
points={args.points.y}
radius={DOT_RADIUS}
color={DEFAULT_CHART_COLOR}
/>
{!!font && xAxisLabelHeight !== undefined && (
<ChartXAxisLabels
labels={truncatedLabels}
labelRotation={labelRotation}
labelSkipInterval={labelSkipInterval}
font={font}
labelColor={theme.textSupporting}
xScale={args.xScale}
chartBoundsBottom={args.chartBounds.bottom}
/>
)}
</>
);
};
const labelSpace = AXIS_LABEL_GAP + (xAxisLabelHeight ?? 0);
const dynamicChartStyle = {height: CHART_CONTENT_MIN_HEIGHT + labelSpace};
const chartPadding = {...CHART_PADDING, bottom: labelSpace + CHART_PADDING.bottom};
if (isLoading || !font) {
const reasonAttributes: SkeletonSpanReasonAttributes = {context: 'LineChartContent', isLoading, isFontLoading: !font};
return (
<View style={styles.chartActivityIndicator}>
<ActivityIndicator
size="large"
reasonAttributes={reasonAttributes}
/>
</View>
);
}
if (data.length === 0) {
return null;
}
return (
<GestureDetector gesture={customGestures}>
<View
style={[styles.chartContent, dynamicChartStyle, isOverClickableTarget && styles.cursorPointer]}
onLayout={handleLayout}
>
{chartWidth > 0 && (
<CartesianChart
xKey="x"
padding={chartPadding}
yKeys={['y']}
domainPadding={domainPadding}
onChartBoundsChange={handleChartBoundsChange}
onScaleChange={handleScaleChange}
renderOutside={renderOutside}
xAxis={{
tickCount: data.length,
lineWidth: X_AXIS_LINE_WIDTH,
}}
yAxis={[
{
font,
labelColor: theme.textSupporting,
formatYLabel: formatValue,
tickCount: Y_AXIS_TICK_COUNT,
lineWidth: Y_AXIS_LINE_WIDTH,
lineColor: theme.border,
labelOffset: AXIS_LABEL_GAP,
domain: yAxisDomain,
},
]}
frame={{lineWidth: 0}}
data={chartData}
>
{({points}) => (
<Line
points={points.y}
color={DEFAULT_CHART_COLOR}
strokeWidth={2}
curveType="linear"
/>
)}
</CartesianChart>
)}
{isTooltipActive && !!tooltipData && (
<ChartTooltip
label={tooltipData.label}
amount={tooltipData.amount}
percentage={tooltipData.percentage}
chartWidth={chartWidth}
initialTooltipPosition={initialTooltipPosition}
/>
)}
</View>
</GestureDetector>
);
}
export default LineChartContent;
export type {LineChartProps};