Repository Public License
1// CanvasEngine — the editing model of a canvas: every operation, undo/redo, selection, viewport, hit-testing.2import Foundation3import NavigatorCore45/// Tunable limits of the editor. The defaults are what the app ships with.6public struct CanvasConfiguration: Hashable, Sendable {7 /// Grid pitch in canvas units; origins and resized edges snap to multiples of it.8 public var gridSize: Double = 209 public var snapsToGrid: Bool = true10 public var minimumCardSize = CanvasSize(width: 120, height: 80)11 public var maximumCardSize = CanvasSize(width: 4_000, height: 4_000)12 public var minimumScale: Double = 0.113 public var maximumScale: Double = 414 /// Number of undoable commands kept; older ones are dropped.15 public var undoLimit: Int = 20016 public var maximumCards: Int = 20_00017 public var maximumConnections: Int = 50_00018 /// Coordinates are clamped to ±this value so geometry stays finite and exactly representable.19 public var coordinateLimit: Double = 1_000_00020 /// Side of a resize handle's hit area, in view points (divided by the scale when hit-testing).21 public var handleHitSize: Double = 1422 /// How close, in view points, a point must be to a connection to hit it.23 public var connectionHitTolerance: Double = 624 public var maximumLabelLength: Int = 2002526 public init() {}27}2829public enum CanvasEditError: Error, Sendable, Equatable, CustomStringConvertible {30 case unknownCard(CanvasCardID)31 case selfConnection32 case duplicateConnection33 case cardLimitReached(Int)34 case connectionLimitReached(Int)35 case invalidGeometry3637 public var description: String {38 switch self {39 case .unknownCard(let id): return "No card \(id) on this canvas."40 case .selfConnection: return "A card cannot be connected to itself."41 case .duplicateConnection: return "These two cards are already connected in that direction."42 case .cardLimitReached(let limit): return "A canvas holds at most \(limit) cards."43 case .connectionLimitReached(let limit): return "A canvas holds at most \(limit) connections."44 case .invalidGeometry: return "The position or size is not a finite number."45 }46 }47}4849/// A broken invariant found by `CanvasEditor.validate`.50public enum CanvasValidationIssue: Hashable, Sendable {51 case duplicateCardID(CanvasCardID)52 case nonFiniteGeometry(CanvasCardID)53 case sizeOutOfBounds(CanvasCardID)54 case danglingConnection(CanvasConnection)55 case selfConnection(CanvasCardID)56 case duplicateConnection(CanvasConnection)57 case invalidViewport58 case unsafeAttachmentPath(CanvasCardID)59}6061public enum CanvasAlignment: String, Sendable, CaseIterable {62 case left, horizontalCenter, right, top, verticalCenter, bottom63}6465public enum CanvasDistribution: String, Sendable, CaseIterable { case horizontal, vertical }6667public enum CanvasSelectionMode: Sendable { case replace, add, toggle }6869public enum CanvasMarqueeRule: Sendable {70 /// Any card the rectangle touches.71 case intersects72 /// Only cards entirely inside the rectangle.73 case contains74}7576/// What is under a point, front-most first.77public enum CanvasHit: Hashable, Sendable {78 case handle(card: CanvasCardID, handle: CanvasHandle)79 case card(CanvasCardID)80 case connection(CanvasConnection)81 case empty82}8384/// A drag in progress: the cards being moved and where they were when the gesture began. Every update of the85/// same session is folded into one undo step.86public struct CanvasDragSession: Sendable, Hashable {87 public let key: String88 public let origins: [CanvasCardID: CanvasPoint]89}9091/// A value-type editor over one `CanvasDocument`.92///93/// Every mutation of cards, connections or the title goes through one commit path that records an invertible94/// delta, so undo and redo restore the document exactly (including the order of `cards`). The viewport and the95/// selection are view state: they are not undoable, but undo restores the selection that was active.96/// `updatedAt` is not touched here (the editor has no clock); `CanvasAutosaver` stamps it when saving.97public struct CanvasEditor: Sendable {98 public private(set) var document: CanvasDocument99 public private(set) var selection: Set<CanvasCardID> = []100 public let configuration: CanvasConfiguration101 /// Bumped on every change of cards or connections; lets the UI cache a `CanvasSpatialIndex` per revision.102 public private(set) var revision: Int = 0103104 private var undoStack: [Command] = []105 private var redoStack: [Command] = []106107 public init(document: CanvasDocument, configuration: CanvasConfiguration = CanvasConfiguration()) {108 self.document = document109 self.configuration = configuration110 }111112 // MARK: - Undo machinery113114 /// What one command changed. `removed` indices refer to the array before the command, `inserted` indices to115 /// the array after it; applying them in ascending order rebuilds either array exactly.116 private struct Delta: Sendable {117 var removed: [(index: Int, card: CanvasCard)] = []118 var inserted: [(index: Int, card: CanvasCard)] = []119 var modified: [(before: CanvasCard, after: CanvasCard)] = []120 var connections: (before: [CanvasConnection], after: [CanvasConnection])?121 var title: (before: String, after: String)?122123 var isEmpty: Bool {124 removed.isEmpty && inserted.isEmpty && modified.isEmpty && connections == nil && title == nil125 }126 var isPureModification: Bool { removed.isEmpty && inserted.isEmpty && connections == nil && title == nil }127 var isTitleOnly: Bool { removed.isEmpty && inserted.isEmpty && modified.isEmpty && connections == nil && title != nil }128 }129130 private struct Command: Sendable {131 var name: String132 var delta: Delta133 var selectionBefore: Set<CanvasCardID>134 var selectionAfter: Set<CanvasCardID>135 var coalescingKey: String?136 }137138 public var canUndo: Bool { !undoStack.isEmpty }139 public var canRedo: Bool { !redoStack.isEmpty }140 public var undoCount: Int { undoStack.count }141 public var redoCount: Int { redoStack.count }142 /// Name of the command `undo()` would revert ("Move", "Delete"…), for the Edit menu.143 public var undoName: String? { undoStack.last?.name }144 public var redoName: String? { redoStack.last?.name }145146 private static func diff(_ before: CanvasDocument, _ after: CanvasDocument) -> Delta {147 var delta = Delta()148 if before.title != after.title { delta.title = (before.title, after.title) }149 if before.connections != after.connections { delta.connections = (before.connections, after.connections) }150 if before.cards.count == after.cards.count,151 zip(before.cards, after.cards).allSatisfy({ $0.id == $1.id }) {152 // Fast path (moves, resizes, tints…): same cards in the same slots, compare slot by slot.153 for (old, new) in zip(before.cards, after.cards) where old != new { delta.modified.append((old, new)) }154 } else if before.cards != after.cards {155 var afterIndex: [CanvasCardID: Int] = [:]156 afterIndex.reserveCapacity(after.cards.count)157 for (index, card) in after.cards.enumerated() { afterIndex[card.id] = index }158 var kept = Set<CanvasCardID>()159 for (index, card) in before.cards.enumerated() {160 if let position = afterIndex[card.id] {161 kept.insert(card.id)162 if after.cards[position] != card { delta.modified.append((card, after.cards[position])) }163 } else {164 delta.removed.append((index, card))165 }166 }167 if kept.count != after.cards.count {168 for (index, card) in after.cards.enumerated() where !kept.contains(card.id) {169 delta.inserted.append((index, card))170 }171 }172 }173 return delta174 }175176 private mutating func apply(_ delta: Delta, forward: Bool) {177 let leaving = forward ? delta.removed : delta.inserted178 let arriving = forward ? delta.inserted : delta.removed179 if !leaving.isEmpty {180 let ids = Set(leaving.map(\.card.id))181 document.cards.removeAll { ids.contains($0.id) }182 }183 if !delta.modified.isEmpty {184 var replacements: [CanvasCardID: CanvasCard] = [:]185 for change in delta.modified { replacements[change.before.id] = forward ? change.after : change.before }186 for index in document.cards.indices {187 if let card = replacements[document.cards[index].id] { document.cards[index] = card }188 }189 }190 for entry in arriving { document.cards.insert(entry.card, at: min(entry.index, document.cards.count)) }191 if let connections = delta.connections { document.connections = forward ? connections.after : connections.before }192 if let title = delta.title { document.title = forward ? title.after : title.before }193 revision += 1194 }195196 /// Runs an edit on a copy of the document, records what changed and pushes it on the undo stack.197 /// Returns `false` (and records nothing) when the edit changed nothing.198 @discardableResult199 private mutating func commit(_ name: String, coalescingKey: String? = nil,200 selection newSelection: Set<CanvasCardID>? = nil,201 _ edit: (inout CanvasDocument) -> Void) -> Bool {202 var draft = document203 edit(&draft)204 if draft.cards.count != document.cards.count {205 // Connections never outlive their cards.206 let ids = Set(draft.cards.map(\.id))207 draft.connections.removeAll { !ids.contains($0.from) || !ids.contains($0.to) }208 }209 var delta = Self.diff(document, draft)210 guard !delta.isEmpty else {211 if let newSelection { selection = newSelection }212 return false213 }214 let selectionBefore = selection215 document = draft216 revision += 1217 if let newSelection {218 selection = newSelection.intersection(Set(document.cards.map(\.id)))219 } else if !delta.removed.isEmpty {220 selection.subtract(delta.removed.map(\.card.id))221 }222 redoStack.removeAll()223 if let coalescingKey, delta.isTitleOnly, let last = undoStack.last, last.coalescingKey == coalescingKey,224 last.delta.isTitleOnly, let original = last.delta.title?.before {225 // Typing a title: one undo step from the first keystroke to the last.226 undoStack.removeLast()227 if original == document.title { return true }228 delta.title = (original, document.title)229 undoStack.append(Command(name: name, delta: delta, selectionBefore: last.selectionBefore,230 selectionAfter: selection, coalescingKey: coalescingKey))231 return true232 }233 if let coalescingKey, delta.isPureModification, let last = undoStack.last, last.coalescingKey == coalescingKey,234 last.delta.isPureModification,235 Set(last.delta.modified.map(\.before.id)) == Set(delta.modified.map(\.before.id)) {236 // Same gesture touching the same cards: keep the original "before", take the newest "after".237 let originals = Dictionary(uniqueKeysWithValues: last.delta.modified.map { ($0.before.id, $0.before) })238 delta.modified = delta.modified.compactMap { change in239 guard let original = originals[change.before.id], original != change.after else { return nil }240 return (original, change.after)241 }242 undoStack.removeLast()243 if delta.isEmpty { return true }244 undoStack.append(Command(name: name, delta: delta, selectionBefore: last.selectionBefore,245 selectionAfter: selection, coalescingKey: coalescingKey))246 return true247 }248 undoStack.append(Command(name: name, delta: delta, selectionBefore: selectionBefore,249 selectionAfter: selection, coalescingKey: coalescingKey))250 if undoStack.count > max(1, configuration.undoLimit) {251 undoStack.removeFirst(undoStack.count - max(1, configuration.undoLimit))252 }253 return true254 }255256 @discardableResult257 public mutating func undo() -> Bool {258 guard let command = undoStack.popLast() else { return false }259 apply(command.delta, forward: false)260 selection = command.selectionBefore261 redoStack.append(command)262 return true263 }264265 @discardableResult266 public mutating func redo() -> Bool {267 guard let command = redoStack.popLast() else { return false }268 apply(command.delta, forward: true)269 selection = command.selectionAfter270 undoStack.append(command)271 return true272 }273274 /// Ends any gesture coalescing: the next edit starts a new undo step even with the same key.275 public mutating func breakUndoCoalescing() {276 if !undoStack.isEmpty { undoStack[undoStack.count - 1].coalescingKey = nil }277 }278279 // MARK: - Geometry helpers280281 public func snapped(_ value: Double) -> Double {282 guard configuration.snapsToGrid, configuration.gridSize > 0 else { return value }283 return (value / configuration.gridSize).rounded() * configuration.gridSize284 }285286 private func clampCoordinate(_ value: Double) -> Double {287 min(max(value, -configuration.coordinateLimit), configuration.coordinateLimit)288 }289290 private func clampedSize(_ size: CanvasSize) -> CanvasSize {291 CanvasSize(width: min(max(size.width, configuration.minimumCardSize.width), configuration.maximumCardSize.width),292 height: min(max(size.height, configuration.minimumCardSize.height), configuration.maximumCardSize.height))293 }294295 private func placed(_ point: CanvasPoint, snap: Bool) -> CanvasPoint {296 CanvasPoint(x: clampCoordinate(snap ? snapped(point.x) : point.x),297 y: clampCoordinate(snap ? snapped(point.y) : point.y))298 }299300 public func card(_ id: CanvasCardID) -> CanvasCard? { document.cards.first { $0.id == id } }301302 /// Cards from back to front: by `zIndex`, then by position in the document for equal indices.303 public var cardsInZOrder: [CanvasCard] {304 document.cards.enumerated().sorted { ($0.element.zIndex, $0.offset) < ($1.element.zIndex, $1.offset) }.map(\.element)305 }306307 /// Bounding box of the given cards (all cards when `ids` is nil); `nil` when there is none.308 public func bounds(of ids: Set<CanvasCardID>? = nil) -> CanvasRect? {309 CanvasRect.bounding(document.cards.lazy.filter { ids?.contains($0.id) ?? true }.map(\.frame))310 }311312 // MARK: - Cards313314 /// Adds a card at `origin` (snapped) on top of the others and selects it.315 @discardableResult316 public mutating func addCard(_ content: CanvasCard.Content, at origin: CanvasPoint, size: CanvasSize? = nil,317 tint: SpaceTint? = nil, id: CanvasCardID = CanvasCardID()) throws -> CanvasCardID {318 let size = size ?? CanvasSize(width: 260, height: 180)319 guard origin.isFinite, size.width.isFinite, size.height.isFinite else { throw CanvasEditError.invalidGeometry }320 guard document.cards.count < configuration.maximumCards else {321 throw CanvasEditError.cardLimitReached(configuration.maximumCards)322 }323 guard card(id) == nil else { throw CanvasEditError.invalidGeometry }324 let top = (document.cards.map(\.zIndex).max() ?? -1) + 1325 let card = CanvasCard(id: id, content: content, origin: placed(origin, snap: true), size: clampedSize(size),326 tint: tint, zIndex: top)327 commit("Add Card", selection: [id]) { $0.cards.append(card) }328 return id329 }330331 /// Removes cards together with every connection that touches them.332 @discardableResult333 public mutating func removeCards(_ ids: Set<CanvasCardID>) -> Bool {334 guard !ids.isEmpty else { return false }335 return commit("Delete", selection: selection.subtracting(ids)) { draft in336 draft.cards.removeAll { ids.contains($0.id) }337 }338 }339340 @discardableResult341 public mutating func removeSelection() -> Bool { removeCards(selection) }342343 /// Copies cards (and the connections between them) at an offset, on top, and selects the copies.344 /// Returns the new ids in the order of the originals in the document.345 @discardableResult346 public mutating func duplicate(_ ids: Set<CanvasCardID>, offset: CanvasPoint = CanvasPoint(x: 20, y: 20)) throws -> [CanvasCardID] {347 let originals = cardsInZOrder.filter { ids.contains($0.id) }348 guard !originals.isEmpty else { return [] }349 guard document.cards.count + originals.count <= configuration.maximumCards else {350 throw CanvasEditError.cardLimitReached(configuration.maximumCards)351 }352 var top = (document.cards.map(\.zIndex).max() ?? -1)353 var mapping: [CanvasCardID: CanvasCardID] = [:]354 var copies: [CanvasCard] = []355 for original in originals {356 top += 1357 var copy = original358 copy.id = CanvasCardID()359 copy.origin = placed(original.origin.translated(dx: offset.x, dy: offset.y), snap: false)360 copy.zIndex = top361 mapping[original.id] = copy.id362 copies.append(copy)363 }364 let links = document.connections.compactMap { connection -> CanvasConnection? in365 guard let from = mapping[connection.from], let to = mapping[connection.to] else { return nil }366 return CanvasConnection(from: from, to: to, label: connection.label)367 }368 let room = max(0, configuration.maximumConnections - document.connections.count)369 commit("Duplicate", selection: Set(copies.map(\.id))) { draft in370 draft.cards.append(contentsOf: copies)371 draft.connections.append(contentsOf: links.prefix(room))372 }373 let order = Dictionary(uniqueKeysWithValues: document.cards.enumerated().map { ($0.element.id, $0.offset) })374 return copies.map(\.id).sorted { (order[$0] ?? 0) < (order[$1] ?? 0) }375 }376377 /// Replaces the content of a card (editing a note, retargeting a page card, turning a PDF page).378 @discardableResult379 public mutating func setContent(_ content: CanvasCard.Content, of id: CanvasCardID, coalescingKey: String? = nil) -> Bool {380 commit("Edit Card", coalescingKey: coalescingKey) { draft in381 if let index = draft.cards.firstIndex(where: { $0.id == id }) { draft.cards[index].content = content }382 }383 }384385 @discardableResult386 public mutating func setTint(_ tint: SpaceTint?, of ids: Set<CanvasCardID>) -> Bool {387 commit("Change Colour") { draft in388 for index in draft.cards.indices where ids.contains(draft.cards[index].id) { draft.cards[index].tint = tint }389 }390 }391392 @discardableResult393 public mutating func setTitle(_ title: String) -> Bool {394 commit("Rename Canvas", coalescingKey: "title") { $0.title = title }395 }396397 // MARK: - Moving and resizing398399 /// Moves cards by a delta. With snapping, the group's top-left corner lands on the grid and every card400 /// receives the same translation, so the layout of a group never deforms.401 @discardableResult402 public mutating func move(_ ids: Set<CanvasCardID>, by delta: CanvasPoint, snap: Bool = true,403 coalescingKey: String? = nil) -> Bool {404 guard delta.isFinite else { return false }405 var origins: [CanvasCardID: CanvasPoint] = [:]406 for card in document.cards where ids.contains(card.id) { origins[card.id] = card.origin }407 return place(origins: origins, translation: delta, snap: snap, coalescingKey: coalescingKey)408 }409410 /// Starts a drag of the given cards (typically the selection).411 public func beginDrag(_ ids: Set<CanvasCardID>) -> CanvasDragSession {412 var origins: [CanvasCardID: CanvasPoint] = [:]413 for card in document.cards where ids.contains(card.id) { origins[card.id] = card.origin }414 return CanvasDragSession(key: "drag-\(UUID().uuidString)", origins: origins)415 }416417 /// Positions the dragged cards at their starting origins plus `translation` (the total translation since418 /// the gesture began, in canvas units). All updates of one session are one undo step.419 @discardableResult420 public mutating func updateDrag(_ session: CanvasDragSession, translation: CanvasPoint, snap: Bool = true) -> Bool {421 guard translation.isFinite else { return false }422 return place(origins: session.origins, translation: translation, snap: snap, coalescingKey: session.key)423 }424425 private mutating func place(origins: [CanvasCardID: CanvasPoint], translation: CanvasPoint, snap: Bool,426 coalescingKey: String?) -> Bool {427 guard !origins.isEmpty else { return false }428 var dx = translation.x, dy = translation.y429 if snap, configuration.snapsToGrid, let anchorX = origins.values.map(\.x).min(), let anchorY = origins.values.map(\.y).min() {430 dx = snapped(anchorX + dx) - anchorX431 dy = snapped(anchorY + dy) - anchorY432 }433 // Clamp the translation as a whole so the group stays rigid at the coordinate limit.434 let limit = configuration.coordinateLimit435 let xs = origins.values.map(\.x), ys = origins.values.map(\.y)436 dx = min(max(dx, -limit - (xs.min() ?? 0)), limit - (xs.max() ?? 0))437 dy = min(max(dy, -limit - (ys.min() ?? 0)), limit - (ys.max() ?? 0))438 return commit("Move", coalescingKey: coalescingKey) { draft in439 for index in draft.cards.indices {440 if let origin = origins[draft.cards[index].id] {441 draft.cards[index].origin = CanvasPoint(x: origin.x + dx, y: origin.y + dy)442 }443 }444 }445 }446447 /// The frame a resize would produce: the dragged edges follow `translation` (snapped), the opposite edges448 /// stay put, and the size is held within the configured minimum and maximum.449 public func resizedFrame(from frame: CanvasRect, handle: CanvasHandle, translation: CanvasPoint, snap: Bool = true) -> CanvasRect {450 var minX = frame.minX, maxX = frame.maxX, minY = frame.minY, maxY = frame.maxY451 let minimum = configuration.minimumCardSize, maximum = configuration.maximumCardSize452 func edge(_ value: Double) -> Double { clampCoordinate(snap ? snapped(value) : value) }453 if handle.movesLeft { minX = min(max(edge(minX + translation.x), maxX - maximum.width), maxX - minimum.width) }454 if handle.movesRight { maxX = max(min(edge(maxX + translation.x), minX + maximum.width), minX + minimum.width) }455 if handle.movesTop { minY = min(max(edge(minY + translation.y), maxY - maximum.height), maxY - minimum.height) }456 if handle.movesBottom { maxY = max(min(edge(maxY + translation.y), minY + maximum.height), minY + minimum.height) }457 return CanvasRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)458 }459460 /// Resizes a card by dragging one of its handles. `from` is the frame when the gesture began (defaults to461 /// the current frame for a one-shot resize); pass the same `coalescingKey` for every update of a gesture.462 @discardableResult463 public mutating func resize(_ id: CanvasCardID, handle: CanvasHandle, translation: CanvasPoint,464 from start: CanvasRect? = nil, snap: Bool = true, coalescingKey: String? = nil) -> Bool {465 guard translation.isFinite, let current = card(id) else { return false }466 let frame = resizedFrame(from: start ?? current.frame, handle: handle, translation: translation, snap: snap)467 return setFrame(frame, of: id, name: "Resize", coalescingKey: coalescingKey)468 }469470 /// Sets a card's frame directly (size clamped to the limits, no snapping).471 @discardableResult472 public mutating func setFrame(_ frame: CanvasRect, of id: CanvasCardID, coalescingKey: String? = nil) -> Bool {473 setFrame(frame, of: id, name: "Resize", coalescingKey: coalescingKey)474 }475476 private mutating func setFrame(_ frame: CanvasRect, of id: CanvasCardID, name: String, coalescingKey: String?) -> Bool {477 guard frame.origin.isFinite, frame.size.width.isFinite, frame.size.height.isFinite else { return false }478 let size = clampedSize(frame.size), origin = placed(frame.origin, snap: false)479 return commit(name, coalescingKey: coalescingKey) { draft in480 if let index = draft.cards.firstIndex(where: { $0.id == id }) {481 draft.cards[index].origin = origin482 draft.cards[index].size = size483 }484 }485 }486487 // MARK: - Z-order488489 private mutating func reorder(_ name: String, _ transform: ([CanvasCardID]) -> [CanvasCardID]) -> Bool {490 let order = transform(cardsInZOrder.map(\.id))491 var rank: [CanvasCardID: Int] = [:]492 for (index, id) in order.enumerated() { rank[id] = index }493 return commit(name) { draft in494 for index in draft.cards.indices { draft.cards[index].zIndex = rank[draft.cards[index].id] ?? draft.cards[index].zIndex }495 }496 }497498 @discardableResult499 public mutating func bringToFront(_ ids: Set<CanvasCardID>) -> Bool {500 reorder("Bring to Front") { order in order.filter { !ids.contains($0) } + order.filter(ids.contains) }501 }502503 @discardableResult504 public mutating func sendToBack(_ ids: Set<CanvasCardID>) -> Bool {505 reorder("Send to Back") { order in order.filter(ids.contains) + order.filter { !ids.contains($0) } }506 }507508 /// Moves each given card one step towards the front, keeping the given cards in their relative order.509 @discardableResult510 public mutating func bringForward(_ ids: Set<CanvasCardID>) -> Bool {511 reorder("Bring Forward") { order in512 var order = order513 var index = order.count - 2514 while index >= 0 {515 if ids.contains(order[index]), !ids.contains(order[index + 1]) { order.swapAt(index, index + 1) }516 index -= 1517 }518 return order519 }520 }521522 @discardableResult523 public mutating func sendBackward(_ ids: Set<CanvasCardID>) -> Bool {524 reorder("Send Backward") { order in525 var order = order526 for index in order.indices.dropFirst() where ids.contains(order[index]) && !ids.contains(order[index - 1]) {527 order.swapAt(index, index - 1)528 }529 return order530 }531 }532533 // MARK: - Alignment and distribution534535 /// Aligns the cards on one edge or centre line of their common bounding box. Needs at least two cards.536 @discardableResult537 public mutating func align(_ ids: Set<CanvasCardID>, _ alignment: CanvasAlignment) -> Bool {538 let cards = document.cards.filter { ids.contains($0.id) }539 guard cards.count >= 2, let box = CanvasRect.bounding(cards.map(\.frame)) else { return false }540 return commit("Align") { draft in541 for index in draft.cards.indices where ids.contains(draft.cards[index].id) {542 let frame = draft.cards[index].frame543 switch alignment {544 case .left: draft.cards[index].origin.x = box.minX545 case .horizontalCenter: draft.cards[index].origin.x = box.midX - frame.width / 2546 case .right: draft.cards[index].origin.x = box.maxX - frame.width547 case .top: draft.cards[index].origin.y = box.minY548 case .verticalCenter: draft.cards[index].origin.y = box.midY - frame.height / 2549 case .bottom: draft.cards[index].origin.y = box.maxY - frame.height550 }551 }552 }553 }554555 /// Spaces the cards so the gaps between neighbours are equal; the two outermost cards do not move.556 /// Needs at least three cards.557 @discardableResult558 public mutating func distribute(_ ids: Set<CanvasCardID>, _ axis: CanvasDistribution) -> Bool {559 let horizontal = axis == .horizontal560 let cards = document.cards.filter { ids.contains($0.id) }.sorted {561 horizontal ? ($0.frame.minX, $0.id) < ($1.frame.minX, $1.id) : ($0.frame.minY, $0.id) < ($1.frame.minY, $1.id)562 }563 guard cards.count >= 3, let first = cards.first, let last = cards.last else { return false }564 let extent = horizontal ? last.frame.maxX - first.frame.minX : last.frame.maxY - first.frame.minY565 let occupied = cards.reduce(0) { $0 + (horizontal ? $1.size.width : $1.size.height) }566 let gap = (extent - occupied) / Double(cards.count - 1)567 var positions: [CanvasCardID: Double] = [:]568 var cursor = horizontal ? first.frame.minX : first.frame.minY569 for card in cards {570 positions[card.id] = cursor571 cursor += (horizontal ? card.size.width : card.size.height) + gap572 }573 // The last card keeps its exact position (no accumulated rounding).574 positions[last.id] = horizontal ? last.origin.x : last.origin.y575 return commit("Distribute") { draft in576 for index in draft.cards.indices {577 guard let position = positions[draft.cards[index].id] else { continue }578 if horizontal { draft.cards[index].origin.x = position } else { draft.cards[index].origin.y = position }579 }580 }581 }582583 // MARK: - Connections584585 public func connection(from: CanvasCardID, to: CanvasCardID) -> CanvasConnection? {586 document.connections.first { $0.from == from && $0.to == to }587 }588589 private func normalised(_ label: String?) -> String? {590 guard let trimmed = label?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else { return nil }591 return String(trimmed.prefix(configuration.maximumLabelLength))592 }593594 /// Connects two cards. A connection is directed and identified by its (from, to) pair.595 public mutating func connect(from: CanvasCardID, to: CanvasCardID, label: String? = nil) throws {596 guard from != to else { throw CanvasEditError.selfConnection }597 guard card(from) != nil else { throw CanvasEditError.unknownCard(from) }598 guard card(to) != nil else { throw CanvasEditError.unknownCard(to) }599 guard connection(from: from, to: to) == nil else { throw CanvasEditError.duplicateConnection }600 guard document.connections.count < configuration.maximumConnections else {601 throw CanvasEditError.connectionLimitReached(configuration.maximumConnections)602 }603 let connection = CanvasConnection(from: from, to: to, label: normalised(label))604 commit("Connect") { $0.connections.append(connection) }605 }606607 @discardableResult608 public mutating func disconnect(from: CanvasCardID, to: CanvasCardID) -> Bool {609 commit("Disconnect") { draft in draft.connections.removeAll { $0.from == from && $0.to == to } }610 }611612 @discardableResult613 public mutating func relabel(from: CanvasCardID, to: CanvasCardID, label: String?) -> Bool {614 let label = normalised(label)615 return commit("Rename Connection") { draft in616 if let index = draft.connections.firstIndex(where: { $0.from == from && $0.to == to }) {617 draft.connections[index].label = label618 }619 }620 }621622 /// Geometry of every connection, for the renderer.623 public func routes() -> [CanvasRoute] {624 let frames = Dictionary(document.cards.map { ($0.id, $0.frame) }, uniquingKeysWith: { first, _ in first })625 return document.connections.compactMap { connection in626 guard let source = frames[connection.from], let target = frames[connection.to] else { return nil }627 return CanvasRouter.route(connection, from: source, to: target)628 }629 }630631 public func route(for connection: CanvasConnection) -> CanvasRoute? {632 guard let source = card(connection.from), let target = card(connection.to) else { return nil }633 return CanvasRouter.route(connection, from: source.frame, to: target.frame)634 }635636 // MARK: - Selection637638 public mutating func select(_ ids: Set<CanvasCardID>, mode: CanvasSelectionMode = .replace) {639 let present = Set(document.cards.map(\.id))640 let valid = ids.intersection(present)641 switch mode {642 case .replace: selection = valid643 case .add: selection.formUnion(valid)644 case .toggle: selection.formSymmetricDifference(valid)645 }646 }647648 public mutating func selectAll() { selection = Set(document.cards.map(\.id)) }649 public mutating func clearSelection() { selection = [] }650651 /// Marquee selection. Returns the cards the rectangle picked.652 @discardableResult653 public mutating func select(in rect: CanvasRect, rule: CanvasMarqueeRule = .intersects,654 mode: CanvasSelectionMode = .replace) -> Set<CanvasCardID> {655 let picked = Set(document.cards.lazy.filter { card in656 rule == .contains ? rect.contains(card.frame) : rect.intersects(card.frame)657 }.map(\.id))658 select(picked, mode: mode)659 return picked660 }661662 // MARK: - Viewport663664 /// The part of the canvas a view of `viewSize` points shows.665 public func visibleRect(viewSize: CanvasSize) -> CanvasRect {666 let scale = document.viewport.scale667 let width = viewSize.width / scale, height = viewSize.height / scale668 return CanvasRect(x: document.viewport.center.x - width / 2, y: document.viewport.center.y - height / 2,669 width: width, height: height)670 }671672 public func canvasPoint(fromView point: CanvasPoint, viewSize: CanvasSize) -> CanvasPoint {673 let viewport = document.viewport674 return CanvasPoint(x: viewport.center.x + (point.x - viewSize.width / 2) / viewport.scale,675 y: viewport.center.y + (point.y - viewSize.height / 2) / viewport.scale)676 }677678 public func viewPoint(fromCanvas point: CanvasPoint, viewSize: CanvasSize) -> CanvasPoint {679 let viewport = document.viewport680 return CanvasPoint(x: (point.x - viewport.center.x) * viewport.scale + viewSize.width / 2,681 y: (point.y - viewport.center.y) * viewport.scale + viewSize.height / 2)682 }683684 private func clampedScale(_ scale: Double) -> Double {685 guard scale.isFinite else { return document.viewport.scale }686 return min(max(scale, configuration.minimumScale), configuration.maximumScale)687 }688689 private mutating func setViewport(center: CanvasPoint, scale: Double) {690 guard center.isFinite else { return }691 document.viewport = CanvasViewport(center: CanvasPoint(x: clampCoordinate(center.x), y: clampCoordinate(center.y)),692 scale: clampedScale(scale))693 }694695 /// Scrolls by a distance in view points (a drag of the background, a two-finger scroll).696 public mutating func pan(byView delta: CanvasPoint) {697 let viewport = document.viewport698 setViewport(center: viewport.center.translated(dx: -delta.x / viewport.scale, dy: -delta.y / viewport.scale),699 scale: viewport.scale)700 }701702 /// Sets the scale while keeping the canvas point under `anchor` (a view point: the cursor, the pinch703 /// centre) at the same place on screen. The scale is clamped to the configured range.704 public mutating func zoom(to scale: Double, around anchor: CanvasPoint, viewSize: CanvasSize) {705 let fixed = canvasPoint(fromView: anchor, viewSize: viewSize)706 let newScale = clampedScale(scale)707 let center = CanvasPoint(x: fixed.x - (anchor.x - viewSize.width / 2) / newScale,708 y: fixed.y - (anchor.y - viewSize.height / 2) / newScale)709 setViewport(center: center, scale: newScale)710 }711712 public mutating func zoom(by factor: Double, around anchor: CanvasPoint, viewSize: CanvasSize) {713 zoom(to: document.viewport.scale * factor, around: anchor, viewSize: viewSize)714 }715716 /// Centres and scales so the given cards (all cards when nil) fit the view with `padding` view points717 /// around them. Never zooms in beyond 1:1. An empty canvas resets to the origin at 1:1.718 public mutating func zoomToFit(viewSize: CanvasSize, padding: Double = 40, ids: Set<CanvasCardID>? = nil) {719 guard let box = bounds(of: ids), viewSize.width > 0, viewSize.height > 0 else {720 setViewport(center: .zero, scale: 1)721 return722 }723 let available = CanvasSize(width: max(1, viewSize.width - 2 * padding), height: max(1, viewSize.height - 2 * padding))724 let scale = min(available.width / max(box.width, 1), available.height / max(box.height, 1), 1)725 setViewport(center: box.center, scale: scale)726 }727728 // MARK: - Hit-testing and culling729730 /// What is under a canvas point: a resize handle of a selected card, else the front-most card, else a731 /// connection. Handle size and connection tolerance are in view points, so they are divided by the scale.732 public func hitTest(_ point: CanvasPoint, includeHandles: Bool = true) -> CanvasHit {733 let scale = max(document.viewport.scale, .leastNonzeroMagnitude)734 let ordered = cardsInZOrder.reversed()735 if includeHandles {736 let half = configuration.handleHitSize / scale / 2737 for card in ordered where selection.contains(card.id) {738 for handle in CanvasHandle.allCases {739 let position = handle.position(on: card.frame)740 if abs(point.x - position.x) <= half, abs(point.y - position.y) <= half {741 return .handle(card: card.id, handle: handle)742 }743 }744 }745 }746 if let card = ordered.first(where: { $0.frame.contains(point) }) { return .card(card.id) }747 let tolerance = configuration.connectionHitTolerance / scale748 var best: (distance: Double, connection: CanvasConnection)?749 for route in routes() where route.bounds.insetBy(dx: -tolerance, dy: -tolerance).contains(point) {750 let distance = route.distance(to: point)751 if distance <= tolerance, distance < (best?.distance ?? .infinity) { best = (distance, route.connection) }752 }753 return best.map { .connection($0.connection) } ?? .empty754 }755756 /// Cards intersecting `rect`, back to front — a linear scan, adequate up to a few thousand cards.757 /// For larger documents build a `CanvasSpatialIndex` once per `revision` and use `visibleCards(in:index:)`.758 public func visibleCards(in rect: CanvasRect) -> [CanvasCard] {759 document.cards.enumerated().filter { $0.element.frame.intersects(rect) }760 .sorted { ($0.element.zIndex, $0.offset) < ($1.element.zIndex, $1.offset) }.map(\.element)761 }762763 public func makeSpatialIndex(cellSize: Double = 512) -> CanvasSpatialIndex {764 CanvasSpatialIndex(cards: document.cards, cellSize: cellSize)765 }766767 /// Same result as `visibleCards(in:)` using an index built from this editor's current cards.768 public func visibleCards(in rect: CanvasRect, index: CanvasSpatialIndex) -> [CanvasCard] {769 guard index.count == document.cards.count else { return visibleCards(in: rect) }770 return index.indices(intersecting: rect)771 .sorted { (document.cards[$0].zIndex, $0) < (document.cards[$1].zIndex, $1) }.map { document.cards[$0] }772 }773774 /// Connections worth drawing for a viewport: those whose curve's bounding box touches it.775 public func visibleRoutes(in rect: CanvasRect) -> [CanvasRoute] {776 routes().filter { $0.bounds.intersects(rect) }777 }778779 // MARK: - Validation780781 /// Checks every invariant the editor maintains. An empty result means the document is valid.782 public func validate() -> [CanvasValidationIssue] { Self.validate(document, configuration: configuration) }783784 public static func validate(_ document: CanvasDocument,785 configuration: CanvasConfiguration = CanvasConfiguration()) -> [CanvasValidationIssue] {786 var issues: [CanvasValidationIssue] = []787 var ids = Set<CanvasCardID>()788 for card in document.cards {789 if !ids.insert(card.id).inserted { issues.append(.duplicateCardID(card.id)) }790 guard card.origin.isFinite, card.size.width.isFinite, card.size.height.isFinite,791 abs(card.origin.x) <= configuration.coordinateLimit, abs(card.origin.y) <= configuration.coordinateLimit else {792 issues.append(.nonFiniteGeometry(card.id)); continue793 }794 let epsilon = 1e-9795 if card.size.width < configuration.minimumCardSize.width - epsilon || card.size.height < configuration.minimumCardSize.height - epsilon796 || card.size.width > configuration.maximumCardSize.width + epsilon || card.size.height > configuration.maximumCardSize.height + epsilon {797 issues.append(.sizeOutOfBounds(card.id))798 }799 switch card.content {800 case .image(let path), .pdf(let path, _):801 if !CanvasAttachmentStore.isSafeRelativePath(path) { issues.append(.unsafeAttachmentPath(card.id)) }802 case .page, .note: break803 }804 }805 var pairs = Set<[CanvasCardID]>()806 for connection in document.connections {807 if connection.from == connection.to { issues.append(.selfConnection(connection.from)) }808 if !ids.contains(connection.from) || !ids.contains(connection.to) { issues.append(.danglingConnection(connection)) }809 if !pairs.insert([connection.from, connection.to]).inserted { issues.append(.duplicateConnection(connection)) }810 }811 let viewport = document.viewport812 if !viewport.center.isFinite || !viewport.scale.isFinite || viewport.scale <= 0 { issues.append(.invalidViewport) }813 return issues814 }815}816