Cotton code
178 lines · 8.2 KB · SwiftRaw
// One read, one screen: the shape every scaffolded screen is built on.//// The replica IS the cache (design P5), so a screen has nothing to expire and// no query client to configure. What it has is a `read.<name>` and a set of// screen families; it asks the core once when it appears, and asks again when// something the families claim has moved. That is the whole of the loading// story, and it is what `useQuery` was doing on the Expo phone minus the cache.//// **A screen that never re-reads on a `data` event is broken, not merely// stale** (4d-review, B11): the person's own write lands in the file through// the outbox, and the only thing that tells this screen so is the event. So the// re-read is here, in the one place every scaffolded screen goes through,// rather than remembered per page.//// Three states and no fourth: the SKELETON while the first answer is in// flight (never a spinner — the shape of what is coming is information), the// CONTENT once it lands, and the REFUSAL sentence when the core said no. An// empty answer is content, not an error: the page draws its own quiet state.import CottonKitimport SwiftUI/// One screen's answer, and the two facts about how it got here.////// **The last answer is kept for the session** (`AnswerCache`): a read built for/// a screen the person has already been to starts with that answer and no/// pending state, then reads again behind it. `Hosted` attaches the cache;/// a read built with none simply reads.@MainActor@Observablepublic final class ScreenRead: Rereadable, AnswerSeeded {    /// What the core answered, or `nil` before the first answer.    public private(set) var value: JSONValue?    /// The core's refusal sentence, or `nil`.    public private(set) var refusal: String?    /// True until the FIRST answer lands. A re-read leaves the last answer on    /// screen rather than blanking it back to a skeleton: the person is    /// looking at a list, and their own edit should move a row, not empty the    /// page for a frame.    public private(set) var firstAnswerPending = true    /// How many answers this read has drawn — the seed counts as one, and so    /// does EVERY answer the core gives, identical or not.    ///    /// **A screen that derives state from the answer keys on this, with    /// `initial: true`, never on `value`.** `onChange(of: value)` fires on a    /// change of VALUE: a seeded push already holds the answer before the    /// first frame, so a fresh answer equal to the seed changes nothing and    /// the handler never runs — the form opens blank, and a save from blank    /// fields erases the record (`NewsTopicScreens`, `MemoryScreens` did    /// exactly that). `AnswerVersionSweepTests` holds the rule.    public private(set) var answerVersion = 0    /// The families this read claims — what `Rereadable` keys the re-read on.    public let families: Set<ScreenFamily>    /// This screen's writes, bound to the same core and to this read as the    /// fallback re-read (see `ScreenWriter.answering`). Lazy so the two are one    /// object from the screen's side and the writer can hold the read weakly.    @ObservationIgnored public private(set) lazy var writer = ScreenWriter(        core: core,        reload: { [weak self] in await self?.load() }    )    private let core: any CottonCalling    private let method: String    private var arguments: [String: JSONValue]    /// The reads this one CARRIES — a second `read.*` a page needs whose    /// argument the first read answers, built through `following` and loaded    /// after it.    ///    /// `Rereadable`'s own words: "a model with two reads behind one screen    /// runs both here, so a fold that names either re-reads the whole page".    /// This is that sentence made true for a screen built on `ScreenRead`    /// rather than on a model of its own — and it is why the page does not    /// take the core: the core stays inside the scaffold    /// (`ScaffoldSweepTests`' ledger only ever shrinks).    @ObservationIgnored private var followers: [ScreenRead] = []    /// The session cache, once `attach`ed. Every successful answer goes in;    /// a change of argument draws the cached answer for the new question    /// while the read runs.    @ObservationIgnored private var answers: AnswerCache?    public init(        core: any CottonCalling,        read name: String,        args: [String: JSONValue] = [:],        families: Set<ScreenFamily>    ) {        self.core = core        self.method = "read.\(name)"        self.arguments = args        self.families = families    }    /// A SECOND read, carried by this one.    ///    /// For a page that must ask about something its own read only NAMES: the    /// project page draws its conversation's exchanges, and `read.project`    /// answers the conversation's id, not its transcript. The follower is    /// built over the same core, so the screen never holds one, and every    /// `load()` here loads it too — including the one a `data` event starts,    /// so the second read is on the wire exactly as the first is.    ///    /// Its arguments are set the ordinary way (`set(_:_:)`) once the first    /// answer names them.    public func following(        read name: String,        args: [String: JSONValue] = [:],        families: Set<ScreenFamily>    ) -> ScreenRead {        let made = ScreenRead(core: core, read: name, args: args, families: families)        if let answers { made.attach(answers) }        followers.append(made)        return made    }    /// `AnswerSeeded`: the last answer to this question, if the session has    /// one, becomes the first frame — and `firstAnswerPending` is false, so    /// no skeleton stands in front of it. A read that already has a value    /// keeps it; the cache never overwrites an answer the core just gave.    public func attach(_ cache: AnswerCache) {        answers = cache        for follower in followers { follower.attach(cache) }        guard value == nil, let seeded = cache.seed(method, request) else { return }        value = seeded        firstAnswerPending = false        answerVersion += 1    }    private var request: ReadRequest { ReadRequest(args: .object(arguments)) }    /// Change one argument and read again — a filter chip, a status tab.    public func set(_ name: String, _ argument: JSONValue?) async {        if let argument {            arguments[name] = argument        } else {            arguments.removeValue(forKey: name)        }        // The new question's last answer, if the session has one, stands in        // for the old question's while the read runs — a filter chip switches        // to the list it showed last time rather than holding the wrong list.        if let seeded = answers?.seed(method, request) { value = seeded }        await load()    }    public func load() async {        // BUILT ONCE, before the await: `set(_:_:)` can change the arguments        // while this read is in flight, and the answer must be stored under        // the question it answered, never the one asked after it.        let asked = request        do {            let answer = try await core.callJSON(method, asked)            value = answer            refusal = nil            answerVersion += 1            answers?.store(method, asked, value: answer, families: families)        } catch {            // The definition's line, never the error's own words: a refusal's            // message or a transport's text names an address and a resolver,            // and no screen invents its own wording (walker 294 row G).            refusal = CouldNotRead.line(for: error)        }        firstAnswerPending = false        // AFTER, never before: a follower's argument comes off this answer, so        // a page sets it once the id is here and every read from then on is a        // pair. A follower that has not been given its argument yet reads with        // none and the core refuses it — which is why a page builds the        // follower only once it has an id to give it.        for follower in followers {            await follower.load()        }    }}/// `read.<name>`'s request: `{"args":{…}}`.struct ReadRequest: Encodable, Sendable {    var args: JSONValue}