Cotton code
749 lines · 32.9 KB · SwiftRaw
// THE STREAM (Messages on iPhone, 14 Nov 2026): the chat is the face. An app// whose flavour says its face is one stream of chats (`fan.stream`; the core// answers `shell.fan`'s `stream` and `shell.stream`) draws no fan and no hub:// it opens ON a chat, drawn exactly as an opened chat is (`ConversationPage`:// paper, slips, sender names, times, pictures), one chat a page.//// Moving: up and down inside a chat (it opens at its newest message), a swipe// sideways for the next or the previous chat, and a previous / next pair// at the foot of the rail down the chat's right edge (`ChatRail`), whose// thumb moves through the chat by date.// Every move between chats is a plain cut (owner, 15 Nov 2026): the tap on// Previous or Next, and the sideways swipe too — the chat does not follow the// finger and nothing slides; the swipe is read at the lift by the core// (`ink.contest`: a level stroke of its `swipe` points) and the chat changes// in one frame, as a deck's tap does.// No tap zones: a chat is full of things to tap.//// Letters are written anywhere on the chat (owner, 15 Nov 2026), over the// messages too, where the chat scrolls. The scroll is never held back; a// stroke is the ink's once it bends, and the scroll then goes back to where// it was (`InkContest`, the core's `ink::contest`). On the head, where// nothing scrolls, every stroke is the ink's, as on a deck.//// The top line holds the quiet unread count ("3 unread", nothing when none),// the search disc (typed words, or the letters written on the chat)// and ONE button holding what the fan held: Account and New chat. Under it// the chat's title stands in a band of its own with the mark for where the// chat is from; nothing overlaps the first message.//// Everything said is the core's: the order (unread first, then newest), the// count, each mark, what the top button holds, which chats take a reply. This// file draws. Only the chat in front and its neighbours hold their messages// (`ChatStreamModel.keep`); a person may hold hundreds of chats.import CottonFacesimport CottonKitimport CottonPaperimport CottonValuesimport OSLogimport SwiftUI/// `shell.stream`'s answer.struct StreamAnswer: Decodable, Equatable, Sendable {    struct Mark: Decodable, Equatable, Sendable {        var id: String        var label: String    }    struct Chat: Decodable, Equatable, Sendable, Identifiable {        var id: String        var name: String?        var unread: Bool        /// Where it is from (Cotton, WhatsApp, Instagram…); none for a chat naming no source.        var mark: Mark?        /// A message may be written into it from here.        var replies: Bool    }    struct Top: Decodable, Equatable, Sendable, Identifiable {        var id: String        var label: String        /// The object its line wears, by name.        var object: String?        var route: String?    }    var table: String    var chats: [Chat]    /// The chat it opens on: the newest unread, else the newest.    var opens: String?    var unread: Int    var unreadLine: String?    var top: [Top]    var search: String    var empty: String    enum CodingKeys: String, CodingKey {        case table, chats, opens, unread, top, search, empty        case unreadLine = "unread_line"    }}/// One chat held open: its record and its messages.@MainActor@Observablefinal class ChatStreamPageModel {    let id: String    let conversation: ConversationModel    var record: TableRecord?    var unreadable = false    private let table: String    private let store: any Records    private var opening: Task<Void, Never>?    init(id: String, table: String, layout: ConversationLayout, store: any Records, wording: TableDefinition?) {        self.id = id        self.table = table        self.store = store        conversation = ConversationModel(layout: layout, thread: id, store: store, wording: wording)    }    /// The messages are read beside the record, never behind it.    func open() {        guard opening == nil else { return }        opening = Task {            let began = ContinuousClock.now            async let talk: Void = conversation.load()            if let read = try? await store.get(table: table, id: id) {                conversation.threadRecord = read                record = read            } else {                unreadable = true            }            await talk            ChatStreamClock.opened(id, took: ContinuousClock.now - began)        }    }    /// What moved (a message landed, a request answered): the chat read again.    func refresh() async {        await opening?.value        await conversation.load()        if let read = try? await store.get(table: table, id: id) {            conversation.threadRecord = read            record = read        }    }}/// How long the stream's first chat and a chat swiped to took to stand, said/// to the log (`com.cottondb.stream`): what the lane's report quotes.@MainActorenum ChatStreamClock {    private static let log = Logger(subsystem: "com.cottondb.stream", category: "timing")    private static var mounted: ContinuousClock.Instant?    private static var first = true    private static var swiped: (id: String, at: ContinuousClock.Instant)?    static func mount() { if mounted == nil { mounted = .now } }    static func swipe(to id: String) { swiped = (id, .now) }    static func opened(_ id: String, took: Duration) {        log.notice("stream: chat read in \(Self.ms(took), privacy: .public) ms")    }    /// The chat in front stands with its messages drawn.    static func stood(_ id: String) {        if first, let mounted {            first = false            log.notice("stream: first open \(Self.ms(ContinuousClock.now - mounted), privacy: .public) ms")        } else if let swipe = swiped, swipe.id == id {            swiped = nil            log.notice("stream: swipe \(Self.ms(ContinuousClock.now - swipe.at), privacy: .public) ms")        }    }    private static func ms(_ duration: Duration) -> Int {        Int((Double(duration.components.seconds) * 1000 + Double(duration.components.attoseconds) / 1e15).rounded())    }}@MainActor@Observablefinal class ChatStreamModel {    private(set) var answer: StreamAnswer?    /// The chat in front.    var front: String?    /// The chats held open: the one in front and its neighbours.    private(set) var pages: [String: ChatStreamPageModel] = [:]    /// The stream last read was narrowed by a search.    private var narrowed = false    /// A chat the stream was turned to that the stream does not hold yet (one    /// just started holds no message): it stands in front until it does.    private(set) var visitor: StreamAnswer.Chat?    var chats: [StreamAnswer.Chat] {        let held = answer?.chats ?? []        guard let visitor, !held.contains(where: { $0.id == visitor.id }) else { return held }        return [visitor] + held    }    private struct Ask: Encodable, Sendable {        let table: String        let query: String?        let ink: String?        let standing: [String]?    }    /// The stream as the core answers it now. A person standing in it keeps    /// the order they hold (`standing`); a search, and the first read, take    /// the stream's own.    func read(core: (any CottonCalling)?, table: String, query: String, ink: String) async {        guard let core else { return }        let words = query.trimmingCharacters(in: .whitespacesAndNewlines)        let searching = !words.isEmpty || !ink.isEmpty        let ask = Ask(table: table, query: words.isEmpty ? nil : words, ink: ink.isEmpty ? nil : ink,                      standing: searching || narrowed ? nil : answer?.chats.map(\.id))        guard let next = try? await core.call(CottonMethod.shellStream, ask, as: StreamAnswer.self), !Task.isCancelled else { return }        answer = next        narrowed = searching        if let visitor, next.chats.contains(where: { $0.id == visitor.id }) { self.visitor = nil }        // A visitor in front stays in front: the stream does not hold it yet.        if !searching, let visitor, front == visitor.id { return }        front = Self.front(front, in: next, searching: searching)    }    /// Where the stream stands after a read: a search jumps to its first    /// find; else the chat in front stays in front while the stream holds    /// it, and the stream opens on the core's `opens`.    static func front(_ front: String?, in answer: StreamAnswer, searching: Bool) -> String? {        if searching { return answer.opens }        if let front, answer.chats.contains(where: { $0.id == front }) { return front }        return answer.opens    }    /// The stream turns to `thread`, read again in its own order; a chat it    /// does not hold yet stands in front as a visitor.    func turn(to thread: String, core: (any CottonCalling)?, table: String) async {        narrowed = true        await read(core: core, table: table, query: "", ink: "")        if !chats.contains(where: { $0.id == thread }) {            visitor = StreamAnswer.Chat(id: thread, name: nil, unread: false, mark: nil, replies: true)        }        front = thread    }    /// The chat `by` steps from the one in front; nil past either end.    func neighbour(_ by: Int) -> String? {        guard let front, let at = chats.firstIndex(where: { $0.id == front }), chats.indices.contains(at + by) else { return nil }        return chats[at + by].id    }    /// Only the chat in front and its neighbours are loaded; one further out    /// is kept if it was, and the rest let go.    func keep(table: String, definitions: TableDefinitions, store: (any Records)?) {        guard let store, let definition = definitions[table], let layout = definition.conversation else { return }        let ids = chats.map(\.id)        guard let front, let at = ids.firstIndex(of: front) else { return pages = [:] }        let near = Self.window(at: at, count: ids.count, reach: 1).map { ids[$0] }        let kept = Set(Self.window(at: at, count: ids.count, reach: 2).map { ids[$0] })        var next = pages.filter { kept.contains($0.key) }        for id in near where next[id] == nil {            next[id] = ChatStreamPageModel(id: id, table: table, layout: layout, store: store, wording: definitions[layout.table])        }        if next.keys != pages.keys { pages = next }        // The one in front first: its neighbours never hold it back.        for id in near.sorted(by: { a, _ in a == front }) { next[id]?.open() }    }    /// The places within `reach` of `at`, inside `count`.    static func window(at: Int, count: Int, reach: Int) -> [Int] {        guard count > 0 else { return [] }        return Array(max(0, at - reach)...min(count - 1, at + reach))    }}/// Where a chat opened from elsewhere goes while the stream is the app's/// face (a chat just started, an alert tapped, a link followed): the stream/// turns to it, and no second chat page is laid over the first/// (`ConversationRoute` hands the thread here and closes itself).@MainActor@Observablefinal class ChatStreamStand {    static let shared = ChatStreamStand()    /// A stream is the face of this app: set once it is mounted, and kept    /// while a page stands over it (the page that starts a chat).    var stands = false    /// The chat asked for, until the stream has turned to it.    var wanted: String?    /// Whether the stream takes `thread` of `table`: it does where it stands.    func take(_ thread: String) -> Bool {        guard stands else { return false }        wanted = thread        return true    }}enum ChatStreamKnobs {    static let lineHeight = DeckKnobs.lineHeight    static let lineSide = DeckKnobs.lineSide    /// How long typed search words rest before the stream is asked.    static let searchRestMs = 200    /// The stream's name among the alphabet's contested surfaces.    static let contest = "stream"    /// The stream's own space: the ink's strokes and the title band's foot are measured in it.    static let space = "chat-stream"}struct ChatStream: View {    /// The conversation table (`shell.fan`'s `stream.table`).    let table: String    /// The tool the stream is the face of.    let tool: String    @Environment(\.cottonCore) private var core    @Environment(\.records) private var store    @Environment(\.tableDefinitions) private var definitions    @Environment(\.recordsRevision) private var revision    @Environment(\.theme) private var theme    @Environment(\.accessibilityVoiceOverEnabled) private var voiceOver    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var model = ChatStreamModel()    @State private var searching = false    @State private var query = ""    @State private var ink = InkLetters()    @State private var inkPending: [String] = []    @State private var inkSurface = "stream:\(UUID().uuidString)"    @State private var menuOpen = false    /// The Account card stands in the stream's place.    @State private var account = false    @State private var lineWidth: CGFloat = 0    /// Where the chat's title band ends: above it nothing scrolls and every    /// stroke is the ink's; under it a stroke is contested with the scroll.    @State private var headFoot: CGFloat = ChatStreamKnobs.lineHeight    /// Where the chat's foot begins (the typing line and the pair beside    /// it): a stroke begun there is the typing line's, never read.    @State private var footTop: CGFloat = .infinity    /// The ink holds the chat: its scroll stands down.    @State private var inkHolds = false    /// Where the chat's rail begins, at its right edge: a stroke begun on    /// the rail is the rail's, never read.    @State private var railLeft: CGFloat = .infinity    private struct Reading: Hashable {        var revision: Int        var query: String        var ink: String        var definitions: Bool    }    var body: some View {        VStack(spacing: 0) {            if account {                accountPage            } else {                topLine.frame(height: ChatStreamKnobs.lineHeight)                content            }        }        .frame(maxWidth: .infinity, maxHeight: .infinity)        .coordinateSpace(.named(ChatStreamKnobs.space))        // Letters written anywhere on the chat narrow the stream. Under the        // head the chat scrolls: a stroke there is contested with it.        .inkWriting(InkReads.here(voiceOver: voiceOver) && !searching && !account,                    ink: DeckGround.ink(.ink, on: nil, theme: theme),                    surface: InkSurface(name: inkSurface, table: table, tool: tool, tier: "deck"),                    reads: { $0.y >= ChatStreamKnobs.lineHeight && $0.y < footTop && $0.x < railLeft },                    contest: InkContest(name: ChatStreamKnobs.contest, contested: { $0.y > headFoot },                                        holds: { inkHolds = $0 }, stepped: step),                    answered: takeInk, unread: { _ in })        .task { await InkKnobs.shared.load(core) }        .onAppear {            ChatStreamClock.mount()            ChatStreamStand.shared.stands = true        }        // A chat opened from elsewhere: the stream turns to it.        .task(id: ChatStreamStand.shared.wanted) {            guard let thread = ChatStreamStand.shared.wanted else { return }            ChatStreamStand.shared.wanted = nil            account = false            searching = false            query = ""            if !ink.isEmpty { await editInk(.clear) }            await model.turn(to: thread, core: core, table: table)            model.keep(table: table, definitions: definitions, store: store)        }        .task(id: Reading(revision: revision, query: query, ink: ink.letters, definitions: definitions[table] != nil)) {            if !query.isEmpty { try? await Task.sleep(for: .milliseconds(ChatStreamKnobs.searchRestMs)) }            guard !Task.isCancelled else { return }            await model.read(core: core, table: table, query: query, ink: ink.letters)            model.keep(table: table, definitions: definitions, store: store)        }        .onChange(of: model.front) { _, front in            if let front { ChatStreamClock.swipe(to: front) }            model.keep(table: table, definitions: definitions, store: store)        }        .menuTray(isOpen: $menuOpen, items: topItems)        // The shell's paper: no ground of the chat's own, and the page is        // read once the stream is (`FanPageReading`).        .preference(key: DeckGroundPreference.self, value: .known(nil))        .preference(key: FanPageReadingPreference.self, value: FanPageReading(filled: model.answer != nil))        .accessibilityElement(children: .contain)        .accessibilityIdentifier("stream")    }    // MARK: The top line    @ViewBuilder private var topLine: some View {        HStack(spacing: 12) {            if searching {                TextField(model.answer?.search ?? "", text: $query)                    .scaledFace(relativeTo: .callout) { CottonFonts.type((DeckKnobs.positionSize + 1) * $0) }                    .foregroundStyle(theme.print(.ink))                    .textFieldStyle(.plain)                    .autocorrectionDisabled()                    .submitLabel(.search)                    .accessibilityIdentifier("stream-search-field")                NavCircle(symbol: "xmark", label: ShellLines.line("cards", "deck.close_search")) {                    searching = false                    query = ""                }                .accessibilityIdentifier("stream-search-close")            } else {                if let line = model.answer?.unreadLine {                    Text(line)                        .scaledFace(relativeTo: .callout) { CottonFonts.type(DeckKnobs.positionSize * $0) }                        .foregroundStyle(theme.print(.pencil))                        .lineLimit(1)                        .minimumScaleFactor(0.4)                        .layoutPriority(1)                        .accessibilityIdentifier("stream-unread")                }                Spacer()                InkReadout(letters: ink, provisional: inkPending, widest: lineWidth / 2,                           search: { searching = true }, edit: { edit in Task { await editInk(edit) } })                    .accessibilityIdentifier("stream-search")                if model.answer?.top.isEmpty == false {                    NavCircle(symbol: "ellipsis", label: ShellLines.line("chat", "stream.top")) { menuOpen = true }                        .accessibilityIdentifier("stream-top")                }            }        }        .padding(.horizontal, ChatStreamKnobs.lineSide)        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { lineWidth = $0 }    }    /// What the one top button holds, as the core names it.    private var topItems: [PopoverMenuItem] {        (model.answer?.top ?? []).map { item in            PopoverMenuItem(id: "stream-top-\(item.id)", object: item.object, label: item.label) { open(item) }        }    }    private func open(_ item: StreamAnswer.Top) {        if let path = item.route {            guard let route = Route.parse(path) else {                toasts?.show(ShellLines.line("record", "address_failed"), tone: .error)                return            }            navigator?.push(route)        } else {            account = true        }    }    /// The Account card (sign in and out, Your people, the sync), the shell's    /// own page, with the way back to the chats.    private var accountPage: some View {        AccountPage(card: "account", table: table)            .overlay(alignment: .topTrailing) {                NavCircle(symbol: "xmark", label: ShellLines.line("chat", "stream.close")) { account = false }                    .padding(.horizontal, ChatStreamKnobs.lineSide)                    .frame(height: ChatStreamKnobs.lineHeight)                    .accessibilityIdentifier("stream-account-close")            }    }    // MARK: The chats    @ViewBuilder private var content: some View {        if let answer = model.answer {            if model.chats.isEmpty {                Text(answer.empty)                    .paperHand(16)                    .multilineTextAlignment(.center)                    .padding(.horizontal, 28)                    .frame(maxWidth: .infinity, maxHeight: .infinity)                    .accessibilityIdentifier("stream-empty")            } else {                pager(model.chats)            }        } else {            Color.clear        }    }    /// The chat in front, alone: its neighbours hold their messages    /// (`ChatStreamModel.keep`) and stand in its place in one frame.    @ViewBuilder private func pager(_ chats: [StreamAnswer.Chat]) -> some View {        if let chat = chats.first(where: { $0.id == model.front }) ?? chats.first {            ChatStreamPage(                chat: chat, table: table, page: model.pages[chat.id], front: true,                previous: model.neighbour(-1), next: model.neighbour(1),                go: cut,                moved: { Task { await model.read(core: core, table: table, query: query, ink: ink.letters) } },                headFoot: $headFoot, footTop: $footTop, railLeft: $railLeft, inkHolds: inkHolds)            .id(chat.id)            .accessibilityScrollAction { edge in                if edge == .trailing { step(1) } else if edge == .leading { step(-1) }            }        }    }    /// The chat changed at once: a plain cut, no slide.    private func cut(to id: String) {        withTransaction(SplashOverlay.cut) { model.front = id }    }    /// A step the core read (a sideways swipe at its lift): the next chat    /// or the one before, cut to; nothing past either end.    private func step(_ by: Int) {        if let id = model.neighbour(by) { cut(to: id) }    }    // MARK: Ink    private func takeInk(_ answer: InkAnswer) {        Task { @MainActor in            for group in answer.groups {                for stroke in group.strokes { await swipe(stroke) }                if let keep = InkKnobs.shared.values?.keepGroups { await InkCapture.shared.keep(group.line, last: keep) }            }            guard answer.surface.name == inkSurface else { return }            ink = answer.letters            inkPending = answer.provisional        }    }    /// A line the ink read that edited no letters (one drawn on the head,    /// or after a letter): the swipe, by the same rule as one that never    /// bent over the messages.    private func swipe(_ stroke: InkStroke) async {        guard stroke.run.read == "line", stroke.run.edit == nil, let core,              let from = stroke.points.first, let to = stroke.points.last else { return }        struct Ask: Encodable, Sendable { let surface: String, contest: String, from: [Double], to: [Double] }        struct Lifted: Decodable, Sendable { var step: Int? }        let ask = Ask(surface: inkSurface, contest: ChatStreamKnobs.contest, from: [from.x, from.y], to: [to.x, to.y])        if let by = try? await core.call("ink.contest", ask, as: Lifted.self).step { step(by) }    }    private func editInk(_ edit: InkEdit) async {        guard let core else { return }        let surface = inkSurface        if let letters = try? await InkReader.edit(core, surface: surface, edit), surface == inkSurface { ink = letters }    }}/// One chat of the stream: its title in a band of its own, its messages as/// the opened chat draws them with the rail down their right edge (the/// previous / next pair at its foot), and under them the typing line, or the/// archive line where nothing is sent.struct ChatStreamPage: View {    let chat: StreamAnswer.Chat    let table: String    /// Its record and messages, while it is in front or beside the one that is.    let page: ChatStreamPageModel?    let front: Bool    let previous: String?    let next: String?    let go: (String) -> Void    /// Something the stream says changed here (a request answered).    let moved: () -> Void    /// Where the title band ends, said by the chat in front.    let headFoot: Binding<CGFloat>?    /// Where the foot begins, said by the chat in front.    let footTop: Binding<CGFloat>?    /// Where the rail begins, said by the chat in front.    let railLeft: Binding<CGFloat>?    /// The ink holds the chat (a stroke that bent, a letter in progress):    /// the scroll stands down and goes back to where it rested.    let inkHolds: Bool    @Environment(\.tableDefinitions) private var definitions    @Environment(\.records) private var store    @Environment(\.recordsRevision) private var revision    @Environment(\.cottonChat) private var chatEngine    @Environment(\.theme) private var theme    @State private var scroll = ScrollPosition()    @State private var rest = ChatScrollRest()    @State private var rail = ChatRailModel()    @Environment(\.cottonCore) private var core    private var record: TableRecord? { page?.record }    private var cotton: Bool { CottonChatRows.isCotton(thread: record) }    private struct Showing: Hashable {        var front: Bool        var cotton: Bool    }    var body: some View {        VStack(spacing: 0) {            titleBand            ScrollViewReader { proxy in                messages                    // The rail: its own strip at the chat's right edge.                    .overlay(alignment: .trailing) {                        ChatRail(model: rail, previous: previous, next: next, go: go,                                 turn: { stop in withTransaction(SplashOverlay.cut) { proxy.scrollTo(stop.message, anchor: .top) } },                                 reachedTop: older)                            .onGeometryChange(for: CGFloat.self) { $0.frame(in: .named(ChatStreamKnobs.space)).minX } action: { left in                                railLeft?.wrappedValue = left                            }                    }            }            foot        }        .composerColumn()        // A Cotton chat in front is read while it shows (its receipts are        // the core's to send); any other chat in front shows none.        .task(id: Showing(front: front, cotton: cotton)) {            if front { chatEngine?.showing(thread: cotton ? chat.id : nil) }        }        // What lands in the chat in front, or beside it, is drawn at once.        .task(id: revision) {            guard revision > 0, let page else { return }            await page.refresh()        }        // The rail's days, for the messages the chat holds now.        .task(id: railMessages) { await rail.read(core: core, messages: railMessages) }        .onChange(of: page?.conversation.phase == .loaded && front, initial: true) { _, stands in            if stands { ChatStreamClock.stood(chat.id) }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier(front ? "stream-chat" : "stream-chat-\(chat.id)")    }    /// The chat's messages as the rail is asked about them: oldest first,    /// each with its day as the core said it.    private var railMessages: [ChatRailModel.Message] {        (page?.conversation.items ?? []).filter(\.isMessage).map {            ChatRailModel.Message(id: $0.record.id, day: $0.day?.day, label: $0.day?.heading)        }    }    /// The rail's thumb reached its top: the chat's older messages are read.    private func older() {        guard let conversation = page?.conversation, conversation.hasMore else { return }        Task { await conversation.loadMore() }    }    /// The chat's name and where it is from, in a band of their own: a long    /// name wraps here and never onto the first message.    private var titleBand: some View {        HStack(alignment: .firstTextBaseline, spacing: 10) {            Text(record?.said?.slip.name ?? chat.name ?? "")                .paperTitle(theme.scale[.headRecordTitleSize])                .lineLimit(2)                .multilineTextAlignment(.leading)                .fixedSize(horizontal: false, vertical: true)                .frame(maxWidth: .infinity, alignment: .leading)                .accessibilityAddTraits(.isHeader)                .accessibilityIdentifier("stream-title")            if let mark = chat.mark {                Text(mark.label)                    .paperMeta(12)                    .lineLimit(1)                    .fixedSize()                    .accessibilityIdentifier("stream-mark-\(mark.id)")            }        }        .cottonContentMargin()        .padding(.top, 2)        .padding(.bottom, 8)        .onGeometryChange(for: CGFloat.self) { $0.frame(in: .named(ChatStreamKnobs.space)).maxY } action: { foot in            headFoot?.wrappedValue = foot        }    }    @ViewBuilder private var messages: some View {        if let page, let record, let definition = definitions[table] {            ScrollView {                ConversationPage(definition: definition, record: record, model: page.conversation, showsTitle: false, saysArchive: false)                    .cottonContentMargin()                    .padding(.bottom, 12)                    .pageColumn(screen: "a chat")            }            .defaultScrollAnchor(.bottom)            .scrollPosition($scroll)            // The scroll follows the finger at once, always. Where it stood            // as the finger came down is kept, and when the ink takes the            // stroke (it bent: a letter) the scroll stands down and goes            // back there, so writing never moves the chat.            .onScrollGeometryChange(for: CGFloat.self) { $0.contentOffset.y } action: { _, y in rest.now = y }            // Where the scroll stands, for the rail's thumb at rest.            .onScrollGeometryChange(for: Double.self) { geometry in                let room = geometry.contentSize.height - geometry.containerSize.height                return room > 1 ? min(1, max(0, Double(geometry.contentOffset.y / room))) : 1            } action: { _, at in rail.scrolled = at }            // The messages stand clear of the rail's strip.            .contentMargins(.trailing, 12, for: .scrollContent)            .onScrollPhaseChange { _, phase in                if phase == .interacting { rest.held = rest.now }            }            .scrollDisabled(inkHolds)            .onChange(of: inkHolds) { _, holds in                if holds, let held = rest.held { scroll.scrollTo(y: held) }                if !holds { rest.held = nil }            }            .accessibilityIdentifier("stream-messages")        } else if page?.unreadable == true, let definition = definitions[table] {            QuietState(title: ShellLines.line("record", "unreadable_kind", ["kind": definition.name.lowercased()]),                       message: ShellLines.line("empty", "unchanged"))                .frame(maxHeight: .infinity)        } else {            Color.clear.frame(maxHeight: .infinity)        }    }    private var foot: some View {        typingLine            .frame(maxWidth: .infinity)            .background(theme.colors.groundMuted.color)            .onGeometryChange(for: CGFloat.self) { $0.frame(in: .named(ChatStreamKnobs.space)).minY } action: { top in                footTop?.wrappedValue = top            }    }    /// The typing line, as the opened chat stood it (`ConversationRoute`): a    /// stranger's request answered first, a Cotton chat's composer, any other    /// sendable chat's, and the archive's line where nothing is sent.    @ViewBuilder private var typingLine: some View {        if let page, let record, let definition = definitions[table], let layout = definition.conversation {            let takes = record.said?.readOnly != true && layout.takesWords(on: record)            if let chatEngine, cotton, CottonChatRows.isRequest(thread: record) {                ChatRequestCard(thread: chat.id, name: record.said?.slip.name, chat: chatEngine) { _ in                    await page.refresh()                    moved()                }            } else if let chatEngine, cotton, takes {                CottonChatComposer(model: page.conversation, chat: chatEngine, recipient: record.said?.slip.name,                                   identifier: "page-\(definition.id)")            } else if !cotton, takes {                ConversationComposer(model: page.conversation, identifier: "page-\(definition.id)",                                     recipient: record.said?.slip.name) { await page.refresh() }            } else {                Text(ShellLines.line("conversation", "archive"))                    .paperHand(15)                    .multilineTextAlignment(.center)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.vertical, 18)                    .accessibilityIdentifier("stream-archive")            }        } else {            Color.clear.frame(height: 44)        }    }}/// Where a chat's scroll stands (`now`) and where it stood when the finger/// last came down on it (`held`): read by the scroll's own callbacks, never/// drawn from, so a scroll redraws nothing.@MainActorfinal class ChatScrollRest {    var now: CGFloat = 0    var held: CGFloat?}