Cotton code
60 lines · 2.7 KB · SwiftRaw
// The successful writes behind one list-selection receipt.import Foundation/// A list's batch survives receipt-card recreation and keeps partial progress.@MainActorfinal class BulkUndo {    private struct Batch {        var pending: [ChangeRecord]        let count: Int        let byline: String        let undoable: Bool        /// The core's words once it is taken back.        let undone: String?        var completed: ChangeRecord?        var busy = false    }    private let store: any Records    private var batches: [String: Batch] = [:]    init(store: any Records) { self.store = store }    func contains(_ id: String) -> Bool { batches[id] != nil }    /// One receipt over `changes`, saying `done` (the core's words for them    /// all) and, once taken back, `undone`.    func remember(_ changes: [ChangeRecord], done: String, undone: String?) -> ChangeRecord? {        guard let first = changes.first else { return nil }        if changes.count == 1 { return first }        let id = "batch-" + UUID().uuidString        // Keep the inverse handles, not the deleted records' long bodies.        let pending = changes.map { change in            ChangeRecord(id: change.id, byline: change.byline, before: nil, after: nil, command: change.command)        }        let unavailable = changes.first { !$0.undoable }        batches[id] = Batch(pending: pending, count: changes.count, byline: first.byline, undoable: unavailable == nil, undone: undone)        return ChangeRecord(            id: id, byline: first.byline, before: nil, after: nil,            undoable: unavailable == nil, reason: unavailable?.reason,            said: ChangeSaid(kind: "deleted", said: done))    }    func undo(_ id: String) async throws -> ChangeRecord {        guard let batch = batches[id] else { throw RecordsError.unknownChange(id) }        guard batch.undoable else { throw ChangeUndoError.unavailable }        if let completed = batch.completed { return completed }        guard !batch.busy else { throw ChangeUndoError.unavailable }        batches[id]?.busy = true        defer { batches[id]?.busy = false }        while let next = batches[id]?.pending.last {            // One shared command/receipt inverse, also used by ChangeReceiptModel.            _ = try await ChangeUndo.perform(next, through: store)            batches[id]?.pending.removeLast()        }        let completed = ChangeRecord(            id: "undo-" + id, byline: batch.byline, before: nil, after: nil,            undoable: false, said: ChangeSaid(kind: "put_back", said: batch.undone ?? ShellLines.line("record", "restored", ["n": "\(batch.count)"])))        batches[id]?.completed = completed        return completed    }}