SPB Git

Repository Public

editor.diagram.ops.test.ts 25.8 KB 422 lines typescript

1import { describe, expect, it } from "vitest";2import { BlockSchema, type BlockOf } from "@/schema";3import { layoutDiagram } from "@/renderer/diagram/layout";4import {5  EMPTY_SELECTION, GRID, LIMITS, actualSize, addLegendEntry, addNode, addStep, addedIds, align, assignGroup, boxesOf, cleanAnimation, connect, connectIssue,6  createGroup, deleteGroup, deleteSelection, distribute, duplicateSelection, fitView, freshId, hitTest, mergeSelection, moveNodes, moveStep, nudge, optText,7  positionOf, pruneSelection, removeLegendEntry, removeStep, reorder, resetLayout, reverseEdge, selectAll, selectInRect, setLocked, setNodePosition, snap,8  stepsOf, toWorld, toggleSelect, toggleStepItem, updateDiagram, updateEdge, updateGroup, updateLegendEntry, updateNode, updateStep, validate, zoomAt,9  type Diagram,10} from "@/components/editor/diagram/ops";11import { DIAGRAM } from "./renderer.fixture";1213const diagram = (input: unknown): Diagram => BlockSchema.parse(input) as BlockOf<"diagram">;14const base = (): Diagram => diagram(DIAGRAM);15const boxes = (b: Diagram) => boxesOf(layoutDiagram(b));16/** Every operation must return a block the schema accepts unchanged. */17const valid = (b: Diagram): Diagram => { const r = BlockSchema.safeParse(b); expect(r.success, r.success ? "" : JSON.stringify(r.error.issues)).toBe(true); expect(r.data).toEqual(b); return b; };18const node = (b: Diagram, id: string) => b.nodes.find((n) => n.id === id)!;19const three = (): Diagram => diagram({20  id: "t", type: "diagram",21  nodes: [{ id: "a", label: "A", x: 0, y: 0 }, { id: "b", label: "Un libellé nettement plus long", x: 100, y: 40 }, { id: "c", label: "C", x: 400, y: 200 }, { id: "d", label: "D", x: 250, y: 90, locked: true }],22  edges: [{ id: "ab", from: "a", to: "b" }, { id: "bc", from: "b", to: "c" }],23});2425describe("diagram editor ops — selection", () => {26  it("click selects one item, additive click toggles", () => {27    let s = toggleSelect(EMPTY_SELECTION, "nodes", "in", false);28    expect(s).toEqual({ nodes: ["in"], edges: [] });29    s = toggleSelect(s, "edges", "a", true);30    s = toggleSelect(s, "nodes", "out", true);31    expect(s).toEqual({ nodes: ["in", "out"], edges: ["a"] });32    expect(toggleSelect(s, "nodes", "in", true)).toEqual({ nodes: ["out"], edges: ["a"] });33    expect(toggleSelect(s, "edges", "b", false)).toEqual({ nodes: [], edges: ["b"] });34  });35  it("select all, merge, prune", () => {36    const b = base();37    const all = selectAll(b);38    expect(all.nodes).toHaveLength(b.nodes.length); expect(all.edges).toHaveLength(b.edges.length);39    expect(mergeSelection({ nodes: ["in"], edges: [] }, { nodes: ["in", "out"], edges: ["a"] })).toEqual({ nodes: ["in", "out"], edges: ["a"] });40    expect(pruneSelection(b, { nodes: ["in", "ghost"], edges: ["zz"] })).toEqual({ nodes: ["in"], edges: [] });41    const same = { nodes: ["in"], edges: ["a"] };42    expect(pruneSelection(b, same)).toBe(same);43  });44  it("marquee takes the nodes it touches and the edges it contains", () => {45    const b = three(), l = layoutDiagram(b);46    const s = selectInRect(l, { x: 160, y: 80, width: -200, height: -120 });47    expect(s.nodes.sort()).toEqual(["a", "b"]);48    expect(s.edges).toEqual(["ab"]);49    expect(selectInRect(l, { x: -5000, y: -5000, width: 10, height: 10 })).toEqual(EMPTY_SELECTION);50  });51  it("hit-testing: nodes first, topmost wins, edges within tolerance, touch widening", () => {52    const b = three(), l = layoutDiagram(b);53    expect(hitTest(l, { x: 0, y: 0 })).toEqual({ kind: "nodes", id: "a" });54    const edge = l.edges.find((e) => e.id === "bc")!, mid = edge.points[Math.floor(edge.points.length / 2)];55    expect(hitTest({ nodes: [], edges: l.edges }, { x: mid.x, y: mid.y + 3 })).toEqual({ kind: "edges", id: "bc" });56    expect(hitTest(l, { x: 2000, y: 2000 })).toBeNull();57    const a = l.nodes.find((n) => n.id === "a")!;58    const outside = { x: a.x, y: a.top - 10 };59    expect(hitTest({ nodes: l.nodes, edges: [] }, outside)).toBeNull();60    expect(hitTest({ nodes: l.nodes, edges: [] }, outside, { minSize: a.height + 30 })).toEqual({ kind: "nodes", id: "a" });61    const stacked = layoutDiagram(diagram({ id: "s", type: "diagram", nodes: [{ id: "under", label: "X", x: 0, y: 0 }, { id: "over", label: "X", x: 0, y: 0 }] }));62    expect(hitTest(stacked, { x: 0, y: 0 })?.id).toBe("over");63  });64});6566describe("diagram editor ops — move, snap, automatic placement", () => {67  it("snap rounds to the grid", () => {68    expect(snap(11)).toBe(8); expect(snap(12)).toBe(16); expect(snap(-3)).toBe(-0); expect(snap(13, 5)).toBe(15); expect(snap(13.3, 0)).toBe(13.3);69    expect(GRID).toBe(8);70  });71  it("an auto-placed node becomes manual at its computed position: nothing jumps", () => {72    const b = base(), bx = boxes(b);73    const at = bx.get("router")!;74    const moved = valid(moveNodes(b, ["router"], 10, -4, bx));75    expect(node(moved, "router")).toMatchObject({ x: Math.round((at.x + 10) * 10) / 10, y: Math.round((at.y - 4) * 10) / 10 });76    // The others are untouched and still automatic, at the very same place.77    for (const n of moved.nodes) if (n.id !== "router") { expect(n).toBe(node(b, n.id)); expect(n.x).toBeUndefined(); }78    const after = boxes(moved);79    for (const n of b.nodes) if (n.id !== "router") expect(after.get(n.id)).toEqual(bx.get(n.id));80  });81  it("selected nodes move together and keep their offsets; snapping lands the first one on the grid", () => {82    const b = three(), bx = boxes(b);83    const moved = valid(moveNodes(b, ["a", "b"], 13, 21, bx, GRID));84    expect(node(moved, "a")).toMatchObject({ x: 16, y: 24 });85    expect(node(moved, "b")).toMatchObject({ x: 116, y: 64 });86    expect(node(moved, "c")).toBe(node(b, "c"));87    expect(moveNodes(b, ["a"], 2, 2, bx, GRID)).toBe(b);88    expect(moveNodes(b, ["a"], 0, 0, bx)).toBe(b);89  });90  it("locked nodes are not moved, nudged or re-placed", () => {91    const b = three(), bx = boxes(b);92    expect(moveNodes(b, ["d"], 50, 50, bx)).toBe(b);93    const moved = valid(nudge(b, ["a", "d"], 8, 0, bx));94    expect(node(moved, "a").x).toBe(8); expect(node(moved, "d")).toBe(node(b, "d"));95    expect(valid(nudge(b, ["a"], 0, -1, bx)).nodes[0]).toMatchObject({ x: 0, y: -1 });96    const reset = valid(resetLayout(b));97    expect(node(reset, "d")).toMatchObject({ x: 250, y: 90 });98    expect(reset.nodes.filter((n) => n.x !== undefined).map((n) => n.id)).toEqual(["d"]);99    expect(setNodePosition(b, "d", { x: 1 }, bx)).toBe(b);100  });101  it("coordinates stay inside the schema range", () => {102    const b = three(), bx = boxes(b);103    const far = valid(moveNodes(b, ["c"], 1e9, -1e9, bx));104    expect(node(far, "c")).toMatchObject({ x: LIMITS.coord, y: -LIMITS.coord });105  });106  it("reset clears x/y on the selection only, or everywhere", () => {107    const b = three();108    const one = valid(resetLayout(b, ["a"]));109    expect(node(one, "a").x).toBeUndefined(); expect("x" in node(one, "a")).toBe(false); expect(node(one, "b").x).toBe(100);110    expect(resetLayout(base())).toEqual(base());111    const auto = base();112    expect(resetLayout(auto)).toBe(auto);113  });114  it("a single coordinate from the panel completes with the current position", () => {115    const b = base(), bx = boxes(b);116    const next = valid(setNodePosition(b, "in", { x: 42 }, bx));117    expect(node(next, "in")).toMatchObject({ x: 42, y: bx.get("in")!.y });118    expect(setNodePosition(b, "in", { x: Number.NaN }, bx)).toBe(b);119    expect(positionOf(node(next, "in"), bx)).toEqual({ x: 42, y: bx.get("in")!.y });120  });121});122123describe("diagram editor ops — align and distribute", () => {124  const edges = (b: Diagram, id: string) => { const bx = boxes(b).get(id)!; return { left: bx.x - bx.width / 2, right: bx.x + bx.width / 2, top: bx.y - bx.height / 2, bottom: bx.y + bx.height / 2, ...bx }; };125  it("aligns on the six references of the common bounding box", () => {126    const b = three(), bx = boxes(b), ids = ["a", "b", "c"];127    const L = Math.min(...ids.map((i) => edges(b, i).left)), R = Math.max(...ids.map((i) => edges(b, i).right));128    const Tp = Math.min(...ids.map((i) => edges(b, i).top)), B = Math.max(...ids.map((i) => edges(b, i).bottom));129    const left = valid(align(b, ids, "left", bx));130    for (const i of ids) { expect(edges(left, i).left).toBeCloseTo(L, 1); expect(edges(left, i).y).toBe(edges(b, i).y); }131    const right = valid(align(b, ids, "right", bx));132    for (const i of ids) expect(edges(right, i).right).toBeCloseTo(R, 1);133    const centre = valid(align(b, ids, "center", bx));134    for (const i of ids) expect(edges(centre, i).x).toBeCloseTo((L + R) / 2, 1);135    const top = valid(align(b, ids, "top", bx));136    for (const i of ids) { expect(edges(top, i).top).toBeCloseTo(Tp, 1); expect(edges(top, i).x).toBe(edges(b, i).x); }137    const bottom = valid(align(b, ids, "bottom", bx));138    for (const i of ids) expect(edges(bottom, i).bottom).toBeCloseTo(B, 1);139    const middle = valid(align(b, ids, "middle", bx));140    for (const i of ids) expect(edges(middle, i).y).toBeCloseTo((Tp + B) / 2, 1);141  });142  it("needs two nodes; a locked node is a reference but does not move", () => {143    const b = three(), bx = boxes(b);144    expect(align(b, ["a"], "left", bx)).toBe(b);145    const next = valid(align(b, ["a", "d"], "top", bx));146    expect(node(next, "d")).toBe(node(b, "d"));147    expect(edges(next, "a").top).toBeCloseTo(Math.min(edges(b, "a").top, edges(b, "d").top), 1);148  });149  it("auto-placed nodes are aligned from where they are drawn", () => {150    const b = base(), bx = boxes(b);151    const next = valid(align(b, ["in", "out", "db"], "middle", bx));152    const ys = ["in", "out", "db"].map((i) => node(next, i).y);153    expect(new Set(ys).size).toBe(1);154    expect(node(next, "e1").x).toBeUndefined();155  });156  it("distributes with equal gaps, the outermost nodes fixed", () => {157    const b = three(), bx = boxes(b), ids = ["a", "b", "c"];158    const h = valid(distribute(b, ids, "horizontal", bx));159    expect(node(h, "a")).toBe(node(b, "a")); expect(node(h, "c")).toBe(node(b, "c"));160    const gap1 = edges(h, "b").left - edges(h, "a").right, gap2 = edges(h, "c").left - edges(h, "b").right;161    expect(gap1).toBeCloseTo(gap2, 0);162    expect(node(h, "b").y).toBe(40);163    const v = valid(distribute(b, ids, "vertical", bx));164    expect(edges(v, "b").top - edges(v, "a").bottom).toBeCloseTo(edges(v, "c").top - edges(v, "b").bottom, 0);165    expect(node(v, "b").x).toBe(100);166    expect(distribute(b, ["a", "b"], "horizontal", bx)).toBe(b);167  });168});169170describe("diagram editor ops — create, duplicate, delete, connect", () => {171  it("adds a node with a fresh id at the requested place, never on top of another", () => {172    const b = three();173    const one = valid(addNode(b, { x: 0, y: 0 }, "Nouveau"));174    const added = addedIds(b, one);175    expect(added.nodes).toHaveLength(1);176    const n = node(one, added.nodes[0]);177    expect(n.id).toMatch(/^n-[0-9a-f]{8}$/);178    expect(n).toMatchObject({ label: "Nouveau", x: 24, y: 24, shape: "round", tone: "neutral" });179    expect(valid(addNode(b, { x: 7, y: 7 }, "  ")).nodes.at(-1)).toMatchObject({ label: "…", x: 7, y: 7 });180    expect(addNode(b, { x: 1, y: 1 }, "X", "a")).toBe(b);181  });182  it("refuses a 61st node and a 121st edge", () => {183    const full = diagram({ id: "f", type: "diagram", nodes: Array.from({ length: 60 }, (_, i) => ({ id: `n${i}`, label: `N${i}` })), edges: Array.from({ length: 120 }, (_, i) => ({ id: `e${i}`, from: `n${i % 60}`, to: `n${(i + 1 + Math.floor(i / 60)) % 60}` })) });184    expect(addNode(full, { x: 0, y: 0 }, "X")).toBe(full);185    expect(connectIssue(full, "n0", "n30")).toBe("limit");186    expect(connect(full, "n0", "n30")).toBe(full);187    expect(duplicateSelection(full, { nodes: ["n0"], edges: [] }, boxes(full))).toBe(full);188  });189  it("duplicates nodes with fresh unique ids, an offset, and the edges between copies", () => {190    const b = base(), bx = boxes(b);191    const next = valid(duplicateSelection(b, { nodes: ["router", "e1", "e2", "note"], edges: ["a"] }, bx, { offset: 30 }));192    const added = addedIds(b, next);193    expect(added.nodes).toHaveLength(4);194    // router→e1, router→e2 and the self-loop on the note; not in→router (one end outside the copy).195    expect(added.edges).toHaveLength(3);196    const ids = [...next.nodes.map((n) => n.id), ...next.edges.map((e) => e.id)];197    expect(new Set(ids).size).toBe(ids.length);198    const copy = next.nodes.find((n) => added.nodes.includes(n.id) && n.label === "Routeur")!;199    expect(copy).toMatchObject({ sublabel: "choisit k experts", shape: "diamond", tone: "amber", group: "core", x: Math.round((bx.get("router")!.x + 30) * 10) / 10, y: Math.round((bx.get("router")!.y + 30) * 10) / 10 });200    for (const e of next.edges.filter((x) => added.edges.includes(x.id))) { expect(added.nodes).toContain(e.from); expect(added.nodes).toContain(e.to); }201    const dashed = next.edges.find((e) => added.edges.includes(e.id) && e.style === "dashed");202    expect(dashed).toBeDefined();203    // Originals are untouched.204    expect(next.nodes.slice(0, b.nodes.length)).toEqual(b.nodes); expect(next.edges.slice(0, b.edges.length)).toEqual(b.edges);205    expect(duplicateSelection(b, { nodes: [], edges: ["a"] }, bx)).toBe(b);206  });207  it("copies of locked nodes are unlocked; colliding generated ids are retried", () => {208    const b = three(), bx = boxes(b);209    const seq = ["n-a", "n-a", "n-b"]; let i = 0;210    const next = valid(duplicateSelection(diagram({ ...b, nodes: [...b.nodes, { id: "n-a", label: "pris" }] }), { nodes: ["d"], edges: [] }, bx, { makeId: () => seq[i++] ?? `n-x${i}` }));211    expect(next.nodes.at(-1)).toMatchObject({ id: "n-b", label: "D", x: 274, y: 114 });212    expect(next.nodes.at(-1)?.locked).toBeUndefined();213    expect(freshId(b, "n", [], () => "a")).toMatch(/^n-\d+$/);214  });215  it("deleting a node removes its edges and cleans the steps", () => {216    const b = base();217    const next = valid(deleteSelection(b, { nodes: ["router"], edges: [] }));218    expect(next.nodes.some((n) => n.id === "router")).toBe(false);219    expect(next.edges.map((e) => e.id)).toEqual(["d", "e", "f", "g", "h", "i"]);220    expect(stepsOf(next)).toHaveLength(3);221    expect(stepsOf(next)[0]).toMatchObject({ nodes: ["in"], edges: [] });222    expect(stepsOf(next)[1]).toMatchObject({ nodes: ["e1"], edges: [] });223    expect(stepsOf(next)[2]).toBe(stepsOf(b)[2]);224    // Legend entries carry no reference and are kept; the group stays even when it loses a member.225    expect(next.legend).toBe(b.legend); expect(next.groups).toBe(b.groups);226  });227  it("deleting an edge cleans the steps; locked nodes survive; the last node cannot go", () => {228    const b = base();229    const e = valid(deleteSelection(b, { nodes: [], edges: ["a", "d"] }));230    expect(e.nodes).toEqual(b.nodes);231    expect(stepsOf(e)[0].edges).toEqual([]); expect(stepsOf(e)[2].edges).toEqual(["e", "f"]);232    const t = three();233    const kept = valid(deleteSelection(t, selectAll(t)));234    expect(kept.nodes.map((n) => n.id)).toEqual(["d"]); expect(kept.edges).toEqual([]);235    expect(deleteSelection(t, { nodes: ["d"], edges: [] })).toBe(t);236    const solo = diagram({ id: "s", type: "diagram", nodes: [{ id: "only", label: "Seul" }] });237    expect(deleteSelection(solo, { nodes: ["only"], edges: [] })).toBe(solo);238    expect(deleteSelection(b, EMPTY_SELECTION)).toBe(b);239  });240  it("connects two nodes; refuses self-loops, duplicates and unknown ends", () => {241    const b = three();242    const next = valid(connect(b, "a", "c"));243    const added = addedIds(b, next);244    expect(added.edges).toHaveLength(1); expect(added.edges[0]).toMatch(/^e-[0-9a-f]{8}$/);245    expect(next.edges.at(-1)).toMatchObject({ from: "a", to: "c", style: "solid", arrow: "end", tone: "neutral", fromPort: "auto", toPort: "auto" });246    expect(connectIssue(b, "a", "a")).toBe("self"); expect(connect(b, "a", "a")).toBe(b);247    expect(connectIssue(b, "a", "b")).toBe("duplicate"); expect(connect(b, "a", "b")).toBe(b);248    expect(connectIssue(b, "a", "zz")).toBe("unknown"); expect(connect(b, "zz", "a")).toBe(b);249    // The opposite direction is another edge.250    expect(connectIssue(b, "b", "a")).toBeNull();251    expect(valid(connect(b, "b", "a", "ba")).edges.at(-1)?.id).toBe("ba");252    expect(connect(b, "b", "a", "ab")).toBe(b);253  });254});255256describe("diagram editor ops — properties, layers, groups, legend", () => {257  it("edits a node within the schema maxima; optional fields disappear when emptied", () => {258    const b = base();259    const next = valid(updateNode(b, "router", { label: "x".repeat(200), sublabel: "  ", shape: "circle", tone: "red", icon: "brain" }));260    expect(node(next, "router").label).toHaveLength(LIMITS.label);261    expect("sublabel" in node(next, "router")).toBe(false);262    expect(node(next, "router")).toMatchObject({ shape: "circle", tone: "red", icon: "brain", group: "core" });263    expect(node(valid(updateNode(b, "router", { label: "   " })), "router").label).toBe("Routeur");264    const bare = valid(updateNode(b, "e1", { icon: null, group: null }));265    expect("icon" in node(bare, "e1")).toBe(false); expect("group" in node(bare, "e1")).toBe(false);266    expect(node(valid(updateNode(b, "in", { group: "ghost" })), "in").group).toBeUndefined();267    expect(node(valid(updateNode(b, "in", { group: "core", sublabel: "y".repeat(500) })), "in")).toMatchObject({ group: "core", sublabel: "y".repeat(LIMITS.sublabel) });268    expect(updateNode(b, "ghost", { label: "X" })).toBe(b);269  });270  it("edits and reverses an edge", () => {271    const b = base();272    const next = valid(updateEdge(b, "a", { label: "", style: "dotted", arrow: "none", tone: "violet", fromPort: "left", toPort: "top" }));273    const e = next.edges.find((x) => x.id === "a")!;274    expect("label" in e).toBe(false);275    expect(e).toMatchObject({ style: "dotted", arrow: "none", tone: "violet", fromPort: "left", toPort: "top" });276    expect(valid(updateEdge(b, "b", { label: "z".repeat(300) })).edges[1].label).toHaveLength(LIMITS.edgeLabel);277    const rev = valid(reverseEdge(b, "g"));278    expect(rev.edges.find((x) => x.id === "g")).toMatchObject({ from: "e1", to: "db", fromPort: "bottom", toPort: "top" });279    expect(updateEdge(b, "zz", { label: "x" })).toBe(b); expect(reverseEdge(b, "zz")).toBe(b);280  });281  it("edits the diagram-level fields", () => {282    const b = base();283    const next = valid(updateDiagram(b, { kind: "tree", direction: "TB", routing: "straight", title: "", caption: "c".repeat(900), alt: " Nouveau texte " }));284    expect(next).toMatchObject({ kind: "tree", direction: "TB", routing: "straight", alt: "Nouveau texte" });285    expect("title" in next).toBe(false); expect(next.caption).toHaveLength(LIMITS.caption);286    expect(optText("  ", 5)).toBeUndefined(); expect(optText(" abcdefg ", 3)).toBe("abc");287  });288  it("locks and unlocks", () => {289    const b = three();290    const locked = valid(setLocked(b, ["a", "b"], true));291    expect(node(locked, "a").locked).toBe(true); expect(node(locked, "d")).toBe(node(b, "d"));292    const open = valid(setLocked(locked, ["a", "d"], false));293    expect("locked" in node(open, "a")).toBe(false); expect("locked" in node(open, "d")).toBe(false); expect(node(open, "b").locked).toBe(true);294    expect(setLocked(b, ["d"], true)).toBe(b);295  });296  it("reorders layers (array order is paint order)", () => {297    const b = three();298    expect(valid(reorder(b, "nodes", "a", 1)).nodes.map((n) => n.id)).toEqual(["b", "a", "c", "d"]);299    expect(valid(reorder(b, "nodes", "a", 99)).nodes.map((n) => n.id)).toEqual(["b", "c", "d", "a"]);300    expect(valid(reorder(b, "edges", "bc", -1)).edges.map((e) => e.id)).toEqual(["bc", "ab"]);301    expect(reorder(b, "nodes", "a", -1)).toBe(b); expect(reorder(b, "edges", "zz", 1)).toBe(b);302  });303  it("creates, assigns, edits and deletes groups", () => {304    const b = three();305    const g = valid(createGroup(b, ["a", "b"], "  Bloc  ", "green"));306    const gid = g.groups[0].id;307    expect(gid).toMatch(/^g-[0-9a-f]{8}$/);308    expect(g.groups[0]).toEqual({ id: gid, label: "Bloc", tone: "green" });309    expect(g.nodes.filter((n) => n.group === gid).map((n) => n.id)).toEqual(["a", "b"]);310    const more = valid(assignGroup(g, ["c"], gid));311    expect(node(more, "c").group).toBe(gid);312    const out = valid(assignGroup(more, ["a"], null));313    expect("group" in node(out, "a")).toBe(false);314    expect(assignGroup(g, ["c"], "ghost")).toBe(g);315    expect(valid(updateGroup(g, gid, { label: "Autre", tone: "red" })).groups[0]).toEqual({ id: gid, label: "Autre", tone: "red" });316    const gone = valid(deleteGroup(more, gid));317    expect(gone.groups).toEqual([]); expect(gone.nodes.every((n) => n.group === undefined)).toBe(true);318    let many = b;319    for (let i = 0; i < 12; i++) many = valid(createGroup(many, [], `G${i}`));320    expect(many.groups).toHaveLength(12);321    expect(createGroup(many, ["a"], "de trop")).toBe(many);322  });323  it("edits the legend up to eight entries", () => {324    let b = base();325    b = valid(updateLegendEntry(b, 0, { label: "Flux", tone: "blue", shape: "line" }));326    expect(b.legend[0]).toEqual({ label: "Flux", tone: "blue", shape: "line" });327    expect(valid(updateLegendEntry(b, 0, { label: " " })).legend[0].label).toBe("Flux");328    for (let i = 0; i < 10; i++) b = valid(addLegendEntry(b, `Entrée ${i}`));329    expect(b.legend).toHaveLength(LIMITS.legend);330    expect(addLegendEntry(b, "x")).toBe(b);331    expect(valid(removeLegendEntry(b, 0)).legend).toHaveLength(7);332    expect(removeLegendEntry(b, 99)).toBe(b);333  });334});335336describe("diagram editor ops — animation steps", () => {337  const title = (n: number) => `Étape ${n}`;338  it("the first add creates the two steps the schema requires", () => {339    const b = three();340    const two = valid(addStep(b, title));341    expect(stepsOf(two).map((s) => s.title)).toEqual(["Étape 1", "Étape 2"]);342    expect(stepsOf(valid(addStep(two, title))).map((s) => s.title)).toEqual(["Étape 1", "Étape 2", "Étape 3"]);343    let many = two;344    for (let i = 0; i < 30; i++) many = valid(addStep(many, title));345    expect(stepsOf(many)).toHaveLength(LIMITS.steps);346    expect(addStep(many, title)).toBe(many);347  });348  it("removing the last-but-one step removes the animation", () => {349    const b = base();350    const two = valid(removeStep(b, 1));351    expect(stepsOf(two).map((s) => s.title)).toEqual(["Lecture", "Somme"]);352    const none = valid(removeStep(two, 0));353    expect("animation" in none).toBe(false);354    expect(removeStep(b, 9)).toBe(b);355  });356  it("reorders, edits and toggles highlights", () => {357    const b = base();358    expect(stepsOf(valid(moveStep(b, 0, 1))).map((s) => s.title)).toEqual(["Routage", "Lecture", "Somme"]);359    expect(moveStep(b, 0, -1)).toBe(b);360    const edited = valid(updateStep(b, 0, { title: " Début ", text: "" }));361    expect(stepsOf(edited)[0].title).toBe("Début"); expect("text" in stepsOf(edited)[0]).toBe(false);362    expect(stepsOf(valid(updateStep(b, 0, { title: "" })))[0].title).toBe("Lecture");363    const on = valid(toggleStepItem(b, 0, "nodes", "out"));364    expect(stepsOf(on)[0].nodes).toEqual(["in", "out"]);365    expect(stepsOf(valid(toggleStepItem(on, 0, "nodes", "in")))[0].nodes).toEqual(["out"]);366    expect(stepsOf(valid(toggleStepItem(b, 1, "edges", "c")))[1].edges).toEqual(["b", "c"]);367    expect(toggleStepItem(b, 0, "nodes", "ghost")).toBe(b); expect(toggleStepItem(b, 7, "nodes", "in")).toBe(b);368  });369  it("cleanAnimation drops dangling references and too-short animations", () => {370    const b = base();371    expect(cleanAnimation(b)).toBe(b);372    const dangling = { ...b, animation: { steps: [{ title: "A", nodes: ["in", "ghost"], edges: ["zz"] }, { title: "B", nodes: [], edges: [] }] } };373    expect(stepsOf(valid(cleanAnimation(dangling)))[0]).toMatchObject({ nodes: ["in"], edges: [] });374    expect("animation" in cleanAnimation({ ...b, animation: { steps: [{ title: "A", nodes: [], edges: [] }] } })).toBe(false);375  });376});377378describe("diagram editor ops — validity and view", () => {379  it("validate returns the parsed block or the first issue", () => {380    const b = base();381    const ok = validate(b);382    expect(ok.ok && ok.block).toEqual(b);383    const bad = validate({ ...b, edges: [...b.edges, { ...b.edges[0], id: "zz", to: "ghost" }] });384    expect(bad.ok).toBe(false);385    expect(!bad.ok && bad.issue).toContain("unknown endpoint");386    const half = validate({ ...b, nodes: b.nodes.map((n, i) => (i === 0 ? { ...n, x: 3 } : n)) });387    expect(!half.ok && half.issue).toContain("x and y go together");388  });389  it("a long session of mixed operations stays valid", () => {390    let b = base();391    const bx = () => boxes(b);392    b = valid(moveNodes(b, ["in", "out"], 40, 40, bx(), GRID));393    b = valid(duplicateSelection(b, { nodes: ["e1", "e2", "sum"], edges: [] }, bx()));394    b = valid(align(b, b.nodes.slice(-3).map((n) => n.id), "left", bx()));395    b = valid(distribute(b, b.nodes.slice(-3).map((n) => n.id), "vertical", bx()));396    b = valid(createGroup(b, b.nodes.slice(-3).map((n) => n.id), "Copies", "pink"));397    b = valid(connect(b, "in", b.nodes.at(-1)!.id));398    b = valid(toggleStepItem(b, 0, "edges", b.edges.at(-1)!.id));399    b = valid(deleteSelection(b, { nodes: ["e1", b.nodes.at(-1)!.id], edges: ["i"] }));400    b = valid(deleteGroup(b, "core"));401    b = valid(resetLayout(b));402    expect(b.nodes.every((n) => n.x === undefined && n.y === undefined)).toBe(true);403    expect(() => layoutDiagram(b)).not.toThrow();404  });405  it("view maths: zoom about a point, fit, 100 %", () => {406    const v = { k: 1, x: 10, y: 20 };407    const z = zoomAt(v, 2, 110, 120);408    expect(z.k).toBe(2);409    expect(toWorld(z, 110, 120)).toEqual(toWorld(v, 110, 120));410    expect(zoomAt(v, 1000, 0, 0).k).toBe(4); expect(zoomAt(v, 0.0001, 0, 0).k).toBe(0.2);411    const f = fitView({ x: -50, y: -20, width: 1000, height: 400 }, { width: 548, height: 800 }, 24);412    expect(f.k).toBeCloseTo(0.5, 5);413    // Centred: the middle of the box is in the middle of the screen.414    expect(f.x + (-50 + 500) * f.k).toBeCloseTo(274, 5); expect(f.y + (-20 + 200) * f.k).toBeCloseTo(400, 5);415    expect(fitView({ x: 0, y: 0, width: 10, height: 10 }, { width: 1000, height: 1000 }).k).toBe(1.5);416    expect(fitView({ x: 0, y: 0, width: 10, height: 10 }, { width: 0, height: 0 })).toEqual({ k: 1, x: 0, y: 0 });417    const a = actualSize(z, { width: 400, height: 300 });418    expect(a.k).toBe(1);419    expect(toWorld(a, 200, 150)).toEqual(toWorld(z, 200, 150));420  });421});422
Files main
Menu

Theme