Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

charts.tsx

108 lines3.1 KB

1/*
2 * The analytics charts, drawn with TanStack Charts. This module is the only
3 * one that imports the chart library, and it's only ever loaded lazily
4 * (`lazy-charts.tsx`), so the charts' code stays out of the first bundle.
5 */
6import { barX, barY, defineChart, text } from "@tanstack/charts";
7import { Chart } from "@tanstack/charts/react";
8import { scaleBand } from "@tanstack/charts/scales/band";
9import { scaleLinear } from "@tanstack/charts/scales/linear";
10import { tooltip } from "@tanstack/charts/tooltip";
11import { useMemo } from "react";
12​
13import { DAY_CHART_HEIGHT, folderChartHeight } from "./analytics-data";
14import type { DayChartRow, FolderChartRow } from "./analytics-data";
15​
16const numberFormat = new Intl.NumberFormat("en-GB");
17​
18/** Horizontal bars, one per folder, each labelled with its value. */
19export function FolderBarChart({
20 rows,
21 measure,
22}: {
23 rows: readonly FolderChartRow[];
24 measure: "notes" | "words";
25}) {
26 const definition = useMemo(
27 () =>
28 defineChart({
29 marks: [
30 barX(rows, {
31 x: measure,
32 y: "name",
33 key: "folderId",
34 radius: { end: 4 },
35 maxThickness: 22,
36 }),
37 text(rows, {
38 x: measure,
39 y: "name",
40 key: "folderId",
41 text: (row) => numberFormat.format(row[measure]),
42 anchor: "start",
43 dx: 6,
44 fontSize: 11,
45 fill: "currentColor",
46 }),
47 ],
48 scales: {
49 x: { scale: scaleLinear, nice: true, axis: false },
50 y: {
51 scale: () => scaleBand().padding(0.25),
52 axis: { line: false, ticks: { size: 0 }, tickLabels: { fontSize: 12 } },
53 },
54 },
55 svgAnimation: true,
56 tooltip,
57 }),
58 [rows, measure],
59 );
60​
61 return (
62 <Chart
63 definition={definition}
64 height={folderChartHeight(rows.length)}
65 ariaLabel={measure === "notes" ? "Notes per folder" : "Words per folder"}
66 ariaDescription={rows
67 .map((row) => `${row.name}: ${numberFormat.format(row[measure])} ${measure}`)
68 .join(", ")}
69 />
70 );
72​
73/** Vertical bars, one per day. */
74export function DayBarChart({ rows }: { rows: readonly DayChartRow[] }) {
75 const definition = useMemo(
76 () =>
77 defineChart({
78 marks: [barY(rows, { x: "label", y: "notes", key: "day", radius: { end: 3 } })],
79 scales: {
80 x: {
81 scale: () => scaleBand().padding(0.2),
82 axis: { line: false, ticks: { size: 0 } },
83 },
84 y: {
85 scale: scaleLinear,
86 nice: true,
87 grid: { strokeOpacity: 0.12 },
88 axis: { line: false, ticks: { size: 0, format: (value) => String(value) } },
89 },
90 },
91 svgAnimation: true,
92 tooltip,
93 }),
94 [rows],
95 );
96​
97 return (
98 <Chart
99 definition={definition}
100 height={DAY_CHART_HEIGHT}
101 ariaLabel="Notes by day of last edit"
102 ariaDescription={rows
103 .filter((row) => row.notes > 0)
104 .map((row) => `${row.label}: ${row.notes}`)
105 .join(", ")}
106 />
107 );