// 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.importCottonKitimportCottonValuesimportObservationimportSwiftUIpublicstructChangeReceipt: View {let change: ChangeRecordlet table: TableDefinition?let onUndone: (ChangeRecord) -> Void/// The owning surface can retain a batch's partial Undo across card instances.let performUndo: (@MainActor () asyncthrows -> 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: Boolpublicinit( change: ChangeRecord, table: TableDefinition?, canUndo: Bool = true, undone: Bool = false, onUndone: @escaping (ChangeRecord) -> Void = { _ in }, onDismiss: (() -> Void)? = nil, performUndo: (@MainActor () asyncthrows -> ChangeRecord)? = nil ) {self.change = changeself.table = tableself.canUndo = canUndo && change.undoableself.undone = undoneself.onDismiss = onDismissself.onUndone = onUndoneself.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.publicvar body: someView {ChangeReceiptCard( change: change, table: table, canUndo: canUndo, undone: undone, onUndone: onUndone, onDismiss: onDismiss, performUndo: performUndo ) .id(change.id) }}privatestructChangeReceiptCard: View {let change: ChangeRecordlet table: TableDefinition?let canUndo: Boollet onUndone: (ChangeRecord) -> Voidlet performUndo: (@MainActor () asyncthrows -> ChangeRecord)?let onDismiss: (() -> Void)? @Environment(\.records) privatevar records @State privatevar model: ChangeReceiptModelinit( change: ChangeRecord, table: TableDefinition?, canUndo: Bool, undone: Bool, onUndone: @escaping (ChangeRecord) -> Void, onDismiss: (() -> Void)?, performUndo: (@MainActor () asyncthrows -> ChangeRecord)? ) {self.change = changeself.table = tableself.canUndo = canUndoself.onUndone = onUndoneself.performUndo = performUndoself.onDismiss = onDismiss _model = State(initialValue: ChangeReceiptModel(change: change, undone: undone)) }var body: someView {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 inChangeLineView(line: line) } HStack {iflet 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") }iflet 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) }privatefunc undo() async {guardlet 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`).structChangeReceiptFacts: 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: Stringlet lines: [ChangeLines.Line]/// The lines drawn under the head: `lines` less the one the head says.var body: [ChangeLines.Line] {guardlet first = lines.first else { return lines }switch first.kind {case .said, .added, .deleted, .moved: returnArray(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?staticvar failedNote: String { ShellLines.line("editing", "receipt.failed") }staticfunc 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) : madelet allowed = canUndo && change.undoable && hasRecordslet note: String?if failed {// The core's own reason when it refused, else the plain failure. note = failure ?? failedNote } elseif undone || allowed { note = nil } elseif !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 }returnChangeReceiptFacts(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.staticfunc sentence(_ lines: [ChangeLines.Line], change: ChangeRecord, table: TableDefinition?) -> String {switch lines.first?.kind {case .said(let words)?: return wordscase .added(let title)?: returnShellLines.line("receipts", "added", ["name": title])case .deleted(let title)?: returnShellLines.line("receipts", "deleted", ["name": title])case .moved?: returnShellLines.line("receipts", "reordered", ["plural": table?.plural ?? ShellLines.line("editing", "receipt.the_list")])case .changed?, nil:iflet record = change.after ?? change.before { returnShellLines.line("receipts", "changed", ["name": ChangeLines.title(record, table)]) }returnShellLines.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@ObservablefinalclassChangeReceiptModel {let change: ChangeRecordprivate(set) var undone = falseprivate(set) var busy = falseprivate(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 = changeself.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 () asyncthrows -> ChangeRecord)? = nil ) async -> ChangeRecord? {guard !busy, !undone else { returnnil } busy = truedefer { busy = false }do {let back: ChangeRecordiflet perform { back = tryawait perform() }else { back = tryawaitChangeUndo.perform(change, through: records) } undone = true failed = false failure = nilreturn back } catch { failed = true failure = Self.reason(error)returnnil } }/// 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.staticfunc reason(_ error: Error) -> String? {iflet error = error as? CottonCallError, !error.message.isEmpty { return error.message }iflet error = error as? ActionRefused, !error.sentence.isEmpty { return error.sentence }returnnil }}/// Both ordinary and batch receipts use the inverse declared by the change.@MainActorenumChangeUndo {staticfunc perform(_ change: ChangeRecord, through records: any Records) asyncthrows -> ChangeRecord {iflet taken = change.command {guardlet engine = records as? any RecordCommandselse { throwChangeUndoError.unavailable }iflet undo = taken.undo {returntryawait 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.guardlet call = taken.undoCall else { throwChangeUndoError.unavailable }returntryawait engine.undo(call, taken: taken) }returntryawait records.undo(change: change.id) }}enumChangeUndoError: Error { case unavailable }privatestructChangeLineView: View { @Environment(\.theme) privatevar themelet line: ChangeLines.Linevar body: someView {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) {iflet 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`).enumChangeLines {structLine: Identifiable, Equatable {enumKind: Equatable {/// The core's own words for the change.case said(String)case added(String)case deleted(String)case movedcase changed(name: String, before: String?, after: String?) }let id: Stringlet 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.staticfunc restored(_ lines: [Line]) -> [Line] { lines.compactMap { line inguardcase .changed(let name, let before, let after) = line.kind else { returnnil }returnLine(id: line.id, kind: .changed(name: name, before: after, after: before)) } }/// The keys every write stamps itself.staticlet stamps: Set<String> = ["created_at", "updated_at"]staticfunc 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.iflet said = change.said {let words = said.kind == "appended" ? [] : said.wordsreturn [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?):iflet 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? inlet old = before[key]let new = after[key]guard old != new else { returnnil }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 { returnnil }// 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) { returnnil }returnLine( 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.staticfunc 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 { returnnil }let name = title(after, table)let on = RecordValue.isSet(after[column.key])if table.slip.toggle == column.key, table.slip.toggleStyle == .switch {returnShellLines.line("receipts", on ? "turned_on" : "turned_off", ["name": name]) }let label = column.label.prefix(1).lowercased() + column.label.dropFirst()returnShellLines.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.privatestaticfunc 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.staticfunc title(_ record: TableRecord, _ table: TableDefinition?) -> String {guardlet table else { return named(nil) }// A title of spaces is no title: the receipt says the kind, not " ".let said = { (words: String?) -> String? inlet trimmed = words?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""return trimmed.isEmpty ? nil : trimmed }iflet words = said(record.said?.slip.heading) { return words }let head = table.slip.titleif 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 }returnSelf.named(table) }/// "a mood", "an alarm": the kind of record, as the core says its name takes.staticfunc named(_ table: TableDefinition?) -> String {let name = (table?.name ?? ShellLines.line("editing", "receipt.record")).lowercased()returnShellLines.line("receipts", table?.takesAn == true ? "an_name" : "a_name", ["name": name]) }}