Repository Public
1// SP Notes Core2// File: Sources/SPNotesDocument/Canvas.swift3// Description: The canvas format `spn-canvas-1` (pages of type `canvas`): lossless model of nodes, edges and4// viewport with unknown-field preservation, and the editing helpers both apps share.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics1011/// Errors thrown when reading a canvas.12public enum CanvasError: Error, Sendable, Hashable {13 /// The `format` field is not `spn-canvas-1` (the value found, nil when absent or not a string).14 case unsupportedFormat(String?)15 /// The JSON is valid but is not a canvas (what is wrong).16 case invalid(String)17}1819/// The kind of a canvas node. Unknown kinds are preserved.20public struct CanvasNodeKind: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible {21 public var rawValue: String22 public init(rawValue: String) { self.rawValue = rawValue }2324 public static let text = CanvasNodeKind(rawValue: "text")25 public static let page = CanvasNodeKind(rawValue: "page")26 public static let image = CanvasNodeKind(rawValue: "image")27 public static let pdf = CanvasNodeKind(rawValue: "pdf")28 public static let link = CanvasNodeKind(rawValue: "link")29 public static let drawing = CanvasNodeKind(rawValue: "drawing")30 public static let shape = CanvasNodeKind(rawValue: "shape")31 public static let reference = CanvasNodeKind(rawValue: "reference")32 public static let math = CanvasNodeKind(rawValue: "math")33 public static let table = CanvasNodeKind(rawValue: "table")3435 public static let allKnown: [CanvasNodeKind] = [.text, .page, .image, .pdf, .link, .drawing, .shape, .reference, .math, .table]36 public var isKnown: Bool { Self.allKnown.contains(self) }37 public var description: String { rawValue }38}3940/// The outline of a `shape` node. Unknown shapes are preserved.41public struct CanvasShape: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible {42 public var rawValue: String43 public init(rawValue: String) { self.rawValue = rawValue }4445 public static let rect = CanvasShape(rawValue: "rect")46 public static let ellipse = CanvasShape(rawValue: "ellipse")47 public static let diamond = CanvasShape(rawValue: "diamond")48 public var isKnown: Bool { self == .rect || self == .ellipse || self == .diamond }49 public var description: String { rawValue }50}5152/// The kind of an edge. Unknown kinds are preserved.53public struct CanvasEdgeKind: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible {54 public var rawValue: String55 public init(rawValue: String) { self.rawValue = rawValue }5657 public static let arrow = CanvasEdgeKind(rawValue: "arrow")58 public static let line = CanvasEdgeKind(rawValue: "line")59 public var isKnown: Bool { self == .arrow || self == .line }60 public var description: String { rawValue }61}6263/// A card of the canvas. `fields` is the JSON object as stored, so unknown keys, absent optional keys and explicit64/// nulls round-trip; the typed properties read and write it.65public struct CanvasNode: Sendable, Hashable, Codable, Identifiable {66 /// The whole JSON object of the node (known and unknown keys).67 public private(set) var fields: [String: JSONValue]6869 public init(id: String = UUID().uuidString.lowercased(), kind: CanvasNodeKind, x: Double = 0, y: Double = 0, w: Double = 240, h: Double = 120, z: Double = 0) {70 fields = ["id": .string(id), "kind": .string(kind.rawValue), "x": InkJSON.number(x), "y": InkJSON.number(y),71 "w": InkJSON.number(w), "h": InkJSON.number(h), "z": InkJSON.number(z)]72 }7374 public init(json: JSONValue) throws {75 guard case .object(let o) = json else { throw CanvasError.invalid("A canvas node must be a JSON object") }76 guard case .string(let id)? = o["id"], !id.isEmpty else { throw CanvasError.invalid("A canvas node must have a string id") }77 fields = InkJSON.normalized(o)78 }7980 public var jsonValue: JSONValue { .object(fields) }81 public init(from decoder: Decoder) throws { try self.init(json: JSONValue(from: decoder)) }82 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }8384 public var id: String { fields["id"]?.stringValue ?? "" }85 /// `text` when the field is missing.86 public var kind: CanvasNodeKind {87 get { CanvasNodeKind(rawValue: fields["kind"]?.stringValue ?? "text") }88 set { fields["kind"] = .string(newValue.rawValue) }89 }90 public var x: Double { get { number("x") } set { fields["x"] = InkJSON.number(newValue) } }91 public var y: Double { get { number("y") } set { fields["y"] = InkJSON.number(newValue) } }92 public var w: Double { get { number("w") } set { fields["w"] = InkJSON.number(newValue) } }93 public var h: Double { get { number("h") } set { fields["h"] = InkJSON.number(newValue) } }94 /// Stacking order: the highest is in front.95 public var z: Double { get { number("z") } set { fields["z"] = InkJSON.number(newValue) } }96 public var text: String? { get { string("text") } set { setString("text", newValue) } }97 public var pageId: String? { get { string("pageId") } set { setString("pageId", newValue) } }98 public var attachmentId: String? { get { string("attachmentId") } set { setString("attachmentId", newValue) } }99 public var url: String? { get { string("url") } set { setString("url", newValue) } }100 public var refId: String? { get { string("refId") } set { setString("refId", newValue) } }101 public var latex: String? { get { string("latex") } set { setString("latex", newValue) } }102 public var color: String? { get { string("color") } set { setString("color", newValue) } }103 /// Attachment id of the `spn-ink-1` document of a `drawing` node.104 public var ink: String? { get { string("ink") } set { setString("ink", newValue) } }105 public var shape: CanvasShape? {106 get { string("shape").map(CanvasShape.init(rawValue:)) }107 set { setString("shape", newValue?.rawValue) }108 }109110 public var frame: CGRect {111 get { CGRect(x: x, y: y, width: w, height: h) }112 set { x = Double(newValue.minX); y = Double(newValue.minY); w = Double(newValue.width); h = Double(newValue.height) }113 }114 public var center: CGPoint {115 get { CGPoint(x: x + w / 2, y: y + h / 2) }116 set { x = Double(newValue.x) - w / 2; y = Double(newValue.y) - h / 2 }117 }118119 /// Reads or writes any field but `id` (unknown ones included); nil removes the key.120 public subscript(field: String) -> JSONValue? {121 get { fields[field] }122 set { if field != "id" { fields[field] = newValue.map(InkJSON.normalized) } }123 }124125 private func number(_ key: String) -> Double {126 let v = fields[key]?.doubleValue ?? 0127 return v.isFinite ? v : 0128 }129 private func string(_ key: String) -> String? { fields[key]?.stringValue }130 private mutating func setString(_ key: String, _ value: String?) { fields[key] = value.map(JSONValue.string) }131}132133/// A link between two nodes. Same storage rule as `CanvasNode`.134public struct CanvasEdge: Sendable, Hashable, Codable, Identifiable {135 /// The whole JSON object of the edge (known and unknown keys).136 public private(set) var fields: [String: JSONValue]137138 public init(id: String = UUID().uuidString.lowercased(), from: String, to: String, label: String? = nil, kind: CanvasEdgeKind? = nil, color: String? = nil) {139 fields = ["id": .string(id), "from": .string(from), "to": .string(to)]140 self.label = label141 self.kind = kind142 self.color = color143 }144145 public init(json: JSONValue) throws {146 guard case .object(let o) = json else { throw CanvasError.invalid("A canvas edge must be a JSON object") }147 guard case .string(let id)? = o["id"], !id.isEmpty else { throw CanvasError.invalid("A canvas edge must have a string id") }148 fields = InkJSON.normalized(o)149 }150151 public var jsonValue: JSONValue { .object(fields) }152 public init(from decoder: Decoder) throws { try self.init(json: JSONValue(from: decoder)) }153 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }154155 public var id: String { fields["id"]?.stringValue ?? "" }156 /// Id of the source node (empty when the field is missing).157 public var from: String { get { fields["from"]?.stringValue ?? "" } set { fields["from"] = .string(newValue) } }158 /// Id of the target node (empty when the field is missing).159 public var to: String { get { fields["to"]?.stringValue ?? "" } set { fields["to"] = .string(newValue) } }160 public var label: String? { get { fields["label"]?.stringValue } set { fields["label"] = newValue.map(JSONValue.string) } }161 public var color: String? { get { fields["color"]?.stringValue } set { fields["color"] = newValue.map(JSONValue.string) } }162 /// Nil when absent (drawn as an arrow).163 public var kind: CanvasEdgeKind? {164 get { fields["kind"]?.stringValue.map(CanvasEdgeKind.init(rawValue:)) }165 set { fields["kind"] = (newValue?.rawValue).map(JSONValue.string) }166 }167168 /// Reads or writes any field but `id` (unknown ones included); nil removes the key.169 public subscript(field: String) -> JSONValue? {170 get { fields[field] }171 set { if field != "id" { fields[field] = newValue.map(InkJSON.normalized) } }172 }173}174175/// The visible region of a canvas: top-left offset and zoom factor.176public struct CanvasViewport: Sendable, Hashable, Codable {177 /// The JSON object as stored (unknown keys included).178 public private(set) var fields: [String: JSONValue]179180 public init(x: Double = 0, y: Double = 0, zoom: Double = 1) {181 fields = ["x": InkJSON.number(x), "y": InkJSON.number(y), "zoom": InkJSON.number(zoom)]182 }183 init(fields: [String: JSONValue]) { self.fields = InkJSON.normalized(fields) }184185 public var x: Double { get { fields["x"]?.doubleValue ?? 0 } set { fields["x"] = InkJSON.number(newValue) } }186 public var y: Double { get { fields["y"]?.doubleValue ?? 0 } set { fields["y"] = InkJSON.number(newValue) } }187 /// 1 when missing or not positive.188 public var zoom: Double {189 get { if let z = fields["zoom"]?.doubleValue, z > 0, z.isFinite { return z }; return 1 }190 set { fields["zoom"] = InkJSON.number(newValue) }191 }192193 public var jsonValue: JSONValue { .object(fields) }194 public init(from decoder: Decoder) throws {195 guard case .object(let o) = try JSONValue(from: decoder) else {196 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Invalid viewport"))197 }198 self.init(fields: o)199 }200 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }201}202203/// A canvas (`spn-canvas-1`). Decoding then encoding an unmodified canvas gives semantically identical JSON:204/// unknown fields are kept at every level, absent keys stay absent, nulls stay null, integers stay integers.205public struct CanvasDocument: Sendable, Hashable, Codable {206 public static let format = "spn-canvas-1"207208 public var nodes: [CanvasNode]209 public var edges: [CanvasEdge]210 /// Top-level fields other than `nodes` and `edges` (`format`, `viewport`, unknown keys), as stored.211 public internal(set) var fields: [String: JSONValue]212213 /// An empty canvas with the default viewport.214 public static var empty: CanvasDocument { CanvasDocument() }215216 public init(nodes: [CanvasNode] = [], edges: [CanvasEdge] = [], viewport: CanvasViewport = CanvasViewport()) {217 self.nodes = nodes218 self.edges = edges219 fields = ["format": .string(Self.format), "viewport": viewport.jsonValue]220 }221222 /// Reads a canvas. Throws `CanvasError.unsupportedFormat` when `format` is not `spn-canvas-1`. Missing223 /// `nodes` / `edges` read as empty (and are written back as empty arrays).224 public init(json: JSONValue) throws {225 guard case .object(var o) = json else { throw CanvasError.invalid("A canvas must be a JSON object") }226 guard o["format"]?.stringValue == Self.format else { throw CanvasError.unsupportedFormat(o["format"]?.stringValue) }227 func list(_ key: String) throws -> [JSONValue] {228 switch o[key] {229 case nil: return []230 case .array(let a)?: return a231 default: throw CanvasError.invalid("\(key) must be an array")232 }233 }234 nodes = try list("nodes").map(CanvasNode.init(json:))235 edges = try list("edges").map(CanvasEdge.init(json:))236 o["nodes"] = nil237 o["edges"] = nil238 fields = InkJSON.normalized(o)239 }240241 /// Reads the `data` of a canvas. Throws `DocumentError.invalidJSON` or `CanvasError`.242 public init(data: Data) throws { try self.init(json: JSONValue(data: data)) }243244 public var jsonValue: JSONValue {245 var o = fields246 o["nodes"] = .array(nodes.map(\.jsonValue))247 o["edges"] = .array(edges.map(\.jsonValue))248 return .object(o)249 }250251 /// Canonical JSON (sorted keys, no whitespace).252 public func jsonData() -> Data { jsonValue.canonicalData() }253254 public init(from decoder: Decoder) throws { try self.init(json: JSONValue(from: decoder)) }255 public func encode(to encoder: Encoder) throws { try jsonValue.encode(to: encoder) }256257 /// The viewport; the default one when the field is missing or not an object.258 public var viewport: CanvasViewport {259 get { fields["viewport"]?.objectValue.map(CanvasViewport.init(fields:)) ?? CanvasViewport() }260 set { fields["viewport"] = newValue.jsonValue }261 }262263 /// Reads or writes a top-level field other than `nodes`, `edges` and `format`; nil removes the key.264 public subscript(field: String) -> JSONValue? {265 get { fields[field] }266 set { if !["nodes", "edges", "format"].contains(field) { fields[field] = newValue.map(InkJSON.normalized) } }267 }268269 // MARK: Queries270271 public func node(id: String) -> CanvasNode? { nodes.first { $0.id == id } }272 public func edge(id: String) -> CanvasEdge? { edges.first { $0.id == id } }273274 /// The edges starting or ending at a node.275 public func edges(of nodeId: String) -> [CanvasEdge] { edges.filter { $0.from == nodeId || $0.to == nodeId } }276277 /// The box enclosing every node; `.null` for an empty canvas.278 public var bounds: CGRect { nodes.reduce(CGRect.null) { $0.union($1.frame) } }279280 /// The nodes whose frame intersects `rect`, back to front.281 public func nodes(in rect: CGRect) -> [CanvasNode] {282 nodesBackToFront.filter { $0.frame.intersects(rect) }283 }284285 /// The nodes in drawing order (ascending `z`; array order breaks ties).286 public var nodesBackToFront: [CanvasNode] {287 nodes.enumerated().sorted { ($0.element.z, $0.offset) < ($1.element.z, $1.offset) }.map(\.element)288 }289290 /// The front-most node containing `point`.291 public func node(at point: CGPoint) -> CanvasNode? { nodesBackToFront.last { $0.frame.contains(point) } }292293 /// Edges whose `from` or `to` is not a node of the canvas.294 public var danglingEdges: [CanvasEdge] {295 let ids = Set(nodes.map(\.id))296 return edges.filter { !ids.contains($0.from) || !ids.contains($0.to) }297 }298299 // MARK: Editing300301 /// Appends a node in front of the others (its `z` is raised above the current maximum when it is not already).302 /// Returns false, changing nothing, when the id is already used.303 @discardableResult304 public mutating func addNode(_ node: CanvasNode) -> Bool {305 guard self.node(id: node.id) == nil else { return false }306 var n = node307 if let top = nodes.map(\.z).max(), n.z <= top { n.z = top + 1 }308 nodes.append(n)309 return true310 }311312 /// Edits the node with this id in place. Returns false when there is none.313 @discardableResult314 public mutating func updateNode(id: String, _ change: (inout CanvasNode) -> Void) -> Bool {315 guard let i = nodes.firstIndex(where: { $0.id == id }) else { return false }316 change(&nodes[i])317 return true318 }319320 /// Removes a node and every edge attached to it. Returns the removed edges' ids, nil when there is no such node.321 @discardableResult322 public mutating func removeNode(id: String) -> [String]? {323 guard let i = nodes.firstIndex(where: { $0.id == id }) else { return nil }324 nodes.remove(at: i)325 let gone = edges.filter { $0.from == id || $0.to == id }.map(\.id)326 edges.removeAll { $0.from == id || $0.to == id }327 return gone328 }329330 /// Appends an edge. Returns false, changing nothing, when the id is already used or an end is not a node.331 @discardableResult332 public mutating func addEdge(_ edge: CanvasEdge) -> Bool {333 guard self.edge(id: edge.id) == nil, node(id: edge.from) != nil, node(id: edge.to) != nil else { return false }334 edges.append(edge)335 return true336 }337338 /// Edits the edge with this id in place. Returns false when there is none.339 @discardableResult340 public mutating func updateEdge(id: String, _ change: (inout CanvasEdge) -> Void) -> Bool {341 guard let i = edges.firstIndex(where: { $0.id == id }) else { return false }342 change(&edges[i])343 return true344 }345346 @discardableResult347 public mutating func removeEdge(id: String) -> Bool {348 guard let i = edges.firstIndex(where: { $0.id == id }) else { return false }349 edges.remove(at: i)350 return true351 }352353 /// Puts a node in front of every other.354 @discardableResult355 public mutating func bringToFront(id: String) -> Bool {356 guard let i = nodes.firstIndex(where: { $0.id == id }) else { return false }357 let top = nodes.enumerated().filter { $0.offset != i }.map(\.element.z).max()358 if let top, nodes[i].z <= top { nodes[i].z = top + 1 }359 return true360 }361362 /// Puts a node behind every other.363 @discardableResult364 public mutating func sendToBack(id: String) -> Bool {365 guard let i = nodes.firstIndex(where: { $0.id == id }) else { return false }366 let bottom = nodes.enumerated().filter { $0.offset != i }.map(\.element.z).min()367 if let bottom, nodes[i].z >= bottom { nodes[i].z = bottom - 1 }368 return true369 }370371 /// Renumbers `z` to 0, 1, 2… keeping the stacking order (keeps the values small after many reorderings).372 public mutating func normalizeZ() {373 let order = nodes.enumerated().sorted { ($0.element.z, $0.offset) < ($1.element.z, $1.offset) }.map(\.offset)374 for (rank, i) in order.enumerated() where nodes[i].z != Double(rank) { nodes[i].z = Double(rank) }375 }376}377