SPB Git

Repository Public License

CanvasPersistence.swift 10.6 KB 219 lines swift

1// CanvasEngine — saving through the database, and exports (JSON, Markdown outline, render geometry).2import Foundation3import NavigatorCore4import Persistence56/// Debounced saving of canvases through `database.canvases`.7///8/// The UI calls `schedule` after every edit; the newest version of each document is written once the edits9/// pause for `delay`. What a crash can lose is that delay, nothing else. `flush()` writes immediately (closing10/// a canvas, backgrounding the app).11public actor CanvasAutosaver {12    private let database: NavigatorDatabase13    private let delay: Duration14    private var pending: [CanvasID: CanvasDocument] = [:]15    private var timer: Task<Void, Never>?16    public private(set) var lastError: (any Error)?17    public private(set) var savedCount = 01819    public init(database: NavigatorDatabase, delay: Duration = .milliseconds(800)) {20        self.database = database21        self.delay = delay22    }2324    /// Queues the document; a later call for the same canvas replaces it. `updatedAt` is stamped here.25    public func schedule(_ document: CanvasDocument, at date: Date = .now) {26        var stamped = document27        stamped.updatedAt = date28        pending[document.id] = stamped29        timer?.cancel()30        timer = Task { [delay] in31            try? await Task.sleep(for: delay)32            guard !Task.isCancelled else { return }33            await self.timerFired()34        }35    }3637    private func timerFired() async {38        do { try await writePending() } catch { lastError = error }39    }4041    public var hasPendingChanges: Bool { !pending.isEmpty }4243    /// Writes everything queued now. Documents that fail stay queued and the first error is thrown.44    public func flush() async throws {45        timer?.cancel()46        timer = nil47        try await writePending()48    }4950    private func writePending() async throws {51        var firstError: (any Error)?52        for (id, document) in pending.sorted(by: { $0.key < $1.key }) {53            do {54                try await database.canvases.save(document)55                // Only forget the version that was written: an edit may have arrived during the await.56                if pending[id] == document { pending[id] = nil }57                savedCount += 158            } catch {59                firstError = firstError ?? error60            }61        }62        lastError = firstError63        if let firstError { throw firstError }64    }6566    /// Drops a queued save (the canvas was deleted).67    public func discard(_ id: CanvasID) { pending[id] = nil }68}6970public enum CanvasExportError: Error, Sendable, Equatable, CustomStringConvertible {71    case notACanvasFile72    case unsupportedVersion(Int)73    case invalidDocument(issueCount: Int)7475    public var description: String {76        switch self {77        case .notACanvasFile: return "This is not an ORIX canvas export."78        case .unsupportedVersion(let version): return "Canvas export version \(version) is not supported by this build."79        case .invalidDocument(let count): return "The canvas in this file is invalid (\(count) problems) and was not imported."80        }81    }82}8384/// One card placed in the coordinate space of an exported image: origin at the top-left, units = pixels/points.85public struct CanvasRenderCard: Sendable, Hashable {86    public var id: CanvasCardID87    public var frame: CanvasRect88    public var content: CanvasCard.Content89    public var tint: SpaceTint?90    public var title: String91}9293/// Everything a rasteriser needs to draw a canvas into a PNG or PDF page: the output size, cards from back to94/// front and connection curves, all already in output coordinates.95public struct CanvasRenderPlan: Sendable, Hashable {96    /// The canvas region covered (content bounds plus margin).97    public var sourceBounds: CanvasRect98    public var size: CanvasSize99    public var scale: Double100    public var cards: [CanvasRenderCard]101    public var routes: [CanvasRoute]102}103104public enum CanvasExport {105    public static let formatIdentifier = "orix.canvas"106    public static let currentVersion = 1107108    struct Envelope: Codable {109        var format: String110        var version: Int111        var exportedAt: Date112        var document: CanvasDocument113    }114115    /// Versioned JSON: `{"format":"orix.canvas","version":1,"exportedAt":…,"document":{…}}`, ISO 8601 dates,116    /// sorted keys (stable output for the same document and date). Attachment files are not embedded.117    public static func json(_ document: CanvasDocument, exportedAt: Date = .now) throws -> Data {118        let encoder = JSONEncoder()119        encoder.dateEncodingStrategy = .iso8601120        encoder.outputFormatting = [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes]121        return try encoder.encode(Envelope(format: formatIdentifier, version: currentVersion, exportedAt: exportedAt, document: document))122    }123124    /// Reads a JSON export. The document is validated; an invalid one is rejected as a whole.125    /// `assigningNewIDs` gives the canvas and its cards fresh identifiers (import next to the original).126    public static func document(fromJSON data: Data, assigningNewIDs: Bool = false,127                                configuration: CanvasConfiguration = CanvasConfiguration()) throws -> CanvasDocument {128        struct Probe: Decodable { var format: String?; var version: Int? }129        let decoder = JSONDecoder()130        decoder.dateDecodingStrategy = .iso8601131        guard let probe = try? decoder.decode(Probe.self, from: data), probe.format == formatIdentifier,132              let version = probe.version else { throw CanvasExportError.notACanvasFile }133        guard version == currentVersion else { throw CanvasExportError.unsupportedVersion(version) }134        guard var document = (try? decoder.decode(Envelope.self, from: data))?.document else {135            throw CanvasExportError.notACanvasFile136        }137        let issues = CanvasEditor.validate(document, configuration: configuration)138        guard issues.isEmpty, document.cards.count <= configuration.maximumCards,139              document.connections.count <= configuration.maximumConnections else {140            throw CanvasExportError.invalidDocument(issueCount: max(issues.count, 1))141        }142        if assigningNewIDs {143            var mapping: [CanvasCardID: CanvasCardID] = [:]144            for index in document.cards.indices {145                let fresh = CanvasCardID()146                mapping[document.cards[index].id] = fresh147                document.cards[index].id = fresh148            }149            for index in document.connections.indices {150                document.connections[index].from = mapping[document.connections[index].from] ?? document.connections[index].from151                document.connections[index].to = mapping[document.connections[index].to] ?? document.connections[index].to152            }153            document.id = CanvasID()154            document.spaceID = nil155        }156        return document157    }158159    private static func escape(_ text: String) -> String {160        var result = ""161        for character in text {162            if "\\`*_[]<>#|".contains(character) { result.append("\\") }163            result.append(character.isNewline ? " " : character)164        }165        return result166    }167168    /// A Markdown outline: the title, then one bullet per card in reading order (top to bottom, left to right)169    /// with its outgoing connections as sub-bullets.170    public static func markdownOutline(_ document: CanvasDocument) -> String {171        let cards = document.cards.sorted { ($0.origin.y, $0.origin.x, $0.id) < ($1.origin.y, $1.origin.x, $1.id) }172        let titles = Dictionary(document.cards.map { ($0.id, $0.displayTitle) }, uniquingKeysWith: { first, _ in first })173        var lines = ["# \(escape(document.title.isEmpty ? "Untitled canvas" : document.title))", ""]174        for card in cards {175            switch card.content {176            case .page(let url, _):177                let target = url.absoluteString.replacingOccurrences(of: ")", with: "%29").replacingOccurrences(of: " ", with: "%20")178                lines.append("- [\(escape(card.displayTitle))](\(target))")179            case .note(let text):180                let paragraphs = text.split(whereSeparator: \.isNewline).map(String.init)181                lines.append("- \(escape(paragraphs.first ?? "Note"))")182                for paragraph in paragraphs.dropFirst() { lines.append("  \(escape(paragraph))") }183            case .image(let path):184                lines.append("- Image `\(path)`")185            case .pdf(let path, let page):186                lines.append("- PDF `\(path)`, page \(page)")187            }188            for connection in document.connections where connection.from == card.id {189                let target = escape(titles[connection.to] ?? "?")190                lines.append(connection.label.map { "  - → \(target) — \(escape($0))" } ?? "  - → \(target)")191            }192        }193        return lines.joined(separator: "\n") + "\n"194    }195196    /// Geometry for a PNG/PDF export of the whole canvas (or of the given cards). `scale` is output units per197    /// canvas unit; it is lowered if needed so neither side exceeds `maximumDimension`. `nil` for an empty canvas.198    public static func renderPlan(_ document: CanvasDocument, ids: Set<CanvasCardID>? = nil, margin: Double = 40,199                                  scale: Double = 2, maximumDimension: Double = 16_384) -> CanvasRenderPlan? {200        let editor = CanvasEditor(document: document)201        let cards = editor.cardsInZOrder.filter { ids?.contains($0.id) ?? true }202        guard let content = CanvasRect.bounding(cards.map(\.frame)) else { return nil }203        let bounds = content.insetBy(dx: -max(0, margin), dy: -max(0, margin))204        var scale = scale.isFinite && scale > 0 ? scale : 1205        scale = min(scale, maximumDimension / max(bounds.width, 1), maximumDimension / max(bounds.height, 1))206        let included = Set(cards.map(\.id))207        let renderCards = cards.map { card in208            CanvasRenderCard(id: card.id,209                             frame: CanvasRect(x: (card.origin.x - bounds.minX) * scale, y: (card.origin.y - bounds.minY) * scale,210                                               width: card.size.width * scale, height: card.size.height * scale),211                             content: card.content, tint: card.tint, title: card.displayTitle)212        }213        let routes = editor.routes().filter { included.contains($0.connection.from) && included.contains($0.connection.to) }214            .map { $0.offsetBy(dx: -bounds.minX, dy: -bounds.minY, scale: scale) }215        return CanvasRenderPlan(sourceBounds: bounds, size: CanvasSize(width: bounds.width * scale, height: bounds.height * scale),216                                scale: scale, cards: renderCards, routes: routes)217    }218}219
Files main
Menu

Theme