Repository Public
1import CoreGraphics2import Foundation34/// AURA Canvas: a free surface where links, excerpts, notes, images and tabs become movable cards.5/// The same document format is used on Mac, iPad and iPhone.6struct CanvasCard: Codable, Equatable, Identifiable, Sendable {7 enum Kind: String, Codable, CaseIterable, Sendable { case link, text, note, image, tab, pdf, capture, reference }8 var id: UUID = UUID()9 var kind: Kind10 var title: String = ""11 /// Body text: the note, the excerpt, the citation.12 var text: String = ""13 var url: String?14 /// File name of a locally stored image (captures, dropped images) inside the board's asset folder. Never synchronized.15 var asset: String?16 var x: Double = 017 var y: Double = 018 var width: Double = 24019 var height: Double = 13220 var colorIndex: Int = 021 var groupID: UUID?22 var createdAt: Date = Date()23 var modifiedAt: Date = Date()2425 var frame: CGRect { CGRect(x: x, y: y, width: width, height: height) }26 var center: CGPoint { CGPoint(x: x + width / 2, y: y + height / 2) }27 var host: String { url.flatMap { URL(string: $0)?.host } ?? "" }2829 static func defaultSize(for kind: Kind) -> CGSize {30 switch kind {31 case .note, .text: return CGSize(width: 240, height: 150)32 case .image, .capture: return CGSize(width: 280, height: 200)33 case .link, .tab, .pdf, .reference: return CGSize(width: 250, height: 112)34 }35 }36}3738struct CanvasConnection: Codable, Equatable, Identifiable, Sendable {39 var id: UUID = UUID()40 var from: UUID41 var to: UUID42 var label: String = ""43}4445struct CanvasGroup: Codable, Equatable, Identifiable, Sendable {46 var id: UUID = UUID()47 var name: String48 var colorIndex: Int = 049}5051struct CanvasBoard: Codable, Equatable, Identifiable, Sendable {52 static let currentVersion = 153 var version = CanvasBoard.currentVersion54 var id: UUID = UUID()55 var name: String56 var cards: [CanvasCard] = []57 var connections: [CanvasConnection] = []58 var groups: [CanvasGroup] = []59 /// Opt-in: only boards the user chose to synchronize ever reach SP Sync.60 var isSynced = false61 var createdAt: Date = Date()62 var modifiedAt: Date = Date()6364 static let zoomRange: ClosedRange<Double> = 0.2...3.065 static let snapDistance: Double = 866 static let maxCards = 20006768 // MARK: Editing6970 func card(_ id: UUID?) -> CanvasCard? { id.flatMap { id in cards.first { $0.id == id } } }7172 /// Adds a card near `point` (or after the existing content when nil), nudged so it does not hide another card.73 @discardableResult74 mutating func add(_ kind: CanvasCard.Kind, title: String = "", text: String = "", url: String? = nil, asset: String? = nil, at point: CGPoint? = nil, now: Date = Date()) -> CanvasCard? {75 guard cards.count < Self.maxCards else { return nil }76 let size = CanvasCard.defaultSize(for: kind)77 var origin = point.map { CGPoint(x: $0.x - size.width / 2, y: $0.y - size.height / 2) } ?? nextFreeOrigin(for: size)78 var attempts = 079 while attempts < 40, cards.contains(where: { abs($0.x - origin.x) < 12 && abs($0.y - origin.y) < 12 }) {80 origin.x += 24; origin.y += 24; attempts += 181 }82 let card = CanvasCard(kind: kind, title: String(title.prefix(300)), text: String(text.prefix(20_000)), url: url, asset: asset,83 x: origin.x, y: origin.y, width: size.width, height: size.height,84 colorIndex: kind == .note ? cards.filter { $0.kind == .note }.count % 6 : 0, createdAt: now, modifiedAt: now)85 cards.append(card)86 modifiedAt = now87 return card88 }8990 /// Where the next card goes when the user did not point anywhere: a tidy grid under what is already there.91 func nextFreeOrigin(for size: CGSize) -> CGPoint {92 guard let box = contentBounds else { return CGPoint(x: 80, y: 80) }93 let lastRow = cards.filter { $0.y >= box.maxY - 260 }94 if let right = lastRow.map(\.frame.maxX).max(), right + 24 + size.width <= box.minX + 1200 {95 return CGPoint(x: right + 24, y: lastRow.map(\.y).min() ?? box.minY)96 }97 return CGPoint(x: box.minX, y: box.maxY + 24)98 }99100 mutating func update(_ card: CanvasCard, now: Date = Date()) {101 guard let index = cards.firstIndex(where: { $0.id == card.id }) else { return }102 var copy = card103 copy.modifiedAt = now104 cards[index] = copy105 modifiedAt = now106 }107108 mutating func move(_ ids: Set<UUID>, by delta: CGSize, now: Date = Date()) {109 for index in cards.indices where ids.contains(cards[index].id) {110 cards[index].x += delta.width111 cards[index].y += delta.height112 cards[index].modifiedAt = now113 }114 modifiedAt = now115 }116117 mutating func remove(_ ids: Set<UUID>, now: Date = Date()) {118 cards.removeAll { ids.contains($0.id) }119 connections.removeAll { ids.contains($0.from) || ids.contains($0.to) }120 groups.removeAll { group in !cards.contains { $0.groupID == group.id } }121 modifiedAt = now122 }123124 /// Connects two cards once; connecting them again removes the link (a toggle, as on a whiteboard).125 mutating func toggleConnection(_ a: UUID, _ b: UUID, now: Date = Date()) {126 guard a != b, card(a) != nil, card(b) != nil else { return }127 if let index = connections.firstIndex(where: { ($0.from == a && $0.to == b) || ($0.from == b && $0.to == a) }) {128 connections.remove(at: index)129 } else {130 connections.append(CanvasConnection(from: a, to: b))131 }132 modifiedAt = now133 }134135 @discardableResult136 mutating func group(_ ids: Set<UUID>, name: String, now: Date = Date()) -> CanvasGroup? {137 guard ids.count > 1 else { return nil }138 let group = CanvasGroup(name: name, colorIndex: groups.count % 6)139 groups.append(group)140 for index in cards.indices where ids.contains(cards[index].id) { cards[index].groupID = group.id; cards[index].modifiedAt = now }141 groups.removeAll { g in !cards.contains { $0.groupID == g.id } }142 modifiedAt = now143 return group144 }145146 mutating func ungroup(_ groupID: UUID, now: Date = Date()) {147 for index in cards.indices where cards[index].groupID == groupID { cards[index].groupID = nil; cards[index].modifiedAt = now }148 groups.removeAll { $0.id == groupID }149 modifiedAt = now150 }151152 // MARK: Geometry153154 var contentBounds: CGRect? {155 guard !cards.isEmpty else { return nil }156 return cards.reduce(CGRect.null) { $0.union($1.frame) }157 }158159 func bounds(ofGroup id: UUID) -> CGRect? {160 let members = cards.filter { $0.groupID == id }161 guard !members.isEmpty else { return nil }162 return members.reduce(CGRect.null) { $0.union($1.frame) }.insetBy(dx: -16, dy: -30)163 }164165 struct Snap: Equatable, Sendable {166 var origin: CGPoint167 /// Guide lines to draw: x positions of vertical guides, y positions of horizontal ones.168 var verticalGuides: [Double] = []169 var horizontalGuides: [Double] = []170 }171172 /// Magnetic alignment: a moved card snaps its edges and centre to those of its neighbours when within `distance`.173 func snap(_ frame: CGRect, excluding ids: Set<UUID>, distance: Double = CanvasBoard.snapDistance) -> Snap {174 var bestX: (delta: Double, guide: Double)?175 var bestY: (delta: Double, guide: Double)?176 for other in cards where !ids.contains(other.id) {177 let o = other.frame178 // Only neighbours close enough to matter take part, so a far card does not pull this one.179 guard abs(o.midX - frame.midX) < 900, abs(o.midY - frame.midY) < 900 else { continue }180 for (mine, theirs) in [(frame.minX, o.minX), (frame.minX, o.maxX), (frame.maxX, o.maxX), (frame.maxX, o.minX), (frame.midX, o.midX)] {181 let delta = theirs - mine182 if abs(delta) <= distance, abs(delta) < abs(bestX?.delta ?? .infinity) { bestX = (delta, theirs) }183 }184 for (mine, theirs) in [(frame.minY, o.minY), (frame.minY, o.maxY), (frame.maxY, o.maxY), (frame.maxY, o.minY), (frame.midY, o.midY)] {185 let delta = theirs - mine186 if abs(delta) <= distance, abs(delta) < abs(bestY?.delta ?? .infinity) { bestY = (delta, theirs) }187 }188 }189 return Snap(origin: CGPoint(x: frame.minX + (bestX?.delta ?? 0), y: frame.minY + (bestY?.delta ?? 0)),190 verticalGuides: bestX.map { [$0.guide] } ?? [], horizontalGuides: bestY.map { [$0.guide] } ?? [])191 }192193 static func clampZoom(_ value: Double) -> Double { min(max(value, zoomRange.lowerBound), zoomRange.upperBound) }194195 // MARK: Search and export196197 func search(_ query: String) -> [CanvasCard] {198 let needle = query.trimmingCharacters(in: .whitespaces).lowercased()199 guard !needle.isEmpty else { return [] }200 return cards.filter { $0.title.lowercased().contains(needle) || $0.text.lowercased().contains(needle) || ($0.url ?? "").lowercased().contains(needle) }201 }202203 /// The board as Markdown: groups as sections, cards in reading order (top to bottom, left to right), connections listed at the end.204 func markdown() -> String {205 var out = "# \(name)\n"206 func line(_ card: CanvasCard) -> String {207 let title = card.title.isEmpty ? (card.url ?? card.kind.rawValue.capitalized) : card.title208 var text = card.url.map { "- [\(title.replacingOccurrences(of: "]", with: "\\]"))](\($0))" } ?? "- **\(title)**"209 if !card.text.isEmpty { text += "\n" + card.text.split(separator: "\n", omittingEmptySubsequences: false).map { " > " + $0 }.joined(separator: "\n") }210 return text211 }212 let ordered = cards.sorted { ($0.y / 80).rounded() == ($1.y / 80).rounded() ? $0.x < $1.x : $0.y < $1.y }213 let loose = ordered.filter { $0.groupID == nil }214 if !loose.isEmpty { out += "\n" + loose.map(line).joined(separator: "\n") + "\n" }215 for group in groups {216 let members = ordered.filter { $0.groupID == group.id }217 guard !members.isEmpty else { continue }218 out += "\n## \(group.name)\n\n" + members.map(line).joined(separator: "\n") + "\n"219 }220 let named = connections.compactMap { c -> String? in221 guard let a = card(c.from), let b = card(c.to) else { return nil }222 let left = a.title.isEmpty ? (a.url ?? "…") : a.title, right = b.title.isEmpty ? (b.url ?? "…") : b.title223 return "- \(left) → \(right)" + (c.label.isEmpty ? "" : " (\(c.label))")224 }225 if !named.isEmpty { out += "\n## " + L("Connections") + "\n\n" + named.joined(separator: "\n") + "\n" }226 return out227 }228}229230/// Stores the boards of a profile as one JSON file each, plus a folder of image assets per board.231final class CanvasStore: @unchecked Sendable {232 let directory: URL?233 private let lock = NSLock()234 private var cache: [UUID: CanvasBoard] = [:]235236 /// `directory == nil` keeps boards in memory only (tests).237 init(directory: URL?) {238 self.directory = directory239 guard let directory else { return }240 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)241 let files = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []242 for file in files where file.pathExtension == "json" {243 if let board = try? JSONFile.read(CanvasBoard.self, from: file) { cache[board.id] = board }244 }245 }246247 var boards: [CanvasBoard] { lock.lock(); defer { lock.unlock() }; return cache.values.sorted { $0.modifiedAt > $1.modifiedAt } }248 func board(_ id: UUID) -> CanvasBoard? { lock.lock(); defer { lock.unlock() }; return cache[id] }249250 @discardableResult251 func create(name: String) -> CanvasBoard {252 let board = CanvasBoard(name: name.trimmingCharacters(in: .whitespaces).isEmpty ? L("Untitled canvas") : name)253 save(board)254 return board255 }256257 func save(_ board: CanvasBoard) {258 lock.lock(); cache[board.id] = board; lock.unlock()259 if let url = fileURL(board.id) { try? JSONFile.write(board, to: url) }260 }261262 func delete(_ id: UUID) {263 lock.lock(); cache[id] = nil; lock.unlock()264 if let url = fileURL(id) { try? FileManager.default.removeItem(at: url) }265 if let assets = assetDirectory(id) { try? FileManager.default.removeItem(at: assets) }266 }267268 private func fileURL(_ id: UUID) -> URL? { directory?.appendingPathComponent(id.uuidString + ".json") }269 func assetDirectory(_ id: UUID) -> URL? { directory?.appendingPathComponent(id.uuidString + ".assets", isDirectory: true) }270271 /// Stores image data for a card and returns the asset name. Only called from an explicit user action.272 func storeAsset(_ data: Data, board: UUID, fileExtension: String = "png") -> String? {273 guard let folder = assetDirectory(board), data.count < 30_000_000 else { return nil }274 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)275 let name = UUID().uuidString + "." + fileExtension276 return (try? data.write(to: folder.appendingPathComponent(name), options: .atomic)) != nil ? name : nil277 }278279 func assetURL(_ name: String?, board: UUID) -> URL? {280 // Asset names are generated by `storeAsset`; anything that tries to leave the folder is refused.281 guard let name, !name.contains("/"), !name.contains(".."), let folder = assetDirectory(board) else { return nil }282 return folder.appendingPathComponent(name)283 }284}285286/// Carries the boards the user chose to synchronize through SP Sync, one encrypted record per card so that edits on287/// two devices merge card by card. Local image assets are not uploaded.288struct CanvasSyncBridge: Sendable {289 let store: CanvasStore290 let mirror: SyncDatabase291292 struct BoardHeader: Codable, Equatable, Sendable {293 var id: UUID294 var name: String295 var connections: [CanvasConnection]296 var groups: [CanvasGroup]297 var createdAt: Date298 var modifiedAt: Date299 }300 struct CardRecord: Codable, Equatable, Sendable {301 var board: UUID302 var card: CanvasCard303 }304305 private static func headerKey(_ id: UUID) -> String { "b:" + id.uuidString }306 private static func cardKey(_ board: UUID, _ card: UUID) -> String { "c:" + board.uuidString + ":" + card.uuidString }307308 /// Writes what changed locally into the mirror (marking it to be sent). Boards that are not synced are withdrawn.309 func captureLocalChanges() {310 var wanted = Set<String>()311 for board in store.boards where board.isSynced {312 let header = BoardHeader(id: board.id, name: board.name, connections: board.connections, groups: board.groups, createdAt: board.createdAt, modifiedAt: board.modifiedAt)313 let key = Self.headerKey(board.id)314 wanted.insert(key)315 if mirror.value(SyncCollection.canvas, key: key, as: BoardHeader.self) != header { mirror.put(SyncCollection.canvas, key: key, value: header, modifiedAt: board.modifiedAt) }316 for var card in board.cards {317 card.asset = nil318 let cardKey = Self.cardKey(board.id, card.id)319 wanted.insert(cardKey)320 let record = CardRecord(board: board.id, card: card)321 if mirror.value(SyncCollection.canvas, key: cardKey, as: CardRecord.self) != record { mirror.put(SyncCollection.canvas, key: cardKey, value: record, modifiedAt: card.modifiedAt) }322 }323 }324 for record in mirror.records(SyncCollection.canvas) where !record.deleted && !wanted.contains(record.key) {325 // Only withdraw what this device knows locally; a board that exists only remotely is adopted in `applyRemoteChanges`.326 if let boardID = Self.boardID(of: record.key), let local = store.board(boardID) {327 if !local.isSynced || record.key.hasPrefix("c:") { mirror.remove(SyncCollection.canvas, key: record.key) }328 }329 }330 }331332 /// Rebuilds synced boards from the mirror after a pull. Local assets of existing cards are kept.333 func applyRemoteChanges() {334 let headers = mirror.values(SyncCollection.canvas, as: BoardHeader.self)335 let cards = Dictionary(grouping: mirror.values(SyncCollection.canvas, as: CardRecord.self), by: \.board)336 var live = Set<UUID>()337 for header in headers {338 live.insert(header.id)339 let local = store.board(header.id)340 if let local, !local.isSynced { continue }341 var board = local ?? CanvasBoard(id: header.id, name: header.name, isSynced: true, createdAt: header.createdAt)342 let assets = Dictionary(uniqueKeysWithValues: (local?.cards ?? []).compactMap { c in c.asset.map { (c.id, $0) } })343 board.name = header.name344 board.connections = header.connections345 board.groups = header.groups346 board.modifiedAt = header.modifiedAt347 board.isSynced = true348 board.cards = (cards[header.id] ?? []).map { record in349 var card = record.card350 card.asset = assets[card.id]351 return card352 }.sorted { $0.createdAt < $1.createdAt }353 if board != local { store.save(board) }354 }355 // A synced board whose header was deleted on another device stops being synced here but is not destroyed.356 let deleted = Set(mirror.records(SyncCollection.canvas).filter { $0.deleted && $0.key.hasPrefix("b:") }.compactMap { Self.boardID(of: $0.key) })357 for board in store.boards where board.isSynced && deleted.contains(board.id) && !live.contains(board.id) {358 var copy = board359 copy.isSynced = false360 store.save(copy)361 }362 }363364 private static func boardID(of key: String) -> UUID? {365 let parts = key.split(separator: ":")366 return parts.count >= 2 ? UUID(uuidString: String(parts[1])) : nil367 }368}369