Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(frontend): draw the area chart with Intent UI and add its tooltip and ring

spacesdrive93fd7ea38fde
diff --git a/frontend/src/components/ChartFigure.tsx b/frontend/src/components/ChartFigure.tsx
index 93a2446..ce33033 100644
--- a/frontend/src/components/ChartFigure.tsx
+++ b/frontend/src/components/ChartFigure.tsx
@@ -18,6 +18,10 @@ export interface ChartTableSpec {
}
export interface ChartFigureProps {
+ // the chart's name for screen readers, usually its title
+ label?: string;
+ // the takeaway in words, computed from the data and read in place of the plot
+ description?: string;
summary?: string;
table?: ChartTableSpec;
children: React.ReactNode;
@@ -31,9 +35,17 @@ function cellText(column: ChartTableColumn, row: object): string {
}
// a chart with its takeaway in words and its numbers as a table, for anyone who cannot read the plot
-export default function ChartFigure({ summary, table, children, className }: ChartFigureProps) {
+export default function ChartFigure({ label, description, summary, table, children, className }: ChartFigureProps) {
const [showTable, setShowTable] = useState(false);
const summaryId = useId();
+ if (!summary && !table) {
+ return (
+ <figure aria-label={label} aria-describedby={description ? summaryId : undefined} className={className}>
+ {description && <p id={summaryId} className="sr-only">{description}</p>}
+ {children}
+ </figure>
+ );
+ }
return (
<figure className={cn('flex flex-col gap-2', className)} aria-describedby={summary ? summaryId : undefined}>
{showTable && table ? (
diff --git a/frontend/src/components/ChartPanel.tsx b/frontend/src/components/ChartPanel.tsx
index 4a46384..695f782 100644
--- a/frontend/src/components/ChartPanel.tsx
+++ b/frontend/src/components/ChartPanel.tsx
@@ -9,6 +9,8 @@ import type { ChartTableSpec } from './ChartFigure';
export interface ChartPanelProps {
title?: React.ReactNode;
subheader?: React.ReactNode;
+ // read by screen readers in place of the plot
+ description?: string;
summary?: string;
table?: ChartTableSpec;
height?: number;
@@ -18,13 +20,15 @@ export interface ChartPanelProps {
children: React.ReactElement<{ title?: string; desc?: string }>;
}
-export default function ChartPanel({ title, subheader, summary, table, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }: ChartPanelProps) {
+export default function ChartPanel({ title, subheader, description, summary, table, height = 280, empty = false, emptyMessage = 'Not enough data yet', className, children }: ChartPanelProps) {
// the svg itself is a keyboard stop (recharts' accessibility layer), so it needs a name of its own
const plot = typeof title === 'string' ? React.cloneElement(children, { title, desc: summary }) : children;
return (
<SurfaceBox title={title} subheader={subheader} className={className} contentClassName="px-3 pt-4 pb-3">
{empty ? (
<p className="flex items-center justify-center text-small text-ink-faint" style={{ height }}>{emptyMessage}</p>
+ ) : !summary && !table ? (
+ <ChartFigure label={typeof title === 'string' ? title : undefined} description={description}>{children}</ChartFigure>
) : (
<ChartFigure summary={summary} table={table}>
<ResponsiveContainer width="100%" height={height} debounce={200}>
diff --git a/frontend/src/components/DonutChart.tsx b/frontend/src/components/DonutChart.tsx
new file mode 100644
index 0000000..3f8b6ac
--- /dev/null
+++ b/frontend/src/components/DonutChart.tsx
@@ -0,0 +1,40 @@
+import { Cell, Pie, PieChart } from 'recharts';
+import { Chart, ChartLegend, ChartTooltip } from '@/components/ui/chart';
+import ExactTooltip from './ExactTooltip';
+
+export interface DonutSlice {
+ name: string;
+ value: number;
+ // a design token colour, such as SERIES.primary
+ color: string;
+}
+
+export interface DonutChartProps {
+ data: readonly DonutSlice[];
+ height: number;
+ // the ring sits higher in a short card so the legend fits under it
+ cy?: string;
+ innerRadius?: number;
+ outerRadius?: number;
+ format?: (value: number) => string;
+}
+
+function legendText(value: string) {
+ return <span className="text-ink-muted">{value}</span>;
+}
+
+// parts of a whole as a ring inside Intent UI's chart frame and tooltip; Intent's set has no pie of its own
+export default function DonutChart({ data, height, cy = '50%', innerRadius = 55, outerRadius = 95, format }: DonutChartProps) {
+ const rows = data.map(slice => ({ ...slice, fill: slice.color }));
+ return (
+ <Chart config={{}} data={rows} dataKey="name" containerHeight={height}>
+ <PieChart>
+ <Pie data={rows} dataKey="value" nameKey="name" cx="50%" cy={cy} outerRadius={outerRadius} innerRadius={innerRadius} paddingAngle={2} strokeWidth={0}>
+ {rows.map(slice => <Cell key={slice.name} fill={slice.color} />)}
+ </Pie>
+ <ChartTooltip content={<ExactTooltip hideLabel format={format} />} />
+ <ChartLegend iconType="circle" iconSize={8} formatter={legendText} />
+ </PieChart>
+ </Chart>
+ );
+}
diff --git a/frontend/src/components/ExactTooltip.tsx b/frontend/src/components/ExactTooltip.tsx
new file mode 100644
index 0000000..7f19af4
--- /dev/null
+++ b/frontend/src/components/ExactTooltip.tsx
@@ -0,0 +1,37 @@
+import type { ComponentProps } from 'react';
+import { ChartTooltipContent, useChart } from '@/components/ui/chart';
+import { fmtNumFull } from '@/utils/formatters';
+
+interface ValueRowProps {
+ name: string;
+ value: string;
+ color?: string;
+}
+
+function ValueRow({ name, value, color }: ValueRowProps) {
+ const { config } = useChart();
+ return (
+ <div className="flex w-full items-center gap-2">
+ <span aria-hidden="true" className="size-2.5 shrink-0 rounded-full" style={{ background: color }} />
+ <span className="flex-1 text-ink-muted">{config[name]?.label ?? name}</span>
+ <span className="font-mono font-medium text-ink tabular-nums">{value}</span>
+ </div>
+ );
+}
+
+export type ExactTooltipProps = ComponentProps<typeof ChartTooltipContent> & {
+ // how one value reads; whole numbers in full by default
+ format?: (value: number) => string;
+};
+
+// Intent UI's tooltip with every value in full (1,204,553, not 1.2M), since the axis already shows the rounded scale
+export default function ExactTooltip({ format = fmtNumFull, ...props }: ExactTooltipProps) {
+ return (
+ <ChartTooltipContent
+ {...props}
+ formatter={(value, name, item) => (
+ <ValueRow name={String(name)} value={format(Number(value))} color={item.payload?.fill ?? item.color} />
+ )}
+ />
+ );
+}
diff --git a/frontend/src/components/MetricAreaChart.tsx b/frontend/src/components/MetricAreaChart.tsx
index d23fa5f..a8f4f48 100644
--- a/frontend/src/components/MetricAreaChart.tsx
+++ b/frontend/src/components/MetricAreaChart.tsx
@@ -1,20 +1,18 @@
-import React, { useId } from 'react';
-import {
- AreaChart, Area, XAxis, YAxis, CartesianGrid,
- Tooltip as ReTooltip, ResponsiveContainer,
-} from 'recharts';
+import React from 'react';
+import { AreaChart } from '@/components/ui/area-chart';
import { fmtNum, fmtNumFull } from '../utils/formatters';
-import type { NumberLike } from '../utils/formatters';
-import { axisProps, gridProps, tooltipStyle, trendSummary } from '@/lib/chart';
+import { trendSummary } from '@/lib/chart';
import ChartFigure from './ChartFigure';
+import ExactTooltip from './ExactTooltip';
-// a value over time; for a ranking of separate things use RankingBarChart, since a line implies a sequence
export interface MetricAreaChartProps {
- data?: readonly object[] | null;
+ data?: readonly Record<string, unknown>[] | null;
dataKey: string;
label: string;
- // names the plot and its table; defaults to the label
+ // names the plot for screen readers; defaults to the label
title?: string;
+ // read in place of the plot; defaults to how the value moved from the first point to the last
+ description?: string;
color?: string;
height?: number;
emptyMessage?: React.ReactNode;
@@ -25,61 +23,35 @@ export default function MetricAreaChart({
dataKey,
label,
title = label,
+ description,
color = 'var(--chart-1)',
height = 240,
emptyMessage = 'No data to display',
}: MetricAreaChartProps) {
- // useId keeps each instance's gradient unique; colons are invalid inside a url() reference
- const gradientId = `metric-area-${useId().replace(/:/g, '')}`;
-
if (!data || data.length === 0) {
return <p className="py-8 text-center text-small text-ink-faint">{emptyMessage}</p>;
}
- const rows = data as Record<string, unknown>[];
- const points = rows.map(row => ({ name: String(row.name ?? ''), value: Number(row[dataKey] ?? 0) }));
- const summary = trendSummary(points, fmtNum, label.toLowerCase());
+ const points = data.map(row => ({ name: String(row.name ?? ''), value: Number(row[dataKey] ?? 0) }));
return (
- <ChartFigure
- summary={summary}
- table={{
- caption: title,
- columns: [
- { key: 'name', label: 'Period' },
- { key: dataKey, label, numeric: true, format: value => fmtNumFull(value as NumberLike) },
- ],
- rows,
- }}
- >
- <ResponsiveContainer width="100%" height={height} debounce={200}>
- <AreaChart data={data} margin={{ top: 8, right: 8, left: 0, bottom: 0 }} title={title} desc={summary}>
- <defs>
- <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={color} stopOpacity={0.2} />
- <stop offset="95%" stopColor={color} stopOpacity={0} />
- </linearGradient>
- </defs>
- <CartesianGrid {...gridProps} vertical={false} />
- <XAxis dataKey="name" {...axisProps} interval="preserveStartEnd" />
- <YAxis {...axisProps} tickFormatter={fmtNum} width={48} allowDecimals={false} />
- <ReTooltip
- contentStyle={tooltipStyle}
- cursor={{ stroke: 'var(--line-strong)' }}
- formatter={(v) => [fmtNumFull(v as NumberLike), label]}
- />
- <Area
- type="monotone"
- dataKey={dataKey}
- name={label}
- stroke={color}
- strokeWidth={2}
- fill={`url(#${gradientId})`}
- dot={{ r: 3, fill: color, stroke: 'var(--surface-raised)', strokeWidth: 2 }}
- activeDot={{ r: 6 }}
- />
- </AreaChart>
- </ResponsiveContainer>
+ <ChartFigure label={title} description={description ?? trendSummary(points, fmtNumFull, label.toLowerCase())}>
+ <AreaChart
+ data={[...data]}
+ dataKey="name"
+ config={{ [dataKey]: { label, color } }}
+ containerHeight={height}
+ legend={false}
+ tooltip={<ExactTooltip />}
+ valueFormatter={fmtNum}
+ xAxisProps={{ interval: 'preserveStartEnd' }}
+ yAxisProps={{ allowDecimals: false }}
+ areaProps={{
+ type: 'monotone',
+ dot: { r: 3, fill: color, stroke: 'var(--surface-raised)', strokeWidth: 2 },
+ activeDot: { r: 6 },
+ }}
+ />
</ChartFigure>
);
}