A local-first personal finance app
[AI] Add Sankey report toggle to view values as percentages (#7476)
Emil Tveden Bjerglund213185661f6a
diff --git a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsxindex 392c8f52db..1e3438f0f8 100644--- a/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx+++ b/packages/desktop-client/src/components/reports/graphs/SankeyGraph.tsx@@ -24,6 +24,7 @@ type SankeyGraphNode = SankeyData['nodes'][number] & {toBudget?: number;isNegative?: boolean;actualValue?: number;+ percentageLabel?: string;targetLinks?: Array<Record<string, unknown>>;sourceLinks?: Array<Record<string, unknown>>;};@@ -91,6 +92,7 @@ type SankeyNodeProps = {payload: SankeyGraphNode;containerWidth: number;containerHeight: number;+ showPercentages?: boolean;};function SankeyNode({x,@@ -101,6 +103,7 @@ function SankeyNode({payload,containerWidth,containerHeight,+ showPercentages,}: SankeyNodeProps) {const privacyMode = usePrivacyMode();const format = useFormat();@@ -162,7 +165,9 @@ function SankeyNode({))}{renderText(payload.name || '', height / 2)}{renderText(- format(payload.value, 'financial'),+ showPercentages && payload.percentageLabel+ ? payload.percentageLabel+ : format(payload.value, 'financial'),height / 2 + 13,11,0.5,@@ -195,11 +200,13 @@ type SankeyGraphProps = {data: SankeyData;showTooltip?: boolean;collapsedNodes?: string[];+ showPercentages?: boolean;};export function SankeyGraph({style,data,showTooltip = true,+ showPercentages = false,}: SankeyGraphProps) {const privacyMode = usePrivacyMode();const format = useFormat();@@ -229,6 +236,7 @@ export function SankeyGraph({{...props}containerWidth={width}containerHeight={height}+ showPercentages={showPercentages}/>)}link={props => (diff --git a/packages/desktop-client/src/components/reports/reports/Sankey.tsx b/packages/desktop-client/src/components/reports/reports/Sankey.tsxindex 5d05451f32..98cca58f91 100644--- a/packages/desktop-client/src/components/reports/reports/Sankey.tsx+++ b/packages/desktop-client/src/components/reports/reports/Sankey.tsx@@ -31,7 +31,10 @@ import { Header } from '#components/reports/Header';import { LoadingIndicator } from '#components/reports/LoadingIndicator';import { ModeButton } from '#components/reports/ModeButton';import { calculateTimeRange } from '#components/reports/reportRanges';-import { createSpreadsheet as sankeySpreadsheet } from '#components/reports/spreadsheets/sankey-spreadsheet';+import {+ createSpreadsheet as sankeySpreadsheet,+ withPercentageLabels,+} from '#components/reports/spreadsheets/sankey-spreadsheet';import { useReport } from '#components/reports/useReport';import { fromDateRepr } from '#components/reports/util';import { useCategories } from '#hooks/useCategories';@@ -197,6 +200,46 @@ function GraphModeSelector({ mode, onChange }: GraphModeSelectorProps) {);}+type OptionsButtonProps = {+ showPercentages: boolean;+ onTogglePercentages: () => void;+};++function OptionsButton({+ showPercentages,+ onTogglePercentages,+}: OptionsButtonProps) {+ const { t } = useTranslation();+ const triggerRef = useRef<HTMLButtonElement | null>(null);+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button ref={triggerRef} onPress={() => setIsOpen(true)}>+ <Trans>Options</Trans>+ </Button>+ <Popover+ triggerRef={triggerRef}+ placement="bottom end"+ isOpen={isOpen}+ onOpenChange={() => setIsOpen(false)}+ >+ <Menu+ onMenuSelect={item => {+ if (item === 'show-percentages') onTogglePercentages();+ }}+ items={[+ {+ name: 'show-percentages',+ text: t('Show as percentages'),+ toggle: showPercentages,+ },+ ]}+ />+ </Popover>+ </>+ );+}+type SankeyInnerProps = {widget?: SankeyWidget;};@@ -249,6 +292,10 @@ function SankeyInner({ widget }: SankeyInnerProps) {'per-group' | 'global' | 'budget-order'>(widget?.meta?.categorySort ?? 'per-group');+ const [showPercentages, setShowPercentages] = useState(+ widget?.meta?.showPercentages ?? false,+ );+const { data: { grouped: groupedCategories = [] } = { grouped: [] } } =useCategories();@@ -370,6 +417,7 @@ function SankeyInner({ widget }: SankeyInnerProps) {mode: graphMode,topNcategories,categorySort,+ showPercentages,timeFrame: {start,end,@@ -504,6 +552,12 @@ function SankeyInner({ widget }: SankeyInnerProps) {</>}>+ <View style={{ marginRight: 4 }}>+ <OptionsButton+ showPercentages={showPercentages}+ onTogglePercentages={() => setShowPercentages(v => !v)}+ />+ </View>{widget && (<Button variant="primary" onPress={onSaveWidget}><Trans>Save widget</Trans>@@ -552,7 +606,12 @@ function SankeyInner({ widget }: SankeyInnerProps) {{data && data.links && data.links.length > 0 ? (<SankeyGraphstyle={{ flexGrow: 1 }}- data={data as SankeyData}+ data={+ showPercentages+ ? withPercentageLabels(data as SankeyData)+ : (data as SankeyData)+ }+ showPercentages={showPercentages}/>) : (<Viewdiff --git a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsxindex a964d9d252..d2e306ab39 100644--- a/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SankeyCard.tsx@@ -16,6 +16,7 @@ import { calculateTimeRange } from '#components/reports/reportRanges';import {compactSankeyData,createSpreadsheet as sankeySpreadsheet,+ withPercentageLabels,} from '#components/reports/spreadsheets/sankey-spreadsheet';import { useDashboardWidgetCopyMenu } from '#components/reports/useDashboardWidgetCopyMenu';import { useReport } from '#components/reports/useReport';@@ -153,7 +154,12 @@ export function SankeyCard({{compactData ? (<SankeyGraph- data={compactData}+ data={+ meta?.showPercentages+ ? withPercentageLabels(compactData)+ : compactData+ }+ showPercentages={meta?.showPercentages}showTooltip={!isEditing}style={{ height: 'auto', flex: 1 }}/>diff --git a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.tsindex d5e26f36ba..1b4aa8bfe1 100644--- a/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts+++ b/packages/desktop-client/src/components/reports/spreadsheets/sankey-spreadsheet.ts@@ -41,6 +41,7 @@ type SankeyNode = {name: string;toBudget?: number;isNegative?: boolean;+ percentageLabel?: string;};type SankeyLink = {@@ -728,3 +729,46 @@ export function compactSankeyData(return compactedData;}++export function withPercentageLabels(data: SankeyData): SankeyData {+ // Assign a layer depth to each node, starting from the root (node 0 = depth 0).+ const depth = new Array<number>(data.nodes.length).fill(-1);+ depth[0] = 0;+ let changed = true;+ while (changed) {+ changed = false;+ for (const link of data.links) {+ const src = link.source;+ const tgt = link.target;+ if (depth[src] >= 0 && depth[tgt] < 0) {+ depth[tgt] = depth[src] + 1;+ changed = true;+ }+ }+ }++ // Each node's value is the sum of its incoming links.+ // The root has no incoming links, so use its outgoing links instead.+ const nodeValue = (i: number) =>+ data.links+ .filter(l => (depth[i] === 0 ? l.source === i : l.target === i))+ .reduce((sum, l) => sum + l.value, 0);++ // Compute the total value per layer so percentages within each layer sum to 100%.+ const layerTotal = new Map<number, number>();+ data.nodes.forEach((_, i) => {+ const d = depth[i];+ if (d >= 0) layerTotal.set(d, (layerTotal.get(d) ?? 0) + nodeValue(i));+ });++ const nodes = data.nodes.map((node, i) => {+ const total = layerTotal.get(depth[i]) ?? 0;+ return {+ ...node,+ percentageLabel:+ total === 0 ? '0%' : `${((nodeValue(i) / total) * 100).toFixed(1)}%`,+ };+ });++ return { ...data, nodes };+}diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 4fc92fe9f6..95bc5bac75 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -222,5 +222,6 @@ export type SankeyWidget = AbstractWidget<mode?: 'budgeted' | 'spent';topNcategories?: number;categorySort?: 'per-group' | 'global' | 'budget-order';+ showPercentages?: boolean;} | null>;diff --git a/upcoming-release-notes/7476.md b/upcoming-release-notes/7476.mdnew file mode 100644index 0000000000..0a4069331e--- /dev/null+++ b/upcoming-release-notes/7476.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [emiltb]+---++Added a new Sankey Options menu with a toggle to view values as percentages.