Files
horse/zenno/src/lib/StatChart.svelte
T
2026-07-06 09:41:11 -04:00

144 lines
4.4 KiB
Svelte

<script lang="ts">
import * as Plot from '@observablehq/plot';
import * as d3 from 'd3';
import { Stat } from './race';
import type { ComputedAreas, ComputedSeries, HorizontalRule } from './chart';
import type { ClassValue } from 'svelte/elements';
import type { Attachment } from 'svelte/attachments';
interface Props {
/** The stat the chart shows. */
stat: Stat;
/** Series to show in the chart. */
y?: ComputedSeries | Array<ComputedSeries | null>;
/** Areas to show in the chart. */
yArea?: ComputedAreas | Array<ComputedAreas | null>;
/** Label for the dependent variable. */
yLabel: string;
/**
* Range of the dependent variable to show.
* If not given, the limits are the minimum and maximum values plotted.
* If given as a triple, the second value is the default maximum and
* the third is the maximum when the chart is expanded to 2000.
*/
range?: [number, number] | [number, number, number];
/** Range of the stat to plot. */
xRange?: [number, number] | null;
/**
* Vertical rules to place on the graph.
* Each rule gets a corresponding horizontal rule at the intersection
* with each series.
*/
xRule?: number | number[];
/**
* Horizontal rules to place on the graph.
*/
yRule?: HorizontalRule[];
class?: ClassValue | null;
plotOptions?: Omit<Plot.PlotOptions, 'marks' | 'x' | 'y'>;
}
let {
stat,
y = [],
yArea = [],
yLabel,
range,
xRange,
xRule = [],
yRule = [],
class: className,
plotOptions = {},
}: Props = $props();
let width = $state(0);
let height = $state(0);
const xLabel = $derived(`Raw ${Stat[stat]}`);
const xLines = $derived([xRule].flat(1));
const xMin = $derived(xRange?.[0] ?? 200);
const xMax = $derived.by(() => {
if (xRange?.[1] != null) {
return xRange[1];
}
return 100 * Math.ceil(Math.max(2000, ...xLines) / 100);
});
const xVal = $derived(d3.range(xMin, xMax + 1, 5)); // +1 because d3.range does not include the max
const thrX = 1200;
function adj(x: number): number {
return Math.min(x, 1200) + 0.5 * (Math.max(x, 1200) - 1200);
}
const series = $derived([y].flat(1).filter((s) => s != null));
const areas = $derived([yArea].flat(1).filter((s) => s != null));
const vals = $derived(series.flatMap(({ y, label }) => xVal.map((x) => ({ x, y: y(adj(x), x), label }))));
const areaVals = $derived(
areas.flatMap(({ y1, y2, label }) => xVal.map((x) => ({ x, y1: y1(adj(x), x), y2: y2(adj(x), x), label }))),
);
const yRange: [number, number] = $derived.by(() => {
if (range != null) {
if (range.length === 2) {
return range;
}
return [range[0], range[2]];
}
const l = d3.min(vals, ({ y }) => y) ?? 0;
const r = d3.max(vals, ({ y }) => y) ?? 1;
return [l, r];
});
const yLines = $derived(xLines.flatMap((x) => series.map(({ y, label }) => ({ y: y(adj(x), x), label }))));
const makeChart: Attachment = (el) => {
$effect(() => {
el?.firstChild?.remove();
el?.append(
Plot.plot({
width,
height,
clip: true,
...plotOptions,
x: {
domain: [xMin, xMax],
interval: 5,
ticks: d3.range(2000, 0, -200).filter((x) => xMin <= x && x <= xMax),
label: xLabel,
line: true,
},
y: {
domain: yRange,
grid: true,
label: yLabel,
line: true,
},
marks: [
Plot.ruleX([thrX], { strokeOpacity: 0.25 }),
Plot.ruleX(xLines, { strokeOpacity: 0.5 }),
Plot.ruleY(yLines, { y: 'y', stroke: 'label', strokeOpacity: 0.5 }),
Plot.ruleY(yRule, { y: 'y', strokeOpacity: 0.75 }),
Plot.tip(yRule, { x: xMax, y: 'y', title: 'label', anchor: 'top-right', className: 'plot-tip' }),
Plot.frame(),
Plot.areaY(areaVals, { x: 'x', y1: 'y1', y2: 'y2', fill: 'label', fillOpacity: 0.5 }),
Plot.line(areaVals, { x: 'x', y: 'y1', stroke: 'label' }),
Plot.line(areaVals, { x: 'x', y: 'y2', stroke: 'label' }),
Plot.line(vals, { x: 'x', y: 'y', stroke: 'label', strokeWidth: 3 }),
vals.length > 0 ? Plot.tip(vals, Plot.pointerX({ x: 'x', y: 'y', stroke: 'label', className: 'plot-tip' })) : null,
],
}),
);
});
};
</script>
<div bind:clientWidth={width} bind:clientHeight={height} class={['flex h-full w-full flex-col md:flex-row', className]}>
<div role="img" {@attach makeChart}>
<span>the chart seems to have didn't</span>
</div>
</div>
<style>
:global(.plot-tip) {
--plot-background: light-dark(var(--color-mist-200), var(--color-mist-800));
}
</style>