// 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. import CottonKit import CottonValues import Foundation import Observation @MainActor @Observable final class DeckReading { enum Phase: Equatable { case loading, loaded, failed } /// What the deck is a read of. struct Asked: Equatable, Sendable { let table: String /// `/`, a list's `/group:`; 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: Asked private let core: (any CottonCalling)? private let store: (any Records)? private(set) var phase: Phase = .loading private(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] = [:] private var asks = 0 private var 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. private var standing: String? init(asked: Asked, core: (any CottonCalling)?, store: (any Records)?) { self.asked = asked self.core = core self.store = store } /// The deck's own one, kept across draws while it is the same read. static func retaining(_ previous: DeckReading?, asked: Asked, core: (any CottonCalling)?, store: (any Records)?) -> DeckReading { if let previous, previous.asked == asked { return previous } return DeckReading(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? { guard let page else { return nil } if let 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) } return nil } 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 { guard let 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.count await 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 = id await 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 = true guard !updating, phase == .loaded else { return } Task { @MainActor in while dirty { dirty = false await 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) async throws { guard let store, let patch = answered(record.id)?.toggle, !patch.isEmpty else { return } _ = try await store.update(table: answered(record.id)?.table ?? asked.table, id: record.id, patch: patch) await reload() } private func read(cursor: Int, limit: Int, visiting: String?, replacing: Bool) async { guard let core else { return } asks += 1 let mine = asks updating = true defer { if mine == asks { updating = false } } let landing = asked.lands && landedView == nil do { let answer = try await 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 } if let 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. static var holding: String? { #if os(iOS) PodcastPlayback.shared.now.held?.id #else nil #endif } private struct Ask: Encodable, Sendable { let table: String let view: String? let `where`: [String: RecordValue]? let lands: Bool? let chosen: [String: String]? let cursor: Int let limit: Int let ink: String? let visitor: String? /// The episode the one podcast player holds: a show's radio plays it. let holding: String? let timezone: String let today: String? } }