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
42 changes: 37 additions & 5 deletions src/components/Charts/BarChart/VerticalBarChartContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import {
useSyncPointPositions,
useReadyCartesianCanvas,
} from '@components/Charts/hooks';
import type {ChartSeries} from '@components/Charts/types';
import type {ChartSeries, WrappedLabelConfig} from '@components/Charts/types';
import {getBarLayout, getCartesianPlotBounds, getXAxisLabel, getYAxisLabelWidth} from '@components/Charts/utils';
import VictoryTheme, {CARTESIAN_Y_AXIS, CHART_CONTENT_MIN_HEIGHT, GLYPH_PADDING} from '@components/Charts/VictoryTheme';
import VictoryTheme, {CARTESIAN_Y_AXIS, CHART_CONTENT_MIN_HEIGHT, GLYPH_PADDING, MAX_BAR_LABEL_LINES} from '@components/Charts/VictoryTheme';

import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
Expand All @@ -38,7 +38,17 @@ import type {BarChartContentProps} from './types';

type VerticalBarChartCanvasProps = Omit<BarChartProps, 'isLoading'> & CartesianCanvasInputs;

function VerticalBarChartCanvas({data, series, yAxisUnit, yAxisUnitPosition = 'left', onBarPress, shouldShowLabels = true, chartWidth, fontManager}: VerticalBarChartCanvasProps) {
function VerticalBarChartCanvas({
data,
series,
yAxisUnit,
yAxisUnitPosition = 'left',
onBarPress,
shouldShowLabels = true,
shouldWrapLabels = false,
chartWidth,
fontManager,
}: VerticalBarChartCanvasProps) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
Expand Down Expand Up @@ -85,11 +95,31 @@ function VerticalBarChartCanvas({data, series, yAxisUnit, yAxisUnitPosition = 'l
fontSize: variables.iconSizeExtraSmall,
measurements,
tickSpacing: shouldShowLabels && plotBounds.width > 0 ? barLayout.barWidth + barLayout.gap : 0,
labelAreaWidth: plotBounds.width,
// Wrapped labels are always horizontal, never skipped, and sized from wrapConfig, so the rotation/skip/truncation
// pass is discarded. Pass 0 to short-circuit the hook, matching how the line chart skips it via labelAreaWidth.
labelAreaWidth: shouldWrapLabels ? 0 : plotBounds.width,
firstTickLeftSpace: plotBounds.left + barLayout.edgeSpace,
lastTickRightSpace: chartWidth - plotBounds.right + barLayout.edgeSpace,
});

// Named bar labels wrap to two centered lines in the full column width, always horizontal and
// never skipped, so they bypass the rotation/skip/single-line treatment the axis labels use.
const labelColumnWidth = Math.min(barLayout.barWidth + barLayout.gap, plotBounds.width);
const wrapConfig: WrappedLabelConfig | undefined =
shouldWrapLabels && measurements.lineHeight > 0
? {
columnWidth: labelColumnWidth,
maxLines: MAX_BAR_LABEL_LINES,
lineHeight: measurements.lineHeight,
hasLabel: originalLabels.map((label) => label.length > 0),
canvasWidth: chartWidth,
}
: undefined;
const wrapLabelHeight = wrapConfig ? wrapConfig.maxLines * wrapConfig.lineHeight : 0;
// When wrapping, labelAreaWidth is 0 above so the hook returns EMPTY_LAYOUT (horizontal, skip 1).
// xAxisLabelHeight is 0 there too, so the wrap height has to be substituted explicitly.
const resolvedLabelHeight = shouldWrapLabels ? wrapLabelHeight : (xAxisLabelHeight ?? 0);

const barHitHalfWidth = useSharedValue(0);
const plotTop = useSharedValue(0);
const plotBottom = useSharedValue(0);
Expand All @@ -103,6 +133,7 @@ function VerticalBarChartCanvas({data, series, yAxisUnit, yAxisUnitPosition = 'l
labelRotation,
labelSkipInterval,
chartBottom,
wrapConfig,
});

const handleChartBoundsChange = (bounds: ChartBounds) => {
Expand Down Expand Up @@ -195,6 +226,7 @@ function VerticalBarChartCanvas({data, series, yAxisUnit, yAxisUnitPosition = 'l
labelColor={theme.icon}
xScale={args.xScale}
chartBoundsBottom={chartBoundsBottom}
wrapConfig={wrapConfig}
/>
)}
<ChartYAxisLabels
Expand All @@ -210,7 +242,7 @@ function VerticalBarChartCanvas({data, series, yAxisUnit, yAxisUnitPosition = 'l
);
};

const labelSpace = shouldShowLabels ? VictoryTheme.axis.xAxisLabelGap + (xAxisLabelHeight ?? 0) : 0;
const labelSpace = shouldShowLabels ? VictoryTheme.axis.xAxisLabelGap + resolvedLabelHeight : 0;
const chartHeight = CHART_CONTENT_MIN_HEIGHT + labelSpace;
const chartPadding = {...VictoryTheme.axis.padding, bottom: labelSpace + VictoryTheme.axis.padding.bottom, right: chartPaddingRight};

Expand Down
3 changes: 3 additions & 0 deletions src/components/Charts/BarChart/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ type BarChartProps = CartesianChartProps & {

/** Whether each bar's label is drawn below it. Turn off when something outside the chart already names the bars. */
shouldShowLabels?: boolean;

/** Whether each bar's label wraps to two centered lines beneath its column instead of the single-line axis treatment (rotation/skip). Used for named bars (merchants, categories, spenders). */
shouldWrapLabels?: boolean;
};

type BarChartContentProps = BarChartProps & {
Expand Down
179 changes: 105 additions & 74 deletions src/components/Charts/PieChart/PieChartContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Text from '@components/Text';

import useLocalize from '@hooks/useLocalize';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';

import React, {useState} from 'react';
Expand All @@ -30,6 +31,9 @@ type PieChartProps = ChartProps & {

/** Whether to draw the slice legend below the donut */
shouldShowLegend?: boolean;

/** Whether the legend sits beside the donut when the card is wide enough (one row per slice) and stacks beneath it when it isn't, instead of the default wrapping row below the donut. */
shouldUseResponsiveLegend?: boolean;
};

type PieChartContentProps = PieChartProps & {
Expand All @@ -41,9 +45,10 @@ type PieChartCanvasProps = Omit<PieChartProps, 'isLoading'> & {
chartWidth: number;
};

function PieChartCanvas({data, series, valueUnit, valueUnitPosition, onSlicePress, shouldShowLegend = true, chartWidth}: PieChartCanvasProps) {
function PieChartCanvas({data, series, valueUnit, valueUnitPosition, onSlicePress, shouldShowLegend = true, shouldUseResponsiveLegend = false, chartWidth}: PieChartCanvasProps) {
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const theme = useTheme();
const {translate} = useLocalize();
const [isHoveringOverPie, setIsHoveringOverPie] = useState(false);

Expand All @@ -58,9 +63,14 @@ function PieChartCanvas({data, series, valueUnit, valueUnitPosition, onSlicePres
const isTooltipActive = useDerivedValue(() => matchedIndex.get() >= 0);

const canvasHeight = CHART_CONTENT_MIN_HEIGHT;
const radius = Math.min(chartWidth, canvasHeight) / 2;

// Side by side when the legend keeps at least its minimum width next to a square donut. Otherwise stacked.
const isLegendSideBySide = shouldUseResponsiveLegend && shouldShowLegend && chartWidth - canvasHeight - VictoryTheme.pie.legendGap >= VictoryTheme.pie.legendMinWidth;
const donutWidth = isLegendSideBySide ? canvasHeight : chartWidth;

const radius = Math.min(donutWidth, canvasHeight) / 2;
const innerRadius = radius * VictoryTheme.pie.innerRadiusRatio;
const pieGeometry = {radius, innerRadius, centerX: chartWidth / 2, centerY: canvasHeight / 2};
const pieGeometry = {radius, innerRadius, centerX: donutWidth / 2, centerY: canvasHeight / 2};

// Slices are sorted by absolute value (largest first) for color assignment,
// so slice indices don't match the original data array. We map back via
Expand Down Expand Up @@ -182,88 +192,109 @@ function PieChartCanvas({data, series, valueUnit, valueUnitPosition, onSlicePres
// Combined gestures - Race allows both hover and tap to work independently
const combinedGesture = Gesture.Race(hoverGesture(), tapGesture());

const renderLegendItem = (slice: PieSlice) => {
const highlightSlice = (slice: PieSlice) => {
tooltipPosition.set(slice.tooltipPosition);
matchedIndex.set(slice.originalIndex);
};
const clearSliceHighlight = () => {
matchedIndex.set(-1);
};

// One legend entry: a color dot plus the slice name, wired to drive the tooltip on hover.
// The responsive variant gives each slice its own row with the dot aligned to the first line. The default variant is an inline item for the wrapping row below the donut.
const renderLegendEntry = (slice: PieSlice, isResponsiveRow: boolean) => {
const dot = <View style={[styles.pieChartLegendDot, StyleUtils.getBackgroundColorStyle(slice.color)]} />;
return (
<View
key={`legend-${slice.originalIndex}`}
style={[styles.flexRow, styles.alignItemsCenter]}
onMouseEnter={() => {
tooltipPosition.set(slice.tooltipPosition);
matchedIndex.set(slice.originalIndex);
}}
onMouseLeave={() => {
matchedIndex.set(-1);
}}
style={isResponsiveRow ? styles.pieChartLegendRow : [styles.flexRow, styles.alignItemsCenter]}
onMouseEnter={() => highlightSlice(slice)}
onMouseLeave={clearSliceHighlight}
>
<View style={[styles.pieChartLegendDot, StyleUtils.getBackgroundColorStyle(slice.color)]} />
<Text style={[styles.textNormal, styles.ml2]}>{slice.label}</Text>
{isResponsiveRow ? <View style={styles.pieChartLegendDotColumn}>{dot}</View> : dot}
<Text style={[styles.textNormal, StyleUtils.getColorStyle(theme.icon), isResponsiveRow ? styles.flex1 : styles.ml2]}>{slice.label}</Text>
Comment thread
adamgrzybowski marked this conversation as resolved.
Resolved
</View>
);
};

return (
<>
<GestureDetector
gesture={combinedGesture}
touchAction="pan-y"
const donut = (
<GestureDetector
gesture={combinedGesture}
touchAction="pan-y"
>
<Animated.View
style={[styles.chartContent, shouldUseResponsiveLegend && StyleUtils.getWidthStyle(donutWidth), isHoveringOverPie && styles.cursorPointer]}
onTouchStart={onChartTouchStart}
>
<Animated.View
style={[styles.chartContent, isHoveringOverPie && styles.cursorPointer]}
onTouchStart={onChartTouchStart}
>
{processedSlices.length > 0 && (
<PolarChart
explicitSize={{width: chartWidth, height: canvasHeight}}
data={processedSlices}
labelKey="label"
valueKey="value"
colorKey="color"
{processedSlices.length > 0 && (
<PolarChart
explicitSize={{width: donutWidth, height: canvasHeight}}
data={processedSlices}
labelKey="label"
valueKey="value"
colorKey="color"
>
<Pie.Chart
startAngle={VictoryTheme.pie.startAngle}
innerRadius={`${VictoryTheme.pie.innerRadiusRatio * 100}%`}
>
<Pie.Chart
startAngle={VictoryTheme.pie.startAngle}
innerRadius={`${VictoryTheme.pie.innerRadiusRatio * 100}%`}
>
{({slice}) => (
<PaddedPieSlice
slice={slice}
padAngle={VictoryTheme.pie.padAngle}
/>
)}
</Pie.Chart>
</PolarChart>
)}

{processedSlices.length > 0 && (
<View
pointerEvents="none"
style={styles.pieChartCenterLabel}
{({slice}) => (
<PaddedPieSlice
slice={slice}
padAngle={VictoryTheme.pie.padAngle}
/>
)}
</Pie.Chart>
</PolarChart>
)}

{processedSlices.length > 0 && (
<View
pointerEvents="none"
style={styles.pieChartCenterLabel}
>
<Text style={[styles.textLabelSupporting, styles.textAlignCenter]}>{translate('common.total')}</Text>
<Text
numberOfLines={1}
adjustsFontSizeToFit
style={[styles.textHeadlineH1, styles.textAlignCenter]}
>
<Text style={[styles.textLabelSupporting, styles.textAlignCenter]}>{translate('common.total')}</Text>
<Text
numberOfLines={1}
adjustsFontSizeToFit
style={[styles.textHeadlineH1, styles.textAlignCenter]}
>
{formatValue(data.reduce((sum, point) => sum + getPrimaryValue(point, primarySeriesKey), 0))}
</Text>
</View>
)}

{/* Tooltip */}
<ChartTooltipLayer
matchedIndex={matchedIndex}
isTooltipActive={isTooltipActive}
data={data}
series={series}
formatValue={formatValue}
chartWidth={chartWidth}
initialTooltipPosition={tooltipPosition}
onChartMoved={onChartMoved}
onDismiss={onTooltipDismiss}
/>
</Animated.View>
</GestureDetector>
{shouldShowLegend && <View style={styles.pieChartLegendContainer}>{processedSlices.map((slice) => renderLegendItem(slice))}</View>}
{formatValue(data.reduce((sum, point) => sum + getPrimaryValue(point, primarySeriesKey), 0))}
</Text>
</View>
)}

{/* Tooltip */}
<ChartTooltipLayer
matchedIndex={matchedIndex}
isTooltipActive={isTooltipActive}
data={data}
series={series}
formatValue={formatValue}
chartWidth={donutWidth}
initialTooltipPosition={tooltipPosition}
onChartMoved={onChartMoved}
onDismiss={onTooltipDismiss}
/>
</Animated.View>
</GestureDetector>
);

if (shouldUseResponsiveLegend) {
return (
<View style={isLegendSideBySide ? styles.pieChartResponsiveRow : styles.pieChartResponsiveColumn}>
{donut}
{shouldShowLegend && (
<View style={isLegendSideBySide ? styles.pieChartLegendSide : styles.pieChartLegendBelow}>{processedSlices.map((slice) => renderLegendEntry(slice, true))}</View>
)}
</View>
);
}

return (
<>
{donut}
{shouldShowLegend && <View style={styles.pieChartLegendContainer}>{processedSlices.map((slice) => renderLegendEntry(slice, false))}</View>}
</>
);
}
Expand Down
17 changes: 17 additions & 0 deletions src/components/Charts/VictoryTheme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ const VictoryTheme = {
innerRadiusRatio: 0.8,
/** Gap between pie slices in degrees */
padAngle: 1,
/**
* Minimum width (px) the donut legend column keeps in the side-by-side layout, wide enough for a
* common category name on two lines. The card switches to the stacked layout below this.
*/
legendMinWidth: 180,
/** Gap (px) between the donut and its legend in the side-by-side layout */
legendGap: 24,
/** Gap (px) between the donut and the legend below it in the stacked layout */
legendStackGap: 32,
},
} as const;

Expand Down Expand Up @@ -134,6 +143,12 @@ const X_AXIS_LABEL_MIN_GAP = 24;

const ELLIPSIS = '...';

/** Single-character ellipsis used when a wrapped label overflows its last allowed line. */
const WRAPPED_LABEL_ELLIPSIS = '…';

/** Maximum number of lines a wrapped bar label uses before it is truncated. */
const MAX_BAR_LABEL_LINES = 2;

/** Minimum visible characters (excluding ellipsis) for truncation to be worthwhile */
const MIN_TRUNCATED_CHARS = 10;

Expand Down Expand Up @@ -162,6 +177,8 @@ export {
SIN_45,
LABEL_PADDING,
ELLIPSIS,
WRAPPED_LABEL_ELLIPSIS,
MAX_BAR_LABEL_LINES,
MIN_TRUNCATED_CHARS,
DIAGONAL_ANGLE_RADIAN_THRESHOLD,
MAX_X_AXIS_LABEL_WIDTH,
Expand Down
Loading
Loading