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
63 changes: 60 additions & 3 deletions src/components/Charts/BarChart/BarChartContent.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,69 @@
import {ChartFontsProvider} from '@components/Charts/hooks';
import BAR_INNER_PADDING, {VERTICAL_BAR_DOMAIN_PADDING} from '@components/Charts/barChartConstants';
import {ChartFontsProvider, useChartFontManager, useChartLabelFormats, useChartLabelLayout, useChartLabelMeasurements} from '@components/Charts/hooks';
import {getVerticalBarLabelLayoutInputs, getVerticalBarPlotBounds, getYAxisLabelWidth} from '@components/Charts/utils';
import {GLYPH_PADDING, LABEL_ROTATIONS} from '@components/Charts/VictoryTheme';

import variables from '@styles/variables';

import type {LayoutChangeEvent} from 'react-native';

import React, {useState} from 'react';
import {View} from 'react-native';

import type {BarChartContentProps} from './types';

import HorizontalBarChartContentBody from './HorizontalBarChartContent';
import VerticalBarChartContentBody from './VerticalBarChartContent';

function BarChartContent({isHorizontal = false, ...props}: BarChartContentProps) {
return <ChartFontsProvider>{isHorizontal ? <HorizontalBarChartContentBody {...props} /> : <VerticalBarChartContentBody {...props} />}</ChartFontsProvider>;
const FONT_SIZE = variables.iconSizeExtraSmall;

/**
* Resolves the bar chart orientation on every layout change and renders the matching body. Wide layouts pass
* `isHorizontal`. Narrow layouts predict the vertical chart's label fit from the container width, so the chart
* switches to horizontal bars when labels don't fit even at 45° and back to vertical when the container grows.
*/
function BarChartOrientationDispatcher({isHorizontal = false, canFallBackToHorizontalBars = false, ...props}: BarChartContentProps) {
const fontManager = useChartFontManager();
const [containerWidth, setContainerWidth] = useState(0);
const {data, yAxisUnit, yAxisUnitPosition = 'left'} = props;

const {formatCompactValue} = useChartLabelFormats({data, unit: yAxisUnit, unitPosition: yAxisUnitPosition});
const measurements = useChartLabelMeasurements(data, fontManager, FONT_SIZE);

// Predict the vertical chart's plot geometry from the container width so the fit decision matches what it would measure after mounting.
Comment thread
adamgrzybowski marked this conversation as resolved.
Resolved
const yAxisLabelWidth = getYAxisLabelWidth(data, formatCompactValue, fontManager, FONT_SIZE, VERTICAL_BAR_DOMAIN_PADDING);
const plotBounds = getVerticalBarPlotBounds(containerWidth, yAxisLabelWidth + GLYPH_PADDING);

const {labelRotation} = useChartLabelLayout({
data,
fontManager,
fontSize: FONT_SIZE,
measurements,
...getVerticalBarLabelLayoutInputs({
containerWidth,
plotLeft: plotBounds.left,
plotRight: plotBounds.right,
plotWidth: plotBounds.width,
dataLength: data.length,
innerPadding: BAR_INNER_PADDING,
}),
});
Comment thread
adamgrzybowski marked this conversation as resolved.
Resolved

const renderHorizontal = isHorizontal || (canFallBackToHorizontalBars && labelRotation === LABEL_ROTATIONS.VERTICAL);

const handleLayout = (event: LayoutChangeEvent) => {
setContainerWidth(event.nativeEvent.layout.width);
};

return <View onLayout={handleLayout}>{renderHorizontal ? <HorizontalBarChartContentBody {...props} /> : <VerticalBarChartContentBody {...props} />}</View>;
}

function BarChartContent(props: BarChartContentProps) {
return (
<ChartFontsProvider>
<BarChartOrientationDispatcher {...props} />
</ChartFontsProvider>
);
}

export default BarChartContent;
42 changes: 19 additions & 23 deletions src/components/Charts/BarChart/HorizontalBarChartContent.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import ActivityIndicator from '@components/ActivityIndicator';
import {HORIZONTAL_BAR_DOMAIN_PADDING, MIN_BAR_ROW_HEIGHT} from '@components/Charts/barChartConstants';
import ChartTooltipLayer from '@components/Charts/components/ChartTooltipLayer';
import ChartYAxisLabels from '@components/Charts/components/ChartYAxisLabels';
import type {HitTestArgs, ResolveTargetIndexArgs} from '@components/Charts/hooks';
import {useChartFontManager, useChartInteractions, useChartLabelFormats, useChartParagraphs} from '@components/Charts/hooks';
import {findClosestPoint} from '@components/Charts/hooks/useChartInteractions';
import {calculateMinDomainPadding, getFontLineMetrics, getNiceValueDomain, getNiceValueTicks, measureTextWidth} from '@components/Charts/utils';
import VictoryTheme, {CHART_CONTENT_MIN_HEIGHT, GLYPH_PADDING, LABEL_PADDING, MAX_Y_AXIS_LABEL_WIDTH} from '@components/Charts/VictoryTheme';
import {getFontLineMetrics, getHorizontalChartHeight, getNiceValueDomain, getNiceValueTicks, measureTextWidth} from '@components/Charts/utils';
import VictoryTheme, {CATEGORY_LABEL_WIDTH_RATIO, CHART_CONTENT_MIN_HEIGHT, GLYPH_PADDING, LABEL_PADDING, MAX_Y_AXIS_LABEL_WIDTH} from '@components/Charts/VictoryTheme';

import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
Expand All @@ -26,9 +27,6 @@ import {CartesianChart} from 'victory-native';

import type {BarChartProps} from './types';

/** Extra pixel spacing between the chart boundary and the data range. `right` keeps the longest bar's tip and its tooltip off the edge. */
const BASE_DOMAIN_PADDING = {top: 8, bottom: 8, left: 0, right: 8};

/** Gap between the bar tip and the tooltip pointer, lifting the tooltip clear of the bar. */
const TOOLTIP_TIP_GAP = 4;

Expand Down Expand Up @@ -157,7 +155,6 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
const styles = useThemeStyles();
const fontManager = useChartFontManager();
const [chartWidth, setChartWidth] = useState(0);
const [barAreaHeight, setBarAreaHeight] = useState(0);

// Transpose: value on the x-axis, category index on the y-axis.
// Categories are reversed (index 0 mapped to the top row) so a descending-sorted ranking reads top-to-bottom.
Expand All @@ -169,7 +166,7 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos

const valueDomain = getNiceValueDomain(data, VictoryTheme.axis.tickCount);

const {formatValue} = useChartLabelFormats({
const {formatValue, formatCompactValue} = useChartLabelFormats({
data,
unit: yAxisUnit,
unitPosition: yAxisUnitPosition,
Expand All @@ -189,22 +186,13 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
setChartWidth(event.nativeEvent.layout.width);
};

const domainPadding = (() => {
if (barAreaHeight === 0) {
return BASE_DOMAIN_PADDING;
}
const verticalPadding = calculateMinDomainPadding(barAreaHeight, data.length, HORIZONTAL_BAR_PADDING);
return {...BASE_DOMAIN_PADDING, top: verticalPadding, bottom: verticalPadding};
})();

const barThickness = useSharedValue(0);
const rowHeight = useSharedValue(0);
const xZero = useSharedValue(0);
const plotLeft = useSharedValue(0);

const handleChartBoundsChange = (bounds: ChartBounds) => {
const plotHeight = bounds.bottom - bounds.top;
setBarAreaHeight(plotHeight);
barThickness.set(data.length > 0 ? (1 - HORIZONTAL_BAR_PADDING) * (plotHeight / data.length) : 0);
plotLeft.set(bounds.left);
};
Expand Down Expand Up @@ -288,6 +276,10 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
cursor: isCursorOverClickable.get() ? 'pointer' : 'auto',
}));

// Cap the label column as a fraction of the width so long labels can't starve the plot on narrow containers.
// Shared by the left padding and ChartYAxisLabels truncation so the gutter and rendered labels agree.
const categoryLabelMaxWidth = chartWidth > 0 ? Math.min(MAX_Y_AXIS_LABEL_WIDTH, CATEGORY_LABEL_WIDTH_RATIO * chartWidth) : MAX_Y_AXIS_LABEL_WIDTH;

const categoryLabelWidth = (() => {
if (!fontManager || data.length === 0) {
return 0;
Expand All @@ -296,7 +288,7 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
for (const point of data) {
widest = Math.max(widest, measureTextWidth(point.label, fontManager, variables.iconSizeExtraSmall));
}
return Math.min(MAX_Y_AXIS_LABEL_WIDTH, widest);
return Math.min(categoryLabelMaxWidth, widest);
})();

const {ascent, descent} = fontManager ? getFontLineMetrics(fontManager, variables.iconSizeExtraSmall) : {ascent: 0, descent: 0};
Expand All @@ -312,7 +304,7 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
}
let widest = 0;
for (const tick of getNiceValueTicks(valueDomain, VictoryTheme.axis.tickCount)) {
widest = Math.max(widest, measureTextWidth(formatValue(tick), fontManager, variables.iconSizeExtraSmall));
widest = Math.max(widest, measureTextWidth(formatCompactValue(tick), fontManager, variables.iconSizeExtraSmall));
}
return widest / 2;
})();
Expand All @@ -333,7 +325,7 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
fontSize={variables.iconSizeExtraSmall}
fontManager={fontManager}
labelColor={theme.textSupporting}
formatValue={formatValue}
formatValue={formatCompactValue}
/>
<ChartYAxisLabels
yTicks={chartData.map((point) => point.y)}
Expand All @@ -343,22 +335,26 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
fontManager={fontManager}
labelColor={theme.textSupporting}
formatValue={(yValue: number) => data.at(lastIndex - yValue)?.label ?? ''}
labelGap={CATEGORY_LABEL_GAP}
maxLabelWidth={categoryLabelMaxWidth}
leftAlign
avoidOverlap
/>
</>
);
};

