From fec56edf437731bd353e8f5a79f285f16748887a Mon Sep 17 00:00:00 2001 From: jack Date: Sat, 28 Nov 2026 01:10:21 -1000 Subject: [PATCH] Clamp chat ScrollView offset against programmatic overscroll on iOS --- bitchat/Views/ContentView.swift | 55 ++---- bitchat/Views/MessageListView.swift | 285 +++++++++++++++++++--------- bitchatTests/ViewSmokeTests.swift | 108 +++++++++++ 3 files changed, 321 insertions(+), 127 deletions(-) diff --git a/bitchat/Views/ContentView.swift b/bitchat/Views/ContentView.swift index 4f9ebf34..af77d398 100644 --- a/bitchat/Views/ContentView.swift +++ b/bitchat/Views/ContentView.swift @@ -765,22 +765,24 @@ struct ContentView: View { publicMessageList .overlay(alignment: .top) { headerView(onBack: onBack, placeTitle: placeTitle) - .background(ChromeHeightReader(edge: .top)) + .onGeometryChange(for: CGFloat.self) { proxy in + proxy.size.height + } action: { height in + if abs(topChromeHeight - height) > 0.5 { + topChromeHeight = height + } + } } .overlay(alignment: .bottom) { if selectedPrivatePeerID == nil { composerView - .background(ChromeHeightReader(edge: .bottom)) - } - } - .onPreferenceChange(TopChromeHeightKey.self) { height in - if abs(topChromeHeight - height) > 0.5 { - topChromeHeight = height - } - } - .onPreferenceChange(BottomChromeHeightKey.self) { height in - if abs(bottomChromeHeight - height) > 0.5 { - bottomChromeHeight = height + .onGeometryChange(for: CGFloat.self) { proxy in + proxy.size.height + } action: { height in + if abs(bottomChromeHeight - height) > 0.5 { + bottomChromeHeight = height + } + } } } } else { @@ -959,32 +961,3 @@ struct ContentView: View { } } } - -private struct TopChromeHeightKey: PreferenceKey { - static let defaultValue: CGFloat = 0 - static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { - value = max(value, nextValue()) - } -} - -private struct BottomChromeHeightKey: PreferenceKey { - static let defaultValue: CGFloat = 0 - static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { - value = max(value, nextValue()) - } -} - -private struct ChromeHeightReader: View { - let edge: VerticalEdge - - var body: some View { - GeometryReader { proxy in - switch edge { - case .top: - Color.clear.preference(key: TopChromeHeightKey.self, value: proxy.size.height) - case .bottom: - Color.clear.preference(key: BottomChromeHeightKey.self, value: proxy.size.height) - } - } - } -} diff --git a/bitchat/Views/MessageListView.swift b/bitchat/Views/MessageListView.swift index d808aaf9..0b1e37d0 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -267,102 +267,107 @@ private struct MessageListContentView: View { ScrollViewReader { proxy in ScrollView { - if isEmptyPublic { - publicEmptyState( - fillHeight: max(0, emptyStateViewportHeight - topContentInset - bottomContentInset) - ) - } else { - VStack(alignment: .leading, spacing: 0) { - LazyVStack(alignment: .leading, spacing: 0) { - ForEach(messageItems) { item in - let message = item.message - MessageRowView( - message: message, - deliveryStatus: message.deliveryStatus, - privatePeer: privatePeer, - reactions: reactionSummary.reactionsByMessageID[message.id] ?? [], - isHighlighted: activeHighlightID == message.id, - imagePreviewURL: $imagePreviewURL, - showSidebar: $showSidebar, - onInsertMention: insertMention, - onReply: { target in - appEnvironmentModels?.composerDraftModel.setReplyTarget(target) - isTextFieldFocused.wrappedValue = true - }, - onReact: { emoji in - let payload = MessageInteractionCodec.encodeReaction( - emoji: emoji, - toMessageID: message.id - ) - conversationUIModel.sendMessage(payload) - }, - onTapQuote: { quotedSender, quotedSnippet in - jumpToQuotedMessage( - sender: quotedSender, - snippet: quotedSnippet, - beforeMessageID: message.id, - proxy: proxy - ) - } - ) - .equatable() - .onAppear { - // Callbacks lag a timeline switch: the new - // rows appear before the old ones disappear, - // each with its own render's view of which row - // was last. Only rows of the timeline the list - // has landed in may move its state, checked - // against live state rather than the render's. - guard isLandedRow(item.id) else { return } - if item.id == newestRowID(for: privatePeer) { - isAtBottom = true - unseenCount = 0 - if bottomRowID != item.id { - bottomRowID = item.id + Group { + if isEmptyPublic { + publicEmptyState( + fillHeight: max(0, emptyStateViewportHeight - topContentInset - bottomContentInset) + ) + } else { + VStack(alignment: .leading, spacing: 0) { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(messageItems) { item in + let message = item.message + MessageRowView( + message: message, + deliveryStatus: message.deliveryStatus, + privatePeer: privatePeer, + reactions: reactionSummary.reactionsByMessageID[message.id] ?? [], + isHighlighted: activeHighlightID == message.id, + imagePreviewURL: $imagePreviewURL, + showSidebar: $showSidebar, + onInsertMention: insertMention, + onReply: { target in + appEnvironmentModels?.composerDraftModel.setReplyTarget(target) + isTextFieldFocused.wrappedValue = true + }, + onReact: { emoji in + let payload = MessageInteractionCodec.encodeReaction( + emoji: emoji, + toMessageID: message.id + ) + conversationUIModel.sendMessage(payload) + }, + onTapQuote: { quotedSender, quotedSnippet in + jumpToQuotedMessage( + sender: quotedSender, + snippet: quotedSnippet, + beforeMessageID: message.id, + proxy: proxy + ) } - if bottomSettledContextKey != contextKey { - bottomSettledContextKey = contextKey + ) + .equatable() + .onAppear { + // Callbacks lag a timeline switch: the new + // rows appear before the old ones disappear, + // each with its own render's view of which row + // was last. Only rows of the timeline the list + // has landed in may move its state, checked + // against live state rather than the render's. + guard isLandedRow(item.id) else { return } + if item.id == newestRowID(for: privatePeer) { + isAtBottom = true + unseenCount = 0 + if bottomRowID != item.id { + bottomRowID = item.id + } + if bottomSettledContextKey != contextKey { + bottomSettledContextKey = contextKey + } + returnWindowToInitialSize(for: privatePeer, contextKey: contextKey, messages: messages) + } + if item.id == firstRowID, hasEarlierMessages { + expandWindow( + ifNeededFor: message, + allMessages: messages, + privatePeer: privatePeer, + proxy: proxy + ) } - returnWindowToInitialSize(for: privatePeer, contextKey: contextKey, messages: messages) } - if item.id == firstRowID, hasEarlierMessages { - expandWindow( - ifNeededFor: message, - allMessages: messages, - privatePeer: privatePeer, - proxy: proxy - ) - } - } - .onDisappear { - // A row of the landed timeline shares this - // closure's peer, so newestRowID is live here. - guard isLandedRow(item.id) else { return } - if item.id == newestRowID(for: privatePeer) || item.id == bottomRowID { - isAtBottom = false - bottomRowID = nil - // Leaving the bottom drops a follow-scroll - // still waiting on the throttle: it would - // yank the reader back down. - cancelFollowScroll() + .onDisappear { + // A row of the landed timeline shares this + // closure's peer, so newestRowID is live here. + guard isLandedRow(item.id) else { return } + if item.id == newestRowID(for: privatePeer) || item.id == bottomRowID { + isAtBottom = false + bottomRowID = nil + // Leaving the bottom drops a follow-scroll + // still waiting on the throttle: it would + // yank the reader back down. + cancelFollowScroll() + } } } } - } - .padding(.top, 8) - .padding(.bottom, 2) + .padding(.top, 8) + .padding(.bottom, 2) - // Only carried history on screen: the ambient layer (radar, - // sightings, live hints) stays visible below it instead of - // vanishing the moment echoes exist. - if privatePeer == nil, showsAmbientFooter(messageItems: messageItems) { - MeshEmptyStateView(compact: true) - .padding(.horizontal, 12) - .padding(.top, 20) - .padding(.bottom, 8) + // Only carried history on screen: the ambient layer (radar, + // sightings, live hints) stays visible below it instead of + // vanishing the moment echoes exist. + if privatePeer == nil, showsAmbientFooter(messageItems: messageItems) { + MeshEmptyStateView(compact: true) + .padding(.horizontal, 12) + .padding(.top, 20) + .padding(.bottom, 8) + } } } } + #if os(iOS) + .background(ScrollViewOffsetClamper()) + #endif } .scrollDismissesKeyboard(.interactively) .modifier(ScrollChromeInsetsModifier(top: topContentInset, bottom: bottomContentInset)) @@ -1105,6 +1110,114 @@ private struct ScrollChromeInsetsModifier: ViewModifier { } } +#if os(iOS) +/// Guards the SwiftUI-backed `UIScrollView` against programmatic overscroll +/// past `-adjustedContentInset.top` or beyond the bottom bound when +/// `.contentMargins` or keyboard safe-area insets change on a short timeline. +/// Never touches `scrollView.delegate` and never interferes while the user is +/// tracking, dragging, or decelerating. +private struct ScrollViewOffsetClamper: UIViewRepresentable { + func makeCoordinator() -> Coordinator { + Coordinator() + } + + func makeUIView(context: Context) -> ClamperAnchorView { + let view = ClamperAnchorView() + view.backgroundColor = .clear + view.isUserInteractionEnabled = false + view.onMoveToWindow = { [weak coordinator = context.coordinator] anchor in + coordinator?.attachIfNeeded(from: anchor) + } + return view + } + + func updateUIView(_ uiView: ClamperAnchorView, context: Context) { + context.coordinator.attachIfNeeded(from: uiView) + context.coordinator.clampIfNeeded() + } + + final class ClamperAnchorView: UIView { + var onMoveToWindow: ((UIView) -> Void)? + + override func didMoveToWindow() { + super.didMoveToWindow() + onMoveToWindow?(self) + } + } + + @MainActor + final class Coordinator { + private weak var scrollView: UIScrollView? + private var observations: [NSKeyValueObservation] = [] + private var isClamping = false + + deinit { + observations.removeAll() + } + + func attachIfNeeded(from anchor: UIView) { + var current = anchor.superview + var found: UIScrollView? + while let view = current { + if let sv = view as? UIScrollView { + found = sv + break + } + current = view.superview + } + guard let found, found !== scrollView else { return } + observations.removeAll() + scrollView = found + + observations.append(found.observe(\.contentOffset, options: [.new]) { [weak self] _, _ in + MainActor.assumeIsolated { + self?.clampIfNeeded() + } + }) + observations.append(found.observe(\.adjustedContentInset, options: [.new]) { [weak self] _, _ in + MainActor.assumeIsolated { + self?.clampIfNeeded() + self?.scheduleDeferredClamp() + } + }) + observations.append(found.observe(\.contentSize, options: [.new]) { [weak self] _, _ in + MainActor.assumeIsolated { + self?.clampIfNeeded() + self?.scheduleDeferredClamp() + } + }) + clampIfNeeded() + } + + func clampIfNeeded() { + guard !isClamping, + let sv = scrollView, + sv.window != nil, + sv.bounds.height > 0, + !sv.isTracking, + !sv.isDragging, + !sv.isDecelerating else { return } + + let minY = -sv.adjustedContentInset.top + let maxY = max(minY, sv.contentSize.height - sv.bounds.height + sv.adjustedContentInset.bottom) + let currentY = sv.contentOffset.y + let clampedY = min(max(currentY, minY), maxY) + guard abs(currentY - clampedY) > 0.5 else { return } + + isClamping = true + sv.contentOffset.y = clampedY + isClamping = false + } + + private func scheduleDeferredClamp() { + DispatchQueue.main.async { [weak self] in + self?.clampIfNeeded() + } + } + } +} +#endif + private extension ChannelID { var contextKey: String { switch self { diff --git a/bitchatTests/ViewSmokeTests.swift b/bitchatTests/ViewSmokeTests.swift index 9818ae01..b929802f 100644 --- a/bitchatTests/ViewSmokeTests.swift +++ b/bitchatTests/ViewSmokeTests.swift @@ -955,6 +955,114 @@ struct ViewSmokeTests { assertSingleTopInset(for: meshHost, label: "fresh #mesh after banner dismissal + 1 message + keyboard") window.isHidden = true } + + @Test("Liquid Glass short #mesh timeline stays anchored under header after voice note and chrome resize") + func liquidGlassMessageList_shortTimelineAfterVoiceNoteAndChromeChanges() async { + let (viewModel, _, _) = makeSmokeViewModel() + let featureModels = makeSmokeFeatureModels(for: viewModel) + + // Reproduce the exact #mesh state from field testing: + // 1 system header + 6 archived echoes, then append a taller voice-note-sized message. + var archived: [BitchatMessage] = [ + BitchatMessage( + id: "hdr-1", + sender: "system", + content: "Heard here earlier ยท last 6h", + timestamp: Date(timeIntervalSince1970: 1_700_000_000), + isRelay: false + ) + ] + for i in 0..<6 { + archived.append( + BitchatMessage( + id: "echo-\(i)", + sender: "anon6990", + content: "echo line \(i)", + timestamp: Date(timeIntervalSince1970: 1_700_000_001 + Double(i)), + isRelay: false + ) + ) + } + viewModel.conversations.appendBatch(archived, to: .mesh) + + let host = UIHostingController(rootView: installSmokeEnvironment( + ContentView(initialTab: .nearby).environment(\.appTheme, .liquidGlass), + featureModels: featureModels + )) + let windowScene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let window = windowScene.map { UIWindow(windowScene: $0) } ?? UIWindow(frame: CGRect(x: 0, y: 0, width: 393, height: 852)) + if let windowScene { + window.frame = windowScene.coordinateSpace.bounds + } + window.rootViewController = host + window.makeKeyAndVisible() + host.view.frame = window.bounds + host.view.setNeedsLayout() + host.view.layoutIfNeeded() + try? await Task.sleep(nanoseconds: 150_000_000) + + func findScrollView(in view: UIView) -> UIScrollView? { + if let sv = view as? UIScrollView { return sv } + for subview in view.subviews { + if let found = findScrollView(in: subview) { return found } + } + return nil + } + + func assertPinnedUnderHeader(_ label: String, maxExtraTop: CGFloat = 80) { + host.view.setNeedsLayout() + host.view.layoutIfNeeded() + guard let sv = findScrollView(in: host.view) else { + Issue.record("\(label): expected UIScrollView") + return + } + let contentZeroY = sv.convert(CGPoint.zero, to: window).y + let safeTop = host.view.safeAreaInsets.top + #expect( + contentZeroY >= safeTop + 40 && contentZeroY <= safeTop + maxExtraTop, + "\(label): First message drifted to \(contentZeroY) (safeTop=\(safeTop), offset=\(sv.contentOffset), adjInset=\(sv.adjustedContentInset), size=\(sv.contentSize))" + ) + #expect( + sv.contentOffset.y >= -sv.adjustedContentInset.top - 0.5, + "\(label): ScrollView overscrolled past top (offset=\(sv.contentOffset), adjInset=\(sv.adjustedContentInset))" + ) + } + + assertPinnedUnderHeader("initial-7-archived") + + // 1. Trigger a top banner (BT off -> on) like startup/foreground transitions + viewModel.bluetoothState = .poweredOff + try? await Task.sleep(nanoseconds: 100_000_000) + assertPinnedUnderHeader("bt-banner-shown", maxExtraTop: 120) + + viewModel.bluetoothState = .poweredOn + try? await Task.sleep(nanoseconds: 100_000_000) + assertPinnedUnderHeader("bt-banner-dismissed") + + // 2. Append a live message (removes showsAmbientFooter and triggers followToBottom) + viewModel.conversations.append( + BitchatMessage( + id: "live-1", + sender: "bob", + content: "Line 1\nLine 2\nLine 3\nLine 4", + timestamp: Date(timeIntervalSince1970: 1_700_000_100), + isRelay: false + ), + to: .mesh + ) + try? await Task.sleep(nanoseconds: 150_000_000) + assertPinnedUnderHeader("after-live-append") + + // 3. Simulate keyboard up then down (regression: previously overscrolled contentOffset.y to -215.67) + host.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 330, right: 0) + try? await Task.sleep(nanoseconds: 100_000_000) + assertPinnedUnderHeader("keyboard-up") + + host.additionalSafeAreaInsets = .zero + try? await Task.sleep(nanoseconds: 150_000_000) + assertPinnedUnderHeader("keyboard-down") + window.isHidden = true + } #endif @Test("Message list external URL allowlist permits only safe schemes")