// A per-step chart: one line for the mean of each step, optionally a dot for every episode behind it. // Hover a step for its numbers; click a dot to open that episode. import { useEffect, useRef, useState } from "react"; export interface Dot { x: number; y: number; id: string; title: string } function niceTicks(max: number): number[] { if (max <= 1) return [0, 0.25, 0.5, 0.75, 1]; const step = max <= 5 ? 1 : max <= 10 ? 2 : max <= 25 ? 5 : 10; const out: number[] = []; for (let v = 0; v <= max + 1e-9; v += step) out.push(v); if (out[out.length - 1] < max) out.push(out[out.length - 1] + step); return out; } export default function StepChart({ xs, mean, dots, yMax, fmt, height = 260, onDot, meanName, dotName }: { xs: number[]; mean: Map; dots?: Dot[]; yMax?: number; fmt: (v: number) => string; height?: number; onDot?: (id: string) => void; meanName: string; dotName?: string; }) { const box = useRef(null); const [w, setW] = useState(720); const [hx, setHx] = useState(null); const [hd, setHd] = useState(null); useEffect(() => { if (!box.current) return; const ro = new ResizeObserver(([e]) => setW(Math.max(280, Math.floor(e.contentRect.width)))); ro.observe(box.current); return () => ro.disconnect(); }, []); const m = { l: 44, r: 16, t: 12, b: 30 }; const iw = w - m.l - m.r, ih = height - m.t - m.b; const top = yMax ?? Math.max(...[...mean.values(), ...(dots ?? []).map((d) => d.y)], 1); const ticks = niceTicks(top); const ymax = ticks[ticks.length - 1]; const band = iw / xs.length; const X = (x: number) => m.l + (xs.indexOf(x) + 0.5) * band; const Y = (y: number) => m.t + ih - (y / ymax) * ih; const byX = new Map(); for (const d of dots ?? []) byX.set(d.x, [...(byX.get(d.x) || []), d]); const jit = (d: Dot) => { const g = byX.get(d.x)!; const i = g.indexOf(d); return (i - (g.length - 1) / 2) * Math.min(2.5, band / (g.length * 3)); }; const line = xs.filter((x) => mean.has(x)).map((x, i) => `${i ? "L" : "M"}${X(x)},${Y(mean.get(x)!)}`).join(""); const hdot = dots?.find((d) => d.id === hd); const tipX = hx != null ? X(hx) : 0; return (
{dots && {dotName}} {meanName}
{ setHx(null); setHd(null); }}> {ticks.map((t) => ( {fmt(t)} ))} {xs.map((x) => {x})} {hx != null && } {xs.filter((x) => mean.has(x)).map((x) => )} {xs.map((x) => ( setHx(x)} /> ))} {dots?.map((d) => ( { setHd(d.id); setHx(d.x); }} onMouseLeave={() => setHd(null)} onClick={() => onDot?.(d.id)} /> ))} {hx != null && (
第 {hx} 步
{hdot ?
{hdot.title}{fmt(hdot.y)}
: <>
{meanName}{mean.has(hx) ? fmt(mean.get(hx)!) : "–"}
{byX.get(hx) &&
{byX.get(hx)!.length} 条{dotName ? `,点一个打开` : ""}
} }
)}
); }