// Cotton Chat's screen models: what the list and a thread hold of the// core's answers, and how a change lands — one row or one bubble, never the// whole screen. The models decide nothing the core says; they only keep// pages, cursors and what is in flight.#if os(iOS)importCottonKitimportFoundationimportObservationimport os/// How long the screens took, kept for the lane's report and a walk.enumChatSpeed {staticlet log = Logger(subsystem: "com.cottondb.chat", category: "speed") @MainActor staticvar marks: [String: Double] = [:] @MainActor staticfunc mark(_ name: String, since start: ContinuousClock.Instant) {let ms = Double((ContinuousClock.now - start).components.attoseconds) / 1e15 + Double((ContinuousClock.now - start).components.seconds) * 1000 marks[name] = ms log.notice("\(name, privacy: .public) \(ms, format: .fixed(precision: 1), privacy: .public) ms") }}// MARK: the list@MainActor@ObservablefinalclassChatListModel {private(set) var filter: Stringprivate(set) var search = ""private(set) var rows: [ChatListRow] = []private(set) var words: ChatListWords?private(set) var fan: [ChatFanTile] = []/// The filters above the list, as the core answers them.private(set) var filters: [ChatFanTile] = []/// How many conversations are archived (Archived stands at the foot when any are).private(set) var archived = 0private(set) var next: String?private(set) var failed: String?/// Bumped whenever rows change; the table diffs against it.private(set) var revision = 0/// When a chat's next message goes by its timer (the core's `erasesIn`, from when the answer came): asked again then.private(set) var erasesAt: Date?privatelet book: any ChatBookprivatevar asks = 0privatevar loadingMore = false/// The last answer per filter, so a list opened again draws at once.privatestaticvar warm: [String: ChatListAnswer] = [:]init(book: any ChatBook, filter: String) {self.book = bookself.filter = filteriflet warm = Self.warm[filter] { take(warm) } }func load() async {let start = ContinuousClock.nowawait read()ChatSpeed.mark("list.drawn", since: start) }/// Something landed: the list is asked again and only rows that changed move.func refresh() async { await read() }func set(search: String) async {guard search != self.search else { return }self.search = searchawait read() }privatefunc read() async { asks += 1let asked = asksdo {let answer = tryawait book.list(ChatListAsk(filter: filter, search: search.isEmpty ? nil : search))guard asked == asks else { return }if search.isEmpty { Self.warm[filter] = answer } take(answer)// Who is no longer on Cotton, said on their rows (CIRCLE 2).let people = rows.filter { !$0.group }.map(\.thread)Task { awaitChatCircleGone.shared.read(threads: people) } } catch { failed = String(describing: error) } }func loadMore() async {guardlet next, !loadingMore else { return } loadingMore = truedefer { loadingMore = false }guardlet answer = try? await book.list(ChatListAsk(filter: filter, search: search.isEmpty ? nil : search, after: next)) else { return }let have = Set(rows.map(\.thread)) rows += answer.rows.filter { !have.contains($0.thread) }self.next = answer.next revision += 1 }privatefunc take(_ answer: ChatListAnswer) { rows = answer.rows words = answer.words fan = answer.fan filters = answer.filters archived = answer.counts.archived next = answer.next erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } failed = nil revision += 1 }/// One row changed: replaced where it stands when its place holds, else/// the list is asked again and only the rows that moved move.func apply(_ row: ChatListRow) async {iflet at = rows.firstIndex(where: { $0.thread == row.thread }) {let old = rows[at]let samePlace = old.pinned == row.pinned && old.archived == row.archived && old.when == row.when && old.lastLine == row.lastLine && keeps(row)if samePlace { rows[at] = row revision += 1return } }await read() }privatefunc keeps(_ row: ChatListRow) -> Bool {switch filter {case"unread": row.unread > 0 || row.markedUnreadcase"archived": row.archiveddefault: !row.archived } }/// A swipe's act; the row the core answers replaces the old one. A deleted chat leaves the list the moment the/// core answers (FEEDBACK-4 B2), before the list is asked again; a refusal is said, never swallowed.func act(_ swipe: ChatSwipe, on row: ChatListRow) async -> String? {let answer: ChatActAnswerdo { answer = tryawait book.act(ChatActAsk(act: swipe.act, thread: row.thread)) } catchlet refusal asCottonCallError {return refusal.message } catch {returnnil }if swipe.act == "deleteChat" { rows.removeAll { $0.thread == row.thread } revision += 1 }iflet row = answer.row { await apply(row) } else { await read() }return answer.said }func row(_ thread: String) -> ChatListRow? { rows.first { $0.thread == thread } }}// MARK: a thread/// One item as the thread's table draws it, with an identity that holds/// across pages (a divider is named by what follows it).structChatDrawn: Hashable, Sendable {var id: Stringvar item: ChatThreadItem}@MainActor@ObservablefinalclassChatThreadModel {structPage: Sendable {var items: [ChatDrawn]var older: String?var newer: String? }let thread: Stringprivate(set) var header: ChatHeader?/// Not on Cotton yet, and how many of the person's messages wait (`chat.thread`'s `reach`).private(set) var reach: ChatReach?private(set) var pinned: ChatPinnedBar?private(set) var actions: ChatActionWords?private(set) var composer: ChatComposeAnswer?private(set) var readOnly: String?/// "Loading this chat…" while the first pull runs and nothing of this chat has come (`chat.thread`'s `loading`).private(set) var loading: String?private(set) var request: ChatAskCard?private(set) var jump: ChatJump?/// Pages oldest first; the window holds at most `window` of them.private(set) var pages: [Page] = []/// The message to scroll to and flash.private(set) var focus: String?/// Bumped each time the person's own message lands here from Send: the chat goes down to it, wherever the/// reader stood (a reply written to a message far above is seen, with its quote, once sent).private(set) var sentHere = 0/// Bumped on every change to the items; carries what changed.private(set) var revision = 0private(set) var change: Change = .all/// Messages that came in below the window while the reader was away.private(set) var arrivedBelow = 0private(set) var said: String?/// How `said` stands: a refusal is an error's toast, which takes the lines a long reason needs at the largest/// text (a notice's three cut "Only pictures, videos and voice notes go to WhatsApp for now.").private(set) var saidTone: CottonToast.Tone = .notice/// Pictures picked and waiting in the writing box: Send takes them with what is written as their caption.private(set) var attached: [ChatAttachment] = []/// Bumped each time the core refuses a send: the writing box puts back what was written.private(set) var refusedSends = 0/// The chat's disappearing timer, as `chat.thread` answers it (none where the core answers none).private(set) var timer: ChatTimerCard?/// When this chat's next message goes (the core's `erasesIn`, counted from when the answer came): asked again then.private(set) var erasesAt: Date?/// The card fetched here for the link in what is written (FEEDBACK-4 B4): it stands above the writing box and goes/// with the send.private(set) var card: ChatLinkCard?/// Links whose card he closed: offered none again in this message.privatevar closedLinks: Set<String> = []enumChange: Equatable {case allcase appendedOldercase appendedNewercase bubbles(Set<String>) }staticlet window = 8/// The id a WhatsApp text on its way through the Mac carries until it stands as a message. nonisolated staticlet pending = "outbox:"privatelet book: any ChatBookprivatevar loadingOlder = falseprivatevar loadingNewer = falseprivatevar composeAsks = 0privatestaticvar warm: [String: ChatThreadAnswer] = [:]init(book: any ChatBook, thread: String) {self.book = bookself.thread = threadiflet warm = Self.warm[thread] { take(warm) } }var items: [ChatDrawn] { pages.flatMap(\.items) }var older: String? { pages.first?.older }var newer: String? { pages.last?.newer }var atNewest: Bool { pages.last.map { $0.newer == nil } ?? true }/// The bubble with this message, wherever it is in the window.func bubble(_ message: String) -> ChatBubble? {for page in pages { for d in page.items where d.id == message { return d.item.bubble } }returnnil }funcopen() async {let start = ContinuousClock.nowguardlet answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return }Self.warm[thread] = answer take(answer)ChatSpeed.mark("thread.drawn", since: start) }privatefunc take(_ answer: ChatThreadAnswer) { header = answer.header reach = answer.reach pinned = answer.pinned actions = answer.actions composer = answer.composer ?? composer.flatMap { answer.readOnly == nil ? $0 : nil } readOnly = answer.readOnly request = answer.request loading = answer.loading jump = answer.jump focus = answer.focus timer = answer.timer erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } pages = [Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer)] arrivedBelow = 0 change = .all revision += 1 }/// The page above the oldest held, asked ahead of the finger.func loadOlder() async {guardlet older, !loadingOlder else { return } loadingOlder = truedefer { loadingOlder = false }guardlet answer = try? await book.thread(ChatThreadAsk(thread: thread, before: older)) else { return } pages.insert(Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer), at: 0)if pages.count > Self.window { pages.removeLast(pages.count - Self.window) } change = .appendedOlder revision += 1 }/// The page below the newest held (after a jump into the past).func loadNewer() async {guardlet newer, !loadingNewer else { return } loadingNewer = truedefer { loadingNewer = false }guardlet answer = try? await book.thread(ChatThreadAsk(thread: thread, after: newer)) else { return } pages.append(Page(items: Self.drawn(answer.items), older: answer.older, newer: answer.newer))if pages.count > Self.window { pages.removeFirst(pages.count - Self.window) } jump = answer.jumpif answer.newer == nil { arrivedBelow = 0 } change = .appendedNewer revision += 1 }func jumpToLatest() async {guardlet answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return } take(answer) jump = nil }func go(to message: String) async {guardlet answer = try? await book.thread(ChatThreadAsk(thread: thread, around: message)) else { return } take(answer) }func flashed() { focus = nil }// MARK: composingprivatevar attachedCount: Int? { attached.isEmpty ? nil : attached.count }func type(_ text: String) async { composeAsks += 1let asked = composeAsks// While an edit's strip stands, the words are that message's new words (the core keeps no edit between asks).let editing = composer?.strip.flatMap { $0.kind == .edit ? $0.message : nil }guardlet answer = try? await book.compose(ChatComposeAsk(thread: thread, text: text, edit: editing, attached: attachedCount)) else { return }if asked == composeAsks { composer = answer } }func reply(to message: String) async {iflet answer = try? await book.compose(ChatComposeAsk(thread: thread, replyTo: message, attached: attachedCount)) { composer = answer } }/// The edit strip over the writing box, the message's words in the field; a refusal is said in the core's words.func edit(_ message: String) async {do { composer = tryawait book.compose(ChatComposeAsk(thread: thread, edit: message)) } catchlet refusal asCottonCallError { refused(refusal.message) } catch {} }func cancelStrip() async {iflet answer = try? await book.compose(ChatComposeAsk(thread: thread, cancel: true, attached: attachedCount)) { composer = answer } }/// Pictures picked: they wait in the writing box for their caption, and the core says Send is live.func attach(_ files: [ChatAttachment]) async {guard !files.isEmpty else { return } attached += filesawait type(composer?.text ?? "") }/// The waiting pictures taken out of the box (its Cancel).func unattach() async { attached = []await type(composer?.text ?? "") }/// What waits in the box, taken once by Send.func takeAttached() -> [ChatAttachment] {defer { attached = [] }return attached }/// A voice message let go: it goes at once, like any message (never/// waiting for its words). Then the words this phone hears in it, on the/// device only, follow as a change to it (`chat.act transcript`), and its/// bubble carries them under the player. None heard, nothing follows.func sendVoice(_ voice: ChatAttachment) async {guardlet message = await send("", attachments: [voice]) else { return }let file = URL(fileURLWithPath: voice.path)Task { [weakself] inguardlet words = awaitChatVoiceWords.heard(in: file), letselfelse { return }guardlet answer = try? awaitself.book.act(ChatActAsk(act: "transcript", thread: self.thread, message: message, text: words)) else { return }iflet bubble = answer.bubble { self.replace(bubble) }if answer.flush { Task.detached(priority: .utility) { [book = self.book] inawait book.flush() } } } }/// Sends what is written. The bubble the core answers lands at once,/// before the network; the flush goes off the main thread. Answers the message sent./// With the core's reply strip standing, the send answers that message (`replyTo`), so the bubble quotes it;/// with its edit strip, the words change that message instead (`chat.act edit`). @discardableResultfunc send(_ text: String, attachments: [ChatAttachment] = []) async -> String? {let start = ContinuousClock.now composeAsks += 1let strip = composer?.stripiflet strip, strip.kind == .edit, attachments.isEmpty {do {let answer = tryawait book.act(ChatActAsk(act: "edit", thread: thread, message: strip.message, text: text))iflet bubble = answer.bubble { replace(bubble) }if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } } } catchlet refusal asCottonCallError { refused(refusal.message) } catch {}iflet composer = try? await book.compose(ChatComposeAsk(thread: thread, text: "", cancel: true)) { self.composer = composer }return strip.message }// The card standing for a link still in the words goes with them (FEEDBACK-4 B4); the core checks it.// A file sent at once with no words of its own leaves the words still being written, and their card, standing.let card = self.card.flatMap { text.contains($0.url) ? $0 : nil }if !text.isEmpty {self.card = nil closedLinks = [] }let ask = ChatActAsk(act: "send", thread: thread, text: text.isEmpty ? nil : text, attachments: attachments.isEmpty ? nil : attachments, replyTo: strip?.kind == .reply ? strip?.message : nil, preview: card)let answer: ChatActAnswerdo { answer = tryawait book.act(ask) } catchlet refusal asCottonCallError {// Refused (a file too large for WhatsApp, a kind it does not take yet): said in the core's words, and what// was picked goes back in the box beside the words, so a second tap sends them (as Android, a592647355). attached = attachments.filter { $0.kind != "voice" } + attached refused(refusal.message) refusedSends += 1// A file picked with Files goes at once with no words of its own, so the words still being written stay// the draft; a Send from the box gives its words back.await type(text.isEmpty ? composer?.text ?? "" : text)returnnil } catch {returnnil }iflet bubble = answer.bubble {if answer.message.map({ self.bubble($0) != nil }) ?? false { replace(bubble) } elseif atNewest { place(bubble) } else {await jumpToLatest() } sentHere += 1 }// One tap to WhatsApp can be several messages (a file a message; a document's words go first as their own// text), and the core answers the first one's bubble only: the chat is read again, so each stands at once.if answer.message?.hasPrefix(Self.pending) == true, !attachments.isEmpty { await reread() }iflet composer = try? await book.compose(ChatComposeAsk(thread: thread, text: "")) { self.composer = composer }ChatSpeed.mark("send.drawn", since: start)if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } }return answer.message }// MARK: link previews/// The card for the link the core offers in what is written (`composer.preview`, FEEDBACK-4 B4): fetched by this/// phone (the page, read by the core; then its picture, made small), unless he closed it. A link no longer offered/// drops its card. Run as the writing box's task for that link, so a link changed mid-fetch is never shown.func fetchCard(_ url: String?) async {guardlet url, !closedLinks.contains(url) else { card = nil; return }if card?.url == url { return } card = nilguardlet page = awaitChatLinkFetch.page(url), !Task.isCancelled,let read = await book.linkCard(thread: thread, url: url, page: page), let title = read.title, !Task.isCancelled else { return }var thumb: String?iflet image = read.image { thumb = awaitChatLinkFetch.thumb(image) }guard !Task.isCancelled, composer?.preview?.url == url, !closedLinks.contains(url) else { return } card = ChatLinkCard(url: url, site: read.site, title: title, description: read.description, thumb: thumb) }/// He closed the card: that link offers none again in this message.func closeCard() {iflet url = card?.url { closedLinks.insert(url) } card = nil }/// Any of `chat.act`'s acts on a message: the bubble answered replaces its own. A refusal (a delete for everyone/// past WhatsApp's window) is said in the core's words.func act(_ act: String, message: String? = nil, messages: [String]? = nil, emoji: String? = nil, to: [String]? = nil) async {let answer: ChatActAnswerdo { answer = tryawait book.act(ChatActAsk(act: act, thread: thread, message: message, messages: messages, emoji: emoji, to: to)) } catchlet refusal asCottonCallError { refused(refusal.message)return } catch {return }iflet bubble = answer.bubble { replace(bubble) } saidTone = .notice said = answer.saidif act == "pin" || act == "unpin" {// The pinned bar is the thread's, not the bubble's: read it again.iflet fresh = try? await book.thread(ChatThreadAsk(thread: thread, around: message)) { pinned = fresh.pinned } }// A WhatsApp message deleted is erased, a marker in its place (the answer names the marker, not the message),// or nothing at all for Delete for me: the chat is read again (CONTRACT.md "Editing and deleting his own message").if act == "deleteMine" || (act == "delete" && answer.message != nil && answer.message != message) { await reread() } }/// A poll he made on its sheet (`chat.act poll`, CONTRACT.md "Making a poll"): the core checks it and queues it,/// and its card stands at once, "Waiting to send". A refusal is said in the core's words. Whether it went.func makePoll(question: String, options: [String], many: Bool) async -> Bool {var ask = ChatActAsk(act: "poll", thread: thread) ask.question = question ask.options = options ask.many = manylet answer: ChatActAnswerdo { answer = tryawait book.act(ask) } catchlet refusal asCottonCallError { refused(refusal.message)returnfalse } catch {returnfalse }iflet bubble = answer.bubble {if atNewest { place(bubble) } else { await jumpToLatest() } sentHere += 1 }if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } }returntrue }/// A tap on option `option` of a WhatsApp poll he can vote on (`chat.act vote`, CONTRACT.md "A vote"): the core/// works out his choice and draws it at once on the poll it answers, "Vote waiting to send"; a refusal is said in/// the core's words. The phone decides nothing.func vote(_ message: String, option: Int) async {var ask = ChatActAsk(act: "vote", thread: thread, message: message) ask.option = optiondo {let answer = tryawait book.act(ask)iflet bubble = answer.bubble { replace(bubble) }if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } } } catchlet refusal asCottonCallError { refused(refusal.message) } catch {} }func heard() { said = nil }/// A refusal, said in the core's words as an error.privatefunc refused(_ words: String) { saidTone = .error said = words }/// The chat's disappearing timer set (`chat.act timer`, CONTRACT.md "Disappearing messages"): the core writes the/// chat's line at once and what it queued for the other side goes with the next flush; the chat is read again,/// its line, its header's status and its timer with it. A refusal is said in the core's words.func setTimer(_ seconds: Int) async {do {var ask = ChatActAsk(act: "timer", thread: thread) ask.seconds = secondslet answer = tryawait book.act(ask)if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } } } catch { refused(ActionRefused.words(for: error)) }guardlet answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return }Self.warm[thread] = answerif atNewest { mergeNewest(answer) } else { header = answer.header; timer = answer.timer } }/// A failed message tried again: back in the outbox (`chat.act retry`),/// its bubble answered at once, then sent off the main thread./// A refusal (a WhatsApp text still waiting is `cannot`) is said in the core's words.func retry(_ message: String) async {let answer: ChatActAnswerdo { answer = tryawait book.act(ChatActAsk(act: "retry", thread: thread, message: message)) } catchlet refusal asCottonCallError { refused(refusal.message)return } catch {return }iflet bubble = answer.bubble { replace(bubble) }if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } } }/// The chat asked again as it shows and on sync (a WhatsApp text's state moves on the Mac, and its pending/// bubble leaves once the sent message stands): the newest page merged, only what changed drawn again.func reread() async {guard atNewest, !pages.isEmpty, let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { return }Self.warm[thread] = answer mergeNewest(answer) }/// The thread is on screen: theirs are stamped read (`chat.act read`),/// and when the core answers `flush` the person's other phones are told/// by the next `chat.flush`, off the main thread as a send's is. What/// the read changed is said to the list (its row) and to the/// notifications, which ask `chat.notices` again.func markRead() async {guardlet answer = try? await book.act(ChatActAsk(act: "read", thread: thread)) else { return }if answer.flush { Task.detached(priority: .utility) { [book] inawait book.flush() } }var info: [String: Any] = ["thread": thread]iflet row = answer.row { info["row"] = row }NotificationCenter.default.post(name: .cottonChatRead, object: nil, userInfo: info) }privatefunc place(_ bubble: ChatBubble) {// The bubble before it, if its run lost its tail, arrives as its own// change from the core: the phone never regroups.guard !pages.isEmpty else { return } pages[pages.count - 1].items.append(ChatDrawn(id: bubble.message, item: .bubble(bubble))) change = .appendedNewer revision += 1 }privatefunc replace(_ bubble: ChatBubble) {for p in pages.indices {iflet at = pages[p].items.firstIndex(where: { $0.id == bubble.message }) { pages[p].items[at].item = .bubble(bubble) change = .bubbles([bubble.message]) revision += 1return } } }/// A change the core streamed: one bubble, or news below.func apply(_ change: ChatChange) async {switch change {case .bubble(let thread, let bubble) where thread == self.thread: replace(bubble)case .arrived(let thread) where thread == self.thread:guard atNewest, let answer = try? await book.thread(ChatThreadAsk(thread: thread)) else { arrivedBelow += 1return } mergeNewest(answer)default:break } }/// The newest page read again: what is new is appended and what changed is replaced, so only those bubbles draw/// again. What the page no longer names has left (erased by its timer, deleted in WhatsApp, a text on its way that/// now stands as a message), and a new item amid the held ones (a deleted message's marker, in its place) means the/// span is laid again in the core's order: a message never lingers after the core has erased it.privatefunc mergeNewest(_ answer: ChatThreadAnswer) {let fresh = Self.drawn(answer.items)let held = Dictionary(items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })guardlet firstHeld = fresh.firstIndex(where: { held[$0.id] != nil }) else { take(answer)return }defer { header = answer.header reach = answer.reach timer = answer.timer erasesAt = answer.erasesIn.map { Date().addingTimeInterval($0 / 1_000) } }let tail = Array(fresh[firstHeld...])iflet (p, i) = position(of: tail[0].id), Self.laidAgain(held: pages[p...].enumerated().flatMap { k, page in (k == 0 ? Array(page.items[i...]) : page.items).map(\.id) }, tail: tail.map(\.id)) { pages[p].items = Array(pages[p].items[..<i]) + tail pages[p].newer = answer.newerif p < pages.count - 1 { pages.removeSubrange((p + 1)...) } change = .all revision += 1return }var changed: Set<String> = []var appended: [ChatDrawn] = []for d in tail {iflet old = held[d.id] {if old != d { changed.insert(d.id) } } else { appended.append(d) } }for id in changed {iflet d = tail.first(where: { $0.id == id }), let bubble = d.item.bubble { replace(bubble) } }if !appended.isEmpty, !pages.isEmpty { pages[pages.count - 1].items += appended change = .appendedNewer revision += 1 } }/// Where an item stands in the window: its page and its place there.privatefunc position(of id: String) -> (Int, Int)? {for p in pages.indices { iflet i = pages[p].items.firstIndex(where: { $0.id == id }) { return (p, i) } }returnnil }/// Whether the newest span must be laid again from the core's answer: something held there is no longer named,/// the held ones stand in another order, or something new stands amid them rather than after them. nonisolated staticfunc laidAgain(held: [String], tail: [String]) -> Bool {let now = Set(tail)if held.contains(where: { !now.contains($0) }) { returntrue }let had = Set(held)if tail.filter({ had.contains($0) }) != held { returntrue }guardlet last = tail.lastIndex(where: { had.contains($0) }) else { returnfalse }return tail[..<last].contains { !had.contains($0) } }/// Items named for the table: a divider by what follows it.staticfunc drawn(_ items: [ChatThreadItem]) -> [ChatDrawn] {var out: [ChatDrawn] = [] out.reserveCapacity(items.count)var pending: [ChatThreadItem] = []for item in items {switch item {case .day, .unread: pending.append(item)case .event(let message, _, _, _, _):for p in pending { out.append(ChatDrawn(id: "\(prefix(p))\(message)", item: p)) } pending = [] out.append(ChatDrawn(id: "event:\(message)", item: item))case .bubble(let b):for p in pending { out.append(ChatDrawn(id: "\(prefix(p))\(b.message)", item: p)) } pending = [] out.append(ChatDrawn(id: b.message, item: item)) } }for (i, p) in pending.enumerated() { out.append(ChatDrawn(id: "\(prefix(p))end\(i)", item: p)) }return out }privatestaticfunc prefix(_ item: ChatThreadItem) -> String {ifcase .unread = item { return"unread@" }return"day@" }}#endif