storebound/apps/desktop/src/ui/LineChart.tsx

80 lines
5 KiB
TypeScript

// A small line chart for daily store analytics. Reach (impressions, visitors), installs and conversion differ by one
// to three orders of magnitude, so on one count axis installs lay flat at the bottom. The chart therefore plots each
// line as an index (100 = that line's own average over the days shown, views.ts indexSeries) on one shared axis: every
// line uses the full height and a listing change shows as lines moving apart. Hover (or arrow keys when focused) shows
// the real values of one day; store changes from git are dashed markers.
import { type KeyboardEvent, useId, useState } from 'react';
import { date, num, pct } from '../lib/format';
import { indexSeries } from '../lib/views';
export interface ChartLine {
label: string;
/** Real daily values (counts, or a 0-1 rate with unit "rate"); plotted as an index, shown as they are on hover. */
values: (number | null)[];
cls: 'l1' | 'l2' | 'l3';
unit: 'count' | 'rate';
}
const W = 800, H = 230, L = 46, R = 18, T = 14, B = 26;
/** Index axis: a round top above the highest point (at least 150 so 100 sits in the lower two thirds) and 4 ticks. */
export function indexAxis(lines: (number | null)[][]): { max: number; ticks: number[] } {
const hi = Math.max(150, ...lines.flat().filter((v): v is number => v !== null));
const step = hi <= 200 ? 50 : hi <= 400 ? 100 : Math.ceil(hi / 4 / 100) * 100;
const max = Math.ceil(hi / step) * step;
return { max, ticks: Array.from({ length: max / step + 1 }, (_, i) => i * step) };
}
export function LineChart({ dates, lines, events, label, eventsLabel, indexLabel }: {
dates: string[]; lines: ChartLine[]; events: { date: string; subject: string }[]; label: string; eventsLabel: string; indexLabel: string;
}) {
const gid = useId().replace(/:/g, '');
const [hover, setHover] = useState<number | null>(null);
const n = dates.length;
if (n < 2) return null;
const plotted = lines.map(l => indexSeries(l.values));
const { max, ticks } = indexAxis(plotted);
const x = (i: number) => L + (i / (n - 1)) * (W - L - R);
const y = (v: number) => H - B - (v / max) * (H - T - B);
const path = (vs: (number | null)[]) => vs.map((v, i) => (v === null ? '' : `${i && vs[i - 1] !== null ? 'L' : 'M'}${x(i).toFixed(1)} ${y(v).toFixed(1)}`)).join(' ');
const onMove = (ev: React.MouseEvent<SVGSVGElement>) => {
const r = ev.currentTarget.getBoundingClientRect();
const px = ((ev.clientX - r.left) / r.width) * W;
setHover(Math.max(0, Math.min(n - 1, Math.round(((px - L) / (W - L - R)) * (n - 1)))));
};
const onKey = (ev: KeyboardEvent) => {
if (ev.key === 'ArrowRight') { ev.preventDefault(); setHover(h => Math.min(n - 1, (h ?? -1) + 1)); }
if (ev.key === 'ArrowLeft') { ev.preventDefault(); setHover(h => Math.max(0, (h ?? n) - 1)); }
};
const fmt = (l: ChartLine, v: number | null) => (v === null ? '–' : l.unit === 'rate' ? pct(v, 1) : num(v));
return (
<div className="lchart">
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${label} (${indexLabel})`} tabIndex={0} onMouseMove={onMove} onMouseLeave={() => setHover(null)} onKeyDown={onKey} onBlur={() => setHover(null)}>
<defs><linearGradient id={`lg${gid}`} x1="0" y1="0" x2="0" y2="1"><stop offset="0" className="stop-a" /><stop offset="1" className="stop-b" /></linearGradient></defs>
{ticks.map(v => (
<g key={v} className="grid-l">
<line x1={L} x2={W - R} y1={y(v)} y2={y(v)} />
<text x={L - 6} y={y(v) + 4} textAnchor="end">{v}</text>
</g>
))}
<line className="base" x1={L} x2={W - R} y1={y(100)} y2={y(100)} />
{events.map((e, i) => {
const k = dates.indexOf(e.date);
if (k < 0) return null;
return <g key={i} className="ev"><line x1={x(k)} x2={x(k)} y1={T} y2={H - B} /><circle cx={x(k)} cy={T + 4} r={4}><title>{`${date(e.date)} · ${e.subject}`}</title></circle></g>;
})}
{plotted[0] && <path className="area" d={`${path(plotted[0])} L${x(n - 1)} ${H - B} L${x(0)} ${H - B} Z`} fill={`url(#lg${gid})`} />}
{lines.map((l, k) => <path key={l.label} className={`ln ${l.cls}`} d={path(plotted[k]!)} />)}
{hover !== null && <g className="hov"><line x1={x(hover)} x2={x(hover)} y1={T} y2={H - B} />{lines.map((l, k) => (plotted[k]![hover] === null ? null : <circle key={l.label} className={l.cls} cx={x(hover)} cy={y(plotted[k]![hover]!)} r={3.5} />))}</g>}
<text className="ax" x={L} y={H - 6}>{date(dates[0])}</text>
<text className="ax" x={W - R} y={H - 6} textAnchor="end">{date(dates[n - 1])}</text>
</svg>
<div className="lchart-legend" aria-live="polite">
<span className="lg idx">{indexLabel}</span>
{hover !== null && <b className="num">{date(dates[hover])}</b>}
{lines.map(l => <span key={l.label} className="lg"><span className={`sw ${l.cls}`} />{l.label}{hover !== null && <b className="num">{fmt(l, l.values[hover] ?? null)}</b>}</span>)}
{events.length > 0 && <span className="lg"><span className="sw ev" />{eventsLabel}</span>}
</div>
</div>
);
}