SPB Git

Repository Public

editor.forms.test.tsx 30.9 KB 518 lines tsx

1import { describe, expect, it } from "vitest";2import { renderToStaticMarkup } from "react-dom/server";3import {4  BLOCK_TYPES, BlockSchema, LeafBlockSchema, LOCALES, SIM_KINDS, SheetSchema, emptySheet, mustParseSheet, type Block, type BlockOf, type LeafBlock, type Sheet,5} from "@/schema";6import { COMMON_CONFIG_KEYS, SIMULATIONS, paramDefs, validateSimulation } from "@/sim/registry";7import { BlockForm, checkBlock } from "@/components/editor/forms/BlockForm";8import { BLOCK_CATALOG, IMAGE_PLACEHOLDER_REF, duplicateBlock, newBlock, newLeafBlock } from "@/components/editor/forms/defaults";9import {10  comparisonAddColumn, comparisonMoveColumn, comparisonRemoveColumn, convertPointsX, datasetToSeries, detectDelimiter, gridToPoints, looksLikeGrid,11  matrixAddColumn, matrixAddRow, matrixMoveColumn, matrixPaste, matrixRemoveColumn, matrixRemoveRow, moveItem, parseDelimited, parseNumber, pasteCells,12  plainIssues, pointsToGrid, pruneSimConfig, rectangular, removeDiagramEdge, removeDiagramGroup, removeDiagramNode, rowToPoint, simParams, simWithConfig,13  simWithKind, simulationIssues, tableAddColumn, tableAddRow, tableMoveColumn, tablePaste, tableRemoveColumn, tableRemoveRow,14} from "@/components/editor/forms/helpers";15import { SIM_CONFIG, sliderBoundFields } from "@/components/editor/forms/sim-config";16import { S } from "@/components/editor/forms/strings";1718const doc: Sheet = mustParseSheet({19  schemaVersion: 1, metadata: { title: "Essai", locale: "fr" }, blocks: [],20  sources: [{ id: "src-a", type: "article", title: "Attention Is All You Need", year: 2017 }, { id: "src-b", type: "web", title: "Documentation" }],21  assets: [{ id: "img-1", kind: "image", assetId: "7b0f0f1e-52a5-4a4e-9a8e-0d1a0d5f7a10", alt: "Un schéma" }, { id: "data-1", kind: "dataset", assetId: "7b0f0f1e-52a5-4a4e-9a8e-0d1a0d5f7a11" }],22});23const as = <T extends Block["type"]>(type: T, locale: "fr" | "en" = "fr") => newBlock(type, locale) as BlockOf<T>;24const render = (block: Block | LeafBlock, locale: "fr" | "en" = "fr", extra: Partial<Parameters<typeof BlockForm>[0]> = {}) =>25  renderToStaticMarkup(<BlockForm block={block} doc={doc} locale={locale} onChange={() => { throw new Error("onChange must not be called while rendering"); }} {...extra} />);2627describe("BLOCK_CATALOG", () => {28  it("covers every block type exactly once, in both languages", () => {29    expect(BLOCK_CATALOG.map((e) => e.type).sort()).toEqual([...BLOCK_TYPES].sort());30    expect(new Set(BLOCK_CATALOG.map((e) => e.type)).size).toBe(23);31    for (const e of BLOCK_CATALOG) for (const l of LOCALES) { expect(e.label[l].length).toBeGreaterThan(0); expect(e.description[l].length).toBeGreaterThan(0); }32    expect(new Set(BLOCK_CATALOG.map((e) => e.group))).toEqual(new Set(["text", "structure", "visual", "data", "interactive"]));33  });34});3536describe("newBlock", () => {37  for (const locale of LOCALES) for (const type of BLOCK_TYPES) {38    it(`${type} (${locale}) is schema-valid with a fresh id`, () => {39      const a = newBlock(type, locale), b = newBlock(type, locale);40      expect(a.type).toBe(type);41      expect(BlockSchema.safeParse(a).success).toBe(true);42      expect(BlockSchema.parse(a)).toEqual(a);43      expect(a.id).not.toBe(b.id);44    });45  }46  it("writes the starter content in the requested language", () => {47    expect(as("heading", "fr").text).not.toBe(as("heading", "en").text);48    expect(as("paragraph", "en").text).toMatch(/New paragraph/);49  });50  for (const kind of SIM_KINDS) for (const locale of LOCALES) {51    it(`simulation ${kind} (${locale}) is valid for the schema and for the simulation itself`, () => {52      const b = newBlock("simulation", locale, { simKind: kind }) as BlockOf<"simulation">;53      expect(b.kind).toBe(kind);54      expect(BlockSchema.safeParse(b).success).toBe(true);55      expect(validateSimulation(b)).toEqual([]);56      expect(Object.keys(b.params).sort()).toEqual(paramDefs(kind, b.config).map((d) => d.key).sort());57      expect(b.title).toBe(SIMULATIONS[kind].title[locale]);58    });59  }60  it("gives the visual blocks a text alternative, and the image a placeholder or the given asset", () => {61    for (const type of ["diagram", "chart", "matrix", "svg", "simulation"] as const) expect(newBlock(type, "fr").alt).toBeTruthy();62    expect(as("image").assetRef).toBe(IMAGE_PLACEHOLDER_REF);63    expect((newBlock("image", "fr", { assetRef: "img-1" }) as BlockOf<"image">).assetRef).toBe("img-1");64  });65  it("makes a document of all 23 types that passes the sheet schema", () => {66    const blocks = BLOCK_TYPES.map((t) => newBlock(t, "fr", { assetRef: "img-1" }));67    expect(SheetSchema.safeParse({ ...doc, blocks }).success).toBe(true);68  });69  it("newLeafBlock passes LeafBlockSchema for every leaf type", () => {70    for (const type of BLOCK_TYPES) if (type !== "tabs") expect(LeafBlockSchema.safeParse(newLeafBlock(type, "en")).success).toBe(true);71  });72});7374describe("duplicateBlock", () => {75  it("returns a valid deep copy with a fresh id for every type", () => {76    for (const type of BLOCK_TYPES) {77      const a = newBlock(type, "fr"), b = duplicateBlock(a);78      expect(b.id).not.toBe(a.id);79      expect(BlockSchema.safeParse(b).success).toBe(true);80      expect({ ...b, id: a.id, ...(b.type === "tabs" ? { tabs: [] } : {}) }).toEqual({ ...a, ...(a.type === "tabs" ? { tabs: [] } : {}) });81    }82  });83  it("renews tab ids and nested block ids, and never shares structure with the original", () => {84    const a = as("tabs");85    a.tabs[0].blocks.push(newLeafBlock("diagram", "fr"), newLeafBlock("quiz", "fr"));86    const b = duplicateBlock(a);87    const ids = (t: BlockOf<"tabs">) => [t.id, ...t.tabs.flatMap((tab) => [tab.id, ...tab.blocks.map((c) => c.id)])];88    expect(new Set([...ids(a), ...ids(b)]).size).toBe(ids(a).length * 2);89    expect(b.tabs.map((t) => t.blocks.map((c) => c.type))).toEqual(a.tabs.map((t) => t.blocks.map((c) => c.type)));90    // Both copies can live in the same document.91    expect(SheetSchema.safeParse({ ...doc, blocks: [a, b] }).success).toBe(true);92    const child = b.tabs[0].blocks[1];93    if (child.type !== "diagram") throw new Error("expected a diagram");94    child.nodes[0].label = "changé";95    const original = a.tabs[0].blocks[1];96    expect(original.type === "diagram" && original.nodes[0].label).not.toBe("changé");97    // Diagram node and edge ids are local to the block: they stay.98    expect(original.type === "diagram" && original.nodes.map((n) => n.id)).toEqual(child.nodes.map((n) => n.id));99  });100  it("keeps a leaf block a leaf block", () => {101    const leaf = newLeafBlock("table", "en");102    expect(LeafBlockSchema.safeParse(duplicateBlock(leaf)).success).toBe(true);103  });104});105106describe("BlockForm server rendering", () => {107  for (const locale of LOCALES) for (const type of BLOCK_TYPES) {108    it(`${type} (${locale}) renders`, () => {109      const html = render(newBlock(type, locale, { assetRef: "img-1" }), locale);110      expect(html).toContain(S(locale).blockSettings);111      expect(html).toContain(S(locale).width);112      // Every input, select and textarea has a label: a `for`, a wrapping label, or an aria-label.113      const controls = html.match(/<(input|select|textarea)\b[^>]*>/g) ?? [];114      expect(controls.length).toBeGreaterThan(0);115      for (const c of controls) {116        const id = /\sid="([^"]+)"/.exec(c)?.[1];117        const labelled = /aria-label="/.test(c) || (id !== undefined && html.includes(`for="${id}"`)) || /type="(radio|checkbox)"/.test(c);118        expect(labelled, c).toBe(true);119      }120    });121  }122  for (const kind of SIM_KINDS) it(`simulation ${kind} renders its sliders`, () => {123    const b = newBlock("simulation", "fr", { simKind: kind }) as BlockOf<"simulation">;124    const html = render(b);125    expect((html.match(/type="range"/g) ?? []).length).toBe(paramDefs(kind, b.config).length);126  });127  it("marks the text alternative as required on visual blocks only", () => {128    for (const type of ["diagram", "chart", "matrix", "svg", "image", "simulation"] as const) expect(render(newBlock(type, "fr", { assetRef: "img-1" }))).toContain(">requis<");129    expect(render(newBlock("divider", "fr"))).not.toContain(">requis<");130    expect(render({ ...as("chart"), alt: undefined })).toContain(S("fr").altMissing);131  });132  it("offers the sources of the document and shows the selected ones", () => {133    const html = render({ ...as("paragraph"), sourceIds: ["src-a", "disparue"] });134    expect(html).toContain("Attention Is All You Need (2017)");135    expect(html).toContain("Source introuvable : disparue");136    expect((html.match(/aria-pressed="true"/g) ?? []).length).toBe(2);137    expect(render(as("paragraph"), "fr", { doc: emptySheet("fr", "Vide") })).toContain(S("fr").noSources);138  });139  it("shows host-dependent controls only when the host provides them", () => {140    expect(render(as("diagram"))).not.toContain(S("fr").openDiagramEditor);141    expect(render(as("diagram"), "fr", { onOpenDiagramEditor: () => {} })).toContain("Ouvrir l’éditeur visuel");142    expect(render(as("chart"))).not.toContain(S("fr").importDataset);143    expect(render(as("chart"), "fr", { onPickAsset: async () => null })).not.toContain(S("fr").importDataset);144    expect(render(as("chart"), "fr", { onPickAsset: async () => null, loadDataset: async () => null })).toContain("Importer d’un jeu de données");145    expect(render(as("image"))).not.toContain(S("fr").imagePick);146    expect(render(as("image"), "fr", { onPickAsset: async () => null })).toContain(S("fr").imagePick);147  });148  it("shows the asset's alt read-only on an image, and a warning while no picture is chosen", () => {149    const html = render(newBlock("image", "fr", { assetRef: "img-1" }));150    expect(html).toContain("Un schéma");151    expect(html).toContain("lecture seule");152    expect(render(as("image"))).toContain(S("fr").imageNone);153  });154  it("previews the equation and reports a LaTeX syntax error under the field", () => {155    expect(render(as("equation"))).toContain("katex");156    const html = render({ ...as("equation"), latex: "\\frac{1}{" });157    expect(html).toContain("Erreur de syntaxe LaTeX");158    expect(html).toMatch(/aria-invalid="true"[^>]*aria-describedby="[^"]+-err"/);159  });160  it("warns when no quiz choice is correct (a block the schema would refuse)", () => {161    const q = as("quiz");162    expect(render({ ...q, choices: q.choices.map((c) => ({ ...c, correct: false })) })).toContain(S("fr").quizNoCorrect);163    expect(render(q)).not.toContain(S("fr").quizNoCorrect);164  });165  it("renders tab children as a list and a leaf block as a form of its own", () => {166    const html = render(as("tabs"));167    expect(html).toContain("Blocs de l’onglet");168    expect(html).toContain("Modifier : Paragraphe « Contenu de l’onglet 1. »");169    expect(html).toContain("Type du bloc à ajouter à l’onglet 1");170    expect((html.match(/<option /g) ?? []).length).toBe(22);171    expect(render(newLeafBlock("legend", "en"), "en")).toContain("Legend entries");172  });173});174175describe("checkBlock (the gate before onChange)", () => {176  it("passes valid blocks and drops absent optional values", () => {177    const h = as("heading");178    const r = checkBlock({ ...h, eyebrow: undefined, locked: undefined }, false, "fr");179    expect(r.ok && Object.keys(r.block)).not.toContain("eyebrow");180    expect(r.ok && BlockSchema.safeParse(r.block).success).toBe(true);181  });182  it("refuses an emptied required text with a plain sentence on the right path", () => {183    const r = checkBlock({ ...as("heading"), text: "" }, false, "fr");184    expect(r).toEqual({ ok: false, issues: [{ path: "text", message: "Ce champ ne peut pas être vide." }] });185    const en = checkBlock({ ...as("cards", "en"), items: [{ title: "", text: "", tone: "neutral" }] }, false, "en");186    expect(en).toEqual({ ok: false, issues: [{ path: "items.0.title", message: "This field cannot be empty." }] });187  });188  it("explains the cross-field rules in plain words", () => {189    const q = as("quiz");190    const r = checkBlock({ ...q, choices: q.choices.map((c) => ({ ...c, correct: false })) }, false, "fr");191    expect(!r.ok && r.issues[0].message).toBe("Cochez au moins une bonne réponse.");192    const t = as("table");193    const bad = checkBlock({ ...t, rows: [["a"]] }, false, "en");194    expect(!bad.ok && bad.issues[0].message).toBe("Every row needs one cell per column.");195    const d = as("diagram");196    const xy = checkBlock({ ...d, nodes: [{ ...d.nodes[0], x: 10 }, ...d.nodes.slice(1)] }, false, "fr");197    expect(!xy.ok && xy.issues[0].message).toBe("Donnez les deux coordonnées x et y, ou aucune.");198  });199  it("refuses tabs inside a tab", () => {200    expect(checkBlock(as("tabs"), true, "fr").ok).toBe(false);201    expect(checkBlock(as("tabs"), false, "fr").ok).toBe(true);202  });203  it("brings simulation sliders back to the ones the kind defines, and refuses a bad expression", () => {204    const s = newBlock("simulation", "fr", { simKind: "regression" }) as BlockOf<"simulation">;205    const r = checkBlock({ ...s, params: { ...s.params, slope: 99, inconnu: 3 } }, false, "fr");206    expect(r.ok && r.block.type === "simulation" && r.block.params).toEqual({ ...s.params, slope: 3 });207    const f = newBlock("simulation", "fr", { simKind: "function-plot" }) as BlockOf<"simulation">;208    const bad = checkBlock({ ...f, config: { expr: "a * sin(" } }, false, "fr");209    expect(bad.ok).toBe(false);210    expect(!bad.ok && bad.issues[0].path).toBe("config.expr");211  });212});213214describe("paste parsing", () => {215  it("detects the delimiter: tab, then semicolon, then comma", () => {216    expect(detectDelimiter("a\tb,c;d")).toBe("\t");217    expect(detectDelimiter("1,5;2,5")).toBe(";");218    expect(detectDelimiter("a,b")).toBe(",");219  });220  it("parses spreadsheet (tab) text with Windows line ends and trailing blank lines", () => {221    expect(parseDelimited("a\tb\tc\r\n1\t2\t3\r\n\r\n")).toEqual([["a", "b", "c"], ["1", "2", "3"]]);222    expect(parseDelimited(" x \t y ")).toEqual([["x", "y"]]);223    expect(parseDelimited("a\t\tc\n\t\t\nd")).toEqual([["a", "", "c"], ["", "", ""], ["d"]]);224  });225  it("parses CSV with quoted cells, doubled quotes and embedded line breaks", () => {226    expect(parseDelimited('nom,valeur\n"Boucher, S.-P.",3\n"dit ""oui""",4')).toEqual([["nom", "valeur"], ["Boucher, S.-P.", "3"], ['dit "oui"', "4"]]);227    expect(parseDelimited('"deux\nlignes",x')).toEqual([["deux\nlignes", "x"]]);228    expect(parseDelimited("a;b\n1,5;2,5")).toEqual([["a", "b"], ["1,5", "2,5"]]);229  });230  it("returns nothing for empty text", () => {231    expect(parseDelimited("")).toEqual([]);232    expect(parseDelimited("\n\n")).toEqual([]);233  });234  it("tells a block of cells from a word or a sentence", () => {235    expect(looksLikeGrid("a\tb")).toBe(true);236    expect(looksLikeGrid("a\nb")).toBe(true);237    expect(looksLikeGrid("une phrase, avec une virgule")).toBe(false);238    expect(looksLikeGrid("mot\n")).toBe(false);239  });240  it("reads numbers as people type them", () => {241    expect(parseNumber("1,5")).toBe(1.5);242    expect(parseNumber(" 1 234,5 ")).toBe(1234.5);243    expect(parseNumber("1,234,567.8")).toBe(1234567.8);244    expect(parseNumber("−3.2e-1")).toBe(-0.32);245    expect(parseNumber("12 %")).toBe(12);246    expect(parseNumber(".5")).toBe(0.5);247    for (const bad of ["", "  ", "abc", "1.2.3", "0x10", "Infinity", "NaN", "1e999", "--1"]) expect(parseNumber(bad)).toBeNull();248  });249});250251describe("rectangular grids", () => {252  const isRect = (g: readonly (readonly unknown[])[], cols: number) => g.every((r) => r.length === cols);253  it("pads and cuts rows", () => {254    expect(rectangular([["a"], ["b", "c", "d"]], 2, "")).toEqual([["a", ""], ["b", "c"]]);255    expect(rectangular([], 2, 0, 2)).toEqual([[0, 0], [0, 0]]);256  });257  it("pastes into a grid, growing it within the limits and counting what did not fit", () => {258    const grid = [["a", "b"], ["c", "d"]];259    const r = pasteCells(grid, { row: 1, col: 1 }, [["1", "2", "3"], ["4"], ["5", "6"]], { maxRows: 3, maxCols: 3, growCols: true });260    expect(r.grid).toEqual([["a", "b", ""], ["c", "1", "2"], ["", "4", ""]]);261    expect(r).toMatchObject({ droppedRows: 1, droppedCols: 1 });262    expect(grid).toEqual([["a", "b"], ["c", "d"]]);263    const fixed = pasteCells(grid, { row: 0, col: 0 }, [["x", "y", "z"]], { maxRows: 10, maxCols: 8 });264    expect(fixed.grid).toEqual([["x", "y"], ["c", "d"]]);265    expect(fixed.droppedCols).toBe(1);266    expect(pasteCells(grid, { row: 0, col: 0 }, [["abcdef"]], { maxRows: 2, maxCols: 2, maxCell: 3 }).grid[0][0]).toBe("abc");267  });268  it("keeps a table rectangular through every structural edit", () => {269    let t = as("table");270    t = { ...t, rows: [["1", "2"], ["3", "4"]] };271    t = tableAddColumn(t, "C3");272    expect(t.rows).toEqual([["1", "2", ""], ["3", "4", ""]]);273    t = tableMoveColumn(t, 0, 1);274    expect(t.rows).toEqual([["2", "1", ""], ["4", "3", ""]]);275    expect(t.columns.map((c) => c.label)).toEqual(["Colonne 2", "Colonne 1", "C3"]);276    t = tableRemoveColumn(t, 0);277    expect(t.rows).toEqual([["1", ""], ["3", ""]]);278    t = tableAddRow(t);279    t = tableRemoveRow(t, 0);280    expect(t.rows).toEqual([["3", ""], ["", ""]]);281    expect(isRect(t.rows, t.columns.length)).toBe(true);282    expect(BlockSchema.safeParse(t).success).toBe(true);283    // Limits: one column and one row always remain, never more than 8 × 40.284    let one = tableRemoveColumn(tableRemoveColumn(t, 0), 0);285    expect(one.columns.length).toBe(1);286    one = tableRemoveRow(tableRemoveRow(one, 0), 0);287    expect(one.rows.length).toBe(1);288    let wide = t;289    for (let i = 0; i < 12; i++) wide = tableAddColumn(wide, "x");290    for (let i = 0; i < 50; i++) wide = tableAddRow(wide);291    expect([wide.columns.length, wide.rows.length]).toEqual([8, 40]);292    expect(BlockSchema.safeParse(wide).success).toBe(true);293  });294  it("pastes a spreadsheet block into a table, adding columns and rows as needed", () => {295    const t = as("table");296    const data = parseDelimited("a\tb\tc\n1\t2\t3\n4\t5\t6");297    const r = tablePaste(t, { row: 1, col: 0 }, data, (n) => `Col ${n}`);298    expect(r.block.columns.map((c) => c.label)).toEqual(["Colonne 1", "Colonne 2", "Col 3"]);299    expect(r.block.rows).toEqual([["", "", ""], ["a", "b", "c"], ["1", "2", "3"], ["4", "5", "6"]]);300    expect(BlockSchema.safeParse(r.block).success).toBe(true);301    const big = tablePaste(t, { row: 0, col: 0 }, Array.from({ length: 45 }, (_, i) => Array.from({ length: 10 }, (_, j) => `${i}:${j}`)), (n) => `Col ${n}`);302    expect([big.block.rows.length, big.block.columns.length, big.droppedRows, big.droppedCols]).toEqual([40, 8, 5, 2]);303    expect(isRect(big.block.rows, 8)).toBe(true);304    expect(BlockSchema.safeParse(big.block).success).toBe(true);305    // A ragged table coming from elsewhere is repaired by the paste.306    expect(isRect(tablePaste({ ...t, rows: [["x"], ["y", "z", "w"]] }, { row: 0, col: 0 }, [["q"]], String).block.rows, 2)).toBe(true);307  });308  it("keeps comparison cells aligned with its columns", () => {309    let c = as("comparison");310    c = { ...c, rows: [{ label: "prix", cells: ["1", "2"] }] };311    c = comparisonAddColumn(c, "C");312    expect(c.rows[0].cells).toEqual(["1", "2", ""]);313    c = comparisonMoveColumn(c, 2, -1);314    expect(c.rows[0].cells).toEqual(["1", "", "2"]);315    expect(c.columns.map((x) => x.title)).toEqual(["Option A", "C", "Option B"]);316    c = comparisonRemoveColumn(c, 0);317    expect(c.rows[0].cells).toEqual(["", "2"]);318    expect(comparisonRemoveColumn(c, 0)).toBe(c);319    expect(comparisonAddColumn(comparisonAddColumn(comparisonAddColumn(c, "x"), "y"), "z").columns.length).toBe(4);320    expect(BlockSchema.safeParse(c).success).toBe(true);321  });322  it("keeps a matrix rowLabels × colLabels through every structural edit", () => {323    let m = as("matrix");324    m = matrixAddRow(m, "D");325    m = matrixAddColumn(m, "E");326    expect(m.values.length).toBe(4);327    expect(isRect(m.values, 4)).toBe(true);328    expect(m.values[3]).toEqual([0, 0, 0, 0]);329    m = matrixMoveColumn(m, 0, 1);330    expect(m.colLabels).toEqual(["B", "A", "C", "E"]);331    expect(m.values[0]).toEqual([0.5, 1, 0.2, 0]);332    m = matrixRemoveRow(m, 0);333    m = matrixRemoveColumn(m, 3);334    expect([m.rowLabels.length, m.colLabels.length, m.values.length]).toEqual([3, 3, 3]);335    expect(BlockSchema.safeParse(m).success).toBe(true);336    let big = m;337    for (let i = 0; i < 20; i++) big = matrixAddColumn(matrixAddRow(big, `r${i}`), `c${i}`);338    expect([big.rowLabels.length, big.colLabels.length]).toEqual([16, 16]);339    expect(BlockSchema.safeParse(big).success).toBe(true);340    let one = m;341    for (let i = 0; i < 5; i++) one = matrixRemoveColumn(matrixRemoveRow(one, 0), 0);342    expect([one.rowLabels.length, one.colLabels.length, one.values.length, one.values[0].length]).toEqual([1, 1, 1, 1]);343    expect(BlockSchema.safeParse(one).success).toBe(true);344  });345  it("pastes numbers into a matrix, growing it and leaving unreadable cells alone", () => {346    const m = as("matrix");347    const r = matrixPaste(m, { row: 2, col: 2 }, parseDelimited("9\t8,5\nabc\t7"), (n) => `L${n}`, (n) => `C${n}`);348    expect(r.block.rowLabels).toEqual(["A", "B", "C", "L4"]);349    expect(r.block.colLabels).toEqual(["A", "B", "C", "C4"]);350    expect(r.block.values).toEqual([[1, 0.5, 0.2, 0], [0.5, 1, 0.4, 0], [0.2, 0.4, 9, 8.5], [0, 0, 0, 7]]);351    expect(r.invalid).toBe(1);352    expect(BlockSchema.safeParse(r.block).success).toBe(true);353    const over = matrixPaste(m, { row: 0, col: 0 }, Array.from({ length: 20 }, () => Array.from({ length: 18 }, () => "1")), String, String);354    expect([over.block.values.length, over.block.values[0].length, over.droppedRows, over.droppedCols]).toEqual([16, 16, 4, 2]);355    expect(BlockSchema.safeParse(over.block).success).toBe(true);356  });357});358359describe("list moves", () => {360  it("moves within bounds and ignores the rest", () => {361    expect(moveItem(["a", "b", "c"], 0, 1)).toEqual(["b", "a", "c"]);362    expect(moveItem(["a", "b", "c"], 2, -1)).toEqual(["a", "c", "b"]);363    expect(moveItem(["a", "b", "c"], 0, -1)).toEqual(["a", "b", "c"]);364    expect(moveItem(["a", "b", "c"], 2, 1)).toEqual(["a", "b", "c"]);365  });366});367368describe("diagram cleanup", () => {369  const diagram = (): BlockOf<"diagram"> => BlockSchema.parse({370    id: "d1", type: "diagram",371    nodes: [{ id: "a", label: "A", group: "g1" }, { id: "b", label: "B", group: "g1" }, { id: "c", label: "C" }],372    edges: [{ id: "ab", from: "a", to: "b" }, { id: "bc", from: "b", to: "c" }, { id: "ca", from: "c", to: "a" }, { id: "cc", from: "c", to: "c" }],373    groups: [{ id: "g1", label: "Groupe" }],374    animation: { steps: [{ title: "Un", nodes: ["a", "b"], edges: ["ab"] }, { title: "Deux", nodes: ["b", "c"], edges: ["bc", "ca"] }] },375  }) as BlockOf<"diagram">;376377  it("deleting a node removes its edges and cleans the animation steps", () => {378    const d = diagram();379    const next = removeDiagramNode(d, "b");380    expect(next.nodes.map((n) => n.id)).toEqual(["a", "c"]);381    expect(next.edges.map((e) => e.id)).toEqual(["ca", "cc"]);382    expect(next.animation?.steps).toEqual([{ title: "Un", nodes: ["a"], edges: [] }, { title: "Deux", nodes: ["c"], edges: ["ca"] }]);383    expect(BlockSchema.safeParse(next).success).toBe(true);384    expect(d.nodes.length).toBe(3);385    // Removing the node naively would not be valid: that is what the helper is for.386    expect(BlockSchema.safeParse({ ...d, nodes: d.nodes.filter((n) => n.id !== "b") }).success).toBe(false);387  });388  it("stays valid down to the last node, which cannot be removed", () => {389    let d = diagram();390    for (const id of ["a", "b"]) { d = removeDiagramNode(d, id); expect(BlockSchema.safeParse(d).success).toBe(true); }391    expect(d.nodes.map((n) => n.id)).toEqual(["c"]);392    expect(d.edges.map((e) => e.id)).toEqual(["cc"]);393    expect(removeDiagramNode(d, "c")).toBe(d);394    expect(removeDiagramNode(d, "nope")).toBe(d);395  });396  it("deleting an edge cleans the steps; deleting a group frees its nodes", () => {397    const d = diagram();398    const e = removeDiagramEdge(d, "ab");399    expect(e.animation?.steps[0].edges).toEqual([]);400    expect(BlockSchema.safeParse(e).success).toBe(true);401    const g = removeDiagramGroup(d, "g1");402    expect(g.groups).toEqual([]);403    expect(g.nodes.every((n) => !("group" in n))).toBe(true);404    expect(BlockSchema.safeParse(g).success).toBe(true);405  });406  it("does not invent an animation on a diagram without one", () => {407    const d = as("diagram");408    const next = removeDiagramNode(d, d.nodes[1].id);409    expect("animation" in next && next.animation !== undefined).toBe(false);410    expect(next.edges).toEqual([]);411    expect(BlockSchema.safeParse(next).success).toBe(true);412  });413});414415describe("chart points and datasets", () => {416  it("round-trips points through the text grid", () => {417    const points = [{ x: 0, y: 1.5 }, { x: 1, y: 2, lo: 1.5, hi: 2.5 }];418    expect(pointsToGrid(points)).toEqual([["0", "1.5", "", ""], ["1", "2", "1.5", "2.5"]]);419    expect(gridToPoints(pointsToGrid(points), "number")).toEqual({ points, skipped: 0, dropped: 0 });420    expect(rowToPoint(["janv.", "3,5"], "category")).toEqual({ x: "janv.", y: 3.5 });421    expect(rowToPoint(["janv.", "3"], "number")).toBeNull();422    expect(rowToPoint(["1", ""], "number")).toBeNull();423  });424  it("reads a pasted block: header skipped, blanks ignored, 600 points at most", () => {425    const r = gridToPoints(parseDelimited("x\ty\n1\t2\n\t\n2\t3,5\t3\t4"), "number");426    expect(r).toEqual({ points: [{ x: 1, y: 2 }, { x: 2, y: 3.5, lo: 3, hi: 4 }], skipped: 1, dropped: 0 });427    const many = gridToPoints(Array.from({ length: 650 }, (_, i) => [String(i), "1"]), "number");428    expect([many.points.length, many.dropped]).toEqual([600, 50]);429  });430  it("converts x when the axis changes type", () => {431    expect(convertPointsX([{ x: 1.5, y: 1 }], "category")).toEqual([{ x: "1.5", y: 1 }]);432    expect(convertPointsX([{ x: "2,5", y: 1 }, { x: "mars", y: 2 }], "number")).toEqual([{ x: 2.5, y: 1 }, { x: 2, y: 2 }]);433  });434  it("builds series from a dataset and says how many rows were dropped", () => {435    const ds = { columns: [{ name: "t", type: "number" as const }, { name: "prix", type: "number" as const }, { name: "ville", type: "string" as const }, { name: "vol", type: "number" as const }], rows: Array.from({ length: 1000 }, (_, i) => [i, i * 2, `v${i}`, i % 7] as (string | number)[]) };436    const r = datasetToSeries(ds, 0, [1, 3]);437    expect(r.series.map((s) => [s.name, s.points.length])).toEqual([["prix", 600], ["vol", 600]]);438    expect(r).toMatchObject({ xType: "number", total: 1000, dropped: 400, unreadable: 0 });439    expect(r.series[0].points[0]).toEqual({ x: 0, y: 0 });440    expect(r.series[0].points[599]).toEqual({ x: 999, y: 1998 });441    expect(new Set(r.series.map((s) => s.tone)).size).toBe(2);442    const chart = { ...as("chart"), series: r.series, datasetRef: "data-1" };443    expect(BlockSchema.safeParse(chart).success).toBe(true);444    expect(SheetSchema.safeParse({ ...doc, blocks: [chart] }).success).toBe(true);445  });446  it("uses labels for a text x column, skips unreadable rows, and keeps small datasets whole", () => {447    const ds = { columns: [{ name: "ville", type: "string" as const }, { name: "prix", type: "number" as const }], rows: [["Québec", 1], ["Gatineau", "2,5"], ["Laval", "n/d"], ["Montréal", 4]] as (string | number)[][] };448    const r = datasetToSeries(ds, 0, [1]);449    expect(r).toMatchObject({ xType: "category", total: 4, dropped: 0, unreadable: 1 });450    expect(r.series[0].points).toEqual([{ x: "Québec", y: 1 }, { x: "Gatineau", y: 2.5 }, { x: "Montréal", y: 4 }]);451    expect(datasetToSeries(ds, 0, []).series).toEqual([]);452    expect(datasetToSeries({ columns: ds.columns, rows: [] }, 0, [1]).series).toEqual([]);453  });454});455456describe("simulation helpers", () => {457  it("resets parameters and configuration when the kind changes", () => {458    const s = newBlock("simulation", "fr", { simKind: "distribution" }) as BlockOf<"simulation">;459    const edited = { ...s, config: { family: "student" }, params: { df: 9, a: -1, b: 1 } };460    for (const kind of SIM_KINDS) {461      const next = simWithKind(edited, kind);462      expect(next.kind).toBe(kind);463      expect(next.params).toEqual(simParams(kind, next.config));464      expect(validateSimulation(next)).toEqual([]);465      expect(BlockSchema.safeParse(next).success).toBe(true);466    }467    expect(simWithKind(edited, "garch").config).toEqual({});468  });469  it("re-derives the sliders when the configuration changes, keeping the values that still apply", () => {470    const s = newBlock("simulation", "fr", { simKind: "distribution" }) as BlockOf<"simulation">;471    const next = simWithConfig({ ...s, params: { ...s.params, a: -2 } }, { family: "student" });472    expect(Object.keys(next.params).sort()).toEqual(["a", "b", "df"]);473    expect(next.params.a).toBe(-2);474    expect(validateSimulation(next)).toEqual([]);475  });476  it("clamps and snaps slider values", () => {477    expect(simParams("garch", {}, { alpha: 7, beta: 0.123456, nope: 1 })).toMatchObject({ alpha: 0.5, beta: 0.12 });478    expect(Object.keys(simParams("garch", {}, { nope: 1 }))).not.toContain("nope");479  });480  it("function-plot: sliders follow the expressions and stale bounds are dropped, but not while there is a typo", () => {481    const f = newBlock("simulation", "fr", { simKind: "function-plot" }) as BlockOf<"simulation">;482    const withBounds = simWithConfig(f, { expr: "a * sin(b * x)", aMin: 0, aMax: 2, bMax: 10 });483    expect(Object.keys(withBounds.params).sort()).toEqual(["a", "b"]);484    expect(validateSimulation(withBounds)).toEqual([]);485    expect(sliderBoundFields("function-plot", withBounds.config).map((x) => x.key)).toEqual(["aMin", "aMax", "aStep", "bMin", "bMax", "bStep"]);486    const noB = simWithConfig(withBounds, { ...withBounds.config, expr: "a * sin(x)" });487    expect(noB.config).toEqual({ expr: "a * sin(x)", aMin: 0, aMax: 2 });488    expect(validateSimulation(noB)).toEqual([]);489    const typo = { ...withBounds.config, expr: "a * sin(b * x" };490    expect(pruneSimConfig("function-plot", typo)).toEqual(typo);491    const issues = simulationIssues({ ...withBounds, config: typo });492    expect(issues[0].path).toBe("config.expr");493    expect(issues[0].message).not.toMatch(/^config\./);494  });495  it("describes exactly the config keys the registry accepts", () => {496    for (const kind of SIM_KINDS) {497      const keys = SIM_CONFIG[kind].map((f) => f.key);498      expect(keys.sort(), kind).toEqual([...(SIMULATIONS[kind].configKeys ?? [])].sort());499      for (const k of keys) expect(COMMON_CONFIG_KEYS).not.toContain(k);500      for (const f of SIM_CONFIG[kind]) if (f.kind === "select") {501        const s = newBlock("simulation", "en", { simKind: kind }) as BlockOf<"simulation">;502        for (const o of f.options) expect(validateSimulation(simWithConfig(s, { ...s.config, [f.key]: o.value })), `${kind}.${f.key}=${o.value}`).toEqual([]);503      }504    }505  });506});507508describe("plainIssues", () => {509  it("gives one sentence per path, in the interface language, without schema jargon", () => {510    const r = BlockSchema.safeParse({ ...as("list"), items: [] });511    expect(!r.success && plainIssues(r.error, "fr")).toEqual([{ path: "items", message: "Il en faut au moins 1." }]);512    const long = BlockSchema.safeParse({ ...as("heading"), text: "x".repeat(201) });513    expect(!long.success && plainIssues(long.error, "en")).toEqual([{ path: "text", message: "Too long: at most 200 characters." }]);514    const many = BlockSchema.safeParse({ ...as("svg"), maxWidth: 5000 });515    expect(!many.success && plainIssues(many.error, "fr")[0]).toEqual({ path: "maxWidth", message: "La valeur maximale est 1120." });516  });517});518
Files main
Menu

Theme