Cotton code
124 lines · 6.5 KB · SwiftRaw
// A CONVERSATION'S OWN SCREEN (door row 14). A thread is a card on its deck;// its inside is the chat (`ConversationPage`): its title, the messages as// notes, the owner's on blue at the right and the others' on cream at the// left, the day lines between days, the composer with the mic and the send.// Opened here on its own — read, its messages loaded at the newest// (or at the message a search found), the composer at its foot; or narrowed// to its photos and files, with no composer.import CottonKitimport CottonValuesimport SwiftUIstruct ConversationRoute: View {    let table: String    let id: String    /// The message the chat opens on (a search hit's), else its newest.    var anchor: String? = nil    /// The thread narrowed to its photos and files (`/messages/…/media`),    /// with no composer: browsing, not writing.    var mediaOnly = false    @Environment(\.tableDefinitions) private var definitions    @Environment(\.records) private var store    @Environment(\.screenRoute) private var screenRoute    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.cottonChat) private var chat    @Environment(\.recordsRevision) private var revision    @State private var record: TableRecord?    @State private var conversation: ConversationModel?    @State private var unread = false    var body: some View {        if let definition = definitions[table], let layout = definition.conversation {            PaperScreen(title: record.flatMap { $0.said?.slip.name }, closes: true, scrollAnchor: .bottom) {                if let record, let conversation {                    // Under the head row, never behind its circles: the                    // row holds no title here, only the X that closes it.                    ConversationPage(definition: definition, record: record, model: conversation, mediaOnly: mediaOnly, showsTitle: false)                        .padding(.top, ScreenBarKnobs.chromeNavCircleTarget + 8)                } else if unread {                    QuietState(title: ShellLines.line("record", "unreadable_kind", ["kind": definition.name.lowercased()]),                               message: ShellLines.line("empty", "unchanged"))                }            }            .safeAreaInset(edge: .bottom) {                // A thread kept elsewhere (an email archive) or ended takes no                // message from here: no composer, only the page's own line                // saying so (`takesWords`).                if let record, let conversation, !mediaOnly, let chat, CottonChatRows.isCotton(thread: record) {                    // A Cotton chat: a stranger's request is answered first;                    // nothing is sent to them until it is accepted.                    if CottonChatRows.isRequest(thread: record) {                        ChatRequestCard(thread: id, name: record.said?.slip.name, chat: chat) { decision in                            if decision == .accept {                                self.record = (try? await store?.get(table: table, id: id)) ?? self.record                            } else {                                navigator?.pop()                            }                        }                    } else if takesWords(definition, layout, record) {                        CottonChatComposer(model: conversation, chat: chat, recipient: record.said?.slip.name,                                           identifier: "page-\(definition.id)")                    }                } else if let record, let conversation, !mediaOnly, takesWords(definition, layout, record) {                    ConversationComposer(model: conversation, identifier: "page-\(definition.id)",                                         recipient: record.said?.slip.name) {                        self.record = (try? await store?.get(table: table, id: id)) ?? self.record                    }                }            }            // A Cotton chat on screen is read while it shows (its receipts            // are the core's to send), and what lands in it is drawn at once.            .onAppear { if CottonChatRows.isCotton(thread: record) { chat?.showing(thread: id) } }            .onChange(of: record?["external_key"].text) { _, _ in if CottonChatRows.isCotton(thread: record) { chat?.showing(thread: id) } }            .onDisappear { if CottonChatRows.isCotton(thread: record) { chat?.showing(thread: nil) } }            .task(id: revision) {                guard revision > 0, let conversation, CottonChatRows.isCotton(thread: record) else { return }                await conversation.load()                self.record = (try? await store?.get(table: table, id: id)) ?? self.record            }            .task(id: "\(table)|\(id)") {                // Where the app's face is one stream of chats, the stream                // turns to this chat: one chat page, never a second over it.                if anchor == nil, !mediaOnly, ChatStreamStand.shared.take(id) {                    navigator?.pop()                    return                }                await open(definition, layout)            }            // A chat owns its foot even when it is an archive. Cotton            // commands stay on the deck; an archive has no composer.            .onAppear {                if let screenRoute { navigator?.carries(composer: true, on: screenRoute) }            }            // The page is named, and what stands on it keeps its own names            // (the composer's, the request card's answers).            .accessibilityElement(children: .contain)            .accessibilityIdentifier("conversation-\(table)")        } else {            UnknownTable()        }    }    /// The thread takes a message from here: not read-only, its send gate    /// open, not ended.    private func takesWords(_ definition: TableDefinition, _ layout: ConversationLayout, _ record: TableRecord) -> Bool {        record.said?.readOnly != true && layout.takesWords(on: record)    }    private func open(_ definition: TableDefinition, _ layout: ConversationLayout) async {        guard let store else { return unread = true }        let thread = ConversationModel(layout: layout, thread: id, store: store, wording: definitions[layout.table])        conversation = thread        // The messages are read beside the record, never behind it.        let talk = Task { await thread.load(anchor: anchor) }        guard let read = try? await store.get(table: table, id: id) else {            unread = true            return        }        thread.threadRecord = read        record = read        await talk.value    }}