const dynamicChartStyle = {height: CHART_CONTENT_MIN_HEIGHT + labelSpace};
const chartPadding = {
...VictoryTheme.axis.padding,
top: 0,
right: VictoryTheme.axis.padding.right + valueLabelRightGutter,
bottom: labelSpace + VictoryTheme.axis.padding.bottom,
// Just enough to hold the axis-label gap and the label itself. The card's own bottom padding sits below the
// canvas, so no extra padding is needed here and the labels stay a card-padding's distance from the edge.
bottom: labelSpace,
left: categoryLabelWidth + CATEGORY_LABEL_GAP + GLYPH_PADDING,
};

const dynamicChartStyle = {height: getHorizontalChartHeight(data.length, MIN_BAR_ROW_HEIGHT, chartPadding.top + chartPadding.bottom, CHART_CONTENT_MIN_HEIGHT + labelSpace)};

// Draw each bar as its own Skia path so the rounded pill sits on the value tip and the axis end stays square,
// for both positive (right-pointing) and negative (left-pointing) bars. thickness mirrors BarGroup's own
// barWidth for a single series: (1 - betweenGroupPadding) * plotHeight / groupCount.
Expand Down Expand Up @@ -416,7 +412,7 @@ function HorizontalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPos
padding={chartPadding}
yKeys={['y']}
domain={valueDomain ? {x: valueDomain} : undefined}
domainPadding={domainPadding}
domainPadding={HORIZONTAL_BAR_DOMAIN_PADDING}
onChartBoundsChange={handleChartBoundsChange}
onScaleChange={handleScaleChange}
renderOutside={renderOutside}
Expand Down
37 changes: 18 additions & 19 deletions src/components/Charts/BarChart/VerticalBarChartContent.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ActivityIndicator from '@components/ActivityIndicator';
import BAR_INNER_PADDING from '@components/Charts/barChartConstants';
import BAR_INNER_PADDING, {VERTICAL_BAR_DOMAIN_PADDING} from '@components/Charts/barChartConstants';
import ChartTooltipLayer from '@components/Charts/components/ChartTooltipLayer';
import ChartXAxisLabels from '@components/Charts/components/ChartXAxisLabels';
import ChartYAxisLabels from '@components/Charts/components/ChartYAxisLabels';
Expand All @@ -13,7 +13,7 @@ import {
useDynamicYDomain,
useLabelHitTesting,
} from '@components/Charts/hooks';
import {calculateMinDomainPadding, getXAxisLabel, getYAxisLabelWidth} from '@components/Charts/utils';
import {calculateMinDomainPadding, getVerticalBarLabelLayoutInputs, getXAxisLabel, getYAxisLabelWidth} from '@components/Charts/utils';
import VictoryTheme, {CHART_CONTENT_MIN_HEIGHT, GLYPH_PADDING} from '@components/Charts/VictoryTheme';

import useTheme from '@hooks/useTheme';
Expand All @@ -32,11 +32,6 @@ import {Bar, CartesianChart} from 'victory-native';

import type {BarChartProps} from './types';

/** Extra pixel spacing between the chart boundary and the data range, applied per side (Victory's `domainPadding` prop)
* We need bottom: 1 for proper display of the bottom label
*/
const BASE_DOMAIN_PADDING = {top: 32, bottom: 1, left: 0, right: 0};

function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosition = 'left', color, onBarPress}: BarChartProps) {
const theme = useTheme();
const styles = useThemeStyles();
Expand Down Expand Up @@ -69,15 +64,12 @@ function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosit

const domainPadding = (() => {
if (chartWidth === 0) {
return BASE_DOMAIN_PADDING;
return VERTICAL_BAR_DOMAIN_PADDING;
}
const horizontalPadding = calculateMinDomainPadding(chartWidth, data.length, BAR_INNER_PADDING);
return {...BASE_DOMAIN_PADDING, left: horizontalPadding, right: horizontalPadding};
return {...VERTICAL_BAR_DOMAIN_PADDING, left: horizontalPadding, right: horizontalPadding};
})();

const totalDomainPadding = domainPadding.left + domainPadding.right;
const paddingScale = barAreaWidth > 0 ? barAreaWidth / (barAreaWidth + totalDomainPadding) : 0;

const originalLabels = data.map(getXAxisLabel);

const measurements = useChartLabelMeasurements(data, fontManager, variables.iconSizeExtraSmall);
Expand All @@ -86,14 +78,18 @@ function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosit
data,
fontManager,
fontSize: variables.iconSizeExtraSmall,
tickSpacing: barAreaWidth > 0 ? barAreaWidth / data.length : 0,
labelAreaWidth: barAreaWidth,
firstTickLeftSpace: boundsLeft + domainPadding.left * paddingScale,
lastTickRightSpace: chartWidth > 0 ? chartWidth - boundsRight + domainPadding.right * paddingScale : 0,
measurements,
...getVerticalBarLabelLayoutInputs({
containerWidth: chartWidth,
plotLeft: boundsLeft,
plotRight: boundsRight,
plotWidth: barAreaWidth,
dataLength: data.length,
innerPadding: BAR_INNER_PADDING,
}),
});

const {formatValue} = useChartLabelFormats({
const {formatValue, formatCompactValue} = useChartLabelFormats({
data,
unit: yAxisUnit,
unitPosition: yAxisUnitPosition,
Expand Down Expand Up @@ -211,7 +207,7 @@ function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosit
fontSize={variables.iconSizeExtraSmall}
fontManager={fontManager}
labelColor={theme.textSupporting}
formatValue={formatValue}
formatValue={formatCompactValue}
leftAlign
/>
</>
Expand All @@ -220,7 +216,7 @@ function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosit

const labelSpace = VictoryTheme.axis.labelGap + (xAxisLabelHeight ?? 0);
const dynamicChartStyle = {height: CHART_CONTENT_MIN_HEIGHT + labelSpace};
const yAxisLabelWidth = getYAxisLabelWidth(data, formatValue, fontManager, variables.iconSizeExtraSmall, BASE_DOMAIN_PADDING);
const yAxisLabelWidth = getYAxisLabelWidth(data, formatCompactValue, fontManager, variables.iconSizeExtraSmall, VERTICAL_BAR_DOMAIN_PADDING);
const chartPadding = {...VictoryTheme.axis.padding, bottom: labelSpace + VictoryTheme.axis.padding.bottom, left: yAxisLabelWidth + GLYPH_PADDING};

if (isLoading || !fontManager) {
Expand Down Expand Up @@ -256,6 +252,9 @@ function VerticalBarChartContentBody({data, isLoading, yAxisUnit, yAxisUnitPosit
xAxis={{
tickCount: data.length,
lineWidth: VictoryTheme.axis.xLineWidth,
// "outset" makes victory-native reserve 2 * yAxis.labelOffset below the plot for labels it
// doesn't draw (we render ChartXAxisLabels ourselves), on top of our own labelSpace.
labelPosition: 'inset',
}}
yAxis={[
{
Expand Down
5 changes: 3 additions & 2 deletions src/components/Charts/BarChart/index.native.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import type {BarChartProps} from './types';
import BarChartContent from './BarChartContent';

function BarChart(props: BarChartProps) {
// Horizontal bars on wide layouts, vertical on narrow (mobile/RHP).
const {isHorizontal} = useBarChartOrientation();
// Horizontal bars on wide layouts, vertical on narrow (mobile/RHP) unless labels don't fit.
const {isHorizontal, canFallBackToHorizontalBars} = useBarChartOrientation();

return (
<BarChartContent
{...props}
isHorizontal={isHorizontal}
canFallBackToHorizontalBars={canFallBackToHorizontalBars}
/>
);
}
Expand Down
6 changes: 3 additions & 3 deletions src/components/Charts/BarChart/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import type {BarChartProps} from './types';

const getBarChartContent = () => import('./BarChartContent');
function BarChart(props: BarChartProps) {
// Horizontal bars on wide layouts, vertical on narrow (mobile/RHP). A single lazy module receives orientation as a prop.
const {isHorizontal} = useBarChartOrientation();
// Horizontal bars on wide layouts, vertical on narrow (mobile/RHP) unless labels don't fit. A single lazy module receives orientation as a prop.
const {isHorizontal, canFallBackToHorizontalBars} = useBarChartOrientation();

return (
<SkiaWebChart
getComponent={getBarChartContent}
componentProps={{...props, isHorizontal}}
componentProps={{...props, isHorizontal, canFallBackToHorizontalBars}}
/>
);
}
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 @@ -11,6 +11,9 @@ type BarChartProps = CartesianChartProps & {
type BarChartContentProps = BarChartProps & {
/** When true, renders horizontal bars (value on the x-axis) instead of the default vertical bars. */
isHorizontal?: boolean;

/** When true, the vertical chart may switch to horizontal bars if category labels don't fit even at 45° (narrow layout, beta on). */
canFallBackToHorizontalBars?: boolean;
};

export type {BarChartProps, BarChartContentProps};
Loading
Loading