Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Canvas/CanvasModel.swift3// Description: View model of the infinite canvas (`spn-canvas-1`): loading, editing with undo / redo, selection, gestures4// expressed in screen coordinates (pan, move, resize, marquee, connect), tidy-up, debounced saving through5// `CanvasRepository.save(pageId:_:editedFrom:)` (works offline, merges by node / edge id), live changes, and6// the review of a sync conflict. No UI: everything here is driven by the unit tests.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreGraphics11import ImageIO12import Foundation13import Observation14import SPNotesDocument15import SPNotesSync1617/// What the host app's drawing editor receives when the user opens a `drawing` card.18public struct CanvasDrawingEditRequest: Sendable {19 public var pageId: String20 public var nodeId: String21 /// The current ink attachment (JSON `spn-ink-1`), nil for a new drawing.22 public var inkAttachmentId: String?23 /// The decoded ink when the canvas already loaded it.24 public var ink: InkDocument?25 /// Size of the card in canvas units (a sensible drawing size for a new one).26 public var size: CGSize27}2829/// What the host app's drawing editor returns: the attachment that now holds the `spn-ink-1` JSON.30public struct CanvasDrawingEditResult: Sendable {31 public var inkAttachmentId: String32 public var ink: InkDocument?33 public init(inkAttachmentId: String, ink: InkDocument? = nil) {34 self.inkAttachmentId = inkAttachmentId35 self.ink = ink36 }37}3839/// **Hook for the iOS app (PencilKit).** Set `CanvasModel.drawingEditor` (or pass it to `CanvasScreen`) to replace the40/// built-in mouse / touch ink editor: the closure presents the app's own editor (PencilKit), uploads the `spn-ink-1`41/// JSON as an attachment and returns its id — or nil when the user cancelled. The canvas then points the card at it.42public typealias CanvasDrawingEditorProvider = @MainActor @Sendable (CanvasDrawingEditRequest) async -> CanvasDrawingEditResult?4344/// A picture ready to draw in a card.45public enum CanvasMedia: @unchecked Sendable {46 case image(CGImage)47 case ink(InkDocument)48 case unavailable49}5051@Observable @MainActor52public final class CanvasModel {53 public enum Tool: String, Sendable, CaseIterable { case select, pan, connect }54 public enum SaveState: Equatable, Sendable { case saved, dirty, saving, failed(FeatureFailure) }55 public enum CompactMode: String, Sendable, CaseIterable { case outline, canvas }56 /// `auto` is the web's « Tidy up » policy (CANVAS.md §5): force-directed when the cards to lay out have connections, else the grid.57 public enum Tidy: Sendable { case auto, grid, force }5859 enum Drag {60 case pan(start: CanvasViewport)61 case move(start: CanvasDocument)62 case resize(handle: CanvasHandle, start: CanvasDocument)63 case marquee(origin: CGPoint, base: Set<String>)64 case connect(from: String)65 }6667 /// The built-in ink editor is open on this card.68 public struct InkSession: Identifiable, Equatable, Sendable {69 public var nodeId: String70 public var document: InkDocument71 public var id: String { nodeId }72 }7374 // MARK: State7576 public let pageId: String77 /// Title of the canvas page (nil until loaded or when the page is not on the device).78 public private(set) var title: String?79 public private(set) var phase: LoadPhase = .idle80 /// Always nil: a canvas is local-first, there is no "cached copy" to date. Kept for the common screen contract.81 public private(set) var freshness: Freshness?82 public var actionFailure: FeatureFailure?83 public private(set) var history = CanvasHistory(CanvasDocument())84 public private(set) var viewport = CanvasViewport()85 public var selection: Set<String> = []86 public var selectedEdgeId: String?87 public var tool: Tool = .select88 public var compactMode: CompactMode = .outline89 public private(set) var saveState: SaveState = .saved90 public private(set) var conflict: CanvasConflictState?91 /// Per conflict (`CanvasModel.key`), true = take the server's version in the merged proposal.92 public private(set) var conflictChoices: [String: Bool] = [:]93 /// Titles of the pages and references the cards point to.94 public private(set) var titles: [String: String] = [:]95 public private(set) var media: [String: CanvasMedia] = [:]96 public private(set) var syncError: String?97 public private(set) var marquee: CGRect?98 public private(set) var connectionPreview: CGPoint?99 /// First card chosen with the connect tool by tap (touch / keyboard path).100 public private(set) var pendingConnectionFrom: String?101 public var inkSession: InkSession?102 /// Size of the canvas surface in points (set by the view; used by fit / zoom buttons and new cards).103 public var viewSize = CGSize(width: 800, height: 600)104 /// True where dragging the empty background pans (touch); false where it draws a marquee (pointer).105 public var emptyDragPans = false106 public var drawingEditor: CanvasDrawingEditorProvider?107 public var attachments: FeatureAttachmentLoader108 /// Quiet time before an edit is saved.109 public var saveDelay: Duration = .milliseconds(600)110111 @ObservationIgnored private let repositories: NotesRepositories112 @ObservationIgnored private weak var router: (any FeatureRouter)?113 @ObservationIgnored private let now: @Sendable () -> Date114 @ObservationIgnored private var loaded = CanvasDocument()115 @ObservationIgnored private var drag: Drag?116 @ObservationIgnored private var dragOrigin = CGPoint.zero117 @ObservationIgnored private var saveTask: Task<Void, Never>?118 @ObservationIgnored private var didFit = false119120 public init(repositories: NotesRepositories, pageId: String, router: (any FeatureRouter)? = nil, attachments: FeatureAttachmentLoader = .unavailable,121 drawingEditor: CanvasDrawingEditorProvider? = nil, now: @escaping @Sendable () -> Date = { Date() }) {122 self.repositories = repositories123 self.pageId = pageId124 self.router = router125 self.attachments = attachments126 self.drawingEditor = drawingEditor127 self.now = now128 }129130 public var document: CanvasDocument { history.present }131 public var canUndo: Bool { history.canUndo }132 public var canRedo: Bool { history.canRedo }133 public var hasConflict: Bool { conflict != nil }134 public var selectedNodes: [CanvasNode] { document.nodes.filter { selection.contains($0.id) } }135 public var selectedEdge: CanvasEdge? { selectedEdgeId.flatMap { document.edge(id: $0) } }136 public var selectionBounds: CGRect { selectedNodes.reduce(CGRect.null) { $0.union(CanvasRouting.rect($1)) } }137138 /// Cards in reading order (top to bottom, then left to right): the outline of the compact layout.139 public var outline: [CanvasNode] {140 document.nodes.enumerated().sorted { a, b in141 let rowA = (a.element.y / 80).rounded(.down), rowB = (b.element.y / 80).rounded(.down)142 return (rowA, a.element.x, a.offset) < (rowB, b.element.x, b.offset)143 }.map(\.element)144 }145146 // MARK: Loading147148 public func load() async {149 if phase == .idle || phase.failure != nil { phase = .loading }150 do {151 var state = try await repositories.canvases.state(pageId: pageId)152 if state == nil { state = try await repositories.canvases.refresh(pageId: pageId) }153 guard let state else { throw RepositoryError.notFound(pageId) }154 adopt(state.document, resetViewport: true)155 syncError = state.syncError156 saveState = .saved157 conflict = state.hasConflict ? try await repositories.canvases.conflict(pageId: pageId) : nil158 conflictChoices = [:]159 phase = .loaded160 title = (try? await repositories.context.store.page(id: pageId))?.title161 await resolveTitles()162 await loadMedia()163 } catch {164 phase = .failed(FeatureFailure(error))165 }166 }167168 /// Follows the store: a sync cycle that changed this canvas (another device, a merge, a conflict) is reflected169 /// here. Runs until cancelled (call it from the screen's `.task`).170 public func observe() async {171 for await ids in await repositories.canvases.changes() where ids.contains(pageId) {172 await storeChanged()173 }174 }175176 func storeChanged() async {177 guard phase == .loaded, saveState != .saving else { return }178 guard let state = try? await repositories.canvases.state(pageId: pageId) else { return }179 syncError = state.syncError180 let hadConflict = conflict != nil181 conflict = state.hasConflict ? try? await repositories.canvases.conflict(pageId: pageId) : nil182 if hadConflict && conflict == nil { conflictChoices = [:] }183 guard !Self.sameContent(state.document, loaded) else { return }184 if saveState == .dirty || history.gesture != nil {185 await saveNow() // merges the user's edit into what the cycle stored186 } else {187 adopt(state.document, resetViewport: false)188 await resolveTitles()189 await loadMedia()190 }191 }192193 private func adopt(_ document: CanvasDocument, resetViewport: Bool) {194 history.replace(document)195 loaded = document196 if resetViewport { viewport = document.viewport; didFit = false }197 let ids = Set(document.nodes.map(\.id))198 selection.formIntersection(ids)199 if let edge = selectedEdgeId, document.edge(id: edge) == nil { selectedEdgeId = nil }200 }201202 static func sameContent(_ a: CanvasDocument, _ b: CanvasDocument) -> Bool {203 var x = a, y = b204 x.viewport = CanvasViewport()205 y.viewport = CanvasViewport()206 return x == y207 }208209 private func resolveTitles() async {210 var found = titles211 let store = repositories.context.store212 for id in Set(document.nodes.compactMap(\.pageId)) where found[id] == nil {213 if let page = try? await store.page(id: id) { found[id] = page.title }214 }215 let references = Set(document.nodes.compactMap(\.refId)).filter { found[$0] == nil }216 if !references.isEmpty, let resolved = try? await repositories.research.resolveLocally(ids: Array(references)) {217 for (id, reference) in resolved {218 let author = reference.authors?.first.map { $0 + (reference.year.map { " (\($0))" } ?? "") }219 found[id] = [author, reference.title].compactMap { $0 }.joined(separator: " — ")220 }221 }222 titles = found223 }224225 /// Loads the pictures of the image / pdf / drawing cards through the attachment loader (missing files stay226 /// placeholders: never an error for the whole canvas).227 public func loadMedia() async {228 let loader = attachments229 for node in document.nodes {230 if node.kind == .drawing, let id = node.ink, media[id] == nil {231 if let data = try? await loader.data(id: id), let ink = try? InkDocument(data: data) { media[id] = .ink(ink) } else { media[id] = .unavailable }232 } else if node.kind == .image || node.kind == .pdf, let id = node.attachmentId, media[id] == nil {233 if let data = try? await loader.data(id: id), let image = CanvasMediaDecoder.image(from: data, pdf: node.kind == .pdf) { media[id] = .image(image) } else { media[id] = .unavailable }234 }235 }236 }237238 // MARK: Editing239240 private func commit(_ change: (inout CanvasDocument) -> Void) {241 var next = document242 change(&next)243 guard next != document else { return }244 history.commit(next)245 markDirty()246 }247248 private func markDirty() {249 saveState = .dirty250 saveTask?.cancel()251 let delay = saveDelay252 saveTask = Task { [weak self] in253 try? await Task.sleep(for: delay)254 guard !Task.isCancelled else { return }255 await self?.saveNow()256 }257 }258259 /// Saves now (the screen calls it when it disappears). Works offline; a canvas that moved under the editor is260 /// merged by node / edge id and the editor continues from the merged document.261 public func saveNow() async {262 saveTask?.cancel()263 history.settle()264 var sent = document265 sent.viewport = viewport266 guard sent != loaded else { saveState = .saved; return }267 saveState = .saving268 do {269 let stored = try await repositories.canvases.save(pageId: pageId, sent, editedFrom: loaded)270 loaded = stored271 var current = document272 current.viewport = sent.viewport273 let result = current == sent ? stored : CanvasDocument.merge(base: sent, local: current, remote: stored).merged274 if !Self.sameContent(result, document) {275 history.replace(result)276 selection.formIntersection(Set(result.nodes.map(\.id)))277 await resolveTitles()278 }279 saveState = Self.sameContent(document, loaded) ? .saved : .dirty280 if saveState == .dirty { markDirty() }281 } catch {282 saveState = .failed(FeatureFailure(error))283 }284 }285286 public func undo() {287 guard history.undo() else { return }288 afterHistoryJump()289 }290291 public func redo() {292 guard history.redo() else { return }293 afterHistoryJump()294 }295296 private func afterHistoryJump() {297 selection.formIntersection(Set(document.nodes.map(\.id)))298 if let edge = selectedEdgeId, document.edge(id: edge) == nil { selectedEdgeId = nil }299 markDirty()300 }301302 /// Adds a card of `kind` (centred in the view unless `at` is given, in canvas units) and selects it.303 @discardableResult304 public func addNode(_ kind: CanvasNodeKind, at point: CGPoint? = nil, configure: (inout CanvasNode) -> Void = { _ in }) -> String {305 let center = point ?? CanvasViewportMath.screenToWorld(viewport, CGPoint(x: viewSize.width / 2, y: viewSize.height / 2))306 var node = CanvasDefaults.node(kind, centeredAt: center)307 configure(&node)308 commit { $0.addNode(node) }309 selection = [node.id]310 selectedEdgeId = nil311 return node.id312 }313314 /// Changes one card. `coalescing` = part of a typing run: one undo step until `endEditing()`.315 public func updateNode(id: String, coalescing: Bool = false, _ change: (inout CanvasNode) -> Void) {316 var next = document317 guard next.updateNode(id: id, change), next != document else { return }318 if coalescing { history.transient(next) } else { history.commit(next) }319 markDirty()320 }321322 public func updateEdge(id: String, coalescing: Bool = false, _ change: (inout CanvasEdge) -> Void) {323 var next = document324 guard next.updateEdge(id: id, change), next != document else { return }325 if coalescing { history.transient(next) } else { history.commit(next) }326 markDirty()327 }328329 /// Ends a typing run started with `coalescing: true`.330 public func endEditing() { history.settle() }331332 public func deleteSelection() {333 let nodes = selection, edge = selectedEdgeId334 guard !nodes.isEmpty || edge != nil else { return }335 commit { document in336 for id in nodes { document.removeNode(id: id) }337 if let edge { document.removeEdge(id: edge) }338 }339 selection = []340 selectedEdgeId = nil341 }342343 @discardableResult344 public func connect(from: String, to: String, kind: CanvasEdgeKind = .arrow) -> String? {345 guard from != to, document.node(id: from) != nil, document.node(id: to) != nil else { return nil }346 if let existing = document.edges.first(where: { $0.from == from && $0.to == to }) { selectedEdgeId = existing.id; return existing.id }347 let edge = CanvasEdge(from: from, to: to, kind: kind)348 commit { $0.addEdge(edge) }349 selection = []350 selectedEdgeId = edge.id351 return edge.id352 }353354 public func bringSelectionToFront() { let ids = selection; commit { d in ids.forEach { d.bringToFront(id: $0) } } }355 public func sendSelectionToBack() { let ids = selection; commit { d in ids.forEach { d.sendToBack(id: $0) } } }356357 /// Tidy-up with the shared deterministic layouts of Core (`CanvasLayout`), with the web's policy (CANVAS.md §5):358 /// the selection when it holds at least two cards (the others pinned), else everything; seed 1; 200 steps (120359 /// above 250 cards, 60 above 600); the top-left corner of the moved cards stays where it was. One undo step.360 public func tidy(_ how: Tidy = .auto) {361 let all = Set(document.nodes.map(\.id))362 let moving = selection.count >= 2 ? selection : all363 let pinned = all.subtracting(moving)364 func corner(_ document: CanvasDocument) -> CGPoint {365 document.nodes.filter { moving.contains($0.id) }.reduce(CGRect.null) { $0.union(CanvasRouting.rect($1)) }.origin366 }367 let before = corner(document)368 guard before.x.isFinite, before.y.isFinite else { return }369 let connected = document.edges.contains { moving.contains($0.from) && moving.contains($0.to) }370 let useForce = how == .force || (how == .auto && connected)371 commit { document in372 if useForce {373 let iterations = moving.count > 600 ? 60 : (moving.count > 250 ? 120 : 200)374 document = CanvasLayout.forceDirected(document, iterations: iterations, seed: 1, pinned: pinned)375 let after = corner(document)376 let dx = before.x - after.x, dy = before.y - after.y377 for i in document.nodes.indices where moving.contains(document.nodes[i].id) {378 document.nodes[i].x = CanvasRouting.r2(document.nodes[i].x + dx)379 document.nodes[i].y = CanvasRouting.r2(document.nodes[i].y + dy)380 }381 } else {382 document = CanvasLayout.grid(document, spacing: 48, origin: before, pinned: pinned)383 }384 }385 fitToContent()386 }387388 // MARK: Selection389390 public func select(_ id: String, extend: Bool = false) {391 selectedEdgeId = nil392 if extend { if selection.contains(id) { selection.remove(id) } else { selection.insert(id) } } else { selection = [id] }393 }394395 public func selectAll() { selection = Set(document.nodes.map(\.id)); selectedEdgeId = nil }396 public func clearSelection() { selection = []; selectedEdgeId = nil; pendingConnectionFrom = nil }397 public func clearPendingConnection() { pendingConnectionFrom = nil }398 /// Starts a connection from a card with the connect tool (the next card tapped is the target).399 public func beginConnection(from nodeId: String) { tool = .connect; pendingConnectionFrom = nodeId; selection = [nodeId]; selectedEdgeId = nil }400401 // MARK: Viewport402403 public func fitToContent() { viewport = CanvasViewportMath.fit(document.bounds, size: viewSize) }404 /// Fits once after the first layout when the stored viewport shows nothing of the content.405 public func fitIfNeeded() {406 guard !didFit, viewSize.width > 0 else { return }407 didFit = true408 let visible = CanvasViewportMath.visibleRect(viewport, size: viewSize)409 // As on the web: a canvas whose stored viewport is the default one is fitted on first open.410 if !document.nodes.isEmpty, viewport == CanvasViewport() || !visible.intersects(document.bounds) { fitToContent() }411 }412 public func pan(dx: Double, dy: Double) { viewport = CanvasViewportMath.pan(viewport, dx: dx, dy: dy) }413 public func zoom(by factor: Double, at point: CGPoint? = nil) {414 viewport = CanvasViewportMath.zoom(viewport, by: factor, at: point ?? CGPoint(x: viewSize.width / 2, y: viewSize.height / 2))415 }416 public func setZoom(_ zoom: Double, at point: CGPoint? = nil) {417 viewport = CanvasViewportMath.zoom(viewport, to: zoom, at: point ?? CGPoint(x: viewSize.width / 2, y: viewSize.height / 2))418 }419 public func center(on nodeId: String) {420 guard let node = document.node(id: nodeId) else { return }421 viewport = CanvasViewportMath.center(viewport, on: node.center, size: viewSize)422 }423424 // MARK: Gestures (screen coordinates of the canvas surface)425426 /// Radius (screen points) within which a resize handle is grabbed.427 public static let handleRadius = 12.0428429 public func handle(at screen: CGPoint) -> CanvasHandle? {430 guard !selection.isEmpty else { return nil }431 let box = CanvasViewportMath.worldToScreen(viewport, selectionBounds)432 guard !box.isNull else { return nil }433 return CanvasHandle.allCases.first { handle in434 let p = handle.point(on: box)435 return hypot(p.x - screen.x, p.y - screen.y) <= Self.handleRadius436 }437 }438439 public func beginDrag(at screen: CGPoint, extend: Bool = false) {440 dragOrigin = screen441 let world = CanvasViewportMath.screenToWorld(viewport, screen)442 let hit = CanvasHit.node(in: document, at: world)443 switch tool {444 case .pan:445 drag = .pan(start: viewport)446 case .connect:447 if let hit { drag = .connect(from: hit.id); connectionPreview = world } else { drag = .pan(start: viewport) }448 case .select:449 if let handle = handle(at: screen) {450 drag = .resize(handle: handle, start: document)451 } else if let hit {452 if !selection.contains(hit.id) { select(hit.id, extend: extend) }453 drag = .move(start: document)454 } else if emptyDragPans {455 drag = .pan(start: viewport)456 } else {457 drag = .marquee(origin: world, base: extend ? selection : [])458 selectedEdgeId = nil459 }460 }461 }462463 public func continueDrag(to screen: CGPoint) {464 guard let drag else { return }465 let dx = screen.x - dragOrigin.x, dy = screen.y - dragOrigin.y466 let world = CanvasViewportMath.screenToWorld(viewport, screen)467 switch drag {468 case .pan(let start):469 viewport = CanvasViewportMath.pan(start, dx: dx, dy: dy)470 case .move(let start):471 var next = start472 let wx = dx / viewport.zoom, wy = dy / viewport.zoom473 for i in next.nodes.indices where selection.contains(next.nodes[i].id) {474 next.nodes[i].x = CanvasRouting.r2(start.nodes[i].x + wx)475 next.nodes[i].y = CanvasRouting.r2(start.nodes[i].y + wy)476 }477 history.transient(next)478 case .resize(let handle, let start):479 history.transient(CanvasResize.nodes(start, ids: selection, handle: handle, dx: dx / viewport.zoom, dy: dy / viewport.zoom))480 case .marquee(let origin, let base):481 let rect = CanvasHit.rect(from: origin, to: world)482 marquee = rect483 selection = base.union(CanvasHit.nodes(in: document, touching: rect).map(\.id))484 case .connect:485 connectionPreview = world486 }487 }488489 public func endDrag(at screen: CGPoint) {490 defer { drag = nil; marquee = nil; connectionPreview = nil }491 guard let drag else { return }492 switch drag {493 case .move, .resize:494 let changed = history.gesture != nil && history.gesture != document495 history.settle()496 if changed { markDirty() }497 case .connect(let from):498 let world = CanvasViewportMath.screenToWorld(viewport, screen)499 if let target = CanvasHit.node(in: document, at: world), target.id != from { connect(from: from, to: target.id) }500 case .pan, .marquee:501 break502 }503 }504505 /// A click / tap without movement.506 public func tap(at screen: CGPoint, extend: Bool = false) {507 let world = CanvasViewportMath.screenToWorld(viewport, screen)508 if let node = CanvasHit.node(in: document, at: world) {509 if tool == .connect {510 if let from = pendingConnectionFrom, from != node.id { connect(from: from, to: node.id); pendingConnectionFrom = nil }511 else { pendingConnectionFrom = node.id; selection = [node.id] }512 } else {513 select(node.id, extend: extend)514 }515 } else if let edge = CanvasHit.edge(in: document, at: world, tolerance: 8 / viewport.zoom) {516 selection = []517 selectedEdgeId = edge.id518 } else {519 clearSelection()520 }521 }522523 // MARK: Opening what a card points to524525 public func open(_ nodeId: String) {526 guard let node = document.node(id: nodeId) else { return }527 switch node.kind {528 case .page:529 if let page = node.pageId { router?.openPage(id: page, blockId: nil) }530 case .link:531 if let url = node.url.flatMap(URL.init(string:)), ["http", "https", "mailto"].contains(url.scheme?.lowercased() ?? "") { router?.openURL(url) }532 case .drawing:533 Task { await editDrawing(nodeId) }534 default:535 break536 }537 }538539 public func canOpen(_ node: CanvasNode) -> Bool {540 switch node.kind {541 case .page: return node.pageId != nil542 case .link: return node.url.flatMap(URL.init(string:)) != nil543 case .drawing: return true544 default: return false545 }546 }547548 /// Opens the drawing of a card: the host's editor when `drawingEditor` is set (PencilKit on iOS), else the549 /// built-in ink editor (`inkSession`, presented by the screen). Convention shared with the web (CANVAS.md §1.1): a new550 /// drawing's `spn-ink-1` document has the size of the card, points relative to its top-left corner; a card resized551 /// later stretches the ink.552 public func editDrawing(_ nodeId: String) async {553 guard let node = document.node(id: nodeId), node.kind == .drawing else { return }554 var ink: InkDocument?555 if let id = node.ink, case .ink(let loaded)? = media[id] { ink = loaded }556 if let drawingEditor {557 let request = CanvasDrawingEditRequest(pageId: pageId, nodeId: nodeId, inkAttachmentId: node.ink, ink: ink, size: CGSize(width: node.w, height: node.h))558 guard let result = await drawingEditor(request) else { return }559 if let document = result.ink { media[result.inkAttachmentId] = .ink(document) }560 updateNode(id: nodeId) { $0.ink = result.inkAttachmentId }561 await loadMedia()562 } else {563 inkSession = InkSession(nodeId: nodeId, document: ink ?? InkDocument(width: max(CanvasResize.minNodeSize, node.w), height: max(CanvasResize.minNodeSize, node.h)))564 }565 }566567 /// Stores what the built-in ink editor produced: the `spn-ink-1` JSON becomes a new attachment (online) and the568 /// card points to it. On failure nothing changes and the editor stays open.569 public func finishInkSession(_ ink: InkDocument) async {570 guard let session = inkSession else { return }571 do {572 let id = try await attachments.upload(ink.jsonData(), filename: "dessin.spn-ink.json", mimeType: "application/json", pageId: pageId)573 media[id] = .ink(ink)574 updateNode(id: session.nodeId) { $0.ink = id }575 inkSession = nil576 } catch {577 actionFailure = FeatureFailure(error)578 }579 }580581 // MARK: Conflict review582583 public static func key(_ conflict: CanvasConflict) -> String { conflict.kind.rawValue + ":" + conflict.id }584585 public func takesRemote(_ conflict: CanvasConflict) -> Bool { conflictChoices[Self.key(conflict)] ?? false }586587 public func choose(_ conflict: CanvasConflict, takingRemote: Bool) { conflictChoices[Self.key(conflict)] = takingRemote }588589 /// The merged proposal with the user's choices applied (the default keeps this device's version of every590 /// conflicting element; an edited card is kept when the other side deleted it).591 public var conflictProposal: CanvasDocument? {592 guard let conflict else { return nil }593 return conflict.merge.conflicts.reduce(conflict.merge.merged) { document, item in594 takesRemote(item) ? document.resolving(item, takingRemote: true) : document595 }596 }597598 public enum ConflictDecision: Sendable { case keepMine, keepTheirs, applyChoices }599600 public func resolveConflict(_ decision: ConflictDecision) async {601 guard let conflict else { return }602 await saveNow()603 // A save changes the edit sequence the conflict was read at: read it again before deciding.604 guard let current = (try? await repositories.canvases.conflict(pageId: pageId)) ?? nil else { self.conflict = nil; return }605 do {606 switch decision {607 case .keepMine: try await repositories.canvases.resolve(current, .keepMine)608 case .keepTheirs: try await repositories.canvases.resolve(current, .keepTheirs)609 case .applyChoices:610 let proposal = current.merge.conflicts.reduce(current.merge.merged) { document, item in611 takesRemote(item) ? document.resolving(item, takingRemote: true) : document612 }613 try await repositories.canvases.resolve(current, .merged(proposal))614 }615 _ = conflict616 await reloadAfterConflict()617 } catch {618 let failure = FeatureFailure(error)619 actionFailure = failure620 if failure.kind == .stale { await reloadAfterConflict() }621 }622 }623624 private func reloadAfterConflict() async {625 guard let state = try? await repositories.canvases.state(pageId: pageId) else { return }626 adopt(state.document, resetViewport: false)627 saveState = .saved628 syncError = state.syncError629 conflict = state.hasConflict ? try? await repositories.canvases.conflict(pageId: pageId) : nil630 conflictChoices = [:]631 await resolveTitles()632 await loadMedia()633 }634635 // MARK: Labels636637 /// One line that names a card in lists and for VoiceOver (never empty).638 public func label(_ node: CanvasNode) -> String { CanvasNodeLabel.label(node, titles: titles) }639}640641/// Names of cards (the same rules as the web `nodeLabel`).642public enum CanvasNodeLabel {643 static func firstLine(_ text: String?) -> String {644 for line in (text ?? "").split(separator: "\n") {645 let cleaned = line.drop { "#>*- \t".contains($0) }.trimmingCharacters(in: .whitespaces)646 if !cleaned.isEmpty { return cleaned }647 }648 return ""649 }650651 public static func label(_ node: CanvasNode, titles: [String: String] = [:]) -> String {652 let text = firstLine(node.text)653 func or(_ fallback: String) -> String { text.isEmpty ? fallback : text }654 switch node.kind {655 case .page: return node.pageId.flatMap { titles[$0] }.flatMap { $0.isEmpty ? nil : $0 } ?? or(L("Page"))656 case .reference: return node.refId.flatMap { titles[$0] } ?? or(L("Référence"))657 case .link: return text.isEmpty ? (node.url.flatMap { $0.isEmpty ? nil : $0 } ?? L("Lien")) : text658 case .math: return node.latex.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.flatMap { $0.isEmpty ? nil : $0 } ?? or(L("Formule"))659 case .image: return or(L("Image"))660 case .pdf: return or(L("PDF"))661 case .drawing: return or(L("Dessin"))662 case .table:663 let header = CanvasTable.parse(node.text).first?.filter { !$0.isEmpty }.joined(separator: " · ") ?? ""664 return header.isEmpty ? L("Tableau") : header665 case .shape:666 if !text.isEmpty { return text }667 switch node.shape {668 case .ellipse?: return L("Ellipse")669 case .diamond?: return L("Losange")670 default: return L("Rectangle")671 }672 case .text: return or(L("Texte"))673 default: return or(LF("Carte (%@)", node.kind.rawValue))674 }675 }676677 public static func kindName(_ kind: CanvasNodeKind) -> String {678 switch kind {679 case .text: return L("Texte")680 case .page: return L("Page")681 case .image: return L("Image")682 case .pdf: return L("PDF")683 case .link: return L("Lien")684 case .drawing: return L("Dessin")685 case .shape: return L("Forme")686 case .reference: return L("Référence")687 case .math: return L("Formule")688 case .table: return L("Tableau")689 default: return LF("Carte (%@)", kind.rawValue)690 }691 }692693 public static func symbol(_ kind: CanvasNodeKind) -> String {694 switch kind {695 case .text: return "text.alignleft"696 case .page: return "doc.text"697 case .image: return "photo"698 case .pdf: return "doc.richtext"699 case .link: return "link"700 case .drawing: return "scribble.variable"701 case .shape: return "square.on.circle"702 case .reference: return "quote.opening"703 case .math: return "function"704 case .table: return "tablecells"705 default: return "questionmark.square.dashed"706 }707 }708}709710/// Decodes attachment bytes into a picture (ImageIO for images, first page for a PDF). CoreGraphics only.711public enum CanvasMediaDecoder {712 public static func image(from data: Data, pdf: Bool, maxPixel: Int = 1024) -> CGImage? {713 if pdf || data.prefix(5) == Data("%PDF-".utf8) { return pdfFirstPage(data, maxPixel: maxPixel) }714 guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }715 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,716 kCGImageSourceThumbnailMaxPixelSize: maxPixel]717 return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)718 }719720 public static func pdfFirstPage(_ data: Data, maxPixel: Int = 1024) -> CGImage? {721 guard let provider = CGDataProvider(data: data as CFData), let document = CGPDFDocument(provider), let page = document.page(at: 1) else { return nil }722 let box = page.getBoxRect(.cropBox)723 let rotated = page.rotationAngle % 180 != 0724 let size = rotated ? CGSize(width: box.height, height: box.width) : box.size725 guard size.width > 0, size.height > 0 else { return nil }726 let scale = min(CGFloat(maxPixel) / max(size.width, size.height), 3)727 let width = Int((size.width * scale).rounded()), height = Int((size.height * scale).rounded())728 guard width > 0, height > 0, let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,729 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }730 context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))731 context.fill(CGRect(x: 0, y: 0, width: width, height: height))732 context.scaleBy(x: scale, y: scale)733 context.concatenate(page.getDrawingTransform(.cropBox, rect: CGRect(origin: .zero, size: size), rotate: 0, preserveAspectRatio: true))734 context.drawPDFPage(page)735 return context.makeImage()736 }737}738