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
80 changes: 80 additions & 0 deletions src/components/Charts/BarChart/StackedBarChartLegend.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/** Keeps comparison swatches together so the period label only needs to appear once. */
import type {ChartSeries} from '@components/Charts/types';
import VictoryTheme from '@components/Charts/VictoryTheme';
import Text from '@components/Text';

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

import {formatList} from '@libs/Localize';

import {View} from 'react-native';

type StackedBarChartLegendProps = {
/** Each stack's first series supplies its group label. Compared swatches follow the primary stage order. */
stacks: ReadonlyArray<readonly ChartSeries[]>;
};

function StackedBarChartLegend({stacks}: StackedBarChartLegendProps) {
const styles = useThemeStyles();
const theme = useTheme();
const StyleUtils = useStyleUtils();

const renderSwatch = ({key, color}: ChartSeries) => (
<View
key={key}
aria-hidden
style={[styles.pieChartLegendDot, styles.flexShrink0, StyleUtils.getBackgroundColorStyle(color ?? VictoryTheme.colors.default)]}
/>
);

return (
<View style={[styles.pieChartLegendContainer, styles.justifyContentStart, styles.mh0, styles.mt0, styles.mb3]}>
{stacks.flatMap((stack) => {
const firstSeries = stack.at(0);
if (!firstSeries?.stackLabel) {
return stack.map((series) => (
<View
key={series.key}
style={[styles.flexRow, styles.alignItemsCenter, styles.gap2, styles.flexShrink1]}
>
{renderSwatch(series)}
<Text
variant="micro"
color={theme.icon}
style={styles.flexShrink1}
>
{series.label}
</Text>
</View>
));
}

const {key, stackLabel} = firstSeries;
const stageLabels = stack.flatMap(({label}) => (label ? [label] : []));
return [
<View
key={key}
style={[styles.flexRow, styles.alignItemsCenter, styles.gap2, styles.flexShrink1]}
role="group"
accessible
accessibilityLabel={formatList([stackLabel, ...stageLabels])}
>
<View style={[styles.flexRow, styles.gap1]}>{stack.map(renderSwatch)}</View>
<Text
variant="micro"
color={theme.icon}
style={styles.flexShrink1}
aria-hidden
>
{stackLabel}
</Text>
</View>,
];
})}
</View>
);
}

export default StackedBarChartLegend;
48 changes: 22 additions & 26 deletions src/components/Charts/BarChart/VerticalBarChartContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ import {getBarLayout, getCartesianPlotBounds, getSteppedLabelLayout, getXAxisLab
import {getBarChartHeight, getXAxisLabelSpace} from '@components/Charts/utils/chartHeights';
import {getSeriesStacks, getStackTotalsData, getStackTotalSeries} from '@components/Charts/utils/stackedBars';
import VictoryTheme, {CARTESIAN_Y_AXIS, GLYPH_PADDING, MAX_BAR_LABEL_LINES} from '@components/Charts/VictoryTheme';
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';
Expand All @@ -32,7 +30,6 @@ import variables from '@styles/variables';
import type {TupleToUnion} from 'type-fest';
import type {CartesianChartRenderArg, ChartBounds, PointsArray, Scale} from 'victory-native';

import {View} from 'react-native';
import {GestureDetector} from 'react-native-gesture-handler';
import Animated, {useAnimatedStyle, useSharedValue} from 'react-native-reanimated';
import {Group, Skia} from 'react-native-skia';
Expand All @@ -41,6 +38,8 @@ import {Bar, CartesianChart, StackedBar} from 'victory-native';
import type BarChartProps from './types';
import type {BarChartContentProps} from './types';

import StackedBarChartLegend from './StackedBarChartLegend';

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

function VerticalBarChartCanvas({
Expand All @@ -63,7 +62,6 @@ function VerticalBarChartCanvas({
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();

const seriesKeys = series.map((seriesItem) => seriesItem.key);
const barSeries = series.filter((seriesItem) => !seriesItem.isAverage);
Expand Down Expand Up @@ -234,7 +232,12 @@ function VerticalBarChartCanvas({
color={color}
barWidth={groupedBarWidth}
barCount={data.length}
roundedCorners={{topLeft: BAR_CORNER_RADIUS, topRight: BAR_CORNER_RADIUS, bottomLeft: BAR_CORNER_RADIUS, bottomRight: BAR_CORNER_RADIUS}}
roundedCorners={{
topLeft: BAR_CORNER_RADIUS,
topRight: BAR_CORNER_RADIUS,
bottomLeft: BAR_CORNER_RADIUS,
bottomRight: BAR_CORNER_RADIUS,
}}
/>
);
};
Expand Down Expand Up @@ -338,7 +341,11 @@ function VerticalBarChartCanvas({

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

const chart = (
<GestureDetector
Expand Down Expand Up @@ -366,7 +373,14 @@ function VerticalBarChartCanvas({
// doesn't draw (we render ChartXAxisLabels ourselves), on top of our own labelSpace.
labelPosition: 'inset',
}}
yAxis={[{...CARTESIAN_Y_AXIS, tickCount: yAxisTickCount, tickValues: yAxisTicks, domain: yAxisTickDomain}]}
yAxis={[
{
...CARTESIAN_Y_AXIS,
tickCount: yAxisTickCount,
tickValues: yAxisTicks,
domain: yAxisTickDomain,
},
]}
frame={{lineWidth: 0}}
data={chartData}
>
Expand Down Expand Up @@ -407,28 +421,10 @@ function VerticalBarChartCanvas({
return chart;
}

// Stacked segments share their bar, so the legend is what names them. Each stage is listed once per period, the period named only when there are several.
return (
<>
<StackedBarChartLegend stacks={stacks} />
{chart}
<View style={styles.pieChartLegendContainer}>
{stacks.flat().map((seriesItem) => (
<View
key={`legend-${seriesItem.key}`}
style={[styles.flexRow, styles.alignItemsCenter]}
>
<View style={[styles.pieChartLegendDot, StyleUtils.getBackgroundColorStyle(seriesItem.color ?? VictoryTheme.colors.default)]} />
<Text style={[styles.pieChartLegendLabel, StyleUtils.getColorStyle(theme.icon), styles.ml2]}>
{stacks.length > 1 && seriesItem.stackLabel && seriesItem.label
? translate('search.seriesInPeriod', {
series: seriesItem.label,
period: seriesItem.stackLabel,
})
: seriesItem.label}
</Text>
</View>
))}
</View>
</>
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/Charts/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type ChartSeries = {
/** Set on a stacked bar chart's series: the stack the series is a segment of. Series sharing it are stacked in drawing order, bottom first. */
stackIndex?: number;

/** Names the period the series' stack covers, like "Jan 1 - Mar 31, 2026" */
/** Groups the stack's swatches under one legend label instead of naming each segment. */
stackLabel?: string;
};

Expand Down
15 changes: 9 additions & 6 deletions src/components/Search/buildStackedSeries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import type {LocaleContextProps} from '@components/LocaleContextProvider';

import StringUtils from '@libs/StringUtils';

import CONST from '@src/CONST';

import type {NonEmptyTuple} from 'type-fest';

import type {ChartComparison, SearchChartModel} from './buildChartSeries';
Expand All @@ -16,7 +18,7 @@ import type {GroupedItem, SearchChartDataRow, SearchGroupBy} from './types';

import {CHART_SERIES_KEY, getAverageLabelKey, isChartAverage} from './buildChartSeries';
import CHART_GROUP_BY_CONFIG from './chartGroupByConfig';
import {formatDates, getComparedBucketLabels, getCounterpartBucketRange, getPositionInPrimaryPeriod, getUnpairedBucketLabels, isTimeGroupBy} from './comparisonBuckets';
import {getComparedBucketLabels, getCounterpartBucketRange, getPositionInPrimaryPeriod, getUnpairedBucketLabels, isTimeGroupBy} from './comparisonBuckets';

/** Position of each period's stack among the stacks of a bucket */
const STACK_INDEX = {
Expand Down Expand Up @@ -106,7 +108,8 @@ function buildStackedSeries({
dateFnsLocale,
}: BuildStackedSeriesParams): SearchChartModel {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ CONSISTENCY-18 (docs)

This line now prefers comparison[CONST.SEARCH.CHART_METRIC.DURATION] over the locally computed getStackedAverage(data, stages), but nothing explains why the backend-supplied duration should win. A future reader can't tell that this is the report-weighted range average (matching the headline summary) and that the bucket average is only a fallback for older cached responses. Add a short comment stating the reason, e.g.:

// Prefer the backend's report-weighted range average so the line matches the headline summary; older cached charts without it fall back to the bucket average.
const averageValue = isChartAverage(comparison) ? (comparison[CONST.SEARCH.CHART_METRIC.DURATION] ?? getStackedAverage(data, stages)) : undefined;

Reviewed at: 76c8f3d | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

const {getDateRange} = CHART_GROUP_BY_CONFIG[groupBy];
const averageValue = isChartAverage(comparison) ? getStackedAverage(data, stages) : undefined;
// Use the report-weighted average to match the headline, with a bucket average for older snapshots.
const averageValue = isChartAverage(comparison) ? (comparison[CONST.SEARCH.CHART_METRIC.DURATION] ?? getStackedAverage(data, stages)) : undefined;
const comparedRows = comparison && !isChartAverage(comparison) ? comparison : undefined;
const periods = comparedRows?.periods;
// Time buckets of another period cover other dates, so they are keyed by start date
Expand Down Expand Up @@ -226,16 +229,16 @@ function buildStackedSeries({
})
.map(({row}) => row);

const buildStackSeries = (stackIndex: number, period: ChartComparisonPeriods['primary'] | undefined) =>
const buildStackSeries = (stackIndex: number, stackLabel?: string) =>
stages.map((stage): ChartSeries => ({
key: getStackSeriesKey(stackIndex, stage.key),
label: stage.label,
color: stackIndex === STACK_INDEX.PRIMARY ? stage.color : stage.comparisonColor,
stackIndex,
stackLabel: period && formatDates(period, dateFnsLocale),
stackLabel,
}));
const [firstSeries, ...otherPrimarySeries] = buildStackSeries(STACK_INDEX.PRIMARY, periods?.primary);
const comparisonSeries = periods ? buildStackSeries(STACK_INDEX.COMPARISON, periods.comparison) : [];
const [firstSeries, ...otherPrimarySeries] = buildStackSeries(STACK_INDEX.PRIMARY);
const comparisonSeries = periods ? buildStackSeries(STACK_INDEX.COMPARISON, translate('insightsPage.compare.previousPeriod')) : [];
const averageSeries: ChartSeries[] =
averageValue === undefined
? []
Expand Down
10 changes: 9 additions & 1 deletion src/languages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,15 @@ const translations: TranslationDeepObject<typeof en> = {
},
},
insightsPage: {
headline: {
averageExpense: (amount) => `Ø ${amount}`,
flaggedExpenses: ({formattedCount}) => ({one: `Bei ${formattedCount} Ausgabe`, other: `Bei ${formattedCount} Ausgaben`}),
violationCount: ({formattedCount}) => ({one: `${formattedCount} Verstoß`, other: `${formattedCount} Verstöße`}),
timeToSubmit: (time) => `${time} bis zur Einreichung`,
timeToApprove: (time) => `${time} bis zur Genehmigung`,
timeToPay: (time) => `${time} bis zur Zahlung`,
vsPreviousPeriod: (change) => `${change} gegenüber dem vorherigen Zeitraum`,
},
tagLevel: (level: string) => `Tag-Stufe ${level}`,
noTaggedExpenses: 'Keine Ausgaben mit Tags',
noExpensesForTagLevel: (tagLevelName: string) => `Für ${tagLevelName} gibt es in diesem Zeitraum keine Ausgaben.`,
Expand Down Expand Up @@ -11737,7 +11746,6 @@ Fügen Sie weitere Ausgabelimits hinzu, um den Cashflow Ihres Unternehmens zu sc
updateExisting: 'Vorhandene aktualisieren',
},
chartValueUnavailable: 'Nicht verfügbar',
seriesInPeriod: ({series, period}: {series: string; period: string}) => `${series} ${period}`,
},
genericErrorPage: {
title: 'Ups, da ist etwas schiefgelaufen!',
Expand Down
10 changes: 9 additions & 1 deletion src/languages/el.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,15 @@ const translations: TranslationDeepObject<typeof en> = {
},
},
insightsPage: {
headline: {
averageExpense: (amount) => `${amount} κατά μέσο όρο`,
flaggedExpenses: ({formattedCount}) => ({one: `Σε ${formattedCount} έξοδο`, other: `Σε ${formattedCount} έξοδα`}),
violationCount: ({formattedCount}) => ({one: `${formattedCount} παράβαση`, other: `${formattedCount} παραβάσεις`}),
timeToSubmit: (time) => `${time} μέχρι την υποβολή`,
timeToApprove: (time) => `${time} μέχρι την έγκριση`,
timeToPay: (time) => `${time} μέχρι την πληρωμή`,
vsPreviousPeriod: (change) => `${change} σε σχέση με την προηγούμενη περίοδο`,
},
tagLevel: (level: string) => `Επίπεδο ετικέτας ${level}`,
noTaggedExpenses: 'Δεν υπάρχουν δαπάνες με ετικέτες',
noExpensesForTagLevel: (tagLevelName: string) => `Δεν υπάρχουν δαπάνες για ${tagLevelName} σε αυτό το εύρος ημερομηνιών.`,
Expand Down Expand Up @@ -11926,7 +11935,6 @@ ${reportName}`,
updateExisting: 'Ενημέρωση υπάρχοντος',
},
chartValueUnavailable: 'Μη διαθέσιμο',
seriesInPeriod: ({series, period}: {series: string; period: string}) => `${series} ${period}`,
},
genericErrorPage: {
title: 'Ωχ, κάτι πήγε στραβά!',
Expand Down
10 changes: 9 additions & 1 deletion src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1411,6 +1411,15 @@ const translations = {
},
},
insightsPage: {
headline: {
averageExpense: (amount: string) => `${amount} average`,
flaggedExpenses: ({formattedCount}: {count: number; formattedCount: string}) => ({one: `On ${formattedCount} expense`, other: `On ${formattedCount} expenses`}),
violationCount: ({formattedCount}: {count: number; formattedCount: string}) => ({one: `${formattedCount} violation`, other: `${formattedCount} violations`}),
timeToSubmit: (time: string) => `${time} to submit`,
timeToApprove: (time: string) => `${time} to approve`,
timeToPay: (time: string) => `${time} to pay`,
vsPreviousPeriod: (change: string) => `${change} vs previous period`,
},
generatingAIInsights: 'Generating AI Insights...',
generatingAIInsightsSubtitle: "This shouldn't take more than a minute",
readingChart: (chartTitle: string) => `Reading ${chartTitle}`,
Expand Down Expand Up @@ -11833,7 +11842,6 @@ const translations = {
spendOverTime: 'Spend over time',
periodSoFar: ({period}: {period: string}) => `${period} so far`,
chartValueUnavailable: 'Unavailable',
seriesInPeriod: ({series, period}: {series: string; period: string}) => `${series} ${period}`,
weekOf: ({date}: {date: string}) => `Week of ${date}`,
groupedExpenses: 'grouped expenses',
bulkActions: {
Expand Down
10 changes: 9 additions & 1 deletion src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,15 @@ const translations: TranslationDeepObject<typeof en> = {
},
},
insightsPage: {
headline: {
averageExpense: (amount) => `${amount} de media`,
flaggedExpenses: ({formattedCount}) => ({one: `En ${formattedCount} gasto`, other: `En ${formattedCount} gastos`}),
violationCount: ({formattedCount}) => ({one: `${formattedCount} infracción`, other: `${formattedCount} infracciones`}),
timeToSubmit: (time) => `${time} para enviar`,
timeToApprove: (time) => `${time} para aprobar`,
timeToPay: (time) => `${time} para pagar`,
vsPreviousPeriod: (change) => `${change} respecto al periodo anterior`,
},
tagLevel: (level: string) => `Nivel de etiqueta ${level}`,
noTaggedExpenses: 'No hay gastos con etiquetas',
noExpensesForTagLevel: (tagLevelName: string) => `No hay gastos para ${tagLevelName} en este intervalo de fechas.`,
Expand Down Expand Up @@ -11617,7 +11626,6 @@ ${reportName}`,
updateExisting: 'Actualizar existente',
},
chartValueUnavailable: 'No disponible',
seriesInPeriod: ({series, period}: {series: string; period: string}) => `${series} ${period}`,
},
genericErrorPage: {
title: '¡Oh-oh, algo salió mal!',
Expand Down
10 changes: 9 additions & 1 deletion src/languages/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,15 @@ const translations: TranslationDeepObject<typeof en> = {
},
},
insightsPage: {
headline: {
averageExpense: (amount) => `${amount} en moyenne`,
flaggedExpenses: ({formattedCount}) => ({one: `Sur ${formattedCount} dépense`, other: `Sur ${formattedCount} dépenses`}),
violationCount: ({formattedCount}) => ({one: `${formattedCount} infraction`, other: `${formattedCount} infractions`}),
timeToSubmit: (time) => `${time} pour soumettre`,
timeToApprove: (time) => `${time} pour approuver`,
timeToPay: (time) => `${time} pour payer`,
vsPreviousPeriod: (change) => `${change} par rapport à la période précédente`,
},
tagLevel: (level: string) => `Niveau de tag ${level}`,
noTaggedExpenses: 'Aucune dépense avec un tag',
noExpensesForTagLevel: (tagLevelName: string) => `Aucune dépense pour ${tagLevelName} sur cette période.`,
Expand Down Expand Up @@ -11766,7 +11775,6 @@ Ajoutez davantage de règles de dépenses pour protéger la trésorerie de l’e
updateExisting: 'Mettre à jour l’existant',
},
chartValueUnavailable: 'Indisponible',
seriesInPeriod: ({series, period}: {series: string; period: string}) => `${series} ${period}`,
},
genericErrorPage: {
title: 'Oups, quelque chose s’est mal passé !',
Expand Down
Loading
Loading