SPB Git

Repository Public

renderer.chart.test.tsx 7.4 KB 123 lines tsx

1import { describe, expect, it } from "vitest";2import { renderToStaticMarkup } from "react-dom/server";3import { BlockSchema, type BlockOf } from "@/schema";4import { ChartSvg } from "@/renderer/chart/ChartSvg";5import { chartGeometry, niceLinear, niceLog } from "@/renderer/chart/scales";6import { formatNumber } from "@/renderer/i18n";7import { tokenizeLines } from "@/renderer/code-highlight";8import { heatOf, HEAT_MAX_WITH_TEXT, HEAT_MIN, MatrixSvg } from "@/renderer/blocks/MatrixSvg";9import { CHART, MATRIX } from "./renderer.fixture";1011const chart = (input: unknown): BlockOf<"chart"> => BlockSchema.parse(input) as BlockOf<"chart">;12const base = { id: "c", type: "chart", dataKind: "illustrative", x: { label: "x" }, y: { label: "y" } };1314describe("chart scales", () => {15  it("makes nice linear ticks that cover the data", () => {16    const { domain, ticks } = niceLinear(0.7, 2.4, 6);17    expect(domain[0]).toBeLessThanOrEqual(0.7); expect(domain[1]).toBeGreaterThanOrEqual(2.4);18    expect(ticks).toEqual([0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4]);19    expect(niceLinear(0.7, 2.4, 4).ticks).toEqual([0.5, 1, 1.5, 2, 2.5]);20    expect(niceLinear(0, 97, 5).ticks).toEqual([0, 20, 40, 60, 80, 100]);21    const flat = niceLinear(5, 5, 5);22    expect(flat.domain[0]).toBeLessThan(5); expect(flat.domain[1]).toBeGreaterThan(5);23  });24  it("makes log ticks at powers of ten", () => {25    const { domain, ticks } = niceLog(3, 4200);26    expect(domain).toEqual([1, 10000]);27    expect(ticks).toEqual([1, 10, 100, 1000, 10000]);28  });29  it("maps points inside the plot and keeps bars on a zero baseline", () => {30    const c = chart({ ...base, kind: "bar", x: { label: "x", type: "category" }, series: [{ name: "s", points: [{ x: "a", y: 3 }, { x: "b", y: -2 }, { x: "c", y: 7 }] }] });31    const g = chartGeometry(c, 720, 400, "fr");32    expect(g.x.type).toBe("band"); expect(g.x.domain).toEqual(["a", "b", "c"]);33    expect(g.y.domain[0]).toBeLessThanOrEqual(-2); expect(g.y.domain[1]).toBeGreaterThanOrEqual(7);34    expect(g.y.baseline).toBeCloseTo(g.y.position(0)!, 6);35    const xs = ["a", "b", "c"].map((k) => g.x.position(k)!);36    expect(xs[0]).toBeLessThan(xs[1]); expect(xs[1]).toBeLessThan(xs[2]);37    for (const x of xs) { expect(x).toBeGreaterThan(g.plot.left); expect(x).toBeLessThan(g.plot.right); }38    expect(g.x.position("zzz")).toBeNull();39    expect(g.y.position(7)!).toBeLessThan(g.y.position(3)!);40  });41  it("honours axis bounds and log axes", () => {42    const c = chart({ ...base, kind: "scatter", x: { label: "x", scale: "log" }, y: { label: "y", min: 0, max: 50 }, series: [{ name: "s", points: [{ x: 1, y: 10 }, { x: 1000, y: 20 }, { x: -5, y: 30 }] }] });43    const g = chartGeometry(c, 720, 400, "en");44    expect(g.y.domain).toEqual([0, 50]);45    expect(g.x.domain).toEqual([1, 1000]);46    expect(g.x.position(-5)).toBeNull(); expect(g.x.position(0)).toBeNull();47    const mid = g.x.position(Math.sqrt(1000))!;48    expect(mid).toBeCloseTo((g.x.position(1)! + g.x.position(1000)!) / 2, 4);49    expect(g.x.ticks.map((t) => t.value)).toEqual([1, 10, 100, 1000]);50  });51  it("sizes histogram bins from the bin centres", () => {52    const c = chart({ ...base, kind: "histogram", series: [{ name: "s", points: [{ x: 0, y: 1 }, { x: 2, y: 5 }, { x: 4, y: 2 }] }] });53    const g = chartGeometry(c, 720, 400, "fr");54    expect(g.x.domain).toEqual([-1, 5]);55    expect(g.histogramBinWidth).toBeCloseTo(g.x.position(2)! - g.x.position(0)!, 6);56    expect(g.y.domain[0]).toBe(0);57  });58  it("formats numbers per locale, identically everywhere", () => {59    expect(formatNumber(1234.5, "fr")).toBe("1234,5"); expect(formatNumber(12345.5, "fr")).toBe("12 345,5");60    expect(formatNumber(12345.5, "en")).toBe("12,345.5"); expect(formatNumber(-0.25, "en")).toBe("−0.25");61    expect(formatNumber(0.5, "fr", 2)).toBe("0,50"); expect(formatNumber(0.1 + 0.2, "en")).toBe("0.3");62  });63});6465describe("ChartSvg", () => {66  const svg = (c: BlockOf<"chart">, locale: "fr" | "en" = "fr") => renderToStaticMarkup(<ChartSvg chart={c} locale={locale} idPrefix="t" />);67  it("draws exactly the points given, with a legend, bands and the data-kind badge", () => {68    const c = chart(CHART);69    const out = svg(c);70    expect(out).toContain('role="img"'); expect(out).toContain("<title>Perte</title>");71    expect(out.match(/<circle [^>]*r="3" [^>]*stroke-width="1.8"/g)).toHaveLength(8);72    expect(out).toContain("DONNÉES SYNTHÉTIQUES"); expect(svg(c, "en")).toContain("SYNTHETIC DATA");73    expect(out).toContain("Entraînement"); expect(out).toContain("Validation");74    expect(out).toContain("Perte (nats)"); expect(out).toContain("Époque");75    expect(out).toContain('fill-opacity="0.16"');76    expect(out).toContain("Début du surapprentissage"); expect(out).toContain("Seuil");77    expect(out).not.toMatch(/NaN|undefined/);78  });79  it("draws one bar per point and no legend for a single series", () => {80    const c = chart({ ...base, kind: "bar", dataKind: "empirical", x: { label: "x", type: "category" }, series: [{ name: "Seule", points: [{ x: "a", y: 3, lo: 2, hi: 4 }, { x: "b", y: 5 }] }] });81    const out = svg(c);82    expect(out.match(/<rect [^>]*rx="3"/g)).toHaveLength(2);83    expect(out).not.toContain("Seule"); expect(out).toContain("DONNÉES EMPIRIQUES");84  });85  it("renders every kind without NaN", () => {86    for (const kind of ["line", "area", "bar", "scatter", "histogram"] as const) for (const scale of ["linear", "log"] as const) {87      const out = svg(chart({ ...base, kind, y: { label: "y", scale }, series: [{ name: "a", points: [{ x: 1, y: 2 }, { x: 2, y: 0 }, { x: 3, y: 40, lo: 30, hi: 50 }] }, { name: "b", tone: "red", points: [{ x: 1, y: 5 }] }] }));88      expect(out, `${kind} ${scale}`).not.toMatch(/NaN|undefined|Infinity/);89    }90  });91});9293describe("matrix", () => {94  it("scales colour intensity", () => {95    expect(heatOf(0, 0, 10, "sequential", 40).percent).toBe(HEAT_MIN);96    expect(heatOf(10, 0, 10, "sequential", 40).percent).toBe(40);97    expect(heatOf(-1, -1, 0.5, "diverging", 40)).toEqual({ percent: 40, negative: true });98    expect(heatOf(0, -1, 1, "diverging", 40).percent).toBe(0);99    expect(heatOf(3, 0, 10, "none", 40).percent).toBe(0);100  });101  it("prints values with the requested decimals and the data-kind badge", () => {102    const m = BlockSchema.parse(MATRIX) as BlockOf<"matrix">;103    const out = renderToStaticMarkup(<MatrixSvg matrix={m} locale="fr" />);104    expect(out).toContain(">1,00<"); expect(out).toContain(">−0,70<"); expect(out).toContain("DONNÉES ILLUSTRATIVES");105    expect(out).toContain(`color-mix(in srgb, var(--sh-contra) ${HEAT_MAX_WITH_TEXT}%`);106    expect(out).toContain('role="img"');107  });108});109110describe("code tokenizer", () => {111  it("splits comments, strings, numbers and keywords by line", () => {112    const lines = tokenizeLines("# c\ndef f(x):\n    return \"a # b\" + 42\n", "python");113    expect(lines).toHaveLength(3);114    expect(lines[0]).toEqual([{ kind: "comment", text: "# c" }]);115    expect(lines[1][0]).toEqual({ kind: "keyword", text: "def" });116    expect(lines[2].map((t) => t.kind)).toEqual(["plain", "keyword", "plain", "string", "plain", "number"]);117    expect(lines.map((l) => l.map((t) => t.text).join("")).join("\n")).toBe("# c\ndef f(x):\n    return \"a # b\" + 42");118    const sql = tokenizeLines("SELECT a -- x\nFROM t /* multi\nline */ WHERE b = 'it''s'", "sql");119    expect(sql[0][0]).toEqual({ kind: "keyword", text: "SELECT" });120    expect(sql[1].some((t) => t.kind === "comment")).toBe(true); expect(sql[2][0].kind).toBe("comment");121  });122});123
Files main
Menu

Theme