Debian Codegraph @

frontend/src/charts/index.ts

raw
1 /**
2 * This module contains the main code to render Fava's charts.
3 *
4 * The charts heavily use d3 libraries.
5 */
6
7 import { collect, err, type Result } from "../lib/result";
8 import type { ValidationError } from "../lib/validation";
9 import { array, object, string, unknown } from "../lib/validation";
10 import type { BarChart } from "./bar";
11 import { bar } from "./bar";
12 import type { ChartContext } from "./context";
13 import type { HierarchyChart } from "./hierarchy";
14 import { hierarchy } from "./hierarchy";
15 import type { LineChart } from "./line";
16 import { balances } from "./line";
17 import type { ScatterPlot } from "./scatterplot";
18 import { scatterplot } from "./scatterplot";
19
20 const parsers: Record<
21 string,
22 (
23 label: string,
24 json: unknown,
25 $chartContext: ChartContext,
26 ) => Result<FavaChart, ValidationError>
27 > = {
28 balances,
29 bar,
30 hierarchy,
31 scatterplot,
32 };
33
34 export type FavaChart = HierarchyChart | BarChart | ScatterPlot | LineChart;
35
36 const chart_data_validator = array(
37 object({ label: string, type: string, data: unknown }),
38 );
39
40 class ChartValidationError extends Error {
41 constructor(type: string, cause: ValidationError) {
42 super(`Parsing of data for ${type} chart failed.`, { cause });
43 }
44 }
45
46 class UnknownChartTypeError extends Error {
47 constructor(type: string) {
48 super(`Unknown chart type ${type}`);
49 }
50 }
51
52 export function parseChartData(
53 data: unknown,
54 $chartContext: ChartContext,
55 ): Result<FavaChart[], ChartValidationError | UnknownChartTypeError> {
56 return chart_data_validator(data).and_then((chartData) =>
57 collect(
58 chartData.map(({ type, label, data }) => {
59 const parser = parsers[type];
60 return parser
61 ? parser(label, data, $chartContext).map_err(
62 (error) => new ChartValidationError(type, error),
63 )
64 : err(new UnknownChartTypeError(type));
65 }),
66 ),
67 );
68 }