Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import CanvasEngine56@Suite struct CanvasEditingTests {7 @Test func addCardSnapsClampsSelectsAndStacksOnTop() throws {8 var (editor, ids) = makeEditor(cards: 2)9 let id = try editor.addCard(note(), at: CanvasPoint(x: 13, y: 27), size: CanvasSize(width: 10, height: 9_000))10 let card = try #require(editor.card(id))11 #expect(card.origin == CanvasPoint(x: 20, y: 20))12 #expect(card.size == CanvasSize(width: 120, height: 4_000))13 #expect(card.zIndex == 2)14 #expect(editor.selection == [id])15 #expect(editor.document.cards.map(\.id) == ids + [id])16 #expect(editor.undoName == "Add Card")17 #expect(editor.validate().isEmpty)18 }1920 @Test func addCardRejectsNonFiniteGeometryAndTheCardLimit() throws {21 var configuration = CanvasConfiguration()22 configuration.maximumCards = 123 var (editor, _) = makeEditor(cards: 0, configuration: configuration)24 #expect(throws: CanvasEditError.invalidGeometry) { try editor.addCard(note(), at: CanvasPoint(x: .nan, y: 0)) }25 #expect(throws: CanvasEditError.invalidGeometry) {26 try editor.addCard(note(), at: .zero, size: CanvasSize(width: .infinity, height: 10))27 }28 try editor.addCard(note(), at: .zero)29 #expect(throws: CanvasEditError.cardLimitReached(1)) { try editor.addCard(note(), at: .zero) }30 #expect(editor.undoCount == 1)31 }3233 @Test func removeCardsRemovesTheirConnectionsAndUndoRestoresBoth() throws {34 var (editor, ids) = makeEditor(cards: 3)35 try editor.connect(from: ids[0], to: ids[1], label: "a")36 try editor.connect(from: ids[1], to: ids[2])37 try editor.connect(from: ids[2], to: ids[0])38 let before = editor.document39 editor.select([ids[1]])40 #expect(editor.removeSelection() == true)41 #expect(editor.document.cards.map(\.id) == [ids[0], ids[2]])42 #expect(editor.document.connections == [CanvasConnection(from: ids[2], to: ids[0])])43 #expect(editor.selection.isEmpty)44 #expect(editor.undo() == true)45 #expect(editor.document == before)46 #expect(editor.selection == [ids[1]])47 #expect(editor.redo() == true)48 #expect(editor.document.cards.count == 2)49 #expect(editor.removeCards([ids[1]]) == false)50 }5152 @Test func duplicateCopiesCardsAndInnerConnections() throws {53 var (editor, ids) = makeEditor(cards: 3)54 try editor.connect(from: ids[0], to: ids[1], label: "x")55 try editor.connect(from: ids[1], to: ids[2])56 let copies = try editor.duplicate([ids[0], ids[1]])57 #expect(copies.count == 2)58 #expect(editor.selection == Set(copies))59 #expect(editor.document.cards.count == 5)60 let first = try #require(editor.card(copies[0]))61 #expect(first.origin == CanvasPoint(x: 20, y: 20))62 #expect(first.zIndex > 2)63 #expect(editor.connection(from: copies[0], to: copies[1])?.label == "x")64 #expect(editor.document.connections.count == 3)65 #expect(editor.validate().isEmpty)66 editor.undo()67 #expect(editor.document.cards.count == 3 && editor.document.connections.count == 2)68 }6970 @Test func moveSnapsTheGroupRigidly() {71 var (editor, ids) = makeEditor(cards: 2)72 editor.setFrame(CanvasRect(x: 7, y: 3, width: 200, height: 100), of: ids[0])73 editor.setFrame(CanvasRect(x: 311, y: 55, width: 200, height: 100), of: ids[1])74 #expect(editor.move([ids[0], ids[1]], by: CanvasPoint(x: 8, y: 9)) == true)75 let a = editor.card(ids[0])!.origin, b = editor.card(ids[1])!.origin76 #expect(a == CanvasPoint(x: 20, y: 20))77 #expect(b.x - a.x == 304 && b.y - a.y == 52)78 #expect(editor.move([ids[0]], by: CanvasPoint(x: .nan, y: 0)) == false)79 #expect(editor.move([CanvasCardID()], by: CanvasPoint(x: 10, y: 10)) == false)80 }8182 @Test func aDragIsOneUndoStep() {83 var (editor, ids) = makeEditor(cards: 2)84 let start = editor.document85 let session = editor.beginDrag([ids[0]])86 for step in 1...30 { editor.updateDrag(session, translation: CanvasPoint(x: Double(step) * 7, y: Double(step) * 3)) }87 #expect(editor.card(ids[0])!.origin == CanvasPoint(x: 220, y: 100))88 #expect(editor.undoCount == 1)89 editor.undo()90 #expect(editor.document == start)91 // Returning to the starting point leaves nothing to undo.92 let second = editor.beginDrag([ids[1]])93 editor.updateDrag(second, translation: CanvasPoint(x: 100, y: 0))94 editor.updateDrag(second, translation: .zero)95 #expect(editor.undoCount == 0)96 #expect(editor.document == start)97 }9899 @Test func breakingCoalescingStartsANewUndoStep() {100 var (editor, ids) = makeEditor(cards: 1)101 editor.move([ids[0]], by: CanvasPoint(x: 20, y: 0), coalescingKey: "k")102 editor.move([ids[0]], by: CanvasPoint(x: 20, y: 0), coalescingKey: "k")103 #expect(editor.undoCount == 1)104 editor.breakUndoCoalescing()105 editor.move([ids[0]], by: CanvasPoint(x: 20, y: 0), coalescingKey: "k")106 #expect(editor.undoCount == 2)107 }108109 @Test func coordinatesAreClampedToTheLimit() {110 var (editor, ids) = makeEditor(cards: 2)111 editor.move([ids[0], ids[1]], by: CanvasPoint(x: 5e9, y: -5e9))112 let a = editor.card(ids[0])!.origin, b = editor.card(ids[1])!.origin113 #expect(b.x == 1_000_000 && a.x == 1_000_000 - 300)114 #expect(a.y == -1_000_000 && b.y == -1_000_000)115 #expect(editor.validate().isEmpty)116 }117118 @Test(arguments: CanvasHandle.allCases)119 func resizeRespectsMinimumSizeAndKeepsTheOppositeEdges(handle: CanvasHandle) {120 var (editor, ids) = makeEditor(cards: 1)121 let original = editor.card(ids[0])!.frame122 // Push every handle far towards the inside of the card.123 let inward = CanvasPoint(x: handle.movesLeft ? 5_000 : -5_000, y: handle.movesTop ? 5_000 : -5_000)124 editor.resize(ids[0], handle: handle, translation: inward)125 let frame = editor.card(ids[0])!.frame126 if handle.movesLeft || handle.movesRight { #expect(frame.width == 120) } else { #expect(frame.width == original.width) }127 if handle.movesTop || handle.movesBottom { #expect(frame.height == 80) } else { #expect(frame.height == original.height) }128 if !handle.movesLeft { #expect(frame.minX == original.minX) }129 if !handle.movesRight { #expect(frame.maxX == original.maxX) }130 if !handle.movesTop { #expect(frame.minY == original.minY) }131 if !handle.movesBottom { #expect(frame.maxY == original.maxY) }132 #expect(editor.validate().isEmpty)133 }134135 @Test func resizeSnapsTheMovingEdgeAndCoalescesAGesture() {136 var (editor, ids) = makeEditor(cards: 1)137 let start = editor.card(ids[0])!.frame138 for step in 1...10 {139 editor.resize(ids[0], handle: .bottomRight, translation: CanvasPoint(x: Double(step) * 5.5, y: Double(step) * 3.3),140 from: start, coalescingKey: "resize-1")141 }142 let frame = editor.card(ids[0])!.frame143 #expect(frame == CanvasRect(x: 0, y: 0, width: 260, height: 140))144 #expect(editor.undoCount == 1)145 editor.resize(ids[0], handle: .right, translation: CanvasPoint(x: 99_999, y: 0))146 #expect(editor.card(ids[0])!.size.width == 4_000)147 }148149 @Test func zOrderOperations() {150 var (editor, ids) = makeEditor(cards: 4)151 func order() -> [Int] { editor.cardsInZOrder.map { ids.firstIndex(of: $0.id)! } }152 #expect(order() == [0, 1, 2, 3])153 editor.bringToFront([ids[0]]); #expect(order() == [1, 2, 3, 0])154 editor.sendToBack([ids[3], ids[0]]); #expect(order() == [3, 0, 1, 2])155 editor.bringForward([ids[3]]); #expect(order() == [0, 3, 1, 2])156 editor.sendBackward([ids[2]]); #expect(order() == [0, 3, 2, 1])157 editor.bringForward([ids[1]]); #expect(order() == [0, 3, 2, 1])158 #expect(editor.bringToFront([ids[1]]) == false)159 editor.undo(); editor.undo(); editor.undo(); editor.undo()160 #expect(order() == [0, 1, 2, 3])161 // The array order of the document never changes with z-order.162 #expect(editor.document.cards.map(\.id) == ids)163 }164165 @Test func tintContentAndTitleAreUndoable() {166 var (editor, ids) = makeEditor(cards: 2)167 let start = editor.document168 #expect(editor.setTint(.ember, of: Set(ids)) == true)169 #expect(editor.setTint(.ember, of: Set(ids)) == false)170 #expect(editor.setContent(.page(url: URL(string: "https://example.org")!, title: "Example"), of: ids[0]) == true)171 #expect(editor.setTitle("Renamed") == true)172 #expect(editor.setTitle("Renamed again") == true)173 #expect(editor.document.cards.allSatisfy { $0.tint == .ember })174 #expect(editor.undoCount == 3)175 while editor.undo() {}176 #expect(editor.document == start)177 }178179 @Test func alignment() {180 var (editor, ids) = makeEditor(cards: 3)181 editor.setFrame(CanvasRect(x: 0, y: 0, width: 200, height: 100), of: ids[0])182 editor.setFrame(CanvasRect(x: 300, y: 50, width: 120, height: 200), of: ids[1])183 editor.setFrame(CanvasRect(x: 700, y: 400, width: 300, height: 80), of: ids[2])184 let all = Set(ids)185 func frames() -> [CanvasRect] { ids.map { editor.card($0)!.frame } }186 editor.align(all, .left); #expect(frames().allSatisfy { $0.minX == 0 }); editor.undo()187 editor.align(all, .right); #expect(frames().allSatisfy { $0.maxX == 1_000 }); editor.undo()188 editor.align(all, .horizontalCenter); #expect(frames().allSatisfy { $0.midX == 500 }); editor.undo()189 editor.align(all, .top); #expect(frames().allSatisfy { $0.minY == 0 }); editor.undo()190 editor.align(all, .bottom); #expect(frames().allSatisfy { $0.maxY == 480 }); editor.undo()191 editor.align(all, .verticalCenter); #expect(frames().allSatisfy { $0.midY == 240 }); editor.undo()192 #expect(editor.align([ids[0]], .left) == false)193 }194195 @Test func distributionEqualisesGapsAndKeepsTheOuterCards() {196 var (editor, ids) = makeEditor(cards: 4)197 let xs: [Double] = [0, 210, 480, 1_000]198 for (index, id) in ids.enumerated() { editor.setFrame(CanvasRect(x: xs[index], y: Double(index * index) * 60, width: 200 - Double(index) * 20, height: 100), of: id) }199 #expect(editor.distribute(Set(ids), .horizontal) == true)200 let frames = ids.map { editor.card($0)!.frame }201 #expect(frames[0].minX == 0 && frames[3].minX == 1_000)202 let gaps = (1..<4).map { frames[$0].minX - frames[$0 - 1].maxX }203 #expect(abs(gaps[0] - gaps[1]) < 1e-9 && abs(gaps[1] - gaps[2]) < 1e-9)204 #expect(editor.distribute(Set(ids), .vertical) == true)205 let vertical = ids.map { editor.card($0)!.frame }206 let verticalGaps = (1..<4).map { vertical[$0].minY - vertical[$0 - 1].maxY }207 #expect(abs(verticalGaps[0] - verticalGaps[1]) < 1e-9 && abs(verticalGaps[1] - verticalGaps[2]) < 1e-9)208 #expect(editor.distribute(Set(ids.prefix(2)), .horizontal) == false)209 }210211 @Test func connectionsRejectSelfLinksDuplicatesAndUnknownCards() throws {212 var (editor, ids) = makeEditor(cards: 2)213 try editor.connect(from: ids[0], to: ids[1], label: " cites ")214 #expect(editor.connection(from: ids[0], to: ids[1])?.label == "cites")215 #expect(throws: CanvasEditError.selfConnection) { try editor.connect(from: ids[0], to: ids[0]) }216 #expect(throws: CanvasEditError.duplicateConnection) { try editor.connect(from: ids[0], to: ids[1]) }217 let ghost = CanvasCardID()218 #expect(throws: CanvasEditError.unknownCard(ghost)) { try editor.connect(from: ids[0], to: ghost) }219 // The reverse direction is a different connection.220 try editor.connect(from: ids[1], to: ids[0])221 #expect(editor.relabel(from: ids[0], to: ids[1], label: String(repeating: "x", count: 500)) == true)222 #expect(editor.connection(from: ids[0], to: ids[1])?.label?.count == 200)223 #expect(editor.relabel(from: ids[0], to: ids[1], label: " ") == true)224 #expect(editor.connection(from: ids[0], to: ids[1])?.label == nil)225 #expect(editor.disconnect(from: ids[0], to: ids[1]) == true)226 #expect(editor.disconnect(from: ids[0], to: ids[1]) == false)227 #expect(editor.document.connections.count == 1)228 #expect(editor.validate().isEmpty)229 }230231 @Test func selectionByIdsAndMarquee() {232 var (editor, ids) = makeEditor(cards: 4)233 editor.select([ids[0], CanvasCardID()])234 #expect(editor.selection == [ids[0]])235 editor.select([ids[1]], mode: .add); #expect(editor.selection == [ids[0], ids[1]])236 editor.select([ids[1], ids[2]], mode: .toggle); #expect(editor.selection == [ids[0], ids[2]])237 // Cards are 200×100 at x = 0, 300, 600, 900.238 let touched = editor.select(in: CanvasRect(corner: CanvasPoint(x: 450, y: 50), corner: CanvasPoint(x: 150, y: -10)))239 #expect(touched == [ids[0], ids[1]])240 let inside = editor.select(in: CanvasRect(x: 150, y: -10, width: 700, height: 200), rule: .contains)241 #expect(inside == [ids[1], ids[2]])242 editor.select(in: CanvasRect(x: 5_000, y: 5_000, width: 10, height: 10))243 #expect(editor.selection.isEmpty)244 editor.selectAll(); #expect(editor.selection == Set(ids))245 editor.clearSelection(); #expect(editor.selection.isEmpty)246 #expect(editor.undoCount == 0)247 }248249 @Test func undoStackIsBoundedAndRedoIsClearedByANewEdit() {250 var configuration = CanvasConfiguration()251 configuration.undoLimit = 5252 var (editor, ids) = makeEditor(cards: 1, configuration: configuration)253 for step in 1...12 { editor.move([ids[0]], by: CanvasPoint(x: 20, y: 0)); #expect(editor.undoCount == min(step, 5)) }254 var undone = 0255 while editor.undo() { undone += 1 }256 #expect(undone == 5)257 #expect(editor.card(ids[0])!.origin.x == 140)258 #expect(editor.redoCount == 5)259 editor.redo()260 editor.move([ids[0]], by: CanvasPoint(x: 0, y: 20))261 #expect(!editor.canRedo)262 #expect(editor.undoName == "Move")263 }264265 @Test func revisionChangesWithContentOnly() {266 var (editor, ids) = makeEditor(cards: 2)267 let start = editor.revision268 editor.select([ids[0]]); editor.pan(byView: CanvasPoint(x: 10, y: 10))269 #expect(editor.revision == start)270 editor.move([ids[0]], by: CanvasPoint(x: 40, y: 0)); #expect(editor.revision == start + 1)271 editor.undo(); #expect(editor.revision == start + 2)272 }273}274275@Suite struct CanvasRandomisedInvariantTests {276 /// Applies random operations; after each one the document must be valid, and undoing everything must give277 /// back the initial document exactly (viewport aside, which is view state).278 @Test(arguments: [1, 2, 3, 4, 5, 6, 7, 8] as [UInt64])279 func randomOperationSequencesStayValidAndUndoAllRestoresTheStart(seed: UInt64) throws {280 var generator = SeededGenerator(seed: seed)281 var configuration = CanvasConfiguration()282 configuration.undoLimit = 10_000283 var (editor, _) = makeEditor(cards: 6, configuration: configuration)284 let initial = editor.document285 var snapshots: [CanvasDocument] = []286287 func pick(_ editor: CanvasEditor, _ generator: inout SeededGenerator, upTo count: Int = 3) -> Set<CanvasCardID> {288 Set(editor.document.cards.shuffled(using: &generator).prefix(Int.random(in: 0...count, using: &generator)).map(\.id))289 }290 for _ in 0..<400 {291 let undoBefore = editor.undoCount292 let before = editor.document293 switch Int.random(in: 0..<19, using: &generator) {294 case 0: _ = try? editor.addCard(note("n"), at: CanvasPoint(x: .random(in: -900...900, using: &generator), y: .random(in: -900...900, using: &generator)),295 size: CanvasSize(width: .random(in: 10...600, using: &generator), height: .random(in: 10...600, using: &generator)))296 case 1: editor.removeCards(pick(editor, &generator, upTo: 2))297 case 2: _ = try? editor.duplicate(pick(editor, &generator))298 case 3: editor.move(pick(editor, &generator), by: CanvasPoint(x: .random(in: -300...300, using: &generator), y: .random(in: -300...300, using: &generator)),299 snap: Bool.random(using: &generator))300 case 4:301 if let card = editor.document.cards.randomElement(using: &generator) {302 editor.resize(card.id, handle: CanvasHandle.allCases.randomElement(using: &generator)!,303 translation: CanvasPoint(x: .random(in: -500...500, using: &generator), y: .random(in: -500...500, using: &generator)))304 }305 case 5: editor.bringToFront(pick(editor, &generator))306 case 6: editor.sendToBack(pick(editor, &generator))307 case 7: editor.bringForward(pick(editor, &generator))308 case 8: editor.sendBackward(pick(editor, &generator))309 case 9: editor.setTint(SpaceTint.allCases.randomElement(using: &generator), of: pick(editor, &generator))310 case 10: editor.align(pick(editor, &generator, upTo: 4), CanvasAlignment.allCases.randomElement(using: &generator)!)311 case 11: editor.distribute(pick(editor, &generator, upTo: 5), CanvasDistribution.allCases.randomElement(using: &generator)!)312 case 12, 13:313 let cards = editor.document.cards.shuffled(using: &generator)314 if cards.count >= 2 { try? editor.connect(from: cards[0].id, to: cards[1].id, label: Bool.random(using: &generator) ? "l" : nil) }315 case 14:316 if let connection = editor.document.connections.randomElement(using: &generator) { editor.disconnect(from: connection.from, to: connection.to) }317 case 15:318 if let connection = editor.document.connections.randomElement(using: &generator) {319 editor.relabel(from: connection.from, to: connection.to, label: ["a", "b", nil].randomElement(using: &generator)!)320 }321 case 16: editor.setTitle("t\(Int.random(in: 0..<5, using: &generator))"); editor.breakUndoCoalescing()322 case 17:323 // Undo then redo must be the identity.324 if editor.undo() { let undone = editor.document; editor.redo(); #expect(editor.document == before); _ = undone }325 default:326 editor.select(pick(editor, &generator, upTo: 4), mode: .toggle)327 if let card = editor.document.cards.randomElement(using: &generator) { editor.setContent(note("edited"), of: card.id) }328 }329 #expect(editor.validate().isEmpty, "seed \(seed)")330 #expect(editor.selection.isSubset(of: Set(editor.document.cards.map(\.id))))331 if editor.undoCount == undoBefore + 1 { snapshots.append(before) }332 if editor.undoCount == undoBefore { #expect(editor.document == before || editor.canRedo, "a change must be undoable") }333 }334 // Walk back step by step: every undo returns the exact document that preceded the command.335 while let expected = snapshots.popLast() {336 #expect(editor.undo() == true)337 #expect(editor.document == expected, "seed \(seed)")338 }339 #expect(!editor.canUndo)340 #expect(editor.document == initial)341 // And redo-all replays to a valid document.342 while editor.redo() {}343 #expect(editor.validate().isEmpty)344 }345}346347@Suite struct CanvasViewportTests {348 let view = CanvasSize(width: 800, height: 600)349350 @Test func coordinateConversionRoundTrips() {351 var (editor, _) = makeEditor(cards: 1)352 editor.zoom(to: 2.5, around: CanvasPoint(x: 100, y: 450), viewSize: view)353 editor.pan(byView: CanvasPoint(x: -33, y: 71))354 for point in [CanvasPoint(x: 0, y: 0), CanvasPoint(x: 800, y: 600), CanvasPoint(x: 123.5, y: 456.25)] {355 let back = editor.viewPoint(fromCanvas: editor.canvasPoint(fromView: point, viewSize: view), viewSize: view)356 #expect(abs(back.x - point.x) < 1e-9 && abs(back.y - point.y) < 1e-9)357 }358 let visible = editor.visibleRect(viewSize: view)359 #expect(abs(visible.width - 320) < 1e-9 && abs(visible.height - 240) < 1e-9)360 #expect(editor.canvasPoint(fromView: .zero, viewSize: view).distance(to: visible.origin) < 1e-9)361 }362363 @Test func zoomKeepsTheAnchorFixedAndClampsTheScale() {364 var (editor, _) = makeEditor(cards: 1)365 let anchor = CanvasPoint(x: 650, y: 120)366 let fixed = editor.canvasPoint(fromView: anchor, viewSize: view)367 for scale in [0.5, 3.0, 1.2, 100, 0.0001, .nan] {368 editor.zoom(to: scale, around: anchor, viewSize: view)369 let now = editor.canvasPoint(fromView: anchor, viewSize: view)370 #expect(now.distance(to: fixed) < 1e-6)371 #expect(editor.document.viewport.scale >= 0.1 && editor.document.viewport.scale <= 4)372 }373 editor.zoom(to: 1, around: anchor, viewSize: view)374 editor.zoom(by: 2, around: anchor, viewSize: view)375 #expect(editor.document.viewport.scale == 2)376 }377378 @Test func panMovesByViewDistanceOverScale() {379 var (editor, _) = makeEditor(cards: 1)380 editor.zoom(to: 2, around: CanvasPoint(x: 400, y: 300), viewSize: view)381 editor.pan(byView: CanvasPoint(x: 100, y: -40))382 #expect(editor.document.viewport.center == CanvasPoint(x: -50, y: 20))383 editor.pan(byView: CanvasPoint(x: .infinity, y: 0))384 #expect(editor.document.viewport.center == CanvasPoint(x: -50, y: 20))385 editor.pan(byView: CanvasPoint(x: -1e12, y: 0))386 #expect(editor.document.viewport.center.x == 1_000_000)387 }388389 @Test func zoomToFitShowsEverythingAndNeverMagnifies() {390 var (editor, ids) = makeEditor(cards: 5) // spans x 0…1400, y 0…100391 editor.zoomToFit(viewSize: view, padding: 40)392 let visible = editor.visibleRect(viewSize: view)393 #expect(visible.contains(editor.bounds()!))394 #expect(abs(editor.document.viewport.scale - 720.0 / 1_400.0) < 1e-9)395 #expect(editor.document.viewport.center == CanvasPoint(x: 700, y: 50))396 editor.zoomToFit(viewSize: view, ids: [ids[0]])397 #expect(editor.document.viewport.scale == 1)398 var (empty, _) = makeEditor(cards: 0)399 empty.pan(byView: CanvasPoint(x: 50, y: 50))400 empty.zoomToFit(viewSize: view)401 #expect(empty.document.viewport == CanvasViewport())402 #expect(editor.undoCount == 0)403 }404}405406@Suite struct CanvasHitTestingAndRoutingTests {407 @Test func hitTestPrefersHandlesThenFrontCardsThenConnections() throws {408 var (editor, ids) = makeEditor(cards: 3)409 editor.setFrame(CanvasRect(x: 100, y: 0, width: 200, height: 100), of: ids[1]) // overlaps card 0 (0…200)410 #expect(editor.hitTest(CanvasPoint(x: 150, y: 50)) == .card(ids[1]))411 editor.bringToFront([ids[0]])412 #expect(editor.hitTest(CanvasPoint(x: 150, y: 50)) == .card(ids[0]))413 #expect(editor.hitTest(CanvasPoint(x: 50, y: 500)) == .empty)414 // Handles exist only for selected cards.415 #expect(editor.hitTest(CanvasPoint(x: 0, y: 0)) == .card(ids[0]))416 editor.select([ids[0]])417 #expect(editor.hitTest(CanvasPoint(x: 0, y: 0)) == .handle(card: ids[0], handle: .topLeft))418 #expect(editor.hitTest(CanvasPoint(x: 203, y: 53)) == .handle(card: ids[0], handle: .right))419 #expect(editor.hitTest(CanvasPoint(x: 100, y: -5)) == .handle(card: ids[0], handle: .top))420 #expect(editor.hitTest(CanvasPoint(x: 0, y: 0), includeHandles: false) == .card(ids[0]))421 // The hit area is constant on screen: zoomed out, a handle covers more canvas.422 editor.zoom(to: 0.25, around: .zero, viewSize: CanvasSize(width: 800, height: 600))423 #expect(editor.hitTest(CanvasPoint(x: -25, y: -25)) == .handle(card: ids[0], handle: .topLeft))424 editor.zoom(to: 1, around: .zero, viewSize: CanvasSize(width: 800, height: 600))425 // Connection between card 1 (right edge x=300) and card 2 (left edge x=600), both mid-height y=50.426 try editor.connect(from: ids[1], to: ids[2])427 #expect(editor.hitTest(CanvasPoint(x: 450, y: 52)) == .connection(CanvasConnection(from: ids[1], to: ids[2])))428 #expect(editor.hitTest(CanvasPoint(x: 450, y: 80)) == .empty)429 }430431 @Test func routesLeaveAndEnterThroughFacingEdges() {432 let connection = CanvasConnection(from: CanvasCardID(), to: CanvasCardID())433 let source = CanvasRect(x: 0, y: 0, width: 200, height: 100)434 let right = CanvasRouter.route(connection, from: source, to: CanvasRect(x: 600, y: 40, width: 200, height: 100))435 #expect(right.startEdge == .right && right.endEdge == .left)436 #expect(right.start == CanvasPoint(x: 200, y: 50) && right.end == CanvasPoint(x: 600, y: 90))437 #expect(right.control1 == CanvasPoint(x: 400, y: 50) && right.control2 == CanvasPoint(x: 400, y: 90))438 let left = CanvasRouter.route(connection, from: source, to: CanvasRect(x: -900, y: 0, width: 200, height: 100))439 #expect(left.startEdge == .left && left.endEdge == .right)440 #expect(left.control1.x == -300) // reach is capped at 300441 let below = CanvasRouter.route(connection, from: source, to: CanvasRect(x: 20, y: 500, width: 200, height: 100))442 #expect(below.startEdge == .bottom && below.endEdge == .top)443 let above = CanvasRouter.route(connection, from: source, to: CanvasRect(x: 20, y: -130, width: 200, height: 100))444 #expect(above.startEdge == .top && above.endEdge == .bottom)445 #expect(above.control1 == CanvasPoint(x: 100, y: -40)) // minimum reach 40446 // The curve starts and ends on its anchors and stays inside its bounds.447 #expect(right.point(at: 0) == right.start && right.point(at: 1) == right.end)448 #expect(right.polyline(segments: 16).count == 17)449 #expect(right.polyline().allSatisfy { right.bounds.insetBy(dx: -1e-9, dy: -1e-9).contains($0) })450 #expect(right.labelPoint == CanvasPoint(x: 400, y: 70))451 #expect(right.distance(to: right.labelPoint) < 1e-9)452 }453454 @Test func segmentDistance() {455 let a = CanvasPoint(x: 0, y: 0), b = CanvasPoint(x: 10, y: 0)456 #expect(CanvasRouter.distance(from: CanvasPoint(x: 5, y: 3), toSegment: a, b) == 3)457 #expect(CanvasRouter.distance(from: CanvasPoint(x: -4, y: 3), toSegment: a, b) == 5)458 #expect(CanvasRouter.distance(from: CanvasPoint(x: 3, y: 4), toSegment: a, a) == 5)459 }460461 @Test func rectGeometry() {462 let rect = CanvasRect(x: 10, y: 20, width: 100, height: 50)463 #expect(rect.contains(CanvasPoint(x: 110, y: 70)) && !rect.contains(CanvasPoint(x: 110.1, y: 70)))464 #expect(rect.intersects(CanvasRect(x: 110, y: 70, width: 5, height: 5)))465 #expect(!rect.intersects(CanvasRect(x: 111, y: 20, width: 5, height: 5)))466 #expect(rect.union(CanvasRect(x: 0, y: 0, width: 5, height: 5)) == CanvasRect(x: 0, y: 0, width: 110, height: 70))467 #expect(rect.insetBy(dx: 10, dy: 100) == CanvasRect(x: 20, y: 45, width: 80, height: 0))468 #expect(CanvasRect.bounding([CanvasRect]()) == nil)469 #expect(rect.center == CanvasPoint(x: 60, y: 45))470 }471}472473@Suite struct CanvasCullingTests {474 static func grid(_ count: Int, seed: UInt64) -> [CanvasCard] {475 var generator = SeededGenerator(seed: seed)476 return (0..<count).map { index in477 CanvasCard(content: .note(text: "c\(index)"),478 origin: CanvasPoint(x: .random(in: -20_000...20_000, using: &generator), y: .random(in: -20_000...20_000, using: &generator)),479 size: CanvasSize(width: .random(in: 120...600, using: &generator), height: .random(in: 80...500, using: &generator)),480 zIndex: Int.random(in: 0..<50, using: &generator))481 }482 }483484 @Test func indexAgreesWithTheLinearScan() {485 var cards = Self.grid(1_500, seed: 11)486 // One enormous card and one far away, to exercise the oversized list.487 cards.append(CanvasCard(content: .note(text: "huge"), origin: CanvasPoint(x: -30_000, y: -30_000), size: CanvasSize(width: 60_000, height: 60_000)))488 cards.append(CanvasCard(content: .note(text: "far"), origin: CanvasPoint(x: 900_000, y: 900_000)))489 let editor = CanvasEditor(document: CanvasDocument(title: "big", cards: cards))490 let index = editor.makeSpatialIndex()491 #expect(index.count == cards.count)492 var generator = SeededGenerator(seed: 12)493 var rects = (0..<60).map { _ in494 CanvasRect(x: .random(in: -22_000...22_000, using: &generator), y: .random(in: -22_000...22_000, using: &generator),495 width: .random(in: 1...6_000, using: &generator), height: .random(in: 1...6_000, using: &generator))496 }497 rects.append(CanvasRect(x: -2_000_000, y: -2_000_000, width: 4_000_000, height: 4_000_000))498 rects.append(CanvasRect(x: 5e8, y: 5e8, width: 10, height: 10))499 for rect in rects {500 let linear = editor.visibleCards(in: rect)501 #expect(editor.visibleCards(in: rect, index: index) == linear)502 #expect(Set(index.ids(intersecting: rect)) == Set(linear.map(\.id)))503 }504 #expect(editor.visibleCards(in: rects[rects.count - 2]).count == cards.count)505 }506507 @Test func visibleCardsAreBackToFrontAndVisibleRoutesAreCulled() throws {508 var (editor, ids) = makeEditor(cards: 4)509 editor.bringToFront([ids[0]])510 let visible = editor.visibleCards(in: CanvasRect(x: -10, y: -10, width: 520, height: 200))511 #expect(visible.map(\.id) == [ids[1], ids[0]])512 try editor.connect(from: ids[0], to: ids[1])513 try editor.connect(from: ids[2], to: ids[3])514 #expect(editor.visibleRoutes(in: CanvasRect(x: 0, y: 0, width: 320, height: 100)).map(\.connection.from) == [ids[0]])515 #expect(editor.routes().count == 2)516 }517518 @Test func benchmarkFiveThousandCards() {519 let cards = Self.grid(5_000, seed: 21)520 let editor = CanvasEditor(document: CanvasDocument(title: "benchmark", cards: cards))521 let viewport = CanvasRect(x: -960, y: -540, width: 1_920, height: 1_080)522 let clock = ContinuousClock()523 var count = 0524 let iterations = 200525 let linear = clock.measure { for _ in 0..<iterations { count = editor.visibleCards(in: viewport).count } }526 var index = editor.makeSpatialIndex()527 let build = clock.measure { for _ in 0..<20 { index = editor.makeSpatialIndex() } }528 var indexedCount = 0529 let indexed = clock.measure { for _ in 0..<iterations { indexedCount = editor.visibleCards(in: viewport, index: index).count } }530 #expect(count == indexedCount)531 func micros(_ duration: Duration, _ runs: Int) -> Double {532 Double(duration.components.seconds) * 1e6 / Double(runs) + Double(duration.components.attoseconds) / 1e12 / Double(runs)533 }534 print("[benchmark] canvas culling, 5000 cards, viewport 1920x1080 → \(count) visible: linear scan \(String(format: "%.1f", micros(linear, iterations))) µs, "535 + "grid index query \(String(format: "%.1f", micros(indexed, iterations))) µs, index build \(String(format: "%.1f", micros(build, 20))) µs")536 var editable = editor537 let id = cards[0].id538 let move = clock.measure { for step in 0..<iterations { editable.move([id], by: CanvasPoint(x: step % 2 == 0 ? 20 : -20, y: 0)) } }539 print("[benchmark] canvas edit, 5000 cards: one undoable move \(String(format: "%.1f", micros(move, iterations))) µs")540 #expect(micros(linear, iterations) < 50_000)541 }542}543