Debian Codegraph @

frontend/src/charts/bar.ts

raw
1 import { rollup } from "d3-array";
2 import type { Series } from "d3-shape";
3 import { stack, stackOffsetDiverging } from "d3-shape";
4
5 import type { FormatterContext } from "../format";
6 import type { Result } from "../lib/result";
7 import type { ValidationError, ValidationT } from "../lib/validation";
8 import { array, date, number, object, record } from "../lib/validation";
9 import type { ChartContext } from "./context";
10 import type { TooltipContent } from "./tooltip";
11 import { domHelpers } from "./tooltip";
12
13 export interface BarChartDatumValue {
14 currency: string;
15 value: number;
16 budget: number;
17 }
18
19 /** The data for the bars of one interval. */
20 export interface BarChartDatum {
21 /** The label of this interval. */
22 label: string;
23 /** The date of this interval. */
24 date: Date;
25 /** One value for each (operating) currency. */
26 values: BarChartDatumValue[];
27 /** The balances of the child accounts. */
28 account_balances: Record<string, Record<string, number>>;
29 }
30
31 const bar_validator = array(
32 object({
33 date,
34 budgets: record(number),
35 balance: record(number),
36 account_balances: record(record(number)),
37 }),
38 );
39
40 type ParsedBarChartData = ValidationT<typeof bar_validator>;
41
42 export class BarChart {
43 readonly type = "barchart";
44
45 /** The accounts that occur in some bar. */
46 readonly accounts: string[];
47
48 /** For each currency, the stacks (one series per account) */
49 private readonly stacks: [
50 currency: string,
51 stacks: Series<BarChartDatum, string>[],
52 ][];
53
54 constructor(
55 readonly name: string | null,
56 /** The currencies that are shown in this bar chart. */
57 readonly currencies: readonly string[],
58 /** The data for the (single) bars for all the intervals in this chart. */
59 private readonly bar_groups: BarChartDatum[],
60 ) {
61 this.accounts = Array.from(
62 new Set(bar_groups.map((d) => Object.keys(d.account_balances)).flat(2)),
63 ).sort();
64
65 this.stacks = currencies.map((currency) => [
66 currency,
67 stack<BarChartDatum, string>()
68 .keys(this.accounts)
69 .value((d, account) => d.account_balances[account]?.[currency] ?? 0)
70 .offset(stackOffsetDiverging)(bar_groups)
71 .filter((b) => b[0] !== b[1] && !Number.isNaN(b[1])),
72 ]);
73 }
74
75 filter(hidden_names: string[]): {
76 currencies: string[];
77 bar_groups: BarChartDatum[];
78 stacks: [currency: string, stacks: Series<BarChartDatum, string>[]][];
79 } {
80 const hidden_names_set = new Set(hidden_names);
81 const currencies = new Set(
82 this.currencies.filter((c) => !hidden_names_set.has(c)),
83 );
84 const bar_groups = this.bar_groups.map((b) => ({
85 ...b,
86 values: b.values.filter((v) => currencies.has(v.currency)),
87 }));
88 const stacks = this.stacks.filter((s) => currencies.has(s[0]));
89 return { currencies: [...currencies], bar_groups, stacks };
90 }
91
92 /** Whether this chart contains any stacks (or is just a single account). */
93 get hasStackedData(): boolean {
94 return this.accounts.length > 1;
95 }
96
97 /** The tooltip for a hovered account in the stacked bar chart. */
98 tooltipTextAccount(
99 c: FormatterContext,
100 d: BarChartDatum,
101 account: string,
102 $chartToggledCurrencies: readonly string[],
103 ): TooltipContent {
104 const content = [];
105 content.push(domHelpers.em(account));
106 d.values.forEach(({ currency }) => {
107 if (!$chartToggledCurrencies.includes(currency)) {
108 const value = d.account_balances[account]?.[currency] ?? 0;
109 content.push(domHelpers.t(c.amount(value, currency)));
110 content.push(domHelpers.br());
111 }
112 });
113 content.push(domHelpers.em(d.label));
114 return content;
115 }
116
117 /** The tooltip for a hovered bar group in the bar chart. */
118 tooltipText(c: FormatterContext, d: BarChartDatum): TooltipContent {
119 const content = [];
120 d.values.forEach((a) => {
121 content.push(
122 domHelpers.t(
123 a.budget
124 ? `${c.amount(a.value, a.currency)} / ${c.amount(
125 a.budget,
126 a.currency,
127 )}`
128 : c.amount(a.value, a.currency),
129 ),
130 );
131 content.push(domHelpers.br());
132 });
133 content.push(domHelpers.em(d.label));
134 return content;
135 }
136 }
137
138 /** Get the currencies to use for the bar chart. */
139 function currencies_to_show(
140 data: ParsedBarChartData,
141 $chartContext: ChartContext,
142 ): string[] {
143 // Count the usage of each currency in the data.
144 const counts = rollup(
145 data.flatMap((interval) => [
146 ...Object.keys(interval.budgets),
147 ...Object.keys(interval.balance),
148 ]),
149 (v) => v.length,
150 (r) => r,
151 );
152
153 // Show all operating currencies that are used in the data.
154 const to_show = $chartContext.currencies.filter((c) => counts.delete(c));
155
156 // Also add some of the most common other currencies (up to 5 in total)
157 to_show.push(
158 ...[...counts]
159 .sort((a, b) => b[1] - a[1])
160 .map((i) => i[0])
161 .slice(0, Math.max(to_show.length, 5) - to_show.length),
162 );
163
164 return to_show;
165 }
166
167 /**
168 * Try to parse a bar chart.
169 */
170 export function bar(
171 label: string | null,
172 json: unknown,
173 $chartContext: ChartContext,
174 ): Result<BarChart, ValidationError> {
175 return bar_validator(json).map((parsedData) => {
176 const currencies = currencies_to_show(parsedData, $chartContext);
177
178 const bar_groups = parsedData.map((interval) => ({
179 values: currencies.map((currency) => ({
180 currency,
181 value: interval.balance[currency] ?? 0,
182 budget: interval.budgets[currency] ?? 0,
183 })),
184 date: interval.date,
185 label: $chartContext.dateFormat(interval.date),
186 account_balances: interval.account_balances,
187 }));
188
189 return new BarChart(label, currencies, bar_groups);
190 });
191 }