// Cotton Chat's conversation list in the Warm look (warm.html "Chats"): the // large title and the round new-chat button, search, the filters, then rows // (photo or initials, name, last line, time, the unread dot or the pin) with // no lines between them. A row swipes for what the core offers (read or // unread and pin from the leading edge, mute and archive from the trailing) // and a hold offers the same. The list is the phone's recycled table: only // rows that changed are drawn again. #if os(iOS) import CottonKit import SwiftUI import UIKit /// One row as the list draws it, in the Warm look (warm.html "Chats"): the /// photo or initials, the name, one line of the last message, the time; /// under the time the unread dot (never a number) or the pin. No lines /// between rows: spacing separates them. struct ChatRowView: View { let row: ChatListRow @Environment(\.chatLook) private var look @Environment(\.dynamicTypeSize) private var typeSize var body: some View { HStack(alignment: .center, spacing: 13) { ChatAvatarView(avatar: row.picture, side: Warm.rowPicture * min(look.scale, 1.3)) if typeSize.isAccessibilitySize { // At the largest sizes the name keeps the row's width; the time and marks go under it. VStack(alignment: .leading, spacing: 2) { name.lineLimit(2) lastLine HStack(spacing: 8) { when marks } } .frame(maxWidth: .infinity, alignment: .leading) } else { VStack(alignment: .leading, spacing: 2) { name.lineLimit(1) lastLine } .frame(maxWidth: .infinity, alignment: .leading) VStack(alignment: .trailing, spacing: 7) { when marks } .layoutPriority(1) } } .padding(.horizontal, Warm.side) .padding(.vertical, 10) .contentShape(Rectangle()) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(verbatim: spoken)) .accessibilityIdentifier("chat-row-\(row.thread)") } private var name: some View { HStack(alignment: .firstTextBaseline, spacing: 6) { Text(verbatim: row.name) .font(look.font(17, hasUnread ? .bold : .semibold)) .foregroundStyle(look.colours.text) if row.muted { Image(systemName: "bell.slash") .font(.system(size: 12 * look.scale)) .foregroundStyle(look.colours.faint) } } } @ViewBuilder private var when: some View { if let when = row.when { Text(verbatim: when) .font(look.font(13)) .foregroundStyle(look.colours.faint) .lineLimit(1) } } /// The unread dot (never a number), else the pin. @ViewBuilder private var marks: some View { if hasUnread { Circle().fill(row.muted ? look.colours.faint : look.colours.accent).frame(width: 9, height: 9) } else if row.pinned { Image(systemName: "pin") .font(.system(size: 11 * look.scale)) .rotationEffect(.degrees(45)) .foregroundStyle(look.colours.faint) } } private var hasUnread: Bool { row.unread > 0 || row.markedUnread } @ViewBuilder private var lastLine: some View { if let typing = row.typing { Text(verbatim: typing).font(look.font(15)).foregroundStyle(look.colours.accent).lineLimit(1) } else if let draft = row.draft { Text(verbatim: draft).font(look.font(15)).foregroundStyle(look.colours.accent).lineLimit(1) } else if let gone = ChatCircleGone.shared.words(row.thread) { // No longer on Cotton (CIRCLE 2): the core's words in place of the last line. Text(verbatim: gone).font(look.font(15)).foregroundStyle(look.colours.dim).lineLimit(1) .accessibilityIdentifier("chat-row-gone-\(row.thread)") } else if let line = row.lastLine { HStack(alignment: .firstTextBaseline, spacing: 4) { if line.tick == .failed { Image(systemName: "exclamationmark.circle").font(.system(size: 13 * look.scale)).foregroundStyle(look.colours.danger) } if let mark = line.mark { Image(systemName: ChatMarks.symbol(mark)).font(.system(size: 13 * look.scale)).foregroundStyle(look.colours.dim) } Text(verbatim: composed(line)) .font(look.font(15)) .foregroundStyle(hasUnread ? look.colours.text : look.colours.dim) .lineLimit(1) // His own text on its way to WhatsApp says where it stands, in its bubble's words, until it has gone. if let state = line.state, !state.isEmpty { Text(verbatim: " · " + state) .font(look.font(15)) .foregroundStyle(line.tick == .failed ? look.colours.danger : look.colours.faint) .lineLimit(1) .accessibilityIdentifier("chat-row-state-\(row.thread)") } } } } /// "Dev: photos from Sunday" in a group, "You: on my way" for the person's own. private func composed(_ line: ChatLastLine) -> String { if let sender = line.sender { return "\(sender): \(line.text)" } return line.text } private var spoken: String { var parts = [row.name] if hasUnread { parts.append(ChatWords.line("list.a11y_unread")) } if row.pinned { parts.append(ChatWords.line("list.a11y_pinned")) } if row.muted { parts.append(ChatWords.line("list.a11y_muted")) } if let typing = row.typing { parts.append(typing) } else if let draft = row.draft { parts.append(draft) } else if let line = row.lastLine { parts.append(composed(line)); if let state = line.state { parts.append(state) } } if let when = row.when { parts.append(when) } return parts.joined(separator: ", ") } } /// The table behind the list: recycled cells, rows diffed by thread, the /// core's swipes, and the next page asked for before the end shows. /// The list runs to the screen's foot, under the floating pill, and its last /// row scrolls clear above the pill: the inset is the pill's top as laid out, /// at every text size (owner's iPhone, Comms build 19: the last chat was cut). final class ClearOfPill: UITableView { var pillTop: CGFloat = .infinity { didSet { if pillTop != oldValue { setNeedsLayout() } } } /// The core's words for a list with none of the person's chats (`words.empty`), drawn under the rows there are: /// under Cotton's own Downloads chat, or at the top of a list with nothing (the reviewer pass, 24 Nov 2026). var foot: (words: String, look: ChatLook)? { didSet { if foot?.words != oldValue?.words || foot?.look != oldValue?.look { footWidth = 0; setNeedsLayout() } } } private var footWidth: CGFloat = 0 private func layFoot() { let width = bounds.width guard width > 0, width != footWidth else { return } footWidth = width guard let foot else { tableFooterView = nil return } let look = foot.look let host = UIHostingController(rootView: Text(verbatim: foot.words) .font(look.font(16)) .foregroundStyle(look.colours.dim) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity) .padding(.top, numberOfRows(inSection: 0) == 0 ? 72 : 28) .padding(.horizontal, 32) .padding(.bottom, 16) ) host.view.backgroundColor = .clear // A footer hosted outside a view controller is not reached by VoiceOver: the view itself is the element. host.view.isAccessibilityElement = true host.view.accessibilityLabel = foot.words host.view.accessibilityTraits = .staticText host.view.accessibilityIdentifier = "chat-empty" let height = host.view.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height host.view.frame = CGRect(x: 0, y: 0, width: width, height: height) tableFooterView = host.view } override func layoutSubviews() { super.layoutSubviews() layFoot() guard window != nil else { return } let foot = convert(bounds, to: nil).maxY // Below the pill (or, with none, the home indicator): the room the rows stand clear of. let under = pillTop.isFinite ? max(0, foot - pillTop) + Warm.footRoom : safeAreaInsets.bottom let wanted = max(0, under - adjustedContentInset.bottom + contentInset.bottom) if abs(contentInset.bottom - wanted) > 0.5 { contentInset.bottom = wanted verticalScrollIndicatorInsets.bottom = wanted } } } struct ChatListTable: UIViewRepresentable { let model: ChatListModel /// The model's revision, read where the screen draws so a change redraws the table. let revision: Int let look: ChatLook let book: any ChatBook let open: (ChatListRow) -> Void let swiped: (ChatSwipe, ChatListRow) -> Void /// The core's empty words, drawn under the rows (nil while any of the person's chats stands). var empty: String? = nil @Environment(\.chatPillTop) private var pillTop func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIView(context: Context) -> UITableView { let table = ClearOfPill(frame: .zero, style: .plain) table.register(UITableViewCell.self, forCellReuseIdentifier: Coordinator.cell) table.backgroundColor = .clear table.separatorStyle = .none table.estimatedRowHeight = 72 table.rowHeight = UITableView.automaticDimension table.delegate = context.coordinator table.prefetchDataSource = context.coordinator table.pillTop = pillTop table.accessibilityIdentifier = "chat-list" context.coordinator.attach(table) return table } func updateUIView(_ table: UITableView, context: Context) { (table as? ClearOfPill)?.pillTop = pillTop let coordinator = context.coordinator let lookChanged = coordinator.parent.look != look coordinator.parent = self coordinator.apply(model.rows, reconfigureAll: lookChanged) (table as? ClearOfPill)?.foot = empty.map { ($0, look) } } @MainActor final class Coordinator: NSObject, UITableViewDelegate, UITableViewDataSourcePrefetching { static let cell = "chat-row" var parent: ChatListTable private var source: UITableViewDiffableDataSource? private var rows: [String: ChatListRow] = [:] init(_ parent: ChatListTable) { self.parent = parent } func attach(_ table: UITableView) { source = UITableViewDiffableDataSource(tableView: table) { [weak self] table, path, thread in let cell = table.dequeueReusableCell(withIdentifier: Self.cell, for: path) guard let self, let row = self.rows[thread] else { return cell } self.configure(cell, row) return cell } source?.defaultRowAnimation = .fade } private func configure(_ cell: UITableViewCell, _ row: ChatListRow) { cell.contentConfiguration = UIHostingConfiguration { ChatRowView(row: row) .environment(\.chatLook, parent.look) .environment(\.chatBook, parent.book) } .margins(.all, 0) .background(Color.clear) var ground = UIBackgroundConfiguration.clear() ground.backgroundColor = parent.look.colours.ui("ground") cell.backgroundConfiguration = ground cell.backgroundColor = parent.look.colours.ui("ground") var selected = UIBackgroundConfiguration.clear() selected.backgroundColor = parent.look.colours.ui("pill") cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = parent.look.colours.ui("pill") _ = selected } func apply(_ next: [ChatListRow], reconfigureAll: Bool) { guard let source else { return } let old = rows rows = Dictionary(next.map { ($0.thread, $0) }, uniquingKeysWith: { a, _ in a }) var snapshot = NSDiffableDataSourceSnapshot() snapshot.appendSections([0]) snapshot.appendItems(next.map(\.thread)) let changed = next.filter { reconfigureAll || (old[$0.thread].map { $0 != rows[$0.thread] } ?? false) }.map(\.thread) if !changed.isEmpty { snapshot.reconfigureItems(changed.filter { old[$0] != nil }) } source.apply(snapshot, animatingDifferences: !old.isEmpty && !reconfigureAll) } func tableView(_ table: UITableView, didSelectRowAt path: IndexPath) { table.deselectRow(at: path, animated: true) guard let thread = source?.itemIdentifier(for: path), let row = rows[thread] else { return } parent.open(row) } func tableView(_ table: UITableView, prefetchRowsAt paths: [IndexPath]) { let count = source?.snapshot().numberOfItems ?? 0 if paths.contains(where: { $0.row >= count - 20 }) { let model = parent.model Task { await model.loadMore() } } } func tableView(_ table: UITableView, leadingSwipeActionsConfigurationForRowAt path: IndexPath) -> UISwipeActionsConfiguration? { swipes(path, leading: true) } func tableView(_ table: UITableView, trailingSwipeActionsConfigurationForRowAt path: IndexPath) -> UISwipeActionsConfiguration? { swipes(path, leading: false) } private func swipes(_ path: IndexPath, leading: Bool) -> UISwipeActionsConfiguration? { guard let thread = source?.itemIdentifier(for: path), let row = rows[thread] else { return nil } let offered = leading ? row.leading : row.trailing let colours = parent.look.colours let actions = offered.enumerated().map { i, swipe in let action = UIContextualAction(style: swipe.act == "deleteChat" ? .destructive : .normal, title: swipe.label) { [weak self] _, _, done in self?.parent.swiped(swipe, row) // An act that asks first leaves the row where it is until answered. done(swipe.confirm == nil) } action.image = UIImage(systemName: Self.symbol(swipe.act)) action.backgroundColor = colours.ui(swipe.act == "deleteChat" ? "danger" : (i == 0 ? "accent" : "secondary")) return action } let configuration = UISwipeActionsConfiguration(actions: actions) configuration.performsFirstActionWithFullSwipe = true return configuration } /// A hold on a row: the core's menu (Mark as unread or Mark as read first, `hold`), else the swipes' acts. func tableView(_ table: UITableView, contextMenuConfigurationForRowAt path: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard let thread = source?.itemIdentifier(for: path), let row = rows[thread] else { return nil } let offered = row.hold.isEmpty ? row.leading + row.trailing : row.hold guard !offered.isEmpty else { return nil } return UIContextMenuConfiguration(identifier: thread as NSString, previewProvider: nil) { [weak self] _ in UIMenu(children: offered.map { swipe in UIAction(title: swipe.label, image: UIImage(systemName: Self.symbol(swipe.act))) { _ in self?.parent.swiped(swipe, row) } }) } } static func symbol(_ act: String) -> String { switch act { case "read": "envelope.open.fill" case "unread": "envelope.badge.fill" case "pinChat": "pin.fill" case "unpinChat": "pin.slash.fill" case "mute": "speaker.slash.fill" case "unmute": "speaker.wave.2.fill" case "archive": "archivebox.fill" case "unarchive": "tray.and.arrow.up.fill" case "deleteChat": "trash" default: "circle" } } } } /// Chats, in the Warm look (warm.html "Chats"): the large title with the /// round new-chat button, a quiet search pill, the filters (All, Unread, /// Groups, as the core answers them), the rows, and Archived at the foot /// when anything is archived. A conversation opens as its own page. struct ChatHome: View { /// The filter the screen opens on (`all`, `unread`, `groups`, `archived`). let filter: String @Environment(\.cottonCore) private var core @Environment(\.cottonChat) private var chat @Environment(\.chatLook) private var look @Environment(ToastCenter.self) private var toasts: ToastCenter? @Environment(BootModel.self) private var boot: BootModel? @State private var model: ChatListModel? @Environment(\.cottonSync) private var sync @State private var chosen: String? @State private var searchText = "" @State private var searching = false @State private var opened: ChatListRow? @State private var composing = false /// An act waiting on its question (Delete). @State private var asking: (swipe: ChatSwipe, row: ChatListRow)? @FocusState private var searchFocused: Bool private var book: any ChatBook { ChatBooks.make(core: core, chat: chat) } private var current: String { chosen ?? filter } var body: some View { VStack(alignment: .leading, spacing: 0) { top search // While the first pull runs: the one quiet line ("Loading your data… 42%") over the chats that have come. if let bringing = boot?.home?.bringing { LoadingLine(bringing: bringing, ink: look.colours.dim, font: look.font(13)) .padding(.horizontal, Warm.side) .padding(.vertical, 8) } else if !searching { // Where sync stands, in one quiet line (SyncSeenLine); a tap opens You on Sync. SyncSeenLine(font: look.font(13), color: look.colours.dim) { SyncSeenOpens.ask() } .padding(.horizontal, Warm.side) .frame(maxWidth: .infinity, alignment: .leading) } if !searching { filters } if let model { ZStack(alignment: .top) { // With none of the person's chats (Cotton's own Downloads chat aside) the core's words stand under // the rows there are, saying how to begin. let none = model.rows.allSatisfy { $0.thread == ChatListRow.downloads } ChatListTable(model: model, revision: model.revision, look: look, book: book, open: open, swiped: swiped, empty: none && boot?.home?.bringing == nil ? model.words?.empty : nil) .ignoresSafeArea(edges: .bottom) } } else { Spacer() } } .background(look.colours.ground.ignoresSafeArea()) .task { #if COTTON_DEV if ChatWarmSeed.asked, ChatWarmSeed.new { composing = true } #endif } .task(id: current) { let made = model?.filter == current ? model! : ChatListModel(book: book, filter: current) model = made await made.load() // The top chats' newest pictures and the last thirty days come onto the phone in the background, so a chat // opened next draws them at once (nothing in Low Data Mode). ChatAhead.shared.warm(book: book) // The faces' photos not on this phone, brought down in the background (ChatFaces.swift). if let core { ChatFaces.shared.bring(made.rows.compactMap(\.picture.photo), core: core) } } // A chat's message whose time comes leaves the list's line then: asked again 300 ms past the core's moment. .task(id: model?.erasesAt) { guard let at = model?.erasesAt else { return } try? await Task.sleep(for: .seconds(max(0, at.timeIntervalSinceNow) + 0.3)) guard !Task.isCancelled else { return } await model?.refresh() } // A change that came by the file's sync (a vote, an edit, a deletion from the Mac's link) is no chat engine // event: the list is asked again on it. .onChange(of: sync?.foreignRevision) { _, _ in Task { await model?.refresh() } } .task { for await change in book.changes() { switch change { case .row(let row): await model?.apply(row) case .arrived: await model?.refresh() ChatAhead.shared.warm(book: book) case .read: await model?.refresh() case .bubble: break } } } // A chat a notification asked for opens over the list, in this screen's thread. .onChange(of: ChatOpening.shared.asked, initial: true) { _, asked in guard asked != nil, let thread = ChatOpening.shared.take() else { return } Task { await openAsked(thread) } } .onChange(of: searchText) { _, text in Task { await model?.set(search: text) } } .fullScreenCover(item: $opened) { row in ChatThreadScreen(row: row, book: book) { opened = nil } .environment(\.chatLook, look) .receiptsOverCover() .chatCallRoom() } .fullScreenCover(isPresented: $composing) { ChatNewScreen { composing = false } .environment(\.chatLook, look) .receiptsOverCover() .chatCallRoom() } .lookAsk(isPresented: Binding(get: { asking != nil }, set: { if !$0 { asking = nil } }), style: LookPanelStyle(scrim: look.colours.text.opacity(0.28), ground: look.colours.ground, corner: 26), font: look.font(17, .semibold), message: asking?.swipe.confirm, messageColour: look.colours.text, choices: [ // The act asked about, taken as the question is drawn: the panel closes (asking = nil) before it // runs its choice, so reading `asking` then found nothing and Delete did nothing (FEEDBACK-4 B2). LookChoice(id: "delete", label: ChatWords.line("confirm.delete"), colour: look.colours.danger) { [asking] in if let asking { act(asking.swipe, asking.row) } }, LookChoice(id: "keep", label: ChatWords.line("confirm.keep"), colour: look.colours.text) {}, ]) } /// Whether the list stands on the archived place. private var showingArchived: Bool { current == "archived" } /// "Chats", large, with the round new-chat button. private var top: some View { HStack(alignment: .center) { Text(verbatim: showingArchived ? ChatWords.line("fan.archived") : (model?.words?.title ?? ChatWords.line("place.chats"))) .font(look.font(34, .bold)) .kerning(-0.7) .foregroundStyle(look.colours.text) .lineLimit(1) .minimumScaleFactor(0.6) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("chat-title") Spacer(minLength: 12) if current == "archived" { WarmRound(symbol: "xmark", label: ShellLines.line("chat", "stream.close"), id: "chat-archived-close") { chosen = "all" } } else { WarmRound(symbol: "square.and.pencil", label: ShellLines.line("chat", "stream.new"), id: "chat-compose", accent: true) { composing = true } } } .padding(.horizontal, Warm.side) .padding(.top, 6) } private var search: some View { HStack(spacing: 8) { Image(systemName: "magnifyingglass").font(.system(size: 14 * min(look.scale, 1.4), weight: .medium)) .foregroundStyle(look.colours.dim) TextField(text: $searchText) { Text(verbatim: model?.words?.search ?? "").foregroundStyle(look.colours.dim) } .font(look.font(15)) .foregroundStyle(look.colours.text) .focused($searchFocused) .submitLabel(.search) .autocorrectionDisabled() // Named by its own words, not its placeholder alone: VoiceOver says "Search, search field" with or without text in it. .accessibilityLabel(Text(verbatim: model?.words?.search ?? ShellLines.line("words", "search"))) .accessibilityIdentifier("chat-search") if searching { Button { searchText = "" searchFocused = false } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(look.colours.faint) } .accessibilityLabel(Text(verbatim: ShellLines.line("chat", "stream.close"))) } } .padding(.horizontal, 14) .frame(minHeight: 40) .background(Capsule().fill(look.colours.bar)) .padding(.horizontal, Warm.side) .padding(.top, 12) .onChange(of: searchFocused) { _, focused in withAnimation(.easeOut(duration: 0.15)) { searching = focused || !searchText.isEmpty } } } /// The filters: the one on is ink on the ground (All, Unread, Groups, the core's). private var filters: some View { ScrollView(.horizontal) { HStack(spacing: 8) { // People (Senders) is Cotton Post's now (COMMS WITHOUT MAIL): a core of before may still offer its chip, // which is not a filter of this list, so it is not drawn. ForEach((model?.filters ?? []).filter { $0.id != "people" }) { chip in let on = chip.id == current Button { chosen = chip.id } label: { HStack(alignment: .firstTextBaseline, spacing: 3) { Text(verbatim: chip.label).font(look.font(14, on ? .semibold : .regular)) if let count = chip.count { Text(verbatim: String(count)).font(look.font(11, .medium)).opacity(0.8) } } .foregroundStyle(on ? look.colours.ground : look.colours.dim) .padding(.horizontal, 13) .frame(minHeight: 34) .background(Capsule().fill(on ? look.colours.text : Color.clear)) .contentShape(Capsule()) } .buttonStyle(.plain) .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton) .accessibilityIdentifier("chat-filter-\(chip.id)") } if let archived = model?.archived, archived > 0, current != "archived" { Button { chosen = "archived" } label: { Text(verbatim: ChatWords.line("fan.archived")) .font(look.font(14)) .foregroundStyle(look.colours.faint) .padding(.horizontal, 13) .frame(minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityIdentifier("chat-filter-archived") } } .padding(.horizontal, Warm.side - 4) } .scrollIndicators(.hidden) .padding(.top, 10) .padding(.bottom, 4) } private func open(_ row: ChatListRow) { ChatThreadScreen.tapped = ContinuousClock.now var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { opened = row } } /// The asked chat's row, as the list holds it or as the core answers its /// read (the chat is about to be shown, which reads it). private func openAsked(_ thread: String) async { guard opened?.thread != thread else { return } var found = model?.row(thread) if found == nil { found = (try? await book.act(ChatActAsk(act: "read", thread: thread)))?.row } guard let row = found else { return } composing = false open(row) } private func swiped(_ swipe: ChatSwipe, _ row: ChatListRow) { if swipe.confirm != nil { asking = (swipe, row) return } act(swipe, row) } private func act(_ swipe: ChatSwipe, _ row: ChatListRow) { Task { if let said = await model?.act(swipe, on: row) { toasts?.show(said) } } } } /// A chat asked to open from outside the list: a notification's tap, a /// Reply's chat (`ChatNotifier`). Held until a list on screen takes it, so a /// tap that launched the app opens its chat once the list is drawn. @MainActor @Observable public final class ChatOpening { public static let shared = ChatOpening() /// The thread waiting to be opened. public private(set) var asked: String? public init() {} public func open(thread: String) { asked = thread } /// The thread, taken once: a second list on screen finds nothing. func take() -> String? { defer { asked = nil } return asked } } /// A round button of the Warm look: chip-grey, or the accent for the one main act. struct WarmRound: View { let symbol: String let label: String let id: String var accent = false let tap: () -> Void @Environment(\.chatLook) private var look var body: some View { Button(action: tap) { Image(systemName: symbol) .font(.system(size: 17 * min(look.scale, 1.3), weight: .medium)) .foregroundStyle(accent ? look.colours.onAccent : look.colours.text) .frame(width: Warm.round * min(look.scale, 1.3), height: Warm.round * min(look.scale, 1.3)) .background(Circle().fill(accent ? look.colours.accent : look.colours.bar)) .frame(minWidth: 44, minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: label)) .accessibilityIdentifier(id) } } /// The themes last answered, so a screen opened again draws in them at once. @MainActor enum ChatThemesStore { static var last: ChatThemesAnswer? } #endif