// THE DECK'S READ (`shell.deck`): the pages the core answered, held in its// order. The deck asks for the first page when it opens, for the next as it// nears the end of what it holds — never per frame — and again, over every// card it holds, on a data event for its table, a definitions change, a face// choice and ink. A read that lands after another was asked is dropped.importCottonKitimportCottonValuesimportFoundationimportObservation@MainActor @ObservablefinalclassDeckReading {enumPhase: Equatable { case loading, loaded, failed }/// What the deck is a read of.structAsked: Equatable, Sendable {let table: String/// `<tool>/<id>`, a list's `<tool>/group:<id>`; nil for a deck read by its filter alone.let view: String?let filter: [String: RecordValue]/// The day the rows are read from (a date's own calendar); nil for today.let opensOn: String?/// The database shown: another is another deck.let database: String?/// A record's or a blank's deck: the core names the view it lands on.var lands = false }let asked: Askedprivatelet core: (any CottonCalling)?privatelet store: (any Records)?private(set) var phase: Phase = .loadingprivate(set) var readProblem: String?private(set) var readStall: CouldNotRead?/// The cards read so far, in the view's order.private(set) var cards: [DeckAnswer.Card] = []/// The rest of the page: the last answer's (its cards aside).private(set) var page: DeckAnswer?/// The record the deck stands on that the view's pages do not hold.private(set) var visitor: DeckAnswer.Card?/// The letters written over the deck: the core narrows by them.private(set) var ink = ""/// A read is out.private(set) var updating = false/// The view the core landed this deck on (`Asked.lands`), once it has.private(set) var landedView: ToolView.Read?/// The views the ring has chosen, which the first landing read is told.var chosen: [String: String] = [:]privatevar asks = 0privatevar dirty = false/// The record the deck was asked to stand on (`bring`): every read until/// it is dropped asks for it, so a read a data event starts while it is/// being brought (an intake's own write) never leaves it out.privatevar standing: String?init(asked: Asked, core: (any CottonCalling)?, store: (any Records)?) {self.asked = askedself.core = coreself.store = store }/// The deck's own one, kept across draws while it is the same read.staticfunc retaining(_ previous: DeckReading?, asked: Asked, core: (any CottonCalling)?, store: (any Records)?) -> DeckReading {iflet previous, previous.asked == asked { return previous }returnDeckReading(asked: asked, core: core, store: store) }var count: Int? { phase == .loaded ? page?.count : nil }var records: [TableRecord] { cards.map(\.record.record) }var hasMore: Bool { page?.next != nil }/// The card the face draws for `id`, as answered.func card(_ id: String) -> DeckCard? {guardlet page else { returnnil }iflet card = cards.first(where: { $0.id == id }) ?? (visitor?.id == id ? visitor : nil) {return card.drawn(labels: card.table.flatMap { page.labels_of?[$0] } ?? page.labels) }returnnil }func answered(_ id: String) -> DeckAnswer.Card? { cards.first { $0.id == id } ?? (visitor?.id == id ? visitor : nil) }/// Reads the deck from its first card, as far as it had read (at least a page).func reload(visiting: String? = nil) async {let span = max(cards.count, 50)await read(cursor: 0, limit: span, visiting: visiting ?? standing, replacing: true) }/// The letters written over the deck: read again, narrowed by them.func narrow(_ letters: String) async {guard letters != ink else { return } ink = letters cards = []await read(cursor: 0, limit: 50, visiting: nil, replacing: true) }/// The next page, when there is one and none is out.func loadMore() async {guardlet next = page?.next, !updating else { return }await read(cursor: next, limit: 50, visiting: nil, replacing: false) }/// Every page, to the deck's end.func readToEnd() async {while page?.next != nil, phase == .loaded {let before = cards.countawait loadMore()if cards.count == before { return } } }/// Stands on `id`: read on until the view's pages hold it, else asked/// as a visitor on its own card.func bring(_ id: String) async {if cards.contains(where: { $0.id == id }) { return }await readToEnd()if cards.contains(where: { $0.id == id }) { return } standing = idawait read(cursor: 0, limit: max(cards.count, 50), visiting: id, replacing: true) }/// The visitor leaves the deck.func dropVisitor() { visitor = nil standing = nil }/// The data under the deck moved: read again once, after any read out.func dataMoved() { dirty = trueguard !updating, phase == .loaded else { return }Task { @MainActor inwhile dirty { dirty = falseawait reload() } } }/// A write this deck's editor made on its table.func landed(_ change: ChangeRecord?) async { await reload() }/// A tap on a card's check: what the core says it writes.func toggle(_ record: TableRecord) asyncthrows {guardlet store, let patch = answered(record.id)?.toggle, !patch.isEmpty else { return } _ = tryawait store.update(table: answered(record.id)?.table ?? asked.table, id: record.id, patch: patch)await reload() }privatefunc read(cursor: Int, limit: Int, visiting: String?, replacing: Bool) async {guardlet core else { return } asks += 1let mine = asks updating = truedefer { if mine == asks { updating = false } }let landing = asked.lands && landedView == nildo {let answer = tryawait core.call(CottonMethod.shellDeck, Ask( table: asked.table, view: asked.view ?? landedView?.name, where: asked.filter.isEmpty ? nil : asked.filter, lands: landing ? true : nil, chosen: landing ? chosen : nil, cursor: cursor, limit: min(limit, 200), ink: ink.isEmpty ? nil : ink, visitor: visiting, holding: Self.holding, timezone: TimeZone.current.identifier, today: asked.opensOn), as: DeckAnswer.self)guard mine == asks, !Task.isCancelled else { return }iflet view = answer.landed, let tool = answer.view?.split(separator: "/").first { landedView = view.drawnRead(of: String(tool)) }// Which read the deck drew, for a walk's log: the view, the day it reads from, a visitor.Log.write("deck: \(asked.table) view \(answer.view ?? "none") from \(asked.opensOn ?? "today") visiting \(visiting == nil ? "no" : "yes") cursor \(cursor): \(answer.cards.count) of \(answer.count)")if replacing { cards = answer.cards } else {let held = Set(cards.map(\.id)) cards += answer.cards.filter { !held.contains($0.id) } }if replacing { visitor = answer.visitor } page = answer readProblem = nil readStall = nil phase = .loaded } catch {guard mine == asks else { return } readStall = CouldNotRead.reading(error) readProblem = CouldNotRead.line(for: error)if cards.isEmpty { phase = .failed } }if dirty, phase == .loaded { dataMoved() } }/// The episode the app's one podcast player holds, by its record: a show's radio plays it.staticvar holding: String? { #if os(iOS)PodcastPlayback.shared.now.held?.id #elsenil #endif }privatestructAsk: Encodable, Sendable {let table: Stringlet view: String?let `where`: [String: RecordValue]?let lands: Bool?let chosen: [String: String]?let cursor: Intlet limit: Intlet ink: String?let visitor: String?/// The episode the one podcast player holds: a show's radio plays it.let holding: String?let timezone: Stringlet today: String? }}