SPB Git

Repository Public

MediaCanvasGeometryTests.swift 19.6 KB 281 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/MediaCanvasGeometryTests.swift3// Description: Pure geometry of the canvas editor (viewport ⇄ screen, zoom around a point, fit, hit testing on the real4//              outline, marquee, edge anchoring and routes, resize by handle, table cells, history) and the web team's5//              canvas fixtures (merge-cases, layout-cases) decoded and replayed through Core.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import Foundation11import SPNotesDocument12import Testing13@testable import SPNotesFeatures14@testable import SPNotesFeaturesCatalog1516private func near(_ a: Double, _ b: Double, _ tolerance: Double = 1e-9) -> Bool { abs(a - b) <= tolerance }17private func near(_ a: CGPoint, _ b: CGPoint, _ tolerance: Double = 1e-6) -> Bool { near(a.x, b.x, tolerance) && near(a.y, b.y, tolerance) }1819@Suite("Canvas geometry")20struct MediaCanvasGeometryTests {21    @Test("screen = (world − origin) × zoom, and back")22    func transforms() {23        let viewport = CanvasViewport(x: 100, y: -40, zoom: 2)24        #expect(CanvasViewportMath.worldToScreen(viewport, CGPoint(x: 150, y: 10)) == CGPoint(x: 100, y: 100))25        #expect(CanvasViewportMath.screenToWorld(viewport, CGPoint(x: 100, y: 100)) == CGPoint(x: 150, y: 10))26        for point in [CGPoint(x: -3.5, y: 8), CGPoint(x: 1e4, y: -1e3)] {27            #expect(near(CanvasViewportMath.screenToWorld(viewport, CanvasViewportMath.worldToScreen(viewport, point)), point))28        }29        #expect(CanvasViewportMath.worldToScreen(viewport, CGRect(x: 100, y: -40, width: 10, height: 5)) == CGRect(x: 0, y: 0, width: 20, height: 10))30        #expect(CanvasViewportMath.visibleRect(viewport, size: CGSize(width: 800, height: 600)) == CGRect(x: 100, y: -40, width: 400, height: 300))31        #expect(CanvasViewportMath.visibleRect(viewport, size: CGSize(width: 800, height: 600), margin: 20) == CGRect(x: 90, y: -50, width: 420, height: 320))32    }3334    @Test("pan moves the origin against the drag; zoom keeps the point under the cursor fixed and is clamped")35    func panAndZoom() {36        let viewport = CanvasViewport(x: 10, y: 20, zoom: 2)37        let panned = CanvasViewportMath.pan(viewport, dx: 40, dy: -10)38        #expect(panned.x == -10 && panned.y == 25 && panned.zoom == 2)39        let cursor = CGPoint(x: 300, y: 200)40        let before = CanvasViewportMath.screenToWorld(viewport, cursor)41        let zoomed = CanvasViewportMath.zoom(viewport, by: 1.7, at: cursor)42        #expect(near(zoomed.zoom, 3.4))43        #expect(near(CanvasViewportMath.screenToWorld(zoomed, cursor), before))44        #expect(CanvasViewportMath.zoom(viewport, to: 99, at: cursor).zoom == CanvasViewportMath.zoomMax)45        #expect(CanvasViewportMath.zoom(viewport, to: 0, at: cursor).zoom == CanvasViewportMath.zoomMin)46        #expect(CanvasViewportMath.clampZoom(.nan) == 1)47        // In then out by the same wheel delta returns to the start.48        let back = CanvasViewportMath.zoom(CanvasViewportMath.zoom(viewport, by: CanvasViewportMath.wheelZoomFactor(deltaY: -120, pinch: false), at: cursor),49                                           by: CanvasViewportMath.wheelZoomFactor(deltaY: 120, pinch: false), at: cursor)50        #expect(near(back.zoom, 2, 1e-12) && near(back.x, 10, 1e-9) && near(back.y, 20, 1e-9))51        // Unknown viewport fields survive a pan (lossless model).52        var custom = CanvasViewport(x: 0, y: 0, zoom: 1)53        custom = (try? JSONDecoder().decode(CanvasViewport.self, from: Data(#"{"x":0,"y":0,"zoom":1,"lock":true}"#.utf8))) ?? custom54        #expect(CanvasViewportMath.pan(custom, dx: 5, dy: 5).jsonValue["lock"]?.boolValue == true)55    }5657    @Test("fit shows the whole content centred, never magnifies beyond 1, and survives an empty canvas")58    func fit() {59        let size = CGSize(width: 800, height: 600)60        let viewport = CanvasViewportMath.fit(CGRect(x: 0, y: 0, width: 2000, height: 1000), size: size)61        #expect(near(viewport.zoom, (800 - 96) / 2000))62        let visible = CanvasViewportMath.visibleRect(viewport, size: size)63        #expect(visible.contains(CGRect(x: 0, y: 0, width: 2000, height: 1000)))64        #expect(near(visible.midX, 1000, 1e-6) && near(visible.midY, 500, 1e-6))65        #expect(CanvasViewportMath.fit(CGRect(x: 10, y: 10, width: 40, height: 20), size: size).zoom == 1)66        #expect(CanvasViewportMath.fit(.null, size: size) == CanvasViewport())67        let centered = CanvasViewportMath.center(CanvasViewport(x: 0, y: 0, zoom: 2), on: CGPoint(x: 50, y: 50), size: size)68        #expect(centered.x == -150 && centered.y == -100)69    }7071    @Test("hit testing follows the real outline of shapes, the z-order, and the marquee touches inclusively")72    func hitTesting() {73        var ellipse = CanvasNode(id: "e", kind: .shape, x: 0, y: 0, w: 200, h: 100)74        ellipse.shape = .ellipse75        var diamond = CanvasNode(id: "d", kind: .shape, x: 0, y: 0, w: 200, h: 100)76        diamond.shape = .diamond77        let corner = CGPoint(x: 8, y: 8), center = CGPoint(x: 100, y: 50)78        #expect(!CanvasHit.contains(ellipse, corner) && CanvasHit.contains(ellipse, center))79        #expect(!CanvasHit.contains(diamond, corner) && CanvasHit.contains(diamond, center))80        #expect(CanvasHit.contains(diamond, CGPoint(x: 50, y: 25)), "on the edge of the diamond")81        #expect(CanvasHit.contains(CanvasNode(id: "r", kind: .text, x: 0, y: 0, w: 200, h: 100), corner))82        #expect(CanvasHit.contains(ellipse, CGPoint(x: -3, y: 50), tolerance: 4))8384        var back = CanvasNode(id: "back", kind: .text, x: 0, y: 0, w: 100, h: 100, z: 5)85        back.text = "back"86        let front = CanvasNode(id: "front", kind: .text, x: 50, y: 50, w: 100, h: 100, z: 1)87        let document = CanvasDocument(nodes: [back, front])88        #expect(CanvasHit.node(in: document, at: CGPoint(x: 75, y: 75))?.id == "back", "the highest z wins")89        #expect(CanvasHit.node(in: document, at: CGPoint(x: 140, y: 140))?.id == "front")90        #expect(CanvasHit.node(in: document, at: CGPoint(x: 500, y: 500)) == nil)91        #expect(CanvasHit.nodes(in: document, touching: CGRect(x: 150, y: 150, width: 30, height: 30)).map(\.id) == ["front"], "touching edges count")92        #expect(CanvasHit.nodes(in: document, touching: CGRect(x: -10, y: -10, width: 300, height: 300)).map(\.id) == ["front", "back"], "back to front")93        #expect(CanvasHit.nodes(in: document, touching: CGRect(x: 40, y: 40, width: 120, height: 120), containedOnly: true).map(\.id) == ["front"])94        #expect(CanvasHit.rect(from: CGPoint(x: 10, y: 30), to: CGPoint(x: 0, y: 50)) == CGRect(x: 0, y: 30, width: 10, height: 20))95        #expect(CanvasHit.distance(CGPoint(x: 5, y: 5), toPolyline: [CGPoint(x: 0, y: 0), CGPoint(x: 10, y: 0)]) == 5)96    }9798    @Test("edges are anchored on the outline of the cards; the three routes, the self loop and the arrowhead")99    func routing() {100        let a = CanvasNode(id: "a", kind: .text, x: 0, y: 0, w: 100, h: 60)101        let b = CanvasNode(id: "b", kind: .text, x: 300, y: 0, w: 100, h: 60)102        let straight = CanvasRouting.route(from: a, to: b)103        #expect(straight.points == [CGPoint(x: 100, y: 30), CGPoint(x: 300, y: 30)])104        #expect(straight.endAngle == 0 && straight.label == CGPoint(x: 200, y: 30))105        // Diagonal: the ray leaves the rectangle through its right side.106        let c = CanvasNode(id: "c", kind: .text, x: 300, y: 300, w: 100, h: 60)107        let diagonal = CanvasRouting.route(from: a, to: c)108        #expect(near(diagonal.points[0], CGPoint(x: 80, y: 60), 0.01), "\(diagonal.points[0])")109        var ellipse = CanvasNode(id: "e", kind: .shape, x: 0, y: 0, w: 200, h: 100)110        ellipse.shape = .ellipse111        #expect(CanvasRouting.anchor(ellipse, toward: CGPoint(x: 1000, y: 50)) == CGPoint(x: 200, y: 50))112        let onEllipse = CanvasRouting.anchor(ellipse, toward: CGPoint(x: 300, y: 250))113        #expect(near(pow((onEllipse.x - 100) / 100, 2) + pow((onEllipse.y - 50) / 50, 2), 1, 1e-3))114        var diamond = ellipse115        diamond.shape = .diamond116        let onDiamond = CanvasRouting.anchor(diamond, toward: CGPoint(x: 300, y: 250))117        #expect(near(abs(onDiamond.x - 100) / 100 + abs(onDiamond.y - 50) / 50, 1, 1e-3))118        #expect(CanvasRouting.anchor(a, toward: a.center) == CGPoint(x: 50, y: 0), "towards its own centre: top centre")119120        let orthogonal = CanvasRouting.route(from: a, to: c, style: .orthogonal)121        #expect(orthogonal.points == [CGPoint(x: 50, y: 60), CGPoint(x: 50, y: 180), CGPoint(x: 350, y: 180), CGPoint(x: 350, y: 300)], "vertical gap is larger")122        #expect(near(orthogonal.endAngle, .pi / 2))123        let curved = CanvasRouting.route(from: a, to: b, style: .curved)124        #expect(curved.points.count == 25 && curved.points.first == CGPoint(x: 100, y: 30) && curved.points.last == CGPoint(x: 300, y: 30))125        #expect(curved.controls?.0 == CGPoint(x: 200, y: 30))126        let overlapping = CanvasRouting.route(from: a, to: CanvasNode(id: "o", kind: .text, x: 50, y: 20, w: 100, h: 60), style: .orthogonal)127        #expect(overlapping.style == .straight, "overlapping boxes fall back to straight")128        let loop = CanvasRouting.route(from: a, to: a)129        #expect(loop.points.count == 5 && loop.points.first == CGPoint(x: 70, y: 0) && loop.points.last == CGPoint(x: 100, y: 18))130        #expect(CanvasRouting.facingSides(CGRect(x: 0, y: 0, width: 10, height: 10), CGRect(x: 50, y: 0, width: 10, height: 10))?.from == .right)131        #expect(CanvasRouting.facingSides(CGRect(x: 0, y: 0, width: 10, height: 10), CGRect(x: 5, y: 5, width: 10, height: 10)) == nil)132133        let head = CanvasRouting.arrowHead(tip: CGPoint(x: 300, y: 30), angle: 0)134        #expect(head[0] == CGPoint(x: 300, y: 30) && head[1].x < 300 && head[2].x < 300 && near(head[1].y - 30, -(head[2].y - 30), 0.011))135        var edge = CanvasEdge(from: "a", to: "b")136        #expect(CanvasRouting.hasArrow(edge) && CanvasRouting.style(of: edge) == .straight)137        edge.kind = .line138        edge["route"] = .string("curved")139        #expect(!CanvasRouting.hasArrow(edge) && CanvasRouting.style(of: edge) == .curved)140        edge["route"] = .string("zigzag")141        #expect(CanvasRouting.style(of: edge) == .straight)142143        let document = CanvasDocument(nodes: [a, b], edges: [CanvasEdge(id: "e1", from: "a", to: "b")])144        #expect(CanvasHit.edge(in: document, at: CGPoint(x: 200, y: 34), tolerance: 6)?.id == "e1")145        #expect(CanvasHit.edge(in: document, at: CGPoint(x: 200, y: 60), tolerance: 6) == nil)146    }147148    @Test("resize by handle: never below the minimum, never flipped, group scaling, aspect lock")149    func resize() {150        let box = CGRect(x: 100, y: 100, width: 200, height: 100)151        #expect(CanvasResize.rect(box, handle: .se, dx: 50, dy: 20) == CGRect(x: 100, y: 100, width: 250, height: 120))152        #expect(CanvasResize.rect(box, handle: .nw, dx: 50, dy: 20) == CGRect(x: 150, y: 120, width: 150, height: 80))153        #expect(CanvasResize.rect(box, handle: .e, dx: -1000, dy: 0) == CGRect(x: 100, y: 100, width: 24, height: 100), "clamped to the minimum")154        #expect(CanvasResize.rect(box, handle: .w, dx: 1000, dy: 0) == CGRect(x: 276, y: 100, width: 24, height: 100))155        #expect(CanvasResize.rect(box, handle: .n, dx: 0, dy: -50) == CGRect(x: 100, y: 50, width: 200, height: 150))156        #expect(CanvasResize.rect(box, handle: .se, dx: 100, dy: 0, keepAspect: true) == CGRect(x: 100, y: 100, width: 300, height: 150))157        #expect(CanvasHandle.se.point(on: box) == CGPoint(x: 300, y: 200) && CanvasHandle.n.point(on: box) == CGPoint(x: 200, y: 100))158159        let document = CanvasDocument(nodes: [CanvasNode(id: "a", kind: .text, x: 0, y: 0, w: 100, h: 100), CanvasNode(id: "b", kind: .text, x: 100, y: 100, w: 100, h: 100),160                                              CanvasNode(id: "c", kind: .text, x: 500, y: 500, w: 10, h: 10)])161        let scaled = CanvasResize.nodes(document, ids: ["a", "b"], handle: .se, dx: 200, dy: 200)162        #expect(scaled.node(id: "a")?.frame == CGRect(x: 0, y: 0, width: 200, height: 200))163        #expect(scaled.node(id: "b")?.frame == CGRect(x: 200, y: 200, width: 200, height: 200))164        #expect(scaled.node(id: "c") == document.node(id: "c"))165        #expect(CanvasResize.nodes(document, ids: ["zzz"], handle: .se, dx: 5, dy: 5) == document)166    }167168    @Test("defaults, labels and the Markdown-table convention of table cards")169    func defaultsAndTables() {170        #expect(CanvasDefaults.size(.pdf) == CGSize(width: 240, height: 320) && CanvasDefaults.size(.text) == CGSize(width: 240, height: 120))171        let shape = CanvasDefaults.node(.shape, centeredAt: CGPoint(x: 100, y: 100), id: "s")172        #expect(shape.frame == CGRect(x: 20, y: 40, width: 160, height: 120) && shape.shape == .rect)173        let cells = [["Modèle", "QLIKE"], ["GARCH | GJR", "0,4\n0,5"]]174        let text = CanvasTable.serialize(cells)175        #expect(text == "| Modèle | QLIKE |\n| --- | --- |\n| GARCH \\| GJR | 0,4<br>0,5 |")176        #expect(CanvasTable.parse(text) == cells)177        #expect(CanvasTable.parse("| a | b | c |\n|---|:-:|--:|\n| 1 |") == [["a", "b", "c"], ["1", "", ""]])178        #expect(CanvasTable.parse(nil).isEmpty && CanvasTable.parse("pas un tableau").isEmpty)179        #expect(CanvasTable.parse(CanvasDefaults.node(.table, centeredAt: .zero).text).count == 3)180181        var page = CanvasNode(id: "p", kind: .page)182        page.pageId = "x"183        #expect(CanvasNodeLabel.label(page, titles: ["x": "Ma page"]) == "Ma page" && CanvasNodeLabel.label(page) == "Page")184        var text2 = CanvasNode(id: "t", kind: .text)185        text2.text = "\n## Titre\nsuite"186        #expect(CanvasNodeLabel.label(text2) == "Titre")187        #expect(CanvasNodeLabel.label(CanvasNode(id: "u", kind: CanvasNodeKind(rawValue: "hologram"))) == "Carte (hologram)")188        for kind in CanvasNodeKind.allKnown { #expect(!CanvasNodeLabel.kindName(kind).isEmpty && !CanvasNodeLabel.symbol(kind).isEmpty) }189    }190191    @Test("history: a gesture is one step, undo / redo, a foreign document drops the history")192    func history() {193        func doc(_ text: String) -> CanvasDocument {194            var node = CanvasNode(id: "n", kind: .text)195            node.text = text196            return CanvasDocument(nodes: [node])197        }198        var history = CanvasHistory(doc("a"))199        #expect(!history.canUndo && !history.canRedo)200        history.commit(doc("b"))201        history.commit(doc("b"))202        #expect(history.past.count == 1, "a no-op is not a step")203        history.transient(doc("c1"))204        history.transient(doc("c2"))205        #expect(history.canUndo && history.past.count == 1)206        history.settle()207        #expect(history.past.count == 2 && history.present == doc("c2"))208        #expect(history.undo() && history.present == doc("b"))209        #expect(history.undo() && history.present == doc("a") && !history.undo())210        #expect(history.redo() && history.redo() && history.present == doc("c2") && !history.redo())211        history.transient(doc("d"))212        history.cancelGesture()213        #expect(history.present == doc("c2") && history.gesture == nil)214        history.undo()215        history.commit(doc("z"))216        #expect(!history.canRedo, "a new edit clears the redo stack")217        history.replace(doc("server"))218        #expect(!history.canUndo && history.present == doc("server"))219        var long = CanvasHistory(doc("0"))220        for i in 1...(CanvasHistory.limit + 20) { long.commit(doc("\(i)")) }221        #expect(long.past.count == CanvasHistory.limit)222    }223224    // MARK: Web fixtures (tests/fixtures/canvas of the web repo, branch next-c)225226    @Test("web fixture merge-cases.json: every case decodes, round-trips and Core's merge gives the expected canvas and conflicts")227    func webMergeFixtures() throws {228        let root = try JSONValue(jsonString: FeatureSamples.text("canvas", "merge-cases"))229        let cases = try #require(root["cases"]?.arrayValue)230        #expect(cases.count >= 39)231        for item in cases {232            let name = item["name"]?.stringValue ?? "?"233            let base = try CanvasDocument(json: try #require(item["base"])), local = try CanvasDocument(json: try #require(item["local"])), remote = try CanvasDocument(json: try #require(item["remote"]))234            for (side, json) in [("base", item["base"]), ("local", item["local"]), ("remote", item["remote"])] {235                let document = try CanvasDocument(json: try #require(json))236                #expect(try CanvasDocument(data: document.jsonData()) == document, "\(name) \(side): round trip")237            }238            let result = CanvasDocument.merge(base: base, local: local, remote: remote)239            let expected = try #require(item["expected"])240            #expect(result.merged == (try CanvasDocument(json: try #require(expected["merged"]))), "\(name): merged")241            let conflicts = expected["conflicts"]?.arrayValue ?? []242            #expect(result.conflicts.count == conflicts.count, "\(name): conflict count")243            for (found, wanted) in zip(result.conflicts, conflicts) {244                #expect(found.kind.rawValue == wanted["kind"]?.stringValue && found.id == wanted["id"]?.stringValue && found.reason.rawValue == wanted["reason"]?.stringValue, "\(name): \(found.id)")245                #expect(found.local == wanted["local"] && found.remote == wanted["remote"] && found.base == wanted["base"], "\(name): values of \(found.id)")246                // The words of the review exist for every conflict of the fixtures.247                #expect(!CanvasConflictText.title(found).isEmpty && !CanvasConflictText.reason(found).isEmpty)248                #expect(!CanvasConflictText.side(found.local, kind: found.kind).isEmpty && !CanvasConflictText.side(found.remote, kind: found.kind).isEmpty)249            }250        }251    }252253    @Test("web fixture layout-cases.json: grid and seeded force layouts match to 1/100 (what « Ranger » applies)")254    func webLayoutFixtures() throws {255        let root = try JSONValue(jsonString: FeatureSamples.text("canvas", "layout-cases"))256        let cases = try #require(root["cases"]?.arrayValue)257        #expect(cases.count >= 9)258        for item in cases {259            let name = item["name"]?.stringValue ?? "?"260            let input = try CanvasDocument(json: try #require(item["input"])), expected = try CanvasDocument(json: try #require(item["expected"]))261            let params = item["params"]?.objectValue ?? [:]262            let pinned = Set((params["pinned"]?.arrayValue ?? []).compactMap(\.stringValue))263            let output: CanvasDocument264            if item["op"]?.stringValue == "grid" {265                let origin = params["origin"]?.objectValue266                output = CanvasLayout.grid(input, columns: params["columns"]?.intValue, spacing: params["spacing"]?.doubleValue ?? 48,267                                           origin: CGPoint(x: origin?["x"]?.doubleValue ?? 0, y: origin?["y"]?.doubleValue ?? 0), pinned: pinned)268            } else {269                let f = params["forces"]?.objectValue270                let forces = CanvasLayout.Forces(spacing: f?["spacing"]?.doubleValue ?? 48, repulsion: f?["repulsion"]?.doubleValue ?? 0.5,271                                                 attraction: f?["attraction"]?.doubleValue ?? 0.08, maxStep: f?["maxStep"]?.doubleValue ?? 120)272                output = CanvasLayout.forceDirected(input, iterations: params["iterations"]?.intValue ?? 200, seed: UInt64(params["seed"]?.intValue ?? 1), forces: forces, pinned: pinned)273            }274            #expect(output.nodes.count == expected.nodes.count, "\(name)")275            for (found, wanted) in zip(output.nodes, expected.nodes) {276                #expect(found.id == wanted.id && abs(found.x - wanted.x) <= 0.011 && abs(found.y - wanted.y) <= 0.011, "\(name): \(found.id) \(found.x),\(found.y) ≠ \(wanted.x),\(wanted.y)")277            }278        }279    }280}281
Files main
Menu

Theme