SPB Git

Repository Public

next-web-ink.test.ts 16.1 KB 179 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-web-ink.test.ts9 * Description      : the `spn-ink-1` library of the drawing block — byte-stable10 *                    serialisation, strict parsing that preserves unknown keys,11 *                    bounds, stroke eraser, simplification, pressure widths and12 *                    the renderer (against a recording context). Pure logic, no13 *                    database.14 * Module           : tests15 * Repository       : https://git.spboucher.ai/note-spboucher-ai16 * Project Website  : https://note.spboucher.ai17 * Created          : 2026-11-1918 * Last Modified    : 2026-11-1919 *20 * Author           : Simon-Pierre Boucher21 * Position         : Professor of Finance22 * Institution      : Université du Québec en Outaouais (UQO)23 * Organization     : SP Boucher24 * Website          : https://spboucher.ai25 * Git              : https://git.spboucher.ai26 *27 * Preferred Contact: contact@spboucher.ai28 * Development      : dev@spboucher.ai29 * Support          : support@spboucher.ai30 * Security/Admin   : admin@spboucher.ai31 *32 * Copyright (c) 202633 * Simon-Pierre Boucher34 * All rights reserved where applicable. This file is governed by the35 * applicable project license, copyright notices and relevant law.36 * Existing third-party rights and notices remain unaffected.37 *38 * License          : None specified (no license file in this repository)39 *40 * Do not embed credentials, private keys, access tokens,41 * certificates or confidential personal information.42 *43 * =============================================================================44 * END OF SP BOUCHER SOURCE HEADER45 * =============================================================================46 */4748import fs from "node:fs";49import { test } from "node:test";50import assert from "node:assert/strict";51import { emptyInk, serializeInk, parseInk, strokeBounds, inkBounds, eraseAt, simplifyStroke, strokeWidthAt, drawInk, segmentDistance, splitColor, backgroundFill, HIGHLIGHTER_ALPHA, type InkDoc, type InkStroke, type InkPoint, type InkContext } from "../../src/lib/editor/ink";5253const stroke = (points: InkPoint[], over: Partial<InkStroke> = {}): InkStroke => ({ tool: "pen", color: "#112233ff", width: 4, points, ...over });54const sample = (): InkDoc => ({ ...emptyInk(1200, 800), strokes: [stroke([[10, 10, 0.5], [110, 10, 0.8], [110.004, 60.126, 0.33333]]), stroke([[300, 300, 0.5], [400, 400, 0.5]], { tool: "highlighter", color: "#FFEE0059", width: 24 })] });5556test("ink: an empty document has the exact spn-ink-1 shape", () => {57  assert.equal(serializeInk(emptyInk(1200, 800)), '{"format":"spn-ink-1","width":1200,"height":800,"strokes":[]}');58});59test("ink: serialisation rounds (2 decimals, pressure 3), clamps pressure, lower-cases colours and is byte-stable over a round trip", () => {60  const text = serializeInk(sample());61  assert.equal(text, '{"format":"spn-ink-1","width":1200,"height":800,"strokes":[{"tool":"pen","color":"#112233ff","width":4,"points":[[10,10,0.5],[110,10,0.8],[110,60.13,0.333]]},{"tool":"highlighter","color":"#ffee0059","width":24,"points":[[300,300,0.5],[400,400,0.5]]}]}');62  assert.equal(serializeInk(parseInk(text)), text); assert.equal(serializeInk(parseInk(JSON.parse(text))), text, "accepts a parsed value too");63  const odd = serializeInk({ ...emptyInk(10, 10), strokes: [stroke([[-0.001, 1.005, 7], [2, 3, -1]])] });64  assert.ok(odd.includes("[[0,1,1],[2,3,0]]") || odd.includes("[[0,1.01,1],[2,3,0]]"), odd); assert.ok(!odd.includes("-0"));65  assert.equal(serializeInk(parseInk(odd)), odd);66});67test("ink: unknown keys of the document, of a stroke and extra point components survive parse → serialise", () => {68  const src = { zeta: [1, { a: 2 }], format: "spn-ink-1", width: 100, height: 50, app: { name: "SP Notes iOS", build: 7 }, strokes: [{ tool: "marker", color: "#00000080", width: 3, points: [[1, 2, 0.5, 0.25, 12], [3, 4, 1]], tilt: 0.4, id: "s1" }] };69  const doc = parseInk(JSON.stringify(src));70  assert.deepEqual(doc.app, src.app); assert.deepEqual(doc.zeta, src.zeta); assert.equal(doc.strokes[0].tilt, 0.4); assert.equal(doc.strokes[0].id, "s1"); assert.deepEqual(doc.strokes[0].points[0], [1, 2, 0.5, 0.25, 12]);71  const out = serializeInk(doc); assert.deepEqual(JSON.parse(out), src, "nothing lost, nothing added");72  assert.equal(out, serializeInk(parseInk(out))); assert.ok(out.startsWith('{"format":"spn-ink-1","width":100,"height":50,"strokes":['), "known keys first");73  const edited = eraseAt({ ...doc, strokes: [...doc.strokes, stroke([[90, 40, 0.5], [95, 45, 0.5]])] }, [[92, 42]], 2);74  assert.equal(edited.strokes.length, 1); assert.deepEqual(edited.app, src.app, "editing keeps document extras"); assert.equal(edited.strokes[0].tilt, 0.4);75});76test("ink: tolerated inputs are normalised (missing pressure, #rrggbb)", () => {77  const doc = parseInk({ format: "spn-ink-1", width: 10, height: 10, strokes: [{ tool: "pen", color: "#ABCDEF", width: 2, points: [[1, 2]] }] });78  assert.deepEqual(doc.strokes[0].points, [[1, 2, 1]], "a point without pressure counts as p = 1"); assert.equal(doc.strokes[0].color, "#abcdefff");79});80test("ink: invalid inputs are rejected with a clear message", () => {81  const ok = { format: "spn-ink-1", width: 10, height: 10, strokes: [{ tool: "pen", color: "#000000ff", width: 2, points: [[1, 2, 0.5]] }] };82  const bad: [unknown, RegExp][] = [83    ["not json {", /not valid JSON/], ["[]", /JSON object/], [null, /JSON object/], [42, /JSON object/],84    [{ ...ok, format: "spn-ink-2" }, /Unsupported ink format "spn-ink-2"/], [{ width: 1, height: 1, strokes: [] }, /Unsupported ink format \(missing\)/],85    [{ ...ok, width: 0 }, /width and height/], [{ ...ok, height: "800" }, /width and height/], [{ ...ok, strokes: {} }, /strokes must be an array/],86    [{ ...ok, strokes: [null] }, /stroke 1 must be an object/], [{ ...ok, strokes: [{ ...ok.strokes[0], tool: "eraser" }] }, /unknown tool/],87    [{ ...ok, strokes: [{ ...ok.strokes[0], color: "red" }] }, /colour/], [{ ...ok, strokes: [{ ...ok.strokes[0], width: -1 }] }, /positive width/],88    [{ ...ok, strokes: [{ ...ok.strokes[0], points: "x" }] }, /array of points/], [{ ...ok, strokes: [ok.strokes[0], { ...ok.strokes[0], points: [[1, 2, 0.5], [1]] }] }, /stroke 2, point 2/],89    [{ ...ok, strokes: [{ ...ok.strokes[0], points: [[1, "2", 0.5]] }] }, /point 1/], [{ ...ok, strokes: [{ ...ok.strokes[0], points: [[1, NaN, 0.5]] }] }, /point 1/],90  ];91  for (const [input, re] of bad) assert.throws(() => parseInk(input), re, JSON.stringify(input));92  assert.doesNotThrow(() => parseInk(ok));93});94test("ink: bounds include the stroke's width; an empty document has none", () => {95  const s = stroke([[10, 20, 0.5], [50, 80, 1]]);96  assert.deepEqual(strokeBounds(s), { minX: 8, minY: 18, maxX: 52, maxY: 82 }, "pen at pressure 1 = nominal width 4");97  assert.equal(strokeBounds(stroke([])), null); assert.equal(inkBounds(emptyInk(10, 10)), null);98  const b = inkBounds({ ...emptyInk(1200, 800), strokes: [s, stroke([]), stroke([[100, 5, 0.5]], { tool: "highlighter", width: 10 })] });99  assert.deepEqual(b, { minX: 8, minY: 0, maxX: 105, maxY: 82 });100});101test("ink: one width law for every platform — pen = width × (0.35 + 0.65 p), marker and highlighter constant, no pressure = 1", () => {102  const w = (tool: InkStroke["tool"], p: number) => strokeWidthAt({ tool, width: 10 }, p); const near = (a: number, b: number) => assert.ok(Math.abs(a - b) < 1e-9, `${a} ≈ ${b}`);103  near(w("pen", 1), 10); near(w("pen", 0), 3.5); near(w("pen", 0.5), 6.75); near(w("pen", 0.2), 4.8); assert.ok(w("pen", 0.2) < w("pen", 0.8));104  assert.equal(w("marker", 0), 10); assert.equal(w("marker", 0.5), 10); assert.equal(w("marker", 1), 10);105  assert.equal(w("highlighter", 0), 10); assert.equal(w("highlighter", 1), 10);106  near(w("pen", 5), 10); near(w("pen", -3), 3.5); near(w("pen", NaN), 10); assert.equal(HIGHLIGHTER_ALPHA, 0.4);107});108test("ink: the shared numeric fixture (tests/fixtures/ink/width-law.json) — the Swift core asserts the same numbers", () => {109  const fx = JSON.parse(fs.readFileSync("tests/fixtures/ink/width-law.json", "utf8")); const doc = parseInk(fx.ink); assert.equal(doc.strokes.length, 3);110  doc.strokes.forEach((s, i) => {111    const got = s.points.map((p) => Math.round(strokeWidthAt(s, p[2]) * 1000) / 1000); assert.deepEqual(got, fx.expected[i].widths, `stroke ${i + 1} (${s.tool})`);112    assert.deepEqual(s.points.map((p) => p[2]), fx.expected[i].pressures, `pressures read for stroke ${i + 1}`);113    const b = strokeBounds(s)!; assert.deepEqual([b.minX, b.minY, b.maxX, b.maxY].map((v) => Math.round(v * 1000) / 1000), fx.expected[i].bounds, `bounds of stroke ${i + 1}`);114  });115  const rec: { alpha: number; lineWidth: number }[] = []; let alpha = 1, lineWidth = 0;116  const ctx = { save() {}, restore() {}, beginPath() {}, moveTo() {}, lineTo() {}, arc() {}, fill() { rec.push({ alpha, lineWidth }); }, stroke() { rec.push({ alpha, lineWidth }); }, set globalAlpha(v: number) { alpha = v; }, get globalAlpha() { return alpha; }, set lineWidth(v: number) { lineWidth = v; }, get lineWidth() { return lineWidth; }, lineCap: "round", lineJoin: "round", strokeStyle: "", fillStyle: "", globalCompositeOperation: "source-over" } as unknown as InkContext;117  drawInk(ctx, { ...doc, strokes: [doc.strokes[2]] }); assert.equal(rec.at(-1)!.alpha, fx.highlighterAlpha, "an opaque highlighter colour is drawn at alpha 0.40"); assert.equal(fx.highlighterAlpha, 0.4);118});119test("ink: segment distance — crossing, parallel, touching, degenerate", () => {120  assert.equal(segmentDistance([0, 0], [10, 10], [0, 10], [10, 0]), 0); assert.equal(segmentDistance([0, 0], [10, 0], [0, 3], [10, 3]), 3);121  assert.equal(segmentDistance([0, 0], [10, 0], [13, 4], [20, 4]), 5); assert.equal(segmentDistance([0, 0], [0, 0], [3, 4], [3, 4]), 5); assert.equal(segmentDistance([0, 0], [10, 0], [5, 0], [5, 9]), 0);122});123test("ink: the eraser removes exactly the strokes its path passes over", () => {124  const a = stroke([[0, 100, 1], [200, 100, 1]]), b = stroke([[0, 200, 1], [200, 200, 1]]), dot = stroke([[300, 300, 1]]), thick = stroke([[0, 400, 1], [200, 400, 1]], { tool: "highlighter", width: 40 }); // p = 1: the nominal width125  const doc: InkDoc = { ...emptyInk(1200, 800), strokes: [a, b, dot, thick] };126  assert.deepEqual(eraseAt(doc, [[100, 0], [100, 150]], 5).strokes, [b, dot, thick], "a swipe crossing A between two of its points");127  assert.deepEqual(eraseAt(doc, [[100, 108]], 5).strokes, [a, b, dot, thick], "8 away > radius 5 + half width 2");128  assert.deepEqual(eraseAt(doc, [[100, 106.5]], 5).strokes, [b, dot, thick], "6.5 away ≤ 7");129  assert.deepEqual(eraseAt(doc, [[100, 424]], 5).strokes, [a, b, dot], "the stroke's own width counts (24 ≤ 5 + 20)");130  assert.deepEqual(eraseAt(doc, [[100, 50], [100, 450]], 1).strokes, [dot], "a long swipe takes everything on its way");131  assert.deepEqual(eraseAt(doc, [[303, 304]], 4).strokes, [a, b, thick], "single-point strokes can be erased");132  const same = eraseAt(doc, [[600, 600], [700, 700]], 10); assert.equal(same, doc, "no hit → same object"); assert.equal(eraseAt(doc, [], 10), doc);133  assert.equal(doc.strokes.length, 4, "the input is never mutated"); assert.notEqual(eraseAt(doc, [[100, 100]], 1), doc);134});135test("ink: simplification keeps endpoints, corners and pressure, drops collinear points", () => {136  const line: InkPoint[] = Array.from({ length: 50 }, (_, i) => [i * 2, 10 + (i % 2) * 0.05, i / 49] as InkPoint);137  const s = simplifyStroke(line, 0.5); assert.deepEqual(s, [line[0], line[49]]); assert.equal(s[1][2], 1, "pressure kept");138  const corner: InkPoint[] = [[0, 0, 0.1], [5, 0.01, 0.2], [10, 0, 0.3], [10, 5, 0.4], [10, 10, 0.9]];139  assert.deepEqual(simplifyStroke(corner, 0.5), [[0, 0, 0.1], [10, 0, 0.3], [10, 10, 0.9]]);140  assert.deepEqual(simplifyStroke(corner, 0), corner, "tolerance 0 = unchanged"); assert.notEqual(simplifyStroke(corner, 0), corner, "always a copy");141  assert.deepEqual(simplifyStroke([[1, 1, 0.5]] as InkPoint[], 3), [[1, 1, 0.5]]); assert.deepEqual(simplifyStroke([] as InkPoint[], 3), []);142  const loop: InkPoint[] = [[0, 0, 0.5], [10, 0, 0.5], [10, 10, 0.5], [0, 10, 0.5], [0, 0, 0.5]];143  assert.equal(simplifyStroke(loop, 1).length, 5, "a closed shape (first = last) is not collapsed");144  const wavy: InkPoint[] = Array.from({ length: 200 }, (_, i) => [i, Math.sin(i / 10) * 40, 0.5] as InkPoint), out = simplifyStroke(wavy, 1);145  assert.ok(out.length < 60 && out.length > 8, String(out.length)); assert.deepEqual(out[0], wavy[0]); assert.deepEqual(out[out.length - 1], wavy[199]);146});147test("ink: colours and backgrounds", () => {148  assert.deepEqual(splitColor("#FF000080"), { rgb: "#ff0000", alpha: 128 / 255 }); assert.deepEqual(splitColor("#00ff00"), { rgb: "#00ff00", alpha: 1 }); assert.deepEqual(splitColor("nope"), { rgb: "#000000", alpha: 1 });149  assert.equal(backgroundFill("none"), null); assert.equal(backgroundFill(""), null); assert.equal(backgroundFill("#fdf6e3"), "#fdf6e3"); assert.equal(backgroundFill("white"), "#ffffff"); assert.equal(backgroundFill("grid"), "#ffffff");150});151152/** Recording 2D context: every call and the state it was made with. */153function recorder() {154  const calls: { op: string; args: number[]; lineWidth: number; alpha: number; comp: string; stroke: unknown; cap: string }[] = []; const stack: object[] = [];155  const ctx: InkContext = { lineWidth: 1, lineCap: "butt", lineJoin: "miter", strokeStyle: "#000", fillStyle: "#000", globalAlpha: 1, globalCompositeOperation: "source-over",156    save() { stack.push({ lineWidth: ctx.lineWidth, lineCap: ctx.lineCap, lineJoin: ctx.lineJoin, strokeStyle: ctx.strokeStyle, fillStyle: ctx.fillStyle, globalAlpha: ctx.globalAlpha, globalCompositeOperation: ctx.globalCompositeOperation }); }, restore() { Object.assign(ctx, stack.pop()); },157    beginPath() { log("beginPath"); }, moveTo(x, y) { log("moveTo", x, y); }, lineTo(x, y) { log("lineTo", x, y); }, stroke() { log("stroke"); }, arc(x, y, r) { log("arc", x, y, r); }, fill() { log("fill"); } };158  function log(op: string, ...args: number[]) { calls.push({ op, args, lineWidth: ctx.lineWidth, alpha: ctx.globalAlpha, comp: ctx.globalCompositeOperation, stroke: ctx.strokeStyle, cap: ctx.lineCap }); }159  return { ctx, calls, of: (op: string) => calls.filter((c) => c.op === op) };160}161test("ink: the renderer draws pressure-sensitive pen segments, a single translucent highlighter path, dots, and restores the context", () => {162  const doc: InkDoc = { ...emptyInk(100, 100), strokes: [163    stroke([[0, 0, 0.1], [10, 0, 0.5], [20, 0, 1]], { width: 10 }),164    stroke([[0, 50, 0.2], [10, 50, 0.9], [20, 50, 0.4]], { tool: "highlighter", color: "#ffee0080", width: 20 }),165    stroke([[5, 5, 0.5]], { tool: "marker", width: 6 }),166    stroke([[0, 80, 0.5], [9, 80, 0.5]], { tool: "highlighter", color: "#ffee00ff", width: 20 }),167  ] };168  const r = recorder(); drawInk(r.ctx, doc, 2);169  const strokes = r.of("stroke"); assert.equal(strokes.length, 4, "2 pen segments + 1 path per highlighter");170  assert.ok(strokes[0].lineWidth < strokes[1].lineWidth, "the pen thickens with pressure"); assert.equal(strokes[0].lineWidth, strokeWidthAt({ tool: "pen", width: 10 }, 0.3) * 2);171  assert.equal(strokes[0].cap, "round"); assert.equal(strokes[0].alpha, 1); assert.equal(strokes[0].comp, "source-over"); assert.equal(strokes[0].stroke, "#112233");172  assert.equal(strokes[2].lineWidth, 40, "highlighter: constant width × scale"); assert.equal(strokes[2].alpha, 128 / 255); assert.equal(strokes[2].comp, "multiply"); assert.equal(strokes[2].stroke, "#ffee00");173  assert.equal(strokes[3].alpha, HIGHLIGHTER_ALPHA, "an opaque highlighter colour still draws translucent");174  assert.deepEqual(r.of("lineTo").map((c) => c.args), [[20, 0], [40, 0], [20, 100], [40, 100], [18, 160]], "coordinates are scaled");175  assert.deepEqual(r.of("arc")[0].args, [10, 10, 6], "single point = dot of the stroke's width"); assert.equal(r.of("fill").length, 1);176  assert.equal(r.ctx.globalAlpha, 1); assert.equal(r.ctx.globalCompositeOperation, "source-over"); assert.equal(r.ctx.lineCap, "butt", "state restored");177  const none = recorder(); drawInk(none.ctx, emptyInk(10, 10), 1); assert.equal(none.calls.length, 0);178});179
Files main
Menu

Theme