Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 45 additions & 27 deletions src/components/Charts/LineChart/LineChartContent.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import ActivityIndicator from '@components/ActivityIndicator';
import ActivePointIndicator from '@components/Charts/components/ActivePointIndicator';
import AreaGradient from '@components/Charts/components/AreaGradient';
import ChartGridLines from '@components/Charts/components/ChartGridLines';
import ChartTooltipLayer from '@components/Charts/components/ChartTooltipLayer';
import ChartXAxisLabels from '@components/Charts/components/ChartXAxisLabels';
import ChartYAxisLabels from '@components/Charts/components/ChartYAxisLabels';
import ScatterPoints from '@components/Charts/components/ScatterPoints';
import type {HitTestArgs} from '@components/Charts/hooks';
import {
ChartFontsProvider,
Expand Down Expand Up @@ -35,15 +35,6 @@ import {CartesianChart, Line} from 'victory-native';

import type {CartesianChartProps, ChartDataPoint} from '..';

/** Inner dot radius for line chart data points */
const DOT_RADIUS = 4;

/** Extra hover area beyond the dot radius for easier touch targeting */
const DOT_HOVER_EXTRA_RADIUS = 2;

/** Base domain padding applied to all sides */
const BASE_DOMAIN_PADDING = {top: 16, bottom: 16, left: 0, right: 0};

type LineChartProps = CartesianChartProps & {
onPointPress?: (dataPoint: ChartDataPoint, index: number) => void;
};
Expand Down Expand Up @@ -78,6 +69,10 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
};

const chartBottom = useSharedValue(0);
const plotTop = useSharedValue(0);
const plotLeft = useSharedValue(0);
const plotRight = useSharedValue(0);
const bandHalfWidth = useSharedValue(0);

const measurements = useChartLabelMeasurements(data, fontManager, variables.iconSizeExtraSmall);
const {lineHeight, firstLabelWidth, lastLabelWidth, maxLabelWidth, labelWidths} = measurements;
Expand All @@ -88,14 +83,14 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
unitPosition: yAxisUnitPosition,
});

const yAxisLabelWidth = getYAxisLabelWidth(data, formatCompactValue, fontManager, variables.iconSizeExtraSmall, BASE_DOMAIN_PADDING);
const yAxisLabelWidth = getYAxisLabelWidth(data, formatCompactValue, fontManager, variables.iconSizeExtraSmall, VictoryTheme.line.domainPadding);

const tickSpacing = plotAreaWidth > 0 && data.length > 0 ? plotAreaWidth / data.length : 0;
const chartPaddingRight = yAxisLabelWidth + GLYPH_PADDING;

const domainPadding = (() => {
if (!firstLabelWidth || !lastLabelWidth) {
return BASE_DOMAIN_PADDING;
return VictoryTheme.line.domainPadding;
}
const labelsExceedTickSpacing = tickSpacing > 0 && maxLabelWidth + LABEL_PADDING > tickSpacing;
let leftOverhang = firstLabelWidth / 2;
Expand All @@ -111,7 +106,7 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
left: Math.max(0, leftOverhang - VictoryTheme.axis.padding.left),
right: Math.max(0, rightOverhang - chartPaddingRight - VictoryTheme.axis.labelGap),
};
return {...BASE_DOMAIN_PADDING, ...getDomainPaddingForEdgeSpace(edgeSpace, plotAreaWidth)};
return {...VictoryTheme.line.domainPadding, ...getDomainPaddingForEdgeSpace(edgeSpace, plotAreaWidth)};
})();

const totalDomainPadding = domainPadding.left + domainPadding.right;
Expand Down Expand Up @@ -140,29 +135,46 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
});

const handleChartBoundsChange = (bounds: ChartBounds) => {
plotTop.set(bounds.top);
plotLeft.set(bounds.left);
plotRight.set(bounds.right);
setPlotAreaWidth(bounds.right - bounds.left);
setBoundsLeft(bounds.left);
setBoundsRight(bounds.right);
};

const checkIsOverDot = (args: HitTestArgs) => {
const labelSpace = VictoryTheme.axis.xAxisLabelGap + (xAxisLabelHeight ?? 0);

const isInPlotArea = (args: HitTestArgs) => {
'worklet';

return args.cursorX >= plotLeft.get() && args.cursorX <= plotRight.get() && args.cursorY >= plotTop.get() && args.cursorY <= args.chartBottom + labelSpace;
};

const checkIsOverBand = (args: HitTestArgs) => {
'worklet';

return isInPlotArea(args) && Math.abs(args.cursorX - args.targetX) <= bandHalfWidth.get();
};

const checkIsOverLabelInPlotArea = (args: HitTestArgs, activeIndex: number) => {
'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;
return isInPlotArea(args) && isCursorOverLabel(args, activeIndex);
};

const {customGestures, setPointPositions, matchedIndex, isTooltipActive, isCursorOverClickable, initialTooltipPosition} = useChartInteractions({
const {customGestures, setPointPositions, matchedIndex, isTooltipActive, isCursorOverClickable, initialTooltipPosition, activePointPosition} = useChartInteractions({
handlePress: handlePointPress,
checkIsOver: checkIsOverDot,
isCursorOverLabel,
checkIsOver: checkIsOverBand,
isCursorOverLabel: checkIsOverLabelInPlotArea,
resolveLabelTouchX: findLabelCursorX,
chartBottom,
});

const handleScaleChange = (xScale: Scale, yScale: Scale) => {
updateTickPositions(xScale, data.length);
const [rangeStart, rangeEnd] = xScale.range();
bandHalfWidth.set(data.length > 1 ? Math.abs(xScale(1) - xScale(0)) / 2 : Math.abs(rangeEnd - rangeStart));
setPointPositions(
chartData.map((point) => xScale(point.x)),
chartData.map((point) => yScale(point.y)),
Expand All @@ -178,11 +190,6 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
chartBottom.set(chartBoundsBottom);
return (
<>
<ScatterPoints
points={args.points.y}
radius={DOT_RADIUS}
color={VictoryTheme.colors.defaultDot}
/>
{xAxisLabelHeight !== undefined && !!fontManager && (
<ChartXAxisLabels
labels={originalLabels}
Expand Down Expand Up @@ -211,11 +218,20 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
formatValue={formatCompactValue}
/>
)}
<ActivePointIndicator
position={activePointPosition}
isActive={isTooltipActive}
top={args.chartBounds.top}
bottom={chartBoundsBottom}
dotRadius={VictoryTheme.line.activeDotRadius}
dotColor={VictoryTheme.colors.default}
guidelineColor={VictoryTheme.colors.default}
guidelineOpacity={VictoryTheme.line.guidelineOpacity}
/>
</>
);
};

const labelSpace = VictoryTheme.axis.xAxisLabelGap + (xAxisLabelHeight ?? 0);
const dynamicChartStyle = {height: CHART_CONTENT_MIN_HEIGHT + labelSpace};
const chartPadding = {
...VictoryTheme.axis.padding,
Expand Down Expand Up @@ -288,7 +304,9 @@ function LineChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = '
<Line
points={points.y}
color={VictoryTheme.colors.default}
strokeWidth={2}
strokeWidth={VictoryTheme.line.strokeWidth}
strokeCap="round"
strokeJoin="round"
curveType="linear"
/>
</>
Expand Down
15 changes: 10 additions & 5 deletions src/components/Charts/VictoryTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,11 @@ function getChartColor(index: number): string {
/** Index of the default single-color chart color (green400). */
const DEFAULT_CHART_COLOR_INDEX = 3;

/** Index of the default dot color (green500) */
const DEFAULT_CHART_DOT_COLOR_INDEX = DEFAULT_CHART_COLOR_INDEX + CHART_PALETTE_HUES.length * 3;

const VictoryTheme = {
colors: {
palette: CHART_PALETTE,
/** Default color used for single-color charts (e.g., line chart, single-color bar chart) */
default: getChartColor(DEFAULT_CHART_COLOR_INDEX),
/** Default dot color for line chart data points, one shade darker than the line */
defaultDot: getChartColor(DEFAULT_CHART_DOT_COLOR_INDEX),
getColor: getChartColor,
},
fontFamilies: Array.from(CHART_FONT_FAMILY_NAMES),
Expand All @@ -78,6 +73,16 @@ const VictoryTheme = {
/** Base chart padding applied to all sides */
padding: {top: 5, left: 5, right: 5, bottom: 5},
},
line: {
/** Stroke width of the line */
strokeWidth: 4,
/** Radius of the dot drawn on the line at the hovered data point */
activeDotRadius: 6,
/** Opacity of the vertical guideline drawn at the hovered data point */
guidelineOpacity: 0.2,
/** Base domain padding applied to all sides */
domainPadding: {top: 16, bottom: 16, left: 0, right: 0},
},
tooltip: {
/** The height of the chart tooltip pointer */
pointerHeight: 4,
Expand Down
54 changes: 54 additions & 0 deletions src/components/Charts/components/ActivePointIndicator.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type {DerivedValue, SharedValue} from 'react-native-reanimated';

import {Circle, Group, Line} from '@shopify/react-native-skia';
import React from 'react';
import {useDerivedValue} from 'react-native-reanimated';

type ActivePointIndicatorProps = {
/** Canvas position of the active data point */
position: DerivedValue<{x: number; y: number}>;

isActive: SharedValue<boolean>;

/** Top boundary of the plot area, where the guideline starts */
top: number;

/** Bottom boundary of the plot area, where the guideline ends */
bottom: number;

dotRadius: number;
dotColor: string;
guidelineColor: string;
guidelineOpacity: number;
};
Comment thread
OlGierd03 marked this conversation as resolved.
Resolved

const GUIDELINE_WIDTH = 2;

function ActivePointIndicator({position, isActive, top, bottom, dotRadius, dotColor, guidelineColor, guidelineOpacity}: ActivePointIndicatorProps) {
const opacity = useDerivedValue(() => (isActive.get() ? 1 : 0));
const guidelineStart = useDerivedValue(() => ({x: position.get().x, y: top}));
const guidelineEnd = useDerivedValue(() => ({x: position.get().x, y: bottom}));
const cx = useDerivedValue(() => position.get().x);
const cy = useDerivedValue(() => position.get().y);

return (
<Group opacity={opacity}>
<Line
p1={guidelineStart}
p2={guidelineEnd}
color={guidelineColor}
opacity={guidelineOpacity}
strokeWidth={GUIDELINE_WIDTH}
strokeCap="round"
/>
<Circle
cx={cx}
cy={cy}
r={dotRadius}
color={dotColor}
/>
</Group>
);
}

export default ActivePointIndicator;
45 changes: 0 additions & 45 deletions src/components/Charts/components/ScatterPoints.tsx

This file was deleted.

8 changes: 8 additions & 0 deletions src/components/Charts/hooks/useChartInteractions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,12 @@ function useChartInteractions({
};
});

/** Canvas position of the matched data point, for drawing hover indicators inside the chart canvas */
const activePointPosition = useDerivedValue(() => ({
x: chartInteractionState.x.position.get(),
y: chartInteractionState.y.y.position.get(),
}));

const customGestures = Gesture.Race(hoverGesture(), tapGesture());

return {
Expand All @@ -426,6 +432,8 @@ function useChartInteractions({
isCursorOverClickable,
/** Raw tooltip positioning data */
initialTooltipPosition,
/** Canvas position of the matched data point */
activePointPosition,
};
}

Expand Down
7 changes: 0 additions & 7 deletions tests/unit/components/Charts/VictoryTheme.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,6 @@ describe('VictoryTheme', () => {
});
});

describe('colors.defaultDot', () => {
it('equals the palette entry at the default dot index (green500)', () => {
const VictoryTheme = loadVictoryTheme();
expect(VictoryTheme.colors.defaultDot).toBe(colors.green500);
});
});

describe('colors.getColor', () => {
it('returns a non-empty hex string for index 0', () => {
const VictoryTheme = loadVictoryTheme();
Expand Down
Loading