Cotton code
418 lines · 20.4 KB · SwiftRaw
// The thread's list: the phone's recycled table, turned upside down so the// newest message sits at the bottom and the thread stays pinned there as// the keyboard moves. Each row's height is measured once and kept (by the// item, its content and the width), so scrolling a long thread lays out// nothing it has laid out before; pages are asked for well before the// finger reaches the end of what is held, and a page arriving above or// below keeps the reader's place. A change draws only the bubbles it names.#if os(iOS)import SwiftUIimport UIKitstruct ChatThreadTable: UIViewRepresentable {    let model: ChatThreadModel    /// 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 taps: ChatBubbleTaps    /// The reader is at the newest message (nothing below the screen).    let atBottom: (Bool) -> Void    let reply: (ChatBubble) -> Void    let pressed: (ChatBubble, CGRect) -> Void    /// The sideways pull that shows the times, 0 … 1 (and back to 0 on letting go).    let times: (CGFloat) -> Void    /// Scrolls to the bottom when this changes.    let toBottom: Int    /// Where the floating header ends and the writing box begins, in the window's coordinates. What they cover of    /// the page is measured against the table's own frame, which runs under both and under the keyboard: a frame    /// SwiftUI reports for the page stops at the safe area, which the keyboard moves up with the box, so the room the    /// keyboard took (and, at rest, the home indicator's strip) was never counted.    var head: CGFloat = 0    var foot: CGFloat = 0    func makeCoordinator() -> Coordinator { Coordinator(self) }    func makeUIView(context: Context) -> UITableView {        let table = UITableView(frame: .zero, style: .plain)        table.transform = CGAffineTransform(scaleX: 1, y: -1)        table.register(UITableViewCell.self, forCellReuseIdentifier: Coordinator.cell)        table.backgroundColor = .clear        table.separatorStyle = .none        table.allowsSelection = false        table.estimatedRowHeight = 60        table.rowHeight = UITableView.automaticDimension        table.keyboardDismissMode = .interactive        // The page runs under the floating header and writing box; its insets are theirs (`head`, `foot`).        table.contentInsetAdjustmentBehavior = .never        table.delegate = context.coordinator        table.prefetchDataSource = context.coordinator        table.accessibilityIdentifier = "chat-thread"        context.coordinator.attach(table)        return table    }    func updateUIView(_ table: UITableView, context: Context) {        let coordinator = context.coordinator        let lookChanged = coordinator.parent.look != look        let bottomAsked = coordinator.parent.toBottom != toBottom        coordinator.parent = self        coordinator.cover(table)        coordinator.update(lookChanged: lookChanged)        if bottomAsked { coordinator.scrollToBottom(animated: true) }    }    @MainActor    final class Coordinator: NSObject, UITableViewDelegate, UITableViewDataSourcePrefetching, UIGestureRecognizerDelegate {        static let cell = "chat-item"        var parent: ChatThreadTable        private weak var table: UITableView?        private var source: UITableViewDiffableDataSource<Int, String>?        /// Items newest first, as the upside-down table holds them.        private var drawn: [String: ChatDrawn] = [:]        private var order: [String] = []        private var revision = -1        private var heights: [String: CGFloat] = [:]        private var resized: (any NSObjectProtocol)?        private func measureAgain(_ id: String) {            guard let source, drawn[id] != nil else { return }            heights[id] = nil            var snapshot = source.snapshot()            guard snapshot.indexOfItem(id) != nil else { return }            snapshot.reconfigureItems([id])            source.apply(snapshot, animatingDifferences: false)        }        private var width: CGFloat = 0        private var flashing: String?        private var wasAtBottom = true        private var swiping: (cell: UITableViewCell, bubble: ChatBubble, arrow: UIImageView)?        /// A pull to the left is showing the times.        private var pulling = false        init(_ parent: ChatThreadTable) { self.parent = parent }        func attach(_ table: UITableView) {            self.table = table            source = UITableViewDiffableDataSource(tableView: table) { [weak self] table, path, id in                let cell = table.dequeueReusableCell(withIdentifier: Self.cell, for: path)                guard let self, let drawn = self.drawn[id] else { return cell }                self.configure(cell, drawn)                return cell            }            source?.defaultRowAnimation = .fade            // A voice message's player grew or shrank in place (its failure words, its speed's own line at the            // largest text): its row is measured again, with no change to its bubble.            resized = NotificationCenter.default.addObserver(forName: ChatVoiceView.resized, object: nil, queue: .main) { [weak self] note in                guard let id = note.object as? String else { return }                MainActor.assumeIsolated { self?.measureAgain(id) }            }            let press = UILongPressGestureRecognizer(target: self, action: #selector(press(_:)))            press.minimumPressDuration = 0.32            table.addGestureRecognizer(press)            let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:)))            pan.delegate = self            table.addGestureRecognizer(pan)        }        private func configure(_ cell: UITableViewCell, _ d: ChatDrawn) {            let group = parent.model.header?.group ?? false            // A one-to-one chat's runs carry the person's own picture (a group's bubbles name their writer).            let picture = group ? nil : parent.model.header?.picture            let flash = flashing == d.id            let look = parent.look            let book = parent.book            let taps = parent.taps            cell.contentConfiguration = UIHostingConfiguration {                WarmItemView(item: d.item, group: group, picture: picture, flash: flash, taps: taps)                    .environment(\.chatLook, look)                    .environment(\.chatBook, book)            }            .margins(.all, 0)            cell.backgroundConfiguration = .clear()            cell.contentView.transform = CGAffineTransform(scaleX: 1, y: -1)        }        // MARK: changes        func update(lookChanged: Bool) {            guard let table, let source else { return }            if lookChanged { heights.removeAll() }            let model = parent.model            guard model.revision != revision || lookChanged else { return }            let change = revision < 0 ? ChatThreadModel.Change.all : model.change            revision = model.revision            let items = model.items            let old = drawn            drawn = Dictionary(items.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })            order = items.reversed().map(\.id)            var snapshot = NSDiffableDataSourceSnapshot<Int, String>()            snapshot.appendSections([0])            snapshot.appendItems(order)            var changed = order.filter { id in old[id].map { $0 != drawn[id] } ?? false }            if lookChanged { changed = order.filter { old[$0] != nil } }            for id in changed { heights[id] = nil }            if !changed.isEmpty { snapshot.reconfigureItems(changed) }            let atBottom = table.contentOffset.y <= -table.adjustedContentInset.top + 4            let anchor = atBottom ? nil : self.anchor(in: table)            let animate = change == .appendedNewer && atBottom && !old.isEmpty && model.atNewest            source.apply(snapshot, animatingDifferences: animate) { [weak self] in                guard let self, let table = self.table else { return }                if let anchor { self.restore(anchor, in: table) }            }            if let anchor, !animate { restore(anchor, in: table) }            if change == .all, let focus = model.focus { scroll(to: focus) }            // Opened: what it shows first, and both sides of it.            if change == .all {                Task { @MainActor [weak self] in                    guard let self, let table = self.table else { return }                    self.fetchAhead(table.indexPathsForVisibleRows?.map(\.row) ?? Array(0..<min(12, self.order.count)))                }            }        }        /// The first row on screen and where it stood, to hold the reader's place.        private func anchor(in table: UITableView) -> (id: String, offset: CGFloat)? {            guard let path = table.indexPathsForVisibleRows?.first, path.row < order.count else { return nil }            let rect = table.rectForRow(at: path)            return (order[path.row], rect.minY - table.contentOffset.y)        }        private func restore(_ anchor: (id: String, offset: CGFloat), in table: UITableView) {            guard let row = order.firstIndex(of: anchor.id) else { return }            table.layoutIfNeeded()            let rect = table.rectForRow(at: IndexPath(row: row, section: 0))            let y = rect.minY - anchor.offset            if abs(table.contentOffset.y - y) > 0.5 { table.contentOffset.y = y }        }        /// The insets the header and the writing box ask, from the table's frame in the window (asked again once the        /// table stands in its window and is laid out, if it is not yet). A page resting on its newest message keeps it        /// just above the writing box as the box moves: the keyboard rising or changing height, the box growing.        func cover(_ table: UITableView, tries: Int = 0) {            guard table.window != nil, table.bounds.height > 0 else {                guard tries < 20 else { return }                Task { @MainActor [weak self, weak table] in                    guard let self, let table else { return }                    self.cover(table, tries: tries + 1)                }                return            }            let seen = table.convert(table.bounds, to: nil)            let head = parent.head > 0 ? max(0, parent.head - seen.minY) + 6 : 0            let foot = parent.foot > 0 ? max(0, seen.maxY - parent.foot) + 6 : 0            // Upside down: the page's visual foot is the table's top.            let inset = UIEdgeInsets(top: foot, left: 0, bottom: head, right: 0)            guard table.contentInset != inset else { return }            let wasAtFoot = table.contentOffset.y <= -table.contentInset.top + 4            table.contentInset = inset            table.verticalScrollIndicatorInsets = inset            guard wasAtFoot else { return }            // Moved with the keyboard's own curve, so the newest message rides up with the box rather than ahead of it.            UIView.animate(withDuration: 0.25, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction, UIView.AnimationOptions(rawValue: 7 << 16)]) {                table.contentOffset.y = -inset.top            }        }        func scrollToBottom(animated: Bool) {            guard let table, !order.isEmpty else { return }            table.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: animated)        }        private func scroll(to message: String) {            guard let table, let row = order.firstIndex(of: message) else { return }            table.layoutIfNeeded()            table.scrollToRow(at: IndexPath(row: row, section: 0), at: .middle, animated: false)            flashing = message            if let source {                var snapshot = source.snapshot()                snapshot.reconfigureItems([message])                source.apply(snapshot, animatingDifferences: false)            }            let model = parent.model            Task { @MainActor [weak self] in                try? await Task.sleep(for: .seconds(1.2))                guard let self, let source = self.source, self.flashing == message else { return }                self.flashing = nil                var snapshot = source.snapshot()                if snapshot.itemIdentifiers.contains(message) {                    snapshot.reconfigureItems([message])                    await source.apply(snapshot, animatingDifferences: false)                }                model.flashed()            }        }        // MARK: heights        func tableView(_ table: UITableView, heightForRowAt path: IndexPath) -> CGFloat {            noteWidth(table)            guard path.row < order.count, let h = heights[order[path.row]] else { return UITableView.automaticDimension }            return h        }        func tableView(_ table: UITableView, estimatedHeightForRowAt path: IndexPath) -> CGFloat {            guard path.row < order.count else { return 60 }            let id = order[path.row]            if let h = heights[id] { return h }            return Self.estimate(drawn[id]?.item, scale: parent.look.scale)        }        func tableView(_ table: UITableView, willDisplay cell: UITableViewCell, forRowAt path: IndexPath) {            guard path.row < order.count else { return }            let h = cell.bounds.height            if h > 1 { heights[order[path.row]] = h }        }        private func noteWidth(_ table: UITableView) {            if abs(table.bounds.width - width) > 0.5 {                width = table.bounds.width                heights.removeAll()            }        }        static func estimate(_ item: ChatThreadItem?, scale: Double) -> CGFloat {            guard let item else { return 60 }            switch item {            case .day: return 60 * scale            case .unread, .event: return 40 * scale            case .bubble(let b):                var h: CGFloat = 40                let chars = b.text?.count ?? 0                h += CGFloat(chars / 32) * 21                if b.reply != nil { h += 46 }                if b.link != nil { h += 80 }                switch b.kind {                case .photo, .video: h += 240                case .album: h += 248                case .voice, .audio, .file: h += 30                default: break                }                if let words = b.media.first?.transcript { h += CGFloat(words.count / 28 + 1) * 20 }                if !b.reactions.isEmpty { h += 22 }                if b.face { h += 22 }                return h * scale            }        }        // MARK: pages ahead of the finger        func tableView(_ table: UITableView, prefetchRowsAt paths: [IndexPath]) {            ask(near: paths.map(\.row))        }        func scrollViewDidScroll(_ scroll: UIScrollView) {            guard let table = scroll as? UITableView else { return }            let atBottom = table.contentOffset.y <= -table.adjustedContentInset.top + 40            if atBottom != wasAtBottom {                wasAtBottom = atBottom                parent.atBottom(atBottom && parent.model.atNewest)            }            if let rows = table.indexPathsForVisibleRows?.map(\.row) {                ask(near: rows)                fetchAhead(rows)            }        }        /// The pictures on screen and on each side of them come onto the phone (`chat.ahead`), so the reader never        /// meets a picture still on its way; asked once the scroll settles, by the messages it shows.        private func fetchAhead(_ rows: [Int]) {            // A grid to WhatsApp names each tile's own message (FEEDBACK-4 B3): those landed are asked too; one still            // waiting is the phone's own file already.            let shown = rows.sorted().flatMap { row -> [String] in                guard row < order.count, let bubble = drawn[order[row]]?.item.bubble else { return [] }                let tiles = bubble.media.compactMap(\.message).filter { !$0.hasPrefix(ChatThreadModel.pending) && $0 != bubble.message }                return [bubble.message] + tiles            }            ChatAhead.shared.scrolled(thread: parent.model.thread, messages: shown, book: parent.book)        }        private func ask(near rows: [Int]) {            guard let low = rows.min(), let high = rows.max() else { return }            let model = parent.model            // Older lies at the table's far end; newer at its start.            if high >= order.count - 45, model.older != nil { Task { await model.loadOlder() } }            if low <= 30, model.newer != nil { Task { await model.loadNewer() } }        }        // MARK: long press and swipe to reply        @objc private func press(_ g: UILongPressGestureRecognizer) {            guard g.state == .began, let table = g.view as? UITableView else { return }            let point = g.location(in: table)            guard let path = table.indexPathForRow(at: point), path.row < order.count,                  let bubble = drawn[order[path.row]]?.item.bubble, let cell = table.cellForRow(at: path) else { return }            UIImpactFeedbackGenerator(style: .medium).impactOccurred()            parent.pressed(bubble, cell.convert(cell.bounds, to: nil))        }        /// A horizontal pull begins the gesture: to the left anywhere (the        /// times), to the right on a message that can be answered (reply).        func gestureRecognizerShouldBegin(_ g: UIGestureRecognizer) -> Bool {            guard let pan = g as? UIPanGestureRecognizer, let table else { return true }            let v = pan.velocity(in: table)            guard abs(v.x) > abs(v.y) * 2 else { return false }            if v.x < 0 { return true }            let point = pan.location(in: table)            guard let path = table.indexPathForRow(at: point), path.row < order.count,                  let bubble = drawn[order[path.row]]?.item.bubble else { return false }            return bubble.actions.contains("reply")        }        func gestureRecognizer(_ g: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { false }        /// Pulling left shows the times, eased back on letting go; a swipe        /// right on a message moves it along and, past 60 points, replies.        @objc private func pan(_ g: UIPanGestureRecognizer) {            guard let table else { return }            let x = g.translation(in: table).x            switch g.state {            case .began:                if g.velocity(in: table).x < 0 {                    pulling = true                    return                }                let point = g.location(in: table)                guard let path = table.indexPathForRow(at: point), path.row < order.count,                      let bubble = drawn[order[path.row]]?.item.bubble, let cell = table.cellForRow(at: path) else { return }                let arrow = UIImageView(image: UIImage(systemName: "arrowshape.turn.up.left"))                arrow.tintColor = parent.look.colours.ui("accent")                arrow.frame = CGRect(x: 12, y: cell.bounds.midY - 12, width: 24, height: 24)                arrow.alpha = 0                arrow.transform = CGAffineTransform(scaleX: 1, y: -1)                cell.addSubview(arrow)                swiping = (cell, bubble, arrow)            case .changed:                if pulling {                    parent.times(min(1, max(0, -x / WarmTimes.width)))                    return                }                guard let swiping else { return }                let pulled = min(90, max(0, x) * 0.7)                swiping.cell.contentView.transform = CGAffineTransform(translationX: pulled, y: 0).scaledBy(x: 1, y: -1)                swiping.arrow.alpha = min(1, pulled / 60)            default:                if pulling {                    pulling = false                    let times = parent.times                    withAnimation(.spring(duration: 0.3, bounce: 0)) { times(0) }                    return                }                guard let swiping else { return }                let went = x * 0.7 >= 60                UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0) {                    swiping.cell.contentView.transform = CGAffineTransform(scaleX: 1, y: -1)                    swiping.arrow.alpha = 0                } completion: { _ in swiping.arrow.removeFromSuperview() }                if went {                    UIImpactFeedbackGenerator(style: .light).impactOccurred()                    parent.reply(swiping.bubble)                }                self.swiping = nil            }        }    }}#endif