// THE LIST'S READ (`shell.list`): the pages the core answered, held in its // order, and the touches a slip answers. The core says what the list shows — // its sections, rows, words, counts, menu, links, groups and empty words; this // keeps the asking cadence and the receipts. It asks for the first page when // the list opens, the next as the last slip nears, a folded section when it is // opened, and again from the start — as deep as it was read — on a data // event, a definitions change or a receipt. Never per frame. A read that lands // after a newer one was asked is dropped. // // Every write goes through the `Records` verbs and keeps the change it // answered, so the list can say who changed what and offer the undo; the list // is then asked again (`wrote`). // // A table whose rows a shell's own source still answers (a Settings source, // Passwords, Email) is read from that source whole and its rows handed to the // core (`rows`), which words, sections and pages them as its own. // // A list drawn again draws at once what it last read (`ListSeeds`: the last // first-page answer per ask), while it reads afresh; a first read that FAILS // over that seed keeps its rows with the could-not-read line beside them. import CottonKit import CottonValues import CryptoKit import Foundation import Observation @MainActor @Observable public final class RecordListModel { public enum Phase: Equatable { case loading case loaded case failed } public private(set) var linkTitles = LinkTitles() public let definition: TableDefinition /// The list as the core answered its first page: everything beside the rows. private(set) var answer: ListAnswer? /// The sections drawn: every page asked so far, a later page's rows under /// the section of the same id, and each folded section opened. private(set) var drawn: [ListAnswer.Section] = [] { didSet { rowsByID = Dictionary(drawn.flatMap(\.rows).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) records = drawn.flatMap { $0.rows.map(\.record) } } } /// The rows drawn, as records, in order. public private(set) var records: [TableRecord] = [] @ObservationIgnored private var rowsByID: [String: ListAnswer.Row] = [:] public private(set) var phase: Phase = .loading public private(set) var readProblem: String? { didSet { if readProblem == nil { readStall = nil } } } /// The last read was cut by the core (`could_not_read`): its typed line /// is drawn instead of `readProblem` (`CouldNotRead`). private(set) var readStall: CouldNotRead? /// How many first reads have landed (rows or a failure). public private(set) var firstReads = 0 /// A read is on its way over rows already drawn: a small "Updating…" line, never a loader. public private(set) var updating = false /// The newest write this list made, until it is undone or replaced. public private(set) var lastChange: ChangeRecord? { didSet { receiptRevision &+= 1 } } private var receiptRevision = 0 /// The change the receipt took back, so a receipt drawn again for it /// reads as undone rather than offering its Undo a second time. private var undoneChange: String? public var lastChangeUndone: Bool { lastChange.map { $0.id == undoneChange } ?? false } public private(set) var project: String? public private(set) var query: String = "" /// Whether this is the list of the archived. public let archived: Bool /// The columns every record on this list holds (column key → value). public let filter: [String: RecordValue] /// How many rows a page asks for; nil, the core's own page. public let pageSize: Int? /// The one section of the list this is (`earlier`, a folded group's /// whole): asked alone, open, paged. public let section: String? /// The tool's view this list is (`ToolView`). public let view: ToolView.Read? /// A pick: the column it fills and the records already held. public let pick: (column: String, held: [String])? /// The database the list is of, which its seed is kept under. public let database: String? /// The day the list opens on, YYYY-MM-DD; nil is this device's today. public let opensOn: String? /// How many records the whole read holds, as the core counts them. public var total: Int? { answer?.count } /// Whether another page is waiting behind the last slip. public var hasMore: Bool { next != nil } /// A long press drags: the core says the list is a whole hand-written order. public var canReorder: Bool { answer?.reorders ?? false } /// What the search field says, as the core words it. var searchWords: String { answer?.search ?? "" } /// The words of this table's rows under its section on another's page. var sectionWords: ListAnswer.SectionWords? { answer?.section_words } /// What the filter row's `value` narrows the list by: nothing for all, /// or a value the core did not offer. func filterWhere(_ value: String?) -> [String: RecordValue] { guard let filter = answer?.filter, let column = filter.column, let value, filter.values.contains(where: { $0.value == value }) else { return [:] } return [column: .text(value)] } private let store: any Records /// The core asked for a table its store does not read through the core. private let core: (any CottonCalling)? private let bulkUndo: BulkUndo private let seeds: ListSeeds private var next: Int? /// The page size the ask that said `next` was made at: a plain list's /// cursor counts its pages at that size, so the next page is asked at it. private var nextLimit = 50 private var generation = 0 private var loadingMore = false private var moreWaiters: [CheckedContinuation] = [] /// The seed the rows on screen were drawn from, until a read for it lands. private var seedOnScreen: ListSeeds.Key? /// How many reads have landed over a seed on screen, replacing its rows. private(set) var seedsReplaced = 0 /// The folded sections opened here, asked again with every re-read. private var openedSections: [String] = [] /// Each slip toggled here stands under the section it stood in until the /// list is read afresh (arrival, return, a pull): a ticked todo is struck /// through under Today, never jumping to Done under the finger. private var stays: [String: String] = [:] public convenience init( definition: TableDefinition, store: any Records, core: (any CottonCalling)?, archived: Bool = false, where filter: [String: RecordValue] = [:], pageSize: Int? = nil, section: String? = nil, view: ToolView.Read? = nil, pick: (column: String, held: [String])? = nil, database: String? = nil, opensOn: String? = nil ) { self.init(definition: definition, store: store, core: core, archived: archived, where: filter, pageSize: pageSize, section: section, view: view, pick: pick, database: database, opensOn: opensOn, seeds: .shared) } init( definition: TableDefinition, store: any Records, core: (any CottonCalling)?, archived: Bool = false, where filter: [String: RecordValue] = [:], pageSize: Int? = nil, section: String? = nil, view: ToolView.Read? = nil, pick: (column: String, held: [String])? = nil, database: String? = nil, opensOn: String? = nil, seeds: ListSeeds ) { self.definition = definition self.store = store self.core = core self.bulkUndo = BulkUndo(store: store) self.archived = archived self.filter = filter self.pageSize = pageSize self.section = section self.view = view self.pick = pick self.database = database self.opensOn = opensOn self.seeds = seeds } /// Refreshes retain their model and visible rows; only a different list creates one. static func retaining(_ previous: RecordListModel?, definition: TableDefinition, store: any Records, core: (any CottonCalling)?, archived: Bool, filter: [String: RecordValue], section: String? = nil, view: ToolView.Read? = nil, pick: (column: String, held: [String])? = nil, database: String? = nil, opensOn: String? = nil ) -> RecordListModel { if let previous, previous.definition == definition, previous.archived == archived, previous.filter == filter, previous.section == section, previous.view == view, previous.store === store, previous.database == database, previous.opensOn == opensOn, previous.pick?.column == pick?.column, previous.pick?.held == pick?.held { return previous } return RecordListModel(definition: definition, store: store, core: core, archived: archived, where: filter, section: section, view: view, pick: pick, database: database, opensOn: opensOn) } // MARK: What is drawn /// The row the core answered for `id`: its slip words, check, stamp, acts and tap. func row(_ id: String) -> ListAnswer.Row? { rowsByID[id] } /// The sections as drawn, each with its rows' records. public var sections: [RecordSection] { drawn.map { section in var drawn = RecordSection(heading: section.heading, records: section.rows.map(\.record), closed: section.folds) drawn.id = section.id drawn.said = section.count drawn.note = section.note drawn.lines = section.lines ?? [] return drawn } } /// Nothing to draw: the core said the list's empty words. public var holdsNothing: Bool { answer?.empty != nil } // MARK: Asking /// What the list asks the core. struct Ask: Encodable, Sendable { let table: String var view: String? var `where`: [String: RecordValue]? var query: String? var project: String? var archived: Bool? var section: String? var pick: Pick? var cursor: Int var limit: Int let timezone: String var today: String? /// The rows a shell's own source read, handed whole. var rows: [Handed]? /// Select's Delete over these ids, alone (`deleting`), and those the store refused. var deleting: [String]? = nil var failed: [String]? = nil /// The Bin stands on Home: where a record goes is said to be it. var bin_shown: Bool? = nil struct Pick: Encodable, Sendable { let column: String let held: [String] } struct Handed: Encodable, Sendable { let id: String let data: [String: RecordValue] } } /// The ask for a page from `cursor`, `limit` rows; `section` one section alone. private func ask(cursor: Int, limit: Int, section asked: String? = nil) -> Ask { Ask( table: definition.id, view: view?.name, where: filter.isEmpty ? nil : filter, query: query.isEmpty ? nil : query, project: project, archived: archived ? true : nil, section: asked ?? section ?? (view?.name == nil ? view?.section : nil), pick: pick.map { Ask.Pick(column: $0.column, held: $0.held) }, cursor: cursor, limit: limit, timezone: TimeZone.current.identifier, today: opensOn, rows: nil) } private var page: Int { min(pageSize ?? 50, 200) } /// Asks the core: directly where the store reads through it, else with /// the rows the store's own source holds handed whole. private func call(_ asked: Ask) async throws -> (answer: ListAnswer, bytes: Data) { let bytes = try await callBytes(asked) return (try ListSeeds.decode(bytes), bytes) } /// Select's Delete over `ids`, as the core words it: those it takes, its /// question, its receipt; with `failed`, what is said of those that stayed. func deleting(_ ids: [String], failed: [String]? = nil) async throws -> ListDeleting { var asked = ask(cursor: 0, limit: 1) asked.deleting = ids asked.failed = failed asked.bin_shown = BinShelf.shown return try ListSeeds.decode(try await callBytes(asked), as: ListDeleting.Envelope.self).deleting } private func callBytes(_ asked: Ask) async throws -> Data { var asked = asked let calling: any CottonCalling if let core = (store as? CoreRecords)?.listCore(for: definition.id) { calling = core } else { guard let core = (store as? CoreRecords)?.calling ?? self.core else { throw RecordsError.unknownTable(definition.id) } calling = core asked.rows = try await handedRows() } let body = String(decoding: try JSONEncoder().encode(asked), as: UTF8.self) let raw = try await calling.callRaw(CottonMethod.shellList, requestJSON: body) return Data(raw.utf8) } /// Every row the store's own source holds for this read, in its order. private func handedRows() async throws -> [Ask.Handed] { var rows: [Ask.Handed] = [] var seen = Set() var at: Int? = 0 var pages = 0 while let current = at, pages < 200 { let read = archived ? try await store.listArchived(table: definition.id, project: project, query: query.isEmpty ? nil : query, page: current, where: filter) : try await store.list(table: definition.id, project: project, query: query.isEmpty ? nil : query, page: current, where: filter) for record in read.records where seen.insert(record.id).inserted { rows.append(Ask.Handed(id: record.id, data: record.values)) } at = read.next.flatMap { $0 > current ? $0 : nil } pages += 1 } return rows } /// Reads the first page for this project and search, replacing the list. public func reload(project: String?, query: String) async { generation += 1 let mine = generation dirty = false reloading = true defer { if mine == generation { reloading = false settle() } } let began = Date() let first = drawn.isEmpty defer { if first { Log.write("list: \(definition.id) read \(Int(Date().timeIntervalSince(began) * 1000)) ms gen \(mine)\(mine == generation ? "" : " dropped")") } } let searched = query.trimmingCharacters(in: .whitespacesAndNewlines) let again = self.project == project && self.query == searched && phase == .loaded self.project = project self.query = searched // A read afresh (arrival, a pull, a search) places every slip anew. stays = [:] if !again { openedSections = [] filled = [] sectionsWithMore = [] } next = nil let seedKey = ListSeeds.Key( table: definition.id, filter: filter, project: project, archived: archived, section: seedSection, database: database) var seeded = false if drawn.isEmpty, searched.isEmpty, let seed = seeds.answer(for: seedKey) { land(seed, replacing: true) phase = .loaded seeded = true seedOnScreen = seedKey #if COTTON_DEV DevTimings.shared.rowsShown(definition.id) #endif } else if drawn.isEmpty { phase = .loading } updating = !drawn.isEmpty defer { if mine == generation { updating = false } } let read: (answer: ListAnswer, bytes: Data) do { read = try await call(ask(cursor: 0, limit: page)) nextLimit = page } catch { guard mine == generation, !(error is CancellationError), !Task.isCancelled else { return } readProblem = readFailure(error) if again { return } // A first read that fails over the copy it drew keeps that frame. if seeded || (seedOnScreen == seedKey && searched.isEmpty) { firstReads += 1 return } seedOnScreen = nil drawn = [] answer = nil next = nil phase = .failed firstReads += 1 seeds.forget(seedKey) return } guard mine == generation else { return } if seedOnScreen == seedKey { seedsReplaced += 1 } seedOnScreen = nil land(read.answer, replacing: true) phase = .loaded updating = false readProblem = nil firstReads += 1 #if COTTON_DEV DevTimings.shared.rowsShown(definition.id) #endif if searched.isEmpty { seeds.keep(read.bytes, for: seedKey, onDisk: ListSeeds.keepsOnDisk(definition)) } await askOpened(generation: mine) guard mine == generation else { return } await mergeTitles(of: records, generation: mine) } /// The section a seed is kept under: a tool's view is a list of its own. private var seedSection: String? { guard let view else { return section } return "view:\(view.name ?? view.section ?? "")" } /// Lands an answer: the first page replaces what is drawn, a later page /// adds its rows under their sections. private func land(_ landed: ListAnswer, replacing: Bool) { var sections = replacing ? [] : drawn for section in landed.sections { if let at = sections.firstIndex(where: { $0.id == section.id }) { let held = Set(sections[at].rows.map(\.id)) sections[at] = ListAnswer.Section( id: section.id, heading: sections[at].heading ?? section.heading, open: sections[at].open, folds: sections[at].folds, count: section.count ?? sections[at].count, note: sections[at].note ?? section.note, lines: sections[at].lines ?? section.lines, rows: sections[at].rows + section.rows.filter { !held.contains($0.id) }) } else { sections.append(section) } } if replacing || answer == nil { answer = landed } next = landed.next drawn = staying(sections) } /// The sections with every slip toggled here back under the section it stood in. private func staying(_ sections: [ListAnswer.Section]) -> [ListAnswer.Section] { guard !stays.isEmpty else { return sections } var out = sections for (id, home) in stays { guard let from = out.firstIndex(where: { $0.rows.contains { $0.id == id } }), out[from].id != home, let to = out.firstIndex(where: { $0.id == home }), let row = out[from].rows.first(where: { $0.id == id }) else { continue } out[from] = out[from].replacingRows(out[from].rows.filter { $0.id != id }) out[to] = out[to].replacingRows(out[to].rows + [row]) } return out.filter { !$0.rows.isEmpty || $0.folds } } /// A folded section's heading was opened: its first rows are asked once. public func opened(_ id: String) async { guard !openedSections.contains(id) else { return } openedSections.append(id) guard let at = drawn.firstIndex(where: { $0.id == id }), drawn[at].rows.isEmpty else { return } let mine = generation guard let read = try? await call(ask(cursor: 0, limit: Self.groupPreview, section: id)) else { return } guard mine == generation else { return } fill(id, from: read.answer) } /// Asks again each folded section opened here. private func askOpened(generation mine: Int) async { for id in openedSections where drawn.contains(where: { $0.id == id && $0.rows.isEmpty }) { guard let read = try? await call(ask(cursor: 0, limit: Self.groupPreview, section: id)), mine == generation else { return } fill(id, from: read.answer) } } private func fill(_ id: String, from read: ListAnswer) { guard let at = drawn.firstIndex(where: { $0.id == id }) else { return } if read.next != nil { sectionsWithMore.insert(id) } else { sectionsWithMore.remove(id) } filled.insert(id) drawn[at] = drawn[at].replacingRows(read.sections.flatMap(\.rows)) } /// The folded sections whose rows were asked on their own (`fill`). private var filled: Set = [] /// The opened folded sections holding more than their first rows. private var sectionsWithMore: Set = [] /// Whether an opened folded section holds more than it shows: its "All n ›". public func holdsMore(_ id: String) -> Bool { sectionsWithMore.contains(id) } /// How many rows an opened folded section shows before its "All n ›". static let groupPreview = 10 // MARK: The data moved private var dirty = false private var reloading = false private var settling = false /// How many re-reads a data event has landed. public private(set) var settled = 0 /// The data under the list moved: a sync tick or a poll. A read on its way /// is never restarted: it answers, and then the list is asked again ONCE /// however many ticks came meanwhile (`RecordListTickTests`). public func dataMoved() { dirty = true settle() } private func settle() { guard dirty, !settling, !reloading, phase == .loaded else { return } settling = true Task { @MainActor [self] in while dirty, !reloading, phase == .loaded { dirty = false await refresh() settled += 1 } settling = false } } /// Asks again, from the start and as deep as the list was read, for the /// project and search on screen. A read over a seed reads from its start. public func refresh() async { guard phase == .loaded else { return } if seedOnScreen != nil { guard !reloading else { return } await reload(project: project, query: query) return } guard !loadingMore else { owed = true return } let mine = generation let span = min(max(drawn.reduce(0) { $0 + $1.rows.count } - openedRows, page), 5000) do { let read = try await call(ask(cursor: 0, limit: span)) guard mine == generation, !loadingMore else { if loadingMore { owed = true } return } nextLimit = span land(read.answer, replacing: true) readProblem = nil await askOpened(generation: mine) } catch { guard mine == generation, !(error is CancellationError), !Task.isCancelled else { return } readProblem = readFailure(error) } } /// Rows drawn under folded sections asked on their own (`fill`). private var openedRows: Int { drawn.filter { filled.contains($0.id) }.reduce(0) { $0 + $1.rows.count } } /// A re-read that met a page on its way, made when that page lands. private var owed = false /// Every write this list makes ends here: the list is asked again, so its /// rows and every count on it are the database's before the receipt settles. private func wrote() async { if loadingMore { await withCheckedContinuation { moreWaiters.append($0) } } await refresh() } /// Reads the next page onto the end of the list; nothing when there is none. /// An ask made while a page is on its way waits for it, never dropped. /// `toEnd` reads every page left and lands them as one change. public func loadMore(toEnd: Bool = false) async { guard next != nil else { return } guard !loadingMore else { // Served once the read on its way lands, never dropped: it reads // the page after that one. await withCheckedContinuation { moreWaiters.append($0) } await loadMore(toEnd: toEnd) return } loadingMore = true let mine = generation var landed: [ListAnswer] = [] while let cursor = next { do { let read = try await call(ask(cursor: cursor, limit: nextLimit)) guard mine == generation, next == cursor else { break } landed.append(read.answer) next = read.answer.next readProblem = nil if !toEnd { break } if read.answer.next.map({ $0 <= cursor }) ?? false { break } } catch { if mine == generation, !(error is CancellationError), !Task.isCancelled { readProblem = readFailure(error) } break } } if mine == generation { let before = records.count for read in landed { land(read, replacing: false) } await mergeTitles(of: Array(records.dropFirst(before)), generation: mine) } loadingMore = false let waiting = moreWaiters moreWaiters = [] waiting.forEach { $0.resume() } if owed { owed = false await refresh() } } /// Reads page after page to the end — a list with an index rail lands on any letter. public func readToEnd() async { while hasMore { let before = records.count await loadMore(toEnd: true) guard !Task.isCancelled, records.count > before else { return } } } /// Reads the link titles `records` name and merges them in. private func mergeTitles(of records: [TableRecord], generation mine: Int) async { let narrowedTo = TableRecord(id: "", values: filter) do { let titles = try await store.linkTitles(for: definition.links(in: records + [narrowedTo])) guard mine == generation else { return } linkTitles.byID.merge(titles.byID) { _, new in new } } catch { guard mine == generation, !(error is CancellationError), !Task.isCancelled else { return } readProblem = readFailure(error) } } /// What a failed read says: the app's own typed refusals keep their /// words; every other error says the definition's line (`CouldNotRead`). private func readFailure(_ error: Error) -> String { readStall = nil if error is ServingMacTooOld { return ServingMacTooOld.sentence } if let error = error as? ActionRefused { return error.sentence } if let error = error as? SettingsReadTimedOut { return error.sentence } if error is RecordsError || error is DecodingError { Log.write("read failed — \(error)") return ShellLines.line("reading", "list.this_version", ["plural": definition.plural]) } readStall = CouldNotRead.reading(error) return CouldNotRead.line(for: error) } // MARK: Writes /// Writes what the core says a tap on the slip's check writes; the change, /// or nil when the check writes nothing. @discardableResult public func toggle(_ record: TableRecord) async throws -> ChangeRecord? { guard let patch = row(record.id)?.toggle, !patch.isEmpty else { return nil } if let home = drawn.first(where: { $0.rows.contains { $0.id == record.id } })?.id, stays[record.id] == nil { stays[record.id] = home } let change = try await store.update(table: definition.id, id: record.id, patch: patch) lastChange = change await wrote() return change } /// Runs one of the record's engine verbs from its long press. A change /// that opened nothing wears the list's receipt; nil when this store runs no engine verbs. public func run(_ command: RecordCommand, on record: TableRecord) async throws -> ChangeRecord? { guard let engine = store as? any RecordCommands else { return nil } await store.recordUsage(kind: "act_fired", tool: definition.id, record: record.id) let change = try await engine.command(table: definition.id, id: record.id, command: command) if change.opened == nil, let target = change.created, target.table != definition.id { foreignChanges.insert(change.id) } receiptRevision &+= 1 let receipt = receiptRevision await wrote() if receipt == receiptRevision, change.opened == nil, command.kind != .delete { lastChange = change } return change } /// Moves the slip at `from` in section `section` to `to` and writes the /// whole list's order as drawn. The change, or nil when nothing moved. @discardableResult public func move(section: Int = 0, from: Int, to: Int) async throws -> ChangeRecord? { guard canReorder, from != to, drawn.indices.contains(section), drawn[section].rows.indices.contains(from), drawn[section].rows.indices.contains(to) else { return nil } let before = drawn var rows = drawn[section].rows rows.insert(rows.remove(at: from), at: to) drawn[section] = drawn[section].replacingRows(rows) do { let change = try await writeOrder(records.map(\.id)) lastChange = change await wrote() return change } catch { drawn = before throw error } } /// The group this list is the page of, by its id; nil for any other list. private var group: String? { filter[GroupRecords.memberKey]?.text } /// Writes the order `ids` were dragged into: the group's own on its page, the table's elsewhere. private func writeOrder(_ ids: [String]) async throws -> ChangeRecord { if let group, let grouping = GroupRecords.grouping(store) { return try await grouping.updateGroup(group, .order(ids)) } return try await store.reorder(table: definition.id, ids: ids) } /// Writes an answer (or any patch) into one record through `update`. @discardableResult public func write(_ record: TableRecord, _ patch: [String: RecordValue]) async throws -> ChangeRecord { let change = try await store.update(table: definition.id, id: record.id, patch: patch) lastChange = change await wrote() return change } /// Deletes the records one at a time (Select, Clear); those the store /// refused stay, named in `failed`. The receipt over them all, and what /// is said after (`said`), are the core's words for what went and what /// stayed (`deleting`). @discardableResult func delete(ids: [String]) async -> (deleted: [String], failed: [String], said: ListDeleting?) { var deleted: [String] = [] var failed: [String] = [] var changes: [ChangeRecord] = [] var seen: Set = [] for id in ids where seen.insert(id).inserted { do { let change = try await store.delete(table: definition.id, id: id) drop(id) changes.append(change) deleted.append(id) } catch { failed.append(id) } } let said = deleted.isEmpty ? nil : try? await deleting(deleted, failed: failed.isEmpty ? nil : failed) // Unread, the receipt says what the core said of the first change. if let receipt = bulkUndo.remember(changes, done: said?.done ?? changes.first?.said?.said ?? "", undone: said?.undone) { lastChange = receipt await wrote() } return (deleted, failed, said) } /// Makes one record of `table` per picked id, each holding `preset` and /// the id in `column`; those refused are named in `failed`. public func create(in table: String, column: String, preset: [String: RecordValue], ids: [String]) async -> (made: [String], failed: [String]) { var made: [String] = [] var failed: [String] = [] for id in ids { var data = preset data[column] = .text(id) do { _ = try await store.create(table: table, data: data) made.append(id) } catch { failed.append(id) } } return (made, failed) } /// Deletes a slip's record through `delete` (a slip's long press). @discardableResult public func delete(_ record: TableRecord, scope: WriteScope? = nil) async throws -> ChangeRecord { let change = try await store.delete(table: definition.id, id: record.id, scope: scope) drop(record.id) lastChange = change await wrote() return change } /// Answers the slip's question (`answers`): its value written into the answer column. @discardableResult public func answer(_ record: TableRecord, _ value: String) async throws -> ChangeRecord? { guard let answers = definition.slip.answers, definition.answerVerbs(record).contains(where: { $0.value == value }) else { return nil } let change = try await store.update(table: definition.id, id: record.id, patch: [answers.column: .text(value)]) lastChange = change await wrote() return change } /// Makes a record of `data` (the chips over the list) and asks the list again. @discardableResult public func create(_ data: [String: RecordValue]) async throws -> ChangeRecord { let change = try await store.create(table: definition.id, data: Self.narrowed(data, filter: filter, project: project, in: definition)) lastChange = change await reload(project: project, query: query) return change } /// `data` with the list's `filter` values and, for a table filed under /// projects, the current project — each only where `data` names none. /// Only a filter that names one value is one a record can hold: a list /// (any one of), or an object (`{"on": "from_today"}`, `{"values": …}`, /// `{"within_days": …}`) says which records are read, never what a new /// one is (Trips' Upcoming wrote `{"on": "from_today"}` into a new /// trip's end, which refused it, 13 Nov 2026). static func narrowed( _ data: [String: RecordValue], filter: [String: RecordValue], project: String?, in definition: TableDefinition ) -> [String: RecordValue] { var out = data for (key, value) in filter where out[key] == nil { switch value { case .text, .number, .bool: out[key] = value case .null, .list, .object: continue } } if let key = definition.project, let project, out[key] == nil { out[key] = .text(project) } return out } /// A row a write took away leaves at once; the ask that follows confirms. private func drop(_ id: String) { guard drawn.contains(where: { $0.rows.contains { $0.id == id } }) else { return } drawn = drawn.map { $0.replacingRows($0.rows.filter { $0.id != id }) } } // MARK: Receipts /// The list's receipt took `change` back through the verbs itself: remember it and ask again. public func undone(_ change: ChangeRecord? = nil) async { let undid = change ?? lastChange undoneChange = undid?.id if let undid, refreshedUndos.contains(undid.id) { return } await wrote() } private var inverseResults: [String: ChangeRecord] = [:] private var undoing: Set = [] private var refreshedUndos: Set = [] /// The visible Undo settles only after this list has its restored rows. func receiptUndo(for change: ChangeRecord) -> (@MainActor () async throws -> ChangeRecord)? { return { guard !self.undoing.contains(change.id) else { throw ChangeUndoError.unavailable } self.undoing.insert(change.id) defer { self.undoing.remove(change.id) } if self.bulkUndo.contains(change.id) { do { let back = try await self.bulkUndo.undo(change.id) await self.wrote() if let problem = self.readProblem { throw ActionRefused(problem) } self.refreshedUndos.insert(change.id) return back } catch { await self.wrote() throw error } } let back: ChangeRecord if let completed = self.inverseResults[change.id] { back = completed } else { back = try await ChangeUndo.perform(change, through: self.store) self.inverseResults[change.id] = back } await self.wrote() if let problem = self.readProblem { throw ActionRefused(problem) } self.refreshedUndos.insert(change.id) return back } } /// Takes back the newest change and asks the list again. public func undo() async throws { guard let change = lastChange, let perform = receiptUndo(for: change) else { return } _ = try await perform() lastChange = nil } /// A change made beside the verbs above — a table's own act — lands as /// the list's newest change, so it wears the same receipt. public func received(_ change: ChangeRecord, foreign: Bool = false) { if foreign { foreignChanges.insert(change.id) } lastChange = change } /// A write made beside these verbs on a card of this list (the shell's /// editor): the list is asked again as after a write made here. public func landed(_ change: ChangeRecord?) async { await wrote() } /// Changes this list wears the receipt of that were made to another table's record. private var foreignChanges: Set = [] /// A page deleted or archived its record and closed back onto this list: /// the row leaves at once; the ask that follows confirms. public func removed(by change: ChangeRecord) { if let id = change.before?.id ?? change.after?.id { drop(id) } } /// Lets go of the receipt without undoing it. public func dismissChange() { lastChange = nil } } extension ListAnswer.Section { /// The same section holding `rows`. func replacingRows(_ rows: [ListAnswer.Row]) -> ListAnswer.Section { ListAnswer.Section(id: id, heading: heading, open: open, folds: folds, count: count, note: note, lines: lines, rows: rows) } } /// What each list last drew, so drawing it again draws at once (`reload`): /// the core's last first-page answer per database, table, narrowing, project /// and archive; never a search. /// /// Kept in memory for the life of the process and, once the app installs its /// directory at launch (`install`), on disk in the App Group too: a cold open /// of a list the phone has drawn before draws it at once and then asks. /// Nothing a vault holds goes to disk (`keepsOnDisk`), and an erase takes every seed. @MainActor public final class ListSeeds { static let shared = ListSeeds() /// The app's launch, and only the app's: seeds outlive the process in the /// App Group's `list-seeds` directory. A test process installs nothing. public static func installInAppGroup() { shared.install(directory: ShareChannel.container()?.appendingPathComponent(directoryName, isDirectory: true)) } /// The device is erased or starts over: every seed goes. public static func eraseAll() { shared.forgetAll() } struct Key: Hashable, Codable { var table: String var filter: [String: RecordValue] var project: String? var archived: Bool /// The list's one section, or its view: another list of its own. var section: String? /// The database the rows are of: a seed never draws in another. var database: String? = nil } /// The most bytes a seed holds, written or read: a whole file is never /// read into memory without a ceiling (`WholeBodySweepTests`). static let diskBytes = 2 * 1024 * 1024 /// The App Group directory's name, beside the core's own layout. static let directoryName = "list-seeds" /// The core's answer bytes as it said them (`{"ok":…,"data":…}`). private var kept: [Key: Data] = [:] private(set) var directory: URL? private let writer = DispatchQueue(label: "cotton.list-seeds", qos: .utility) init(directory: URL? = nil) { self.directory = directory } func install(directory: URL?) { self.directory = directory } /// Whether a table's answers may be written to disk: never a sealed /// table's, nor any table holding a value written blind or a password. static func keepsOnDisk(_ definition: TableDefinition) -> Bool { !definition.isSealed && !definition.columns.contains { $0.isSecret || $0.presentation == "password" } } /// The answer an envelope carries, or the core's refusal thrown. static func decode(_ bytes: Data) throws -> ListAnswer { try decode(bytes, as: ListAnswer.self) } /// An envelope's answer as `T` (a list's page, Select's Delete), or the core's refusal thrown. static func decode(_ bytes: Data, as: T.Type) throws -> T { let envelope: Envelope do { envelope = try JSONDecoder().decode(Envelope.self, from: bytes) } catch { throw CottonClientError.malformedAnswer(String(decoding: bytes, as: UTF8.self)) } if let error = envelope.error { throw error } guard let data = envelope.data else { throw CottonClientError.malformedAnswer(String(decoding: bytes, as: UTF8.self)) } return data } private struct Envelope: Decodable { let data: T? let error: CottonCallError? } func answer(for key: Key) -> ListAnswer? { if let bytes = kept[key] { return try? Self.decode(bytes) } guard let file = file(for: key), let bytes = Self.read(file), let answer = try? Self.decode(bytes) else { return nil } kept[key] = bytes return answer } private static func read(_ file: URL) -> Data? { guard let handle = try? FileHandle(forReadingFrom: file) else { return nil } defer { try? handle.close() } guard let data = try? handle.read(upToCount: diskBytes + 1), data.count <= diskBytes else { return nil } return data } func keep(_ bytes: Data, for key: Key, onDisk: Bool = true) { kept[key] = bytes guard onDisk, let file = file(for: key) else { return } writer.async { // An answer too long for a seed leaves none: the list reads, as // one never drawn does, rather than drawing what it drew before. guard bytes.count <= Self.diskBytes else { try? FileManager.default.removeItem(at: file) return } try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) #if os(iOS) try? bytes.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) #else try? bytes.write(to: file, options: .atomic) #endif } } func forget(_ key: Key) { kept[key] = nil guard let file = file(for: key) else { return } writer.async { try? FileManager.default.removeItem(at: file) } } /// Every seed, in memory and on disk: the device is erased or starts over. func forgetAll() { kept = [:] guard let directory else { return } writer.async { try? FileManager.default.removeItem(at: directory) } } /// Waits for the writes already asked (tests). func flushed() async { await withCheckedContinuation { done in writer.async { done.resume() } } } /// `//.json`. private func file(for key: Key) -> URL? { guard let directory else { return nil } let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys guard let named = try? encoder.encode(key) else { return nil } let digest = SHA256.hash(data: named).map { String(format: "%02x", $0) }.joined() let database = (key.database ?? "none").replacingOccurrences(of: "/", with: "_") return directory.appendingPathComponent(database, isDirectory: true).appendingPathComponent(digest + ".json") } }