SPB Git

Repository Public

CanvasGeometry.swift 22.1 KB 417 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Canvas/CanvasGeometry.swift3// Description: Pure geometry of the canvas editor, mirroring the web client (`src/lib/canvas/viewport.ts`, `routing.ts`,4//              `core.ts`): viewport ⇄ screen transforms, zoom around a point, fit to content, hit testing on the real5//              outline of a card, marquee, edge routing anchored on the outline, arrowheads, group resize by handle,6//              default sizes and colours, and the Markdown-table convention of `table` cards.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import Foundation12import SPNotesDocument1314/// Viewport mathematics. Convention of `viewport: {x, y, zoom}` (the same on every client): (x, y) is the WORLD point15/// shown at the top-left corner of the view, `zoom` is screen points per world unit — screen = (world − {x, y}) × zoom.16public enum CanvasViewportMath {17    public static let zoomMin = 0.0518    public static let zoomMax = 4.01920    public static func clampZoom(_ zoom: Double) -> Double { zoom.isFinite ? min(zoomMax, max(zoomMin, zoom)) : 1 }2122    public static func worldToScreen(_ viewport: CanvasViewport, _ point: CGPoint) -> CGPoint {23        CGPoint(x: (point.x - viewport.x) * viewport.zoom, y: (point.y - viewport.y) * viewport.zoom)24    }2526    public static func screenToWorld(_ viewport: CanvasViewport, _ point: CGPoint) -> CGPoint {27        CGPoint(x: point.x / viewport.zoom + viewport.x, y: point.y / viewport.zoom + viewport.y)28    }2930    public static func worldToScreen(_ viewport: CanvasViewport, _ rect: CGRect) -> CGRect {31        CGRect(origin: worldToScreen(viewport, rect.origin), size: CGSize(width: rect.width * viewport.zoom, height: rect.height * viewport.zoom))32    }3334    /// The world rectangle visible in a view of `size` points, grown by `margin` screen points on every side.35    public static func visibleRect(_ viewport: CanvasViewport, size: CGSize, margin: Double = 0) -> CGRect {36        CGRect(x: viewport.x - margin / viewport.zoom, y: viewport.y - margin / viewport.zoom,37               width: (size.width + 2 * margin) / viewport.zoom, height: (size.height + 2 * margin) / viewport.zoom)38    }3940    /// Pans by a screen-space delta (dragging the content by (dx, dy) points).41    public static func pan(_ viewport: CanvasViewport, dx: Double, dy: Double) -> CanvasViewport {42        var out = viewport43        out.x = viewport.x - dx / viewport.zoom44        out.y = viewport.y - dy / viewport.zoom45        return out46    }4748    /// Zooms to `zoom` (clamped) keeping the world point under the screen point `at` fixed.49    public static func zoom(_ viewport: CanvasViewport, to zoom: Double, at: CGPoint) -> CanvasViewport {50        let z = clampZoom(zoom)51        guard z != viewport.zoom else { return viewport }52        let world = screenToWorld(viewport, at)53        var out = viewport54        out.zoom = z55        out.x = world.x - at.x / z56        out.y = world.y - at.y / z57        return out58    }5960    public static func zoom(_ viewport: CanvasViewport, by factor: Double, at: CGPoint) -> CanvasViewport {61        zoom(viewport, to: viewport.zoom * factor, at: at)62    }6364    /// The viewport that shows `bounds` entirely, centred, with `padding` points around it; never magnifies beyond65    /// `maxZoom`. Null / empty view → origin at zoom 1.66    public static func fit(_ bounds: CGRect, size: CGSize, padding: Double = 48, maxZoom: Double = 1) -> CanvasViewport {67        guard !bounds.isNull, size.width > 0, size.height > 0 else { return CanvasViewport() }68        let availW = max(1, size.width - 2 * padding), availH = max(1, size.height - 2 * padding)69        let zoom = clampZoom(min(bounds.width > 0 ? availW / bounds.width : .infinity, bounds.height > 0 ? availH / bounds.height : .infinity, maxZoom))70        return CanvasViewport(x: bounds.midX - size.width / (2 * zoom), y: bounds.midY - size.height / (2 * zoom), zoom: zoom)71    }7273    /// The viewport of the same zoom centred on a world point.74    public static func center(_ viewport: CanvasViewport, on point: CGPoint, size: CGSize) -> CanvasViewport {75        var out = viewport76        out.x = point.x - size.width / (2 * viewport.zoom)77        out.y = point.y - size.height / (2 * viewport.zoom)78        return out79    }8081    /// Wheel / pinch delta → zoom factor (exponential: in then out by the same delta returns to the start).82    public static func wheelZoomFactor(deltaY: Double, pinch: Bool) -> Double { exp(-deltaY * (pinch ? 0.01 : 0.0015)) }83}8485/// Hit testing and selection geometry.86public enum CanvasHit {87    /// Is the point inside the node's outline? Shapes are tested against their real outline (ellipse, diamond);88    /// every other kind is its rectangle.89    public static func contains(_ node: CanvasNode, _ point: CGPoint, tolerance: Double = 0) -> Bool {90        let w = max(0, node.w), h = max(0, node.h)91        let hw = w / 2 + tolerance, hh = h / 2 + tolerance92        let dx = point.x - (node.x + w / 2), dy = point.y - (node.y + h / 2)93        if abs(dx) > hw || abs(dy) > hh { return false }94        guard node.kind == .shape, hw != 0, hh != 0 else { return true }95        if node.shape == .ellipse { return (dx * dx) / (hw * hw) + (dy * dy) / (hh * hh) <= 1 }96        if node.shape == .diamond { return abs(dx) / hw + abs(dy) / hh <= 1 }97        return true98    }99100    /// The front-most node under the point (highest `z`, then last in the array).101    public static func node(in document: CanvasDocument, at point: CGPoint, tolerance: Double = 0) -> CanvasNode? {102        document.nodesBackToFront.last { contains($0, point, tolerance: tolerance) }103    }104105    /// Nodes touched by the rectangle (marquee), back to front; edges that only touch count (as on the web).106    public static func nodes(in document: CanvasDocument, touching rect: CGRect, containedOnly: Bool = false) -> [CanvasNode] {107        document.nodesBackToFront.filter { node in108            let r = CGRect(x: node.x, y: node.y, width: max(0, node.w), height: max(0, node.h))109            if containedOnly { return r.minX >= rect.minX && r.minY >= rect.minY && r.maxX <= rect.maxX && r.maxY <= rect.maxY }110            return rect.minX <= r.maxX && r.minX <= rect.maxX && rect.minY <= r.maxY && r.minY <= rect.maxY111        }112    }113114    public static func rect(from a: CGPoint, to b: CGPoint) -> CGRect {115        CGRect(x: min(a.x, b.x), y: min(a.y, b.y), width: abs(a.x - b.x), height: abs(a.y - b.y))116    }117118    /// Distance from a point to a polyline (infinity for an empty one).119    public static func distance(_ point: CGPoint, toPolyline points: [CGPoint]) -> Double {120        guard let first = points.first else { return .infinity }121        if points.count == 1 { return hypot(point.x - first.x, point.y - first.y) }122        var best = Double.infinity123        for i in 1..<points.count {124            let a = points[i - 1], b = points[i]125            let dx = b.x - a.x, dy = b.y - a.y126            let length2 = dx * dx + dy * dy127            let t = length2 == 0 ? 0 : max(0, min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length2))128            best = min(best, hypot(point.x - (a.x + t * dx), point.y - (a.y + t * dy)))129        }130        return best131    }132133    /// The edge whose route passes within `tolerance` world units of the point (the last drawn wins).134    public static func edge(in document: CanvasDocument, at point: CGPoint, tolerance: Double) -> CanvasEdge? {135        document.edges.last { edge in136            guard let a = document.node(id: edge.from), let b = document.node(id: edge.to) else { return false }137            return distance(point, toPolyline: CanvasRouting.route(from: a, to: b, style: CanvasRouting.style(of: edge)).points) <= tolerance138        }139    }140}141142/// Where an edge leaves and reaches a card, and the three routes.143public enum CanvasRouting {144    public enum Style: String, Sendable, Hashable { case straight, orthogonal, curved }145    public enum Side: Sendable, Hashable { case top, right, bottom, left }146147    public struct Route: Sendable, Equatable {148        public var style: Style149        /// Polyline (curves are sampled): first point on the outline of `from`, last on the outline of `to`.150        public var points: [CGPoint]151        /// Bézier control points of the curved route (nil otherwise).152        public var controls: (CGPoint, CGPoint)?153        /// Direction of arrival at the last point, radians (atan2, y down).154        public var endAngle: Double155        /// Midpoint of the route by length.156        public var label: CGPoint157158        public static func == (a: Route, b: Route) -> Bool {159            a.style == b.style && a.points == b.points && a.endAngle == b.endAngle && a.label == b.label160        }161    }162163    static func r2(_ n: Double) -> Double {164        let v = (n * 100).rounded() / 100   // JS Math.round differs only on exact negative halves165        return v == 0 ? 0 : v166    }167168    static func P(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: r2(x), y: r2(y)) }169170    /// The optional edge field `route` (web extension of spn-canvas-1; absent or unknown = straight).171    public static func style(of edge: CanvasEdge) -> Style {172        switch edge["route"]?.stringValue {173        case "orthogonal": return .orthogonal174        case "curved": return .curved175        default: return .straight176        }177    }178179    /// An edge draws an arrowhead unless its kind is `line` (absent or unknown kinds are arrows).180    public static func hasArrow(_ edge: CanvasEdge) -> Bool { edge.kind != .line }181182    static func rect(_ node: CanvasNode) -> CGRect { CGRect(x: node.x, y: node.y, width: max(0, node.w), height: max(0, node.h)) }183184    /// The point where the ray from the node's centre towards `toward` crosses the node's outline.185    public static func anchor(_ node: CanvasNode, toward: CGPoint) -> CGPoint {186        let r = rect(node)187        let cx = r.midX, cy = r.midY188        let dx = toward.x - cx, dy = toward.y - cy189        let hw = r.width / 2, hh = r.height / 2190        if dx == 0 && dy == 0 { return P(cx, r.minY) }191        if hw == 0 || hh == 0 { return P(cx, cy) }192        let t: Double193        if node.kind == .shape, node.shape == .ellipse { t = 1 / ((dx * dx) / (hw * hw) + (dy * dy) / (hh * hh)).squareRoot() }194        else if node.kind == .shape, node.shape == .diamond { t = 1 / (abs(dx) / hw + abs(dy) / hh) }195        else { t = min(dx == 0 ? .infinity : hw / abs(dx), dy == 0 ? .infinity : hh / abs(dy)) }196        return P(cx + dx * t, cy + dy * t)197    }198199    public static func sideAnchor(_ node: CanvasNode, _ side: Side) -> CGPoint {200        let r = rect(node)201        switch side {202        case .top: return P(r.midX, r.minY)203        case .bottom: return P(r.midX, r.maxY)204        case .left: return P(r.minX, r.midY)205        case .right: return P(r.maxX, r.midY)206        }207    }208209    /// The pair of sides facing each other along the axis with the larger gap (horizontal wins a tie); nil when the210    /// boxes overlap on both axes.211    public static func facingSides(_ a: CGRect, _ b: CGRect) -> (from: Side, to: Side)? {212        let gapX = max(b.minX - a.maxX, a.minX - b.maxX), gapY = max(b.minY - a.maxY, a.minY - b.maxY)213        if gapX < 0 && gapY < 0 { return nil }214        if gapX >= gapY { return b.midX >= a.midX ? (.right, .left) : (.left, .right) }215        return b.midY >= a.midY ? (.bottom, .top) : (.top, .bottom)216    }217218    static func normal(_ side: Side) -> CGPoint {219        switch side {220        case .top: return CGPoint(x: 0, y: -1)221        case .bottom: return CGPoint(x: 0, y: 1)222        case .left: return CGPoint(x: -1, y: 0)223        case .right: return CGPoint(x: 1, y: 0)224        }225    }226227    static func polylineMid(_ points: [CGPoint]) -> CGPoint {228        var total = 0.0229        for i in points.indices.dropFirst() { total += hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y) }230        var half = total / 2231        for i in points.indices.dropFirst() {232            let segment = hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y)233            if half <= segment, segment > 0 {234                let t = half / segment235                return P(points[i - 1].x + (points[i].x - points[i - 1].x) * t, points[i - 1].y + (points[i].y - points[i - 1].y) * t)236            }237            half -= segment238        }239        return points.first ?? .zero240    }241242    static func angle(_ a: CGPoint, _ b: CGPoint) -> Double { atan2(b.y - a.y, b.x - a.x) }243244    /// Route of an edge between two nodes (a node connected to itself: a loop above its top-right corner; overlapping245    /// boxes fall back to the straight route).246    public static func route(from a: CanvasNode, to b: CanvasNode, style: Style = .straight) -> Route {247        if a.id == b.id {248            let r = rect(a)249            let x0 = r.minX + r.width * 0.7, s = max(24, min(48, r.width * 0.3))250            let points = [P(x0, r.minY), P(x0, r.minY - s), P(r.maxX + s, r.minY - s), P(r.maxX + s, r.minY + r.height * 0.3), P(r.maxX, r.minY + r.height * 0.3)]251            return Route(style: style, points: points, controls: nil, endAngle: .pi, label: P(r.maxX + s, r.minY - s))252        }253        let ra = rect(a), rb = rect(b)254        guard style != .straight, let sides = facingSides(ra, rb) else {255            let p0 = anchor(a, toward: CGPoint(x: rb.midX, y: rb.midY)), p1 = anchor(b, toward: CGPoint(x: ra.midX, y: ra.midY))256            return Route(style: .straight, points: [p0, p1], controls: nil, endAngle: angle(p0, p1), label: polylineMid([p0, p1]))257        }258        let p0 = sideAnchor(a, sides.from), p1 = sideAnchor(b, sides.to)259        if style == .orthogonal {260            let horizontal = sides.from == .left || sides.from == .right261            let points = horizontal ? [p0, P((p0.x + p1.x) / 2, p0.y), P((p0.x + p1.x) / 2, p1.y), p1]262                                    : [p0, P(p0.x, (p0.y + p1.y) / 2), P(p1.x, (p0.y + p1.y) / 2), p1]263            return Route(style: style, points: points, controls: nil, endAngle: angle(points[2], points[3]), label: polylineMid(points))264        }265        let reach = max(40, hypot(p1.x - p0.x, p1.y - p0.y) / 2)266        let n0 = normal(sides.from), n1 = normal(sides.to)267        let c0 = P(p0.x + n0.x * reach, p0.y + n0.y * reach), c1 = P(p1.x + n1.x * reach, p1.y + n1.y * reach)268        var points: [CGPoint] = []269        for i in 0...24 {270            let t = Double(i) / 24, u = 1 - t271            points.append(P(u * u * u * p0.x + 3 * u * u * t * c0.x + 3 * u * t * t * c1.x + t * t * t * p1.x,272                            u * u * u * p0.y + 3 * u * u * t * c0.y + 3 * u * t * t * c1.y + t * t * t * p1.y))273        }274        return Route(style: style, points: points, controls: (c0, c1), endAngle: angle(c1, p1), label: polylineMid(points))275    }276277    /// Triangle of an arrowhead whose tip is `tip`, pointing along `angle` (tip first).278    public static func arrowHead(tip: CGPoint, angle: Double, size: Double = 11) -> [CGPoint] {279        let spread = Double.pi / 7280        return [P(tip.x, tip.y), P(tip.x - size * cos(angle - spread), tip.y - size * sin(angle - spread)),281                P(tip.x - size * cos(angle + spread), tip.y - size * sin(angle + spread))]282    }283}284285/// Resize handles of the selection box.286public enum CanvasHandle: String, Sendable, Hashable, CaseIterable {287    case n, s, e, w, ne, nw, se, sw288289    var movesWest: Bool { self == .w || self == .nw || self == .sw }290    var movesEast: Bool { self == .e || self == .ne || self == .se }291    var movesNorth: Bool { self == .n || self == .ne || self == .nw }292    var movesSouth: Bool { self == .s || self == .se || self == .sw }293    var isCorner: Bool { rawValue.count == 2 }294295    /// Position of the handle on a box.296    public func point(on box: CGRect) -> CGPoint {297        CGPoint(x: movesWest ? box.minX : (movesEast ? box.maxX : box.midX), y: movesNorth ? box.minY : (movesSouth ? box.maxY : box.midY))298    }299}300301public enum CanvasResize {302    public static let minNodeSize = 24.0303304    /// The box dragged by `handle` by (dx, dy): never smaller than `min` on a side, never flipped.305    public static func rect(_ box: CGRect, handle: CanvasHandle, dx: Double, dy: Double, min minimum: Double = minNodeSize, keepAspect: Bool = false) -> CGRect {306        var x0 = Double(box.minX), y0 = Double(box.minY), x1 = Double(box.maxX), y1 = Double(box.maxY)307        let bw = Double(box.width), bh = Double(box.height)308        let minW = Swift.min(minimum, bw == 0 ? minimum : bw), minH = Swift.min(minimum, bh == 0 ? minimum : bh)309        if handle.movesWest { x0 = Swift.min(x0 + dx, x1 - minW) }310        if handle.movesEast { x1 = Swift.max(x1 + dx, x0 + minW) }311        if handle.movesNorth { y0 = Swift.min(y0 + dy, y1 - minH) }312        if handle.movesSouth { y1 = Swift.max(y1 + dy, y0 + minH) }313        if keepAspect, bw > 0, bh > 0 {314            let sx = (x1 - x0) / bw, sy = (y1 - y0) / bh315            let s = handle.isCorner ? Swift.max(sx, sy) : (handle == .e || handle == .w ? sx : sy)316            let w = bw * s, h = bh * s317            if handle.isCorner {318                if handle.movesWest { x0 = x1 - w } else { x1 = x0 + w }319                if handle.movesNorth { y0 = y1 - h } else { y1 = y0 + h }320            } else if handle == .e || handle == .w {321                y0 = Double(box.midY) - h / 2; y1 = Double(box.midY) + h / 2322            } else {323                x0 = Double(box.midX) - w / 2; x1 = Double(box.midX) + w / 2324            }325        }326        return CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0)327    }328329    /// Resizes a group: the bounding box of the nodes is dragged by `handle` and every node is scaled with it.330    public static func nodes(_ document: CanvasDocument, ids: Set<String>, handle: CanvasHandle, dx: Double, dy: Double, keepAspect: Bool = false) -> CanvasDocument {331        let selected = document.nodes.filter { ids.contains($0.id) }332        let box = selected.reduce(CGRect.null) { $0.union(CanvasRouting.rect($1)) }333        guard !box.isNull else { return document }334        let next = rect(box, handle: handle, dx: dx, dy: dy, keepAspect: keepAspect)335        guard next != box else { return document }336        let sx = box.width > 0 ? next.width / box.width : 1, sy = box.height > 0 ? next.height / box.height : 1337        var out = document338        for i in out.nodes.indices where ids.contains(out.nodes[i].id) {339            let n = out.nodes[i]340            out.nodes[i].x = CanvasRouting.r2(next.minX + (n.x - box.minX) * sx)341            out.nodes[i].y = CanvasRouting.r2(next.minY + (n.y - box.minY) * sy)342            out.nodes[i].w = CanvasRouting.r2(max(0, n.w) * sx)343            out.nodes[i].h = CanvasRouting.r2(max(0, n.h) * sy)344        }345        return out346    }347}348349/// Defaults shared with the web editor.350public enum CanvasDefaults {351    public static func size(_ kind: CanvasNodeKind) -> CGSize {352        switch kind {353        case .text: return CGSize(width: 240, height: 120)354        case .page: return CGSize(width: 280, height: 132)355        case .image: return CGSize(width: 320, height: 240)356        case .pdf: return CGSize(width: 240, height: 320)357        case .link: return CGSize(width: 280, height: 96)358        case .drawing: return CGSize(width: 360, height: 240)359        case .shape: return CGSize(width: 160, height: 120)360        case .reference: return CGSize(width: 300, height: 120)361        case .math: return CGSize(width: 240, height: 100)362        case .table: return CGSize(width: 320, height: 160)363        default: return CGSize(width: 240, height: 120)364        }365    }366367    /// The colours a card can take (the semantic hues of the design system, stored as `#rrggbb`).368    public static let colors: [String] = ["#2f5ddb", "#008b4e", "#d98b09", "#cc272e", "#535862"]369370    /// A new node of `kind` centred on `at`, with the default size of its kind (`z` is set by `addNode`).371    public static func node(_ kind: CanvasNodeKind, centeredAt at: CGPoint, id: String = UUID().uuidString.lowercased()) -> CanvasNode {372        let size = size(kind)373        var node = CanvasNode(id: id, kind: kind, x: CanvasRouting.r2(at.x - size.width / 2), y: CanvasRouting.r2(at.y - size.height / 2), w: size.width, h: size.height, z: 0)374        if kind == .shape { node.shape = .rect }375        if kind == .table { node.text = CanvasTable.serialize(Array(repeating: Array(repeating: "", count: 3), count: 3)) }376        return node377    }378}379380/// Cells of a `table` card. Convention shared with the web: `text` holds a GitHub-flavoured Markdown table.381public enum CanvasTable {382    public static func parse(_ text: String?) -> [[String]] {383        let lines = (text ?? "").split(separator: "\n", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }.filter { $0.hasPrefix("|") }384        let separator = try? Regex(#"^\|\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?$"#)385        let rows: [[String]] = lines.filter { line in separator.map { line.wholeMatch(of: $0) == nil } ?? true }.map { line in386            var body = Substring(line)387            body.removeFirst()388            if body.hasSuffix("|") && !body.hasSuffix("\\|") { body.removeLast() }389            var cells: [String] = [], current = ""390            var previous: Character?391            for character in body {392                if character == "|" && previous != "\\" { cells.append(current); current = "" } else { current.append(character) }393                previous = character394            }395            cells.append(current)396            return cells.map { cell in397                var value = cell.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: "\\|", with: "|")398                if let br = try? Regex(#"(?i)<br\s*/?>"#) { value = value.replacing(br, with: "\n") }399                return value400            }401        }402        let width = rows.map(\.count).max() ?? 0403        return rows.map { $0.count < width ? $0 + Array(repeating: "", count: width - $0.count) : $0 }404    }405406    public static func serialize(_ cells: [[String]]) -> String {407        guard !cells.isEmpty else { return "" }408        let width = max(1, cells.map(\.count).max() ?? 1)409        func line(_ row: [String]) -> String {410            "| " + (0..<width).map { i in411                (i < row.count ? row[i] : "").replacingOccurrences(of: "|", with: "\\|").replacingOccurrences(of: "\r\n", with: "<br>").replacingOccurrences(of: "\n", with: "<br>")412            }.joined(separator: " | ") + " |"413        }414        return ([line(cells[0]), "| " + Array(repeating: "---", count: width).joined(separator: " | ") + " |"] + cells.dropFirst().map(line)).joined(separator: "\n")415    }416}417
Files main
Menu

Theme