Debian Codegraph @

frontend/src/charts/line.ts

raw
1 import { sort } from "d3-array";
2
3 import type { FormatterContext } from "../format";
4 import { day } from "../format";
5 import type { Result } from "../lib/result";
6 import type { ValidationError } from "../lib/validation";
7 import { array, date, number, object, record } from "../lib/validation";
8 import type { TooltipContent } from "./tooltip";
9 import { domHelpers } from "./tooltip";
10
11 /**
12 * A single data point on a line or area chart.
13 */
14 export interface LineChartDatum {
15 readonly name: string;
16 readonly date: Date;
17 readonly value: number;
18 }
19
20 /**
21 * A series of values for a line chart, e.g., for a single currency.
22 */
23 interface LineChartSeries {
24 readonly name: string;
25 readonly values: readonly LineChartDatum[];
26 }
27
28 /**
29 * A line or area chart.
30 *
31 * This consists of several series of points, e.g., a line for each currency
32 * in the balances of an account.
33 */
34 export class LineChart {
35 readonly type = "linechart";
36
37 readonly series_names: readonly string[];
38
39 constructor(
40 readonly name: string | null,
41 private readonly data: readonly LineChartSeries[],
42 readonly tooltipText: (
43 c: FormatterContext,
44 d: LineChartDatum,
45 ) => TooltipContent,
46 ) {
47 this.data = sort(data, (d) => -d.values.length);
48 this.series_names = this.data.map((series) => series.name);
49 }
50
51 /** Filter the data of this chart, excluding some series. */
52 filter(hidden_names: readonly string[]): LineChartSeries[] {
53 const hidden_names_set = new Set(hidden_names);
54 return this.data.filter((series) => !hidden_names_set.has(series.name));
55 }
56 }
57
58 const balances_validator = array(object({ date, balance: record(number) }));
59
60 export function balances_from_parsed_data(
61 label: string | null,
62 parsed_data: { date: Date; balance: Record<string, number> }[],
63 ): LineChart {
64 const groups = new Map<string, LineChartDatum[]>();
65 for (const { date: date_val, balance } of parsed_data) {
66 Object.entries(balance).forEach(([currency, value]) => {
67 const group = groups.get(currency);
68 const datum = { date: date_val, value, name: currency };
69 if (group) {
70 group.push(datum);
71 } else {
72 groups.set(currency, [datum]);
73 }
74 });
75 }
76 const data = [...groups.entries()].map(([name, values]) => ({
77 name,
78 values,
79 }));
80
81 return new LineChart(label, data, (c, d) => [
82 domHelpers.t(c.amount(d.value, d.name)),
83 domHelpers.em(day(d.date)),
84 ]);
85 }
86
87 export function balances(
88 label: string | null,
89 json: unknown,
90 ): Result<LineChart, ValidationError> {
91 return balances_validator(json).map((parsedData) =>
92 balances_from_parsed_data(label, parsedData),
93 );
94 }