Skip to content

A local-first personal finance app

Create an option for stacked net worth graph (#6603)

Mats Nilsson331aafda306a
diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png
index d63fadc5d1..464c35e67f 100644
Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-1-chromium-linux.png differ
diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png
index 15b4c531d4..6e5ea49c44 100644
Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-2-chromium-linux.png differ
diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png
index 38b995026e..e84eca293f 100644
Binary files a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-loads-net-worth-graph-and-checks-visuals-3-chromium-linux.png differ
diff --git a/packages/desktop-client/src/components/reports/ReportCard.tsx b/packages/desktop-client/src/components/reports/ReportCard.tsx
index 1ff7632fba..a9e458da55 100644
--- a/packages/desktop-client/src/components/reports/ReportCard.tsx
+++ b/packages/desktop-client/src/components/reports/ReportCard.tsx
@@ -116,6 +116,7 @@ export function ReportCard({
background: 'transparent',
padding: 0,
textAlign: 'left',
+ overflow: 'visible',
}}
>
{content}
diff --git a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
index b419961717..d231c3dda1 100644
--- a/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
+++ b/packages/desktop-client/src/components/reports/graphs/NetWorthGraph.tsx
@@ -1,8 +1,9 @@
// @ts-strict-ignore
-import React, { useId, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
+import React, { useId, useMemo, useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
import { AlignedText } from '@actual-app/components/aligned-text';
+import { useResponsive } from '@actual-app/components/hooks/useResponsive';
import { type CSSProperties } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { css } from '@emotion/css';
@@ -14,56 +15,71 @@ import {
Tooltip,
XAxis,
YAxis,
+ type TooltipContentProps,
} from 'recharts';
import { computePadding } from './util/computePadding';
import { FinancialText } from '@desktop-client/components/FinancialText';
-import { useRechartsAnimation } from '@desktop-client/components/reports/chart-theme';
+import {
+ getColorScale,
+ useRechartsAnimation,
+} from '@desktop-client/components/reports/chart-theme';
import { Container } from '@desktop-client/components/reports/Container';
import { numberFormatterTooltip } from '@desktop-client/components/reports/numberFormatter';
import { useFormat } from '@desktop-client/hooks/useFormat';
import { usePrivacyMode } from '@desktop-client/hooks/usePrivacyMode';
+type NetWorthDataPoint = {
+ x: string;
+ y: number;
+ assets: string;
+ debt: string;
+ change: string;
+ networth: string;
+ date: string;
+} & Record<string, string | number>;
+
type NetWorthGraphProps = {
style?: CSSProperties;
graphData: {
- data: Array<{
- x: string;
- y: number;
- assets: string;
- debt: string;
- change: string;
- networth: string;
- date: string;
- }>;
+ data: Array<NetWorthDataPoint>;
hasNegative: boolean;
start: string;
end: string;
};
+ accounts?: Array<{ id: string; name: string }>;
compact?: boolean;
showTooltip?: boolean;
interval?: string;
+ mode?: 'trend' | 'stacked';
};
export function NetWorthGraph({
style,
graphData,
+ accounts = [],
compact = false,
showTooltip = true,
interval = 'Monthly',
+ mode = 'trend',
}: NetWorthGraphProps) {
const { t } = useTranslation();
const privacyMode = usePrivacyMode();
const id = useId();
const format = useFormat();
const animationProps = useRechartsAnimation({ isAnimationActive: false });
+ const [isTooltipActive, setIsTooltipActive] = useState(false);
+ const [hoveredAccountId, setHoveredAccountId] = useState<string | null>(null);
+
+ const { isNarrowWidth } = useResponsive();
+ const effectiveShowTooltip = showTooltip && !isNarrowWidth;
// Use more aggressive smoothening for high-frequency data
const interpolationType =
interval === 'Daily' || interval === 'Weekly' ? 'basis' : 'monotone';
- const tickFormatter = tick => {
+ const tickFormatter = (tick: number) => {
const res = privacyMode
? '...'
: `${format(Math.round(tick), 'financial-no-decimals')}`;
@@ -71,6 +87,7 @@ export function NetWorthGraph({
return res;
};
+ // Trend Mode Logic
const gradientOffset = () => {
const dataMax = Math.max(...graphData.data.map(i => i.y));
const dataMin = Math.min(...graphData.data.map(i => i.y));
@@ -88,6 +105,39 @@ export function NetWorthGraph({
const off = gradientOffset();
const gradientId = `splitColor-${id}`;
+ // Stacked Mode Logic
+ // Sort accounts by total value (smallest to largest)
+ const sortedAccounts = useMemo(() => {
+ if (!accounts || mode !== 'stacked') return [];
+
+ const totals = accounts.reduce(
+ (acc, account) => {
+ acc[account.id] = graphData.data.reduce((sum, point) => {
+ return sum + (Number(point[account.id]) || 0);
+ }, 0);
+ return acc;
+ },
+ {} as Record<string, number>,
+ );
+
+ return [...accounts].sort((a, b) => {
+ return totals[a.id] - totals[b.id];
+ });
+ }, [accounts, graphData.data, mode]);
+
+ // Assign colors to accounts
+ const colors = useMemo(() => {
+ if (mode !== 'stacked') return {};
+ const scale = getColorScale('qualitative');
+ return sortedAccounts.reduce(
+ (acc, account, index) => {
+ acc[account.id] = scale[index % scale.length];
+ return acc;
+ },
+ {} as Record<string, string>,
+ );
+ }, [sortedAccounts, mode]);
+
// Generate weekly tick positions when viewing Daily data
const weeklyTicks = useMemo(() => {
if (interval !== 'Daily') {
@@ -101,23 +151,12 @@ export function NetWorthGraph({
.map(point => point.x);
}, [interval, graphData.data]);
- type PayloadItem = {
- payload: {
- date: string;
- assets: number | string;
- debt: number | string;
- networth: number | string;
- change: number | string;
- };
- };
-
- type CustomTooltipProps = {
- active?: boolean;
- payload?: PayloadItem[];
- };
-
+ // Trend Tooltip
// oxlint-disable-next-line react/no-unstable-nested-components
- const CustomTooltip = ({ active, payload }: CustomTooltipProps) => {
+ const TrendTooltip = ({
+ active,
+ payload,
+ }: TooltipContentProps<number, string>) => {
if (active && payload && payload.length) {
return (
<div
@@ -168,6 +207,126 @@ export function NetWorthGraph({
</div>
);
}
+ return null;
+ };
+
+ // Stacked Tooltip
+ // oxlint-disable-next-line react/no-unstable-nested-components
+ const StackedTooltip = ({
+ active,
+ payload,
+ }: TooltipContentProps<number, string>) => {
+ if (active && payload && payload.length) {
+ // Calculate total from payload (visible accounts)
+ const total = payload.reduce(
+ (acc: number, p) => acc + (Number(p.value) || 0),
+ 0,
+ );
+ const sortedPayload = [...payload].sort((a, b) => {
+ const indexA = sortedAccounts.findIndex(acc => acc.id === a.dataKey);
+ const indexB = sortedAccounts.findIndex(acc => acc.id === b.dataKey);
+ return indexB - indexA;
+ });
+
+ const hasPositive = payload.some(p => (Number(p.value) || 0) > 0);
+ const hasNegative = payload.some(p => (Number(p.value) || 0) < 0);
+ const showPercentage = !(hasPositive && hasNegative);
+
+ return (
+ <div
+ className={css([
+ {
+ zIndex: 1000,
+ pointerEvents: 'auto',
+ borderRadius: 2,
+ boxShadow: '0 1px 6px rgba(0, 0, 0, .20)',
+ backgroundColor: theme.menuBackground,
+ color: theme.menuItemText,
+ padding: 10,
+ fontSize: 12,
+ maxHeight: '80vh',
+ overflowY: 'auto',
+ },
+ ])}
+ >
+ <div style={{ marginBottom: 10, fontWeight: 'bold' }}>
+ {payload[0].payload.date}
+ </div>
+ <table style={{ borderSpacing: '15px 0', marginLeft: '-15px' }}>
+ <thead>
+ <tr>
+ <th style={{ textAlign: 'left', paddingLeft: 15 }}>
+ <Trans>Account</Trans>
+ </th>
+ <th style={{ textAlign: 'right' }}>
+ <Trans>Value</Trans>
+ </th>
+ {showPercentage && <th style={{ textAlign: 'right' }}>%</th>}
+ </tr>
+ </thead>
+ <tbody>
+ {sortedPayload.map(entry => {
+ const accountId = entry.dataKey as string;
+ const accountName =
+ accounts.find(a => a.id === accountId)?.name || accountId;
+ const value = Number(entry.value);
+ const percent = total !== 0 ? (value / total) * 100 : 0;
+
+ return (
+ <tr key={accountId} style={{ color: entry.color }}>
+ <td
+ style={{
+ textAlign: 'left',
+ paddingLeft: 15,
+ textDecoration:
+ hoveredAccountId === accountId
+ ? 'underline'
+ : undefined,
+ }}
+ >
+ {accountName}
+ </td>
+ <td style={{ textAlign: 'right' }}>
+ <span style={{ color: theme.pageText }}>
+ <FinancialText>
+ {format(value, 'financial')}
+ </FinancialText>
+ </span>
+ </td>
+ {showPercentage && (
+ <td style={{ textAlign: 'right' }}>
+ <span style={{ color: theme.pageText }}>
+ <FinancialText>{percent.toFixed(1)}%</FinancialText>
+ </span>
+ </td>
+ )}
+ </tr>
+ );
+ })}
+ <tr
+ style={{
+ fontWeight: 'bold',
+ borderTop: '1px solid ' + theme.tableBorder,
+ }}
+ >
+ <td
+ style={{ textAlign: 'left', paddingLeft: 15, paddingTop: 5 }}
+ >
+ <Trans>Total</Trans>
+ </td>
+ <td style={{ textAlign: 'right', paddingTop: 5 }}>
+ <FinancialText>{format(total, 'financial')}</FinancialText>
+ </td>
+ {showPercentage && (
+ <td style={{ textAlign: 'right', paddingTop: 5 }}>100.0%</td>
+ )}
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ );
+ }
+ return null;
};
return (
@@ -175,11 +334,21 @@ export function NetWorthGraph({
style={{
...style,
...(compact && { height: 'auto' }),
+ position: 'relative',
}}
>
{(width, height) =>
graphData && (
- <div style={{ ...(!compact && { marginTop: '15px' }) }}>
+ <div
+ style={{
+ ...(!compact && { marginTop: '15px' }),
+ position: 'relative',
+ }}
+ onMouseLeave={() => {
+ setIsTooltipActive(false);
+ setHoveredAccountId(null);
+ }}
+ >
<AreaChart
responsive
width={width}
@@ -196,6 +365,11 @@ export function NetWorthGraph({
),
bottom: 0,
}}
+ onMouseMove={() =>
+ effectiveShowTooltip &&
+ !isTooltipActive &&
+ setIsTooltipActive(true)
+ }
>
{compact ? null : (
<CartesianGrid strokeDasharray="3 3" vertical={false} />
@@ -208,20 +382,28 @@ export function NetWorthGraph({
ticks={weeklyTicks}
/>
<YAxis
- dataKey="y"
- domain={['auto', 'auto']}
+ dataKey={mode === 'trend' ? 'y' : undefined}
+ domain={mode === 'trend' ? ['auto', 'auto'] : undefined}
hide={compact}
tickFormatter={tickFormatter}
tick={{ fill: theme.pageText }}
tickLine={{ stroke: theme.pageText }}
/>
- {showTooltip && (
- <Tooltip
- content={<CustomTooltip />}
+ {effectiveShowTooltip && mode === 'trend' && (
+ <Tooltip<number, string>
+ content={props => <TrendTooltip {...props} />}
formatter={numberFormatterTooltip}
isAnimationActive={false}
/>
)}
+ {effectiveShowTooltip && mode === 'stacked' && (
+ <Tooltip<number, string>
+ content={props => <StackedTooltip {...props} />}
+ isAnimationActive={false}
+ wrapperStyle={{ zIndex: 9999, pointerEvents: 'auto' }}
+ />
+ )}
+
<defs>
<linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
<stop
@@ -237,18 +419,37 @@ export function NetWorthGraph({
</linearGradient>
</defs>
- <Area
- type={interpolationType}
- dot={false}
- activeDot={false}
- {...animationProps}
- dataKey="y"
- stroke={theme.reportsChartFill}
- strokeWidth={2}
- fill={`url(#${gradientId})`}
- fillOpacity={1}
- connectNulls
- />
+ {mode === 'trend' ? (
+ <Area
+ type={interpolationType}
+ dot={false}
+ activeDot={false}
+ {...animationProps}
+ dataKey="y"
+ stroke={theme.reportsChartFill}
+ strokeWidth={2}
+ fill={`url(#${gradientId})`}
+ fillOpacity={1}
+ connectNulls
+ />
+ ) : (
+ sortedAccounts.map(account => (
+ <Area
+ key={account.id}
+ type={interpolationType}
+ dataKey={account.id}
+ stackId="1"
+ stroke={colors[account.id]}
+ fill={colors[account.id]}
+ fillOpacity={0.5}
+ strokeWidth={2}
+ {...animationProps}
+ connectNulls
+ onMouseEnter={() => setHoveredAccountId(account.id)}
+ onMouseLeave={() => setHoveredAccountId(null)}
+ />
+ ))
+ )}
</AreaChart>
</div>
)
diff --git a/packages/desktop-client/src/components/reports/overview.scss b/packages/desktop-client/src/components/reports/overview.scss
index 20fc01963d..c3364eee74 100644
--- a/packages/desktop-client/src/components/reports/overview.scss
+++ b/packages/desktop-client/src/components/reports/overview.scss
@@ -12,3 +12,7 @@
border-right: 2px solid var(--color-pageTextLight);
border-bottom: 2px solid var(--color-pageTextLight);
}
+
+.react-grid-item:hover {
+ z-index: 1000 !important;
+}
diff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
index 540ff656a0..a430e33cab 100644
--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx
@@ -10,7 +10,7 @@ import { useParams } from 'react-router';
import { Button } from '@actual-app/components/button';
import { useResponsive } from '@actual-app/components/hooks/useResponsive';
-import { SvgCalendar } from '@actual-app/components/icons/v1';
+import { SvgCalendar, SvgChart } from '@actual-app/components/icons/v1';
import { Menu } from '@actual-app/components/menu';
import { Paragraph } from '@actual-app/components/paragraph';
import { Popover } from '@actual-app/components/popover';
@@ -109,6 +109,9 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
const [interval, setInterval] = useState(
widget?.meta?.interval || getDefaultIntervalForMode(mode),
);
+ const [graphMode, setGraphMode] = useState<'trend' | 'stacked'>(
+ widget?.meta?.mode || 'trend',
+ );
// Combined setter: set mode and update interval (unless interval was set in widget meta)
const setModeAndInterval = useCallback(
(newMode: TimeFrame['mode']) => {
@@ -234,6 +237,7 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
conditions,
conditionsOp,
interval,
+ mode: graphMode,
timeFrame: {
start,
end,
@@ -319,7 +323,10 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
conditionsOp={conditionsOp}
onConditionsOpChange={onConditionsOpChange}
inlineContent={
- <IntervalSelector interval={interval} onChange={setInterval} />
+ <>
+ <IntervalSelector interval={interval} onChange={setInterval} />
+ <ModeSelector mode={graphMode} onChange={setGraphMode} />
+ </>
}
>
{widget && (
@@ -360,8 +367,10 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {
<NetWorthGraph
graphData={data.graphData}
+ accounts={data.accounts}
showTooltip={!isNarrowWidth}
interval={interval}
+ mode={graphMode}
/>
<View style={{ marginTop: 30, userSelect: 'none' }}>
@@ -434,3 +443,56 @@ function IntervalSelector({
</>
);
}
+
+function ModeSelector({
+ mode,
+ onChange,
+}: {
+ mode: 'trend' | 'stacked';
+ onChange: (val: 'trend' | 'stacked') => void;
+}) {
+ const { t } = useTranslation();
+
+ const triggerRef = useRef<HTMLButtonElement | null>(null);
+ const [isOpen, setIsOpen] = useState(false);
+
+ const options = [
+ { key: 'trend', description: t('Trend') },
+ { key: 'stacked', description: t('Stacked') },
+ ];
+
+ const currentLabel =
+ options.find(opt => opt.key === mode)?.description ?? mode;
+
+ return (
+ <>
+ <Button
+ ref={triggerRef}
+ variant="bare"
+ onPress={() => setIsOpen(true)}
+ aria-label={t('Change mode')}
+ >
+ <SvgChart style={{ width: 12, height: 12 }} />
+ <span style={{ marginLeft: 5 }}>{currentLabel}</span>
+ </Button>
+
+ <Popover
+ triggerRef={triggerRef}
+ placement="bottom start"
+ isOpen={isOpen}
+ onOpenChange={() => setIsOpen(false)}
+ >
+ <Menu
+ onMenuSelect={item => {
+ onChange(item as 'trend' | 'stacked');
+ setIsOpen(false);
+ }}
+ items={options.map(({ key, description }) => ({
+ name: key,
+ text: description,
+ }))}
+ />
+ </Popover>
+ </>
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx
index 23e9e2e6a2..a1c84350dc 100644
--- a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx
+++ b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx
@@ -183,9 +183,11 @@ export function NetWorthCard({
{data ? (
<NetWorthGraph
graphData={data.graphData}
+ accounts={data.accounts}
compact
showTooltip={!isEditing && !isNarrowWidth}
interval={meta?.interval || 'Monthly'}
+ mode={meta?.mode || 'trend'}
style={{ height: 'auto', flex: 1 }}
/>
) : (
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
index e631c10aec..0bcc60b91f 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
@@ -129,6 +129,7 @@ export function createSpreadsheet(
return {
id: acct.id,
+ name: acct.name,
balances: processedBalances,
starting,
};
@@ -152,6 +153,7 @@ export function createSpreadsheet(
function recalculate(
data: Array<{
id: string;
+ name: string;
balances: Record<string, Balance>;
starting: number;
}>,
@@ -207,8 +209,11 @@ function recalculate(
let total = 0;
const last = arr.length === 0 ? null : arr[arr.length - 1];
- accountBalances.forEach(balances => {
- const balance = balances[idx];
+ const balances: Record<string, number> = {};
+ accountBalances.forEach((acctBalances, i) => {
+ const balance = acctBalances[idx];
+ balances[data[i].id] = balance;
+
if (balance < 0) {
debt += -balance;
} else {
@@ -259,6 +264,7 @@ function recalculate(
change: format(change, 'financial'),
networth: format(total, 'financial'),
date: d.format(x, tooltipFormat, { locale }),
+ ...balances,
};
arr.push(graphPoint);
@@ -274,6 +280,10 @@ function recalculate(
return arr;
}, []);
+ const hasBalance = accountBalances.map(balances =>
+ balances.some(b => b !== 0),
+ );
+
return {
graphData: {
data: graphData,
@@ -285,5 +295,8 @@ function recalculate(
totalChange: endNetWorth - startNetWorth,
lowestNetWorth,
highestNetWorth,
+ accounts: data
+ .filter((_, i) => hasBalance[i])
+ .map(d => ({ id: d.id, name: d.name })),
};
}
diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.ts
index 8600b0118c..17dce9a6b3 100644
--- a/packages/loot-core/src/types/models/dashboard.ts
+++ b/packages/loot-core/src/types/models/dashboard.ts
@@ -43,8 +43,10 @@ export type NetWorthWidget = AbstractWidget<
conditionsOp?: 'and' | 'or';
timeFrame?: TimeFrame;
interval?: 'Daily' | 'Weekly' | 'Monthly' | 'Yearly';
+ mode?: 'trend' | 'stacked';
} | null
>;
+
export type CashFlowWidget = AbstractWidget<
'cash-flow-card',
{
diff --git a/upcoming-release-notes/6603.md b/upcoming-release-notes/6603.md
new file mode 100644
index 0000000000..c2f87586a9
--- /dev/null
+++ b/upcoming-release-notes/6603.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [mnil]
+---
+
+Creates an option for a stacked line graph in the net worth card.