// 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.importCottonKitimportCottonValuesimportCryptoKitimportFoundationimportObservation@MainActor@ObservablepublicfinalclassRecordListModel {publicenumPhase: Equatable {case loadingcase loadedcase failed }publicprivate(set) var linkTitles = LinkTitles()publiclet 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.publicprivate(set) var records: [TableRecord] = [] @ObservationIgnored privatevar rowsByID: [String: ListAnswer.Row] = [:]publicprivate(set) var phase: Phase = .loadingpublicprivate(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).publicprivate(set) var firstReads = 0/// A read is on its way over rows already drawn: a small "Updating…" line, never a loader.publicprivate(set) var updating = false/// The newest write this list made, until it is undone or replaced.publicprivate(set) var lastChange: ChangeRecord? { didSet { receiptRevision &+= 1 } }privatevar 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.privatevar undoneChange: String?publicvar lastChangeUndone: Bool { lastChange.map { $0.id == undoneChange } ?? false }publicprivate(set) var project: String?publicprivate(set) var query: String = ""/// Whether this is the list of the archived.publiclet archived: Bool/// The columns every record on this list holds (column key → value).publiclet filter: [String: RecordValue]/// How many rows a page asks for; nil, the core's own page.publiclet pageSize: Int?/// The one section of the list this is (`earlier`, a folded group's/// whole): asked alone, open, paged.publiclet section: String?/// The tool's view this list is (`ToolView`).publiclet view: ToolView.Read?/// A pick: the column it fills and the records already held.publiclet pick: (column: String, held: [String])?/// The database the list is of, which its seed is kept under.publiclet database: String?/// The day the list opens on, YYYY-MM-DD; nil is this device's today.publiclet opensOn: String?/// How many records the whole read holds, as the core counts them.publicvar total: Int? { answer?.count }/// Whether another page is waiting behind the last slip.publicvar hasMore: Bool { next != nil }/// A long press drags: the core says the list is a whole hand-written order.publicvar 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] {guardlet filter = answer?.filter, let column = filter.column, let value, filter.values.contains(where: { $0.value == value }) else { return [:] }return [column: .text(value)] }privatelet store: any Records/// The core asked for a table its store does not read through the core.privatelet core: (any CottonCalling)?privatelet bulkUndo: BulkUndoprivatelet seeds: ListSeedsprivatevar 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.privatevar nextLimit = 50privatevar generation = 0privatevar loadingMore = falseprivatevar moreWaiters: [CheckedContinuation<Void, Never>] = []/// The seed the rows on screen were drawn from, until a read for it lands.privatevar 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.privatevar 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.privatevar 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 = definitionself.store = storeself.core = coreself.bulkUndo = BulkUndo(store: store)self.archived = archivedself.filter = filterself.pageSize = pageSizeself.section = sectionself.view = viewself.pick = pickself.database = databaseself.opensOn = opensOnself.seeds = seeds }/// Refreshes retain their model and visible rows; only a different list creates one.staticfunc 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 {iflet 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 }returnRecordListModel(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.publicvar sections: [RecordSection] { drawn.map { section invar 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.publicvar holdsNothing: Bool { answer?.empty != nil }// MARK: Asking/// What the list asks the core.structAsk: Encodable, Sendable {let table: Stringvar view: String?var `where`: [String: RecordValue]?var query: String?var project: String?var archived: Bool?var section: String?var pick: Pick?var cursor: Intvar limit: Intlet timezone: Stringvar 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]? = nilvar failed: [String]? = nil/// The Bin stands on Home: where a record goes is said to be it.var bin_shown: Bool? = nilstructPick: Encodable, Sendable {let column: Stringlet held: [String] }structHanded: Encodable, Sendable {let id: Stringlet data: [String: RecordValue] } }/// The ask for a page from `cursor`, `limit` rows; `section` one section alone.privatefunc 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) }privatevar 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.privatefunc call(_ asked: Ask) asyncthrows -> (answer: ListAnswer, bytes: Data) {let bytes = tryawait callBytes(asked)return (tryListSeeds.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) asyncthrows -> ListDeleting {var asked = ask(cursor: 0, limit: 1) asked.deleting = ids asked.failed = failed asked.bin_shown = BinShelf.shownreturntryListSeeds.decode(tryawait callBytes(asked), as: ListDeleting.Envelope.self).deleting }privatefunc callBytes(_ asked: Ask) asyncthrows -> Data {var asked = askedlet calling: any CottonCallingiflet core = (store as? CoreRecords)?.listCore(for: definition.id) { calling = core } else {guardlet core = (store as? CoreRecords)?.calling ?? self.core else { throwRecordsError.unknownTable(definition.id) } calling = core asked.rows = tryawait handedRows() }let body = String(decoding: try JSONEncoder().encode(asked), as: UTF8.self)let raw = tryawait calling.callRaw(CottonMethod.shellList, requestJSON: body)returnData(raw.utf8) }/// Every row the store's own source holds for this read, in its order.privatefunc handedRows() asyncthrows -> [Ask.Handed] {var rows: [Ask.Handed] = []var seen = Set<String>()var at: Int? = 0var pages = 0whilelet current = at, pages < 200 {let read = archived ? tryawait store.listArchived(table: definition.id, project: project, query: query.isEmpty ? nil : query, page: current, where: filter) : tryawait 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.publicfunc reload(project: String?, query: String) async { generation += 1let mine = generation dirty = false reloading = truedefer {if mine == generation { reloading = false settle() } }let began = Date()let first = drawn.isEmptydefer {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 == .loadedself.project = projectself.query = searched// A read afresh (arrival, a pull, a search) places every slip anew. stays = [:]if !again { openedSections = [] filled = [] sectionsWithMore = [] } next = nillet seedKey = ListSeeds.Key( table: definition.id, filter: filter, project: project, archived: archived, section: seedSection, database: database)var seeded = falseif drawn.isEmpty, searched.isEmpty, let seed = seeds.answer(for: seedKey) { land(seed, replacing: true) phase = .loaded seeded = true seedOnScreen = seedKey #if COTTON_DEVDevTimings.shared.rowsShown(definition.id) #endif } elseif drawn.isEmpty { phase = .loading } updating = !drawn.isEmptydefer { if mine == generation { updating = false } }let read: (answer: ListAnswer, bytes: Data)do { read = tryawait call(ask(cursor: 0, limit: page)) nextLimit = page } catch {guard mine == generation, !(error isCancellationError), !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 += 1return } 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_DEVDevTimings.shared.rowsShown(definition.id) #endifif 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.privatevar seedSection: String? {guardlet 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.privatefunc land(_ landed: ListAnswer, replacing: Bool) {var sections = replacing ? [] : drawnfor section in landed.sections {iflet 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.privatefunc staying(_ sections: [ListAnswer.Section]) -> [ListAnswer.Section] {guard !stays.isEmpty else { return sections }var out = sectionsfor (id, home) in stays {guardlet 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.publicfunc opened(_ id: String) async {guard !openedSections.contains(id) else { return } openedSections.append(id)guardlet at = drawn.firstIndex(where: { $0.id == id }), drawn[at].rows.isEmpty else { return }let mine = generationguardlet 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.privatefunc askOpened(generation mine: Int) async {for id in openedSections where drawn.contains(where: { $0.id == id && $0.rows.isEmpty }) {guardlet read = try? await call(ask(cursor: 0, limit: Self.groupPreview, section: id)), mine == generation else { return } fill(id, from: read.answer) } }privatefunc fill(_ id: String, from read: ListAnswer) {guardlet 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`).privatevar filled: Set<String> = []/// The opened folded sections holding more than their first rows.privatevar sectionsWithMore: Set<String> = []/// Whether an opened folded section holds more than it shows: its "All n ›".publicfunc holdsMore(_ id: String) -> Bool { sectionsWithMore.contains(id) }/// How many rows an opened folded section shows before its "All n ›".staticlet groupPreview = 10// MARK: The data movedprivatevar dirty = falseprivatevar reloading = falseprivatevar settling = false/// How many re-reads a data event has landed.publicprivate(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`).publicfunc dataMoved() { dirty = true settle() }privatefunc settle() {guard dirty, !settling, !reloading, phase == .loaded else { return } settling = trueTask { @MainActor [self] inwhile dirty, !reloading, phase == .loaded { dirty = falseawait 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.publicfunc 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 = truereturn }let mine = generationlet span = min(max(drawn.reduce(0) { $0 + $1.rows.count } - openedRows, page), 5000)do {let read = tryawait call(ask(cursor: 0, limit: span))guard mine == generation, !loadingMore else {if loadingMore { owed = true }return } nextLimit = span land(read.answer, replacing: true) readProblem = nilawait askOpened(generation: mine) } catch {guard mine == generation, !(error isCancellationError), !Task.isCancelled else { return } readProblem = readFailure(error) } }/// Rows drawn under folded sections asked on their own (`fill`).privatevar 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.privatevar 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.privatefunc 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.publicfunc loadMore(toEnd: Bool = false) async {guard next != nilelse { 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 = truelet mine = generationvar landed: [ListAnswer] = []whilelet cursor = next {do {let read = tryawait call(ask(cursor: cursor, limit: nextLimit))guard mine == generation, next == cursor else { break } landed.append(read.answer) next = read.answer.next readProblem = nilif !toEnd { break }if read.answer.next.map({ $0 <= cursor }) ?? false { break } } catch {if mine == generation, !(error isCancellationError), !Task.isCancelled { readProblem = readFailure(error) }break } }if mine == generation {let before = records.countfor read in landed { land(read, replacing: false) }await mergeTitles(of: Array(records.dropFirst(before)), generation: mine) } loadingMore = falselet waiting = moreWaiters moreWaiters = [] waiting.forEach { $0.resume() }if owed { owed = falseawait refresh() } }/// Reads page after page to the end — a list with an index rail lands on any letter.publicfunc readToEnd() async {while hasMore {let before = records.countawait loadMore(toEnd: true)guard !Task.isCancelled, records.count > before else { return } } }/// Reads the link titles `records` name and merges them in.privatefunc mergeTitles(of records: [TableRecord], generation mine: Int) async {let narrowedTo = TableRecord(id: "", values: filter)do {let titles = tryawait 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 isCancellationError), !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`).privatefunc readFailure(_ error: Error) -> String { readStall = nilif error isServingMacTooOld { returnServingMacTooOld.sentence }iflet error = error as? ActionRefused { return error.sentence }iflet error = error as? SettingsReadTimedOut { return error.sentence }if error isRecordsError || error isDecodingError {Log.write("read failed — \(error)")returnShellLines.line("reading", "list.this_version", ["plural": definition.plural]) } readStall = CouldNotRead.reading(error)returnCouldNotRead.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. @discardableResultpublicfunc toggle(_ record: TableRecord) asyncthrows -> ChangeRecord? {guardlet patch = row(record.id)?.toggle, !patch.isEmpty else { returnnil }iflet home = drawn.first(where: { $0.rows.contains { $0.id == record.id } })?.id, stays[record.id] == nil { stays[record.id] = home }let change = tryawait store.update(table: definition.id, id: record.id, patch: patch) lastChange = changeawait 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.publicfunc run(_ command: RecordCommand, on record: TableRecord) asyncthrows -> ChangeRecord? {guardlet engine = store as? any RecordCommandselse { returnnil }await store.recordUsage(kind: "act_fired", tool: definition.id, record: record.id)let change = tryawait 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 &+= 1let receipt = receiptRevisionawait 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. @discardableResultpublicfunc move(section: Int = 0, from: Int, to: Int) asyncthrows -> ChangeRecord? {guard canReorder, from != to, drawn.indices.contains(section), drawn[section].rows.indices.contains(from), drawn[section].rows.indices.contains(to)else { returnnil }let before = drawnvar rows = drawn[section].rows rows.insert(rows.remove(at: from), at: to) drawn[section] = drawn[section].replacingRows(rows)do {let change = tryawait writeOrder(records.map(\.id)) lastChange = changeawait wrote()return change } catch { drawn = beforethrow error } }/// The group this list is the page of, by its id; nil for any other list.privatevar group: String? { filter[GroupRecords.memberKey]?.text }/// Writes the order `ids` were dragged into: the group's own on its page, the table's elsewhere.privatefunc writeOrder(_ ids: [String]) asyncthrows -> ChangeRecord {iflet group, let grouping = GroupRecords.grouping(store) {returntryawait grouping.updateGroup(group, .order(ids)) }returntryawait store.reorder(table: definition.id, ids: ids) }/// Writes an answer (or any patch) into one record through `update`. @discardableResultpublicfunc write(_ record: TableRecord, _ patch: [String: RecordValue]) asyncthrows -> ChangeRecord {let change = tryawait store.update(table: definition.id, id: record.id, patch: patch) lastChange = changeawait 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`). @discardableResultfunc delete(ids: [String]) async -> (deleted: [String], failed: [String], said: ListDeleting?) {var deleted: [String] = []var failed: [String] = []var changes: [ChangeRecord] = []var seen: Set<String> = []for id in ids where seen.insert(id).inserted {do {let change = tryawait 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.iflet receipt = bulkUndo.remember(changes, done: said?.done ?? changes.first?.said?.said ?? "", undone: said?.undone) { lastChange = receiptawait 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`.publicfunc 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 { _ = tryawait 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). @discardableResultpublicfunc delete(_ record: TableRecord, scope: WriteScope? = nil) asyncthrows -> ChangeRecord {let change = tryawait store.delete(table: definition.id, id: record.id, scope: scope) drop(record.id) lastChange = changeawait wrote()return change }/// Answers the slip's question (`answers`): its value written into the answer column. @discardableResultpublicfunc answer(_ record: TableRecord, _ value: String) asyncthrows -> ChangeRecord? {guardlet answers = definition.slip.answers, definition.answerVerbs(record).contains(where: { $0.value == value })else { returnnil }let change = tryawait store.update(table: definition.id, id: record.id, patch: [answers.column: .text(value)]) lastChange = changeawait wrote()return change }/// Makes a record of `data` (the chips over the list) and asks the list again. @discardableResultpublicfunc create(_ data: [String: RecordValue]) asyncthrows -> ChangeRecord {let change = tryawait store.create(table: definition.id, data: Self.narrowed(data, filter: filter, project: project, in: definition)) lastChange = changeawait 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).staticfunc narrowed( _ data: [String: RecordValue], filter: [String: RecordValue], project: String?, in definition: TableDefinition ) -> [String: RecordValue] {var out = datafor (key, value) in filter where out[key] == nil {switch value {case .text, .number, .bool: out[key] = valuecase .null, .list, .object: continue } }iflet 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.privatefunc 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.publicfunc undone(_ change: ChangeRecord? = nil) async {let undid = change ?? lastChange undoneChange = undid?.idiflet undid, refreshedUndos.contains(undid.id) { return }await wrote() }privatevar inverseResults: [String: ChangeRecord] = [:]privatevar undoing: Set<String> = []privatevar refreshedUndos: Set<String> = []/// The visible Undo settles only after this list has its restored rows.func receiptUndo(for change: ChangeRecord) -> (@MainActor () asyncthrows -> ChangeRecord)? {return {guard !self.undoing.contains(change.id) else { throwChangeUndoError.unavailable }self.undoing.insert(change.id)defer { self.undoing.remove(change.id) }ifself.bulkUndo.contains(change.id) {do {let back = tryawaitself.bulkUndo.undo(change.id)awaitself.wrote()iflet problem = self.readProblem { throwActionRefused(problem) }self.refreshedUndos.insert(change.id)return back } catch {awaitself.wrote()throw error } }let back: ChangeRecordiflet completed = self.inverseResults[change.id] { back = completed }else { back = tryawaitChangeUndo.perform(change, through: self.store)self.inverseResults[change.id] = back }awaitself.wrote()iflet problem = self.readProblem { throwActionRefused(problem) }self.refreshedUndos.insert(change.id)return back } }/// Takes back the newest change and asks the list again.publicfunc undo() asyncthrows {guardlet change = lastChange, let perform = receiptUndo(for: change) else { return } _ = tryawait 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.publicfunc 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.publicfunc landed(_ change: ChangeRecord?) async {await wrote() }/// Changes this list wears the receipt of that were made to another table's record.privatevar foreignChanges: Set<String> = []/// A page deleted or archived its record and closed back onto this list:/// the row leaves at once; the ask that follows confirms.publicfunc removed(by change: ChangeRecord) {iflet id = change.before?.id ?? change.after?.id { drop(id) } }/// Lets go of the receipt without undoing it.publicfunc dismissChange() { lastChange = nil }}extensionListAnswer.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.@MainActorpublicfinalclassListSeeds {staticlet 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.publicstaticfunc installInAppGroup() { shared.install(directory: ShareChannel.container()?.appendingPathComponent(directoryName, isDirectory: true)) }/// The device is erased or starts over: every seed goes.publicstaticfunc eraseAll() { shared.forgetAll() }structKey: Hashable, Codable {var table: Stringvar 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`).staticlet diskBytes = 2 * 1024 * 1024/// The App Group directory's name, beside the core's own layout.staticlet directoryName = "list-seeds"/// The core's answer bytes as it said them (`{"ok":…,"data":…}`).privatevar kept: [Key: Data] = [:]private(set) var directory: URL?privatelet 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.staticfunc 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.staticfunc 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.staticfunc decode<T: Decodable>(_ bytes: Data, as: T.Type) throws -> T {let envelope: Envelope<T>do { envelope = try JSONDecoder().decode(Envelope<T>.self, from: bytes) } catch {throwCottonClientError.malformedAnswer(String(decoding: bytes, as: UTF8.self)) }iflet error = envelope.error { throw error }guardlet data = envelope.data else { throwCottonClientError.malformedAnswer(String(decoding: bytes, as: UTF8.self)) }return data }privatestructEnvelope<T: Decodable>: Decodable {let data: T?let error: CottonCallError? }func answer(for key: Key) -> ListAnswer? {iflet bytes = kept[key] { returntry? Self.decode(bytes) }guardlet file = file(for: key), let bytes = Self.read(file), let answer = try? Self.decode(bytes) else { returnnil } kept[key] = bytesreturn answer }privatestaticfunc read(_ file: URL) -> Data? {guardlet handle = try? FileHandle(forReadingFrom: file) else { returnnil }defer { try? handle.close() }guardlet data = try? handle.read(upToCount: diskBytes + 1), data.count <= diskBytes else { returnnil }return data }func keep(_ bytes: Data, for key: Key, onDisk: Bool = true) { kept[key] = bytesguard 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]) #elsetry? bytes.write(to: file, options: .atomic) #endif } }func forget(_ key: Key) { kept[key] = nilguardlet 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 = [:]guardlet 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() } } }/// `<directory>/<database>/<digest of the key>.json`.privatefunc file(for key: Key) -> URL? {guardlet directory else { returnnil }let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeysguardlet named = try? encoder.encode(key) else { returnnil }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") }}