Cotton code
452 lines · 21.2 KB · SwiftRaw
// The change receipt: what a write just did, on the receipt face, with Undo.//// Every command — a tap, an editor's value, a toggle, a drag, a Delete, a new// record's first value, a sentence in the input — ends in a change record// (`ChangeRecord`: an id, a byline, the record before and after). The surface// that made the write presents this receipt for it, so every change has a// byline and an undo (layer 12 of the vision, part of the interpreter rather// than a later feature). It is the ONE undo the surfaces draw: no toast, no// second button (`ChangeReceiptTests` holds the Surfaces folder to it).//// The receipt (`ReceiptFace`, the seventh face) types the byline — who made// the change: "You", an assistant's name, a device — and the table across its// head, then prints one line per column that changed — its name, the old words// struck through, the new words — in the table's own column order. Undo calls// the `undo` verb with the change's id, once, through the Records in the// environment (which send it on through `GenericVerbs`), and hands the undoing// change to `onUndone`; the receipt then reads as undone and offers nothing// more — the undo's own change is not offered back. A change the verbs say// cannot be taken back (`ChangeRecord.undoable`, or `canUndo` false), or a// build without the verb, says so in pencil instead of offering an Undo.// Undoing is the one write this folder makes, because it is not an edit: the// verb names the change, and the Records decide what putting it back means.import CottonKitimport CottonValuesimport Observationimport SwiftUIpublic struct ChangeReceipt: View {    let change: ChangeRecord    let table: TableDefinition?    let onUndone: (ChangeRecord) -> Void    /// The owning surface can retain a batch's partial Undo across card instances.    let performUndo: (@MainActor () async throws -> ChangeRecord)?    /// The receipt's own close, for a surface that shows it as a passing card    /// (the list); nil draws none.    let onDismiss: (() -> Void)?    /// The Records said this change cannot be taken back: no Undo is offered.    let canUndo: Bool    /// The surface already took this change back (its model remembers): a    /// receipt drawn again for it reads as undone and sends nothing.    let undone: Bool    public init(        change: ChangeRecord,        table: TableDefinition?,        canUndo: Bool = true,        undone: Bool = false,        onUndone: @escaping (ChangeRecord) -> Void = { _ in },        onDismiss: (() -> Void)? = nil,        performUndo: (@MainActor () async throws -> ChangeRecord)? = nil    ) {        self.change = change        self.table = table        self.canUndo = canUndo && change.undoable        self.undone = undone        self.onDismiss = onDismiss        self.onUndone = onUndone        self.performUndo = performUndo    }    /// The card's state (its Undo, sent once) is keyed by the change's id: a    /// receipt handed another change is a new card, so its Undo can only ever    /// send the id of the change it prints.    public var body: some View {        ChangeReceiptCard(            change: change, table: table, canUndo: canUndo, undone: undone, onUndone: onUndone,            onDismiss: onDismiss, performUndo: performUndo        )        .id(change.id)    }}private struct ChangeReceiptCard: View {    let change: ChangeRecord    let table: TableDefinition?    let canUndo: Bool    let onUndone: (ChangeRecord) -> Void    let performUndo: (@MainActor () async throws -> ChangeRecord)?    let onDismiss: (() -> Void)?    @Environment(\.records) private var records    @State private var model: ChangeReceiptModel    init(        change: ChangeRecord, table: TableDefinition?, canUndo: Bool, undone: Bool,        onUndone: @escaping (ChangeRecord) -> Void, onDismiss: (() -> Void)?,        performUndo: (@MainActor () async throws -> ChangeRecord)?    ) {        self.change = change        self.table = table        self.canUndo = canUndo        self.onUndone = onUndone        self.performUndo = performUndo        self.onDismiss = onDismiss        _model = State(initialValue: ChangeReceiptModel(change: change, undone: undone))    }    var body: some View {        let facts = ChangeReceiptFacts.of(            change, table: table, canUndo: canUndo, hasRecords: records != nil, undone: model.undone,            failed: model.failed, failure: model.failure)        ReceiptFace(label: facts.head, seed: "receipt-\(change.id)", labelIdentifier: "change-receipt-head") {            VStack(alignment: .leading, spacing: 6) {                ForEach(facts.body) { line in                    ChangeLineView(line: line)                }                HStack {                    if let note = facts.note {                        if model.failed { Text(note).paperRed(12.5) } else { Text(note).paperBody(12.5, ink: .pencil) }                    }                    Spacer(minLength: 8)                    if facts.offersUndo {                        PaperTypedButton(model.undoLabel, size: 14) { Task { await undo() } }                            .disabled(model.busy)                            .accessibilityIdentifier("change-receipt-undo")                    }                    if let onDismiss {                        PaperTypedButton("Done", size: 14, action: onDismiss)                            .accessibilityIdentifier("change-receipt-dismiss")                    }                }            }            .frame(maxWidth: .infinity, alignment: .leading)        }        // A container, never one combined element: Undo and Done are buttons        // a reader reaches on their own, beside the lines they act on.        .accessibilityElement(children: .contain)    }    private func undo() async {        guard let records, let back = await model.undo(through: records, perform: performUndo) else { return }        onUndone(back)    }}/// What the receipt prints, decided apart from its drawing. Pure/// (`ChangeReceiptTests`).struct ChangeReceiptFacts: Equatable {    /// The line across the head: the sentence of what happened ("Added Asha    /// to Family", "Deleted Example errand 2"), and — once taken back — that    /// it was undone. Never the kinds ("YOU · PERSON"): a receipt headed by    /// who and which table said nothing about what moved (S5).    let head: String    let lines: [ChangeLines.Line]    /// The lines drawn under the head: `lines` less the one the head says.    var body: [ChangeLines.Line] {        guard let first = lines.first else { return lines }        switch first.kind {        case .said, .added, .deleted, .moved: return Array(lines.dropFirst())        case .changed: return lines        }    }    /// Whether the Undo is drawn.    let offersUndo: Bool    /// The pencil words beside it: why no Undo is offered, or that the undo    /// failed; nil when the Undo speaks for itself or the change was undone.    let note: String?    static var failedNote: String { ShellLines.line("editing", "receipt.failed") }    static func of(        _ change: ChangeRecord, table: TableDefinition?, canUndo: Bool, hasRecords: Bool, undone: Bool,        failed: Bool, failure: String? = nil, now: Date = Date()    ) -> ChangeReceiptFacts {        let made = ChangeLines.lines(change, table: table, now: now)        // Taken back, the head says only that: never the old sentence beside        // it, which would read as if it still held (architect, 5 Oct). And the        // lines under it are what the undo put back, not the change it undid.        let head = undone ? ShellLines.line("editing", "receipt.undone") : sentence(made, change: change, table: table)        let lines = undone ? ChangeLines.restored(made) : made        let allowed = canUndo && change.undoable && hasRecords        let note: String?        if failed {            // The core's own reason when it refused, else the plain failure.            note = failure ?? failedNote        } else if undone || allowed {            note = nil        } else if !hasRecords {            note = GenericVerbsWords.undoAbsent        } else {            // A change that cannot be taken back is its words alone: the            // receipt offers no Undo and never says that it cannot be undone            // — only that this build has no undo at all, when that is why.            note = change.reason == GenericVerbsWords.undoAbsent ? change.reason : nil        }        return ChangeReceiptFacts(head: head, lines: lines, offersUndo: allowed && !undone, note: note)    }    /// The one sentence of a change, from its first line: the core's own    /// words where it gave them, else the add, the delete, the reorder, or    /// "Changed <title>" over the columns the body then shows.    static func sentence(_ lines: [ChangeLines.Line], change: ChangeRecord, table: TableDefinition?) -> String {        switch lines.first?.kind {        case .said(let words)?: return words        case .added(let title)?: return ShellLines.line("receipts", "added", ["name": title])        case .deleted(let title)?: return ShellLines.line("receipts", "deleted", ["name": title])        case .moved?: return ShellLines.line("receipts", "reordered", ["plural": table?.plural ?? ShellLines.line("editing", "receipt.the_list")])        case .changed?, nil:            if let record = change.after ?? change.before { return ShellLines.line("receipts", "changed", ["name": ChangeLines.title(record, table)]) }            return ShellLines.line("receipts", "changed", ["name": ChangeLines.named(table)])        }    }}/// The receipt's one write: its Undo, sent once. A second tap while the first/// is on its way, or after it landed, sends nothing.@MainActor@Observablefinal class ChangeReceiptModel {    let change: ChangeRecord    private(set) var undone = false    private(set) var busy = false    private(set) var failed = false    /// Why the undo was refused, in the core's words; nil when it gave none.    private(set) var failure: String?    var undoLabel: String { ShellLines.line("editing", busy ? "receipt.undoing" : "receipt.undo") }    /// - Parameter undone: the surface already took this change back.    init(change: ChangeRecord, undone: Bool = false) {        self.change = change        self.undone = undone    }    /// Calls `undo` with this change's id; the undoing change, or nil when    /// nothing was sent or the verb refused.    func undo(        through records: any Records, perform: (@MainActor () async throws -> ChangeRecord)? = nil    ) async -> ChangeRecord? {        guard !busy, !undone else { return nil }        busy = true        defer { busy = false }        do {            let back: ChangeRecord            if let perform { back = try await perform() }            else { back = try await ChangeUndo.perform(change, through: records) }            undone = true            failed = false            failure = nil            return back        } catch {            failed = true            failure = Self.reason(error)            return nil        }    }    /// The sentence a refused undo carries: the core's message, or a    /// refusal's own words; nil for a failure that has none to say.    static func reason(_ error: Error) -> String? {        if let error = error as? CottonCallError, !error.message.isEmpty { return error.message }        if let error = error as? ActionRefused, !error.sentence.isEmpty { return error.sentence }        return nil    }}/// Both ordinary and batch receipts use the inverse declared by the change.@MainActorenum ChangeUndo {    static func perform(_ change: ChangeRecord, through records: any Records) async throws -> ChangeRecord {        if let taken = change.command {            guard let engine = records as? any RecordCommands else { throw ChangeUndoError.unavailable }            if let undo = taken.undo {                return try await engine.command(                    table: taken.table, id: taken.record, command: RecordCommand(id: undo, label: ""))            }            // The app method's own way back: how a household was reached, put back.            guard let call = taken.undoCall else { throw ChangeUndoError.unavailable }            return try await engine.undo(call, taken: taken)        }        return try await records.undo(change: change.id)    }}enum ChangeUndoError: Error { case unavailable }private struct ChangeLineView: View {    @Environment(\.theme) private var theme    let line: ChangeLines.Line    var body: some View {        switch line.kind {        case .added(let title):            Text(ShellLines.line("receipts", "added", ["name": title])).paperBody(14)        case .deleted(let title):            // A delete the person asked for. An add its own Undo took back            // arrives with the core's sentence ("Removed <name>") as `said`.            Text(ShellLines.line("receipts", "deleted", ["name": title])).paperBody(14)        case .said(let words):            Text(words).paperBody(14)        case .moved:            Text(ShellLines.line("editing", "receipt.reordered")).paperBody(14)        case .changed(let name, let before, let after):            VStack(alignment: .leading, spacing: 1) {                Text(name).paperMeta(12)                HStack(alignment: .firstTextBaseline, spacing: 6) {                    if let before {                        Text(before).paperBody(14, ink: .pencil).strikethrough(true, color: theme.print(.red))                            .lineLimit(2)                    }                    Text(after ?? ShellLines.line("editing", "receipt.cleared")).paperBody(14, ink: after == nil ? .pencil : .ink).lineLimit(2)                }            }            .accessibilityElement(children: .ignore)            .accessibilityLabel(                before.map { ShellLines.line("editing", "receipt.changed_from", ["name": name, "before": $0, "after": after ?? ShellLines.line("editing", "receipt.nothing")]) }                    ?? ShellLines.line("editing", "receipt.set_to", ["name": name, "after": after ?? ShellLines.line("editing", "receipt.cleared")]))        }    }}/// What a change record says, line by line. Pure (`ChangeLinesTests`).enum ChangeLines {    struct Line: Identifiable, Equatable {        enum Kind: Equatable {            /// The core's own words for the change.            case said(String)            case added(String)            case deleted(String)            case moved            case changed(name: String, before: String?, after: String?)        }        let id: String        let kind: Kind    }    /// What an undo of these lines put back: each changed column the other    /// way, from the value it undid to the value it restored. The sentence,    /// the add, the delete and the reorder were the change itself, which the    /// head's "Undone" already answers.    static func restored(_ lines: [Line]) -> [Line] {        lines.compactMap { line in            guard case .changed(let name, let before, let after) = line.kind else { return nil }            return Line(id: line.id, kind: .changed(name: name, before: after, after: before))        }    }    /// The keys every write stamps itself.    static let stamps: Set<String> = ["created_at", "updated_at"]    static func lines(_ change: ChangeRecord, table: TableDefinition?, now: Date = Date()) -> [Line] {        // The core says what happened: its sentence, and a before and after        // only for words — never for a switch, a state or a stamp. An append        // is the added sentence alone.        if let said = change.said {            let words = said.kind == "appended" ? [] : said.words            return [Line(id: "said", kind: .said(said.said))]                + words.map { Line(id: "words-\($0.name)", kind: .changed(name: $0.name, before: $0.before, after: $0.after)) }        }        switch (change.before, change.after) {        case (nil, nil):            // A reorder names no one record (the core's has no record id).            return [Line(id: "moved", kind: .moved)]        case (nil, let after?):            return [Line(id: "added", kind: .added(title(after, table)))]        case (let before?, nil):            return [Line(id: "deleted", kind: .deleted(title(before, table)))]        case (let before?, let after?):            if let table, let said = switched(before, after, table) {                return [Line(id: "switched", kind: .said(said))]            }            let keys = orderedKeys(before, after, table)            let lines = keys.compactMap { key -> Line? in                let old = before[key]                let new = after[key]                guard old != new else { return nil }                let column =                    table?.column(key) ?? ColumnDefinition(key: key, name: nil, type: .text)                // The manual order column moves; it is not a value anyone reads.                if key == table?.order { return nil }                // A write's own stamps change on every write; a table that does                // not draw them as columns does not read them as a change.                if table?.column(key) == nil, stamps.contains(key) { return nil }                return Line(                    id: key,                    kind: .changed(                        name: column.label,                        before: ColumnWords.words(old, column: column, now: now),                        after: ColumnWords.words(new, column: column, now: now)))            }            if lines.isEmpty, let order = table?.order, before[order] != after[order] {                return [Line(id: "moved", kind: .moved)]            }            return lines        }    }    /// A store that answers no receipt of its own (Settings' tables, the    /// fixtures) still says a switch the way the core says it    /// (`cotton-core` `records/receipt.rs`): one yes-or-no column changed,    /// with nothing but days riding along, is a sentence naming the record —    /// "Turned off Calendar" for a slip's switch, "Marked … done" for any    /// other — never "Yes" struck through beside "No" with the record unnamed.    static func switched(_ before: TableRecord, _ after: TableRecord, _ table: TableDefinition) -> String? {        // A read-only column is the source's own derivation — the Tools        // screen's part, On Home or not, follows its switch — so it never        // makes a switch a list of changes.        let changed = orderedKeys(before, after, table).filter { key in            before[key] != after[key] && key != table.order && !(table.column(key) == nil && stamps.contains(key))                && table.column(key)?.readonly != true        }        let columns = changed.compactMap { table.column($0) }        let switches = columns.filter { $0.type == .bool }        guard columns.count == changed.count, switches.count == 1, let column = switches.first,            columns.allSatisfy({ $0.type == .bool || $0.type == .date })        else { return nil }        let name = title(after, table)        let on = RecordValue.isSet(after[column.key])        if table.slip.toggle == column.key, table.slip.toggleStyle == .switch {            return ShellLines.line("receipts", on ? "turned_on" : "turned_off", ["name": name])        }        let label = column.label.prefix(1).lowercased() + column.label.dropFirst()        return ShellLines.line("receipts", on ? "marked" : "marked_not", ["name": name, "label": label])    }    /// The table's column order first, then any key the definition does not    /// name, alphabetically — a column added by a newer device still shows.    private static func orderedKeys(_ before: TableRecord, _ after: TableRecord, _ table: TableDefinition?) -> [String] {        let known = table?.columns.map(\.key) ?? []        let extra = Set(before.values.keys).union(after.values.keys).subtracting(known).sorted()        return known + extra    }    /// What the receipt calls the record: its title, else the words its slip    /// borrows (a saved page's site), else the column its slip is headed by    /// (an alarm's time), else the kind of record it is ("a mood") — never    /// its id, which names nothing to the person who just made it.    static func title(_ record: TableRecord, _ table: TableDefinition?) -> String {        guard let table else { return named(nil) }        // A title of spaces is no title: the receipt says the kind, not "  ".        let said = { (words: String?) -> String? in            let trimmed = words?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""            return trimmed.isEmpty ? nil : trimmed        }        if let words = said(record.said?.slip.heading) { return words }        let head = table.slip.title        if head != table.title, head != table.date,            let words = said(FaceText.line(record[head], words: record.columnWords(head), column: table.column(head), currency: record[table.column(head)?.currency].text, readsPlaceholder: false))        {            return words        }        return Self.named(table)    }    /// "a mood", "an alarm": the kind of record, as the core says its name takes.    static func named(_ table: TableDefinition?) -> String {        let name = (table?.name ?? ShellLines.line("editing", "receipt.record")).lowercased()        return ShellLines.line("receipts", table?.takesAn == true ? "an_name" : "a_name", ["name": name])    }}