Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Canvas/CanvasHistory.swift3// Description: Undo / redo history of the canvas editor, same rules as the web one (`src/lib/canvas/history.ts`): a4// gesture (drag, resize, typing run) is one step — its intermediate states are transient and only `settle`5// records it; viewport changes are never history; a document that did not come from the user (server copy,6// merge) replaces the present and drops the history.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesDocument1213public struct CanvasHistory: Sendable, Equatable {14 public static let limit = 2001516 public private(set) var past: [CanvasDocument] = []17 public private(set) var present: CanvasDocument18 public private(set) var future: [CanvasDocument] = []19 /// The document before the gesture in progress (nil when idle).20 public private(set) var gesture: CanvasDocument?2122 public init(_ present: CanvasDocument) { self.present = present }2324 public var canUndo: Bool { !past.isEmpty || (gesture != nil && gesture != present) }25 public var canRedo: Bool { !future.isEmpty && gesture == nil }2627 private mutating func push(_ document: CanvasDocument) {28 past.append(document)29 if past.count > Self.limit { past.removeFirst(past.count - Self.limit) }30 }3132 /// One undoable step (a no-op changes nothing). Ends any gesture in progress first.33 public mutating func commit(_ next: CanvasDocument) {34 settle()35 guard next != present else { return }36 push(present)37 present = next38 future = []39 }4041 /// An intermediate state of a gesture: shown, not recorded.42 public mutating func transient(_ next: CanvasDocument) {43 guard next != present else { return }44 if gesture == nil { gesture = present }45 present = next46 }4748 /// Ends the gesture: everything since it began becomes one step.49 public mutating func settle() {50 guard let start = gesture else { return }51 gesture = nil52 guard start != present else { return }53 push(start)54 future = []55 }5657 /// Abandons the gesture: back to the document before it.58 public mutating func cancelGesture() {59 if let start = gesture { present = start; gesture = nil }60 }6162 @discardableResult63 public mutating func undo() -> Bool {64 settle()65 guard let previous = past.popLast() else { return false }66 future.insert(present, at: 0)67 present = previous68 return true69 }7071 @discardableResult72 public mutating func redo() -> Bool {73 guard gesture == nil, !future.isEmpty else { return false }74 push(present)75 present = future.removeFirst()76 return true77 }7879 /// A document that did not come from the user: an older snapshot would not contain what the other session added,80 /// and undoing to it would delete that work on the next save.81 public mutating func replace(_ next: CanvasDocument) { self = CanvasHistory(next) }82}83