From becdeb330b4efca6906ae561e6ebcffc2a94722f Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:23:38 -1000 Subject: [PATCH] fix(ui): fix double top inset in Liquid Glass chat with overlay chrome and content margins (#1917) * fix(ui): replace nested safeAreaInset with overlay chrome and scroll content margins * fix(ui): keep single-level safeAreaInset on iOS 16/macOS 13 for programmatic scroll targets * fix(ui): reset ScrollView identity per timeline context to avoid stale contentOffset * fix(test): share isolated LocationChannelManager between ChatViewModel and smoke feature models --------- Co-authored-by: jack --- bitchat/Views/ContentView.swift | 104 +++++++++++++++++++--- bitchat/Views/MessageListView.swift | 128 ++++++++++++++++++---------- bitchatTests/ViewSmokeTests.swift | 92 ++++++++++++++------ 3 files changed, 239 insertions(+), 85 deletions(-) diff --git a/bitchat/Views/ContentView.swift b/bitchat/Views/ContentView.swift index 3cfc9242..b19fd9d2 100644 --- a/bitchat/Views/ContentView.swift +++ b/bitchat/Views/ContentView.swift @@ -183,6 +183,8 @@ struct ContentView: View { @ScaledMetric(relativeTo: .subheadline) private var headerPeerCountFontSize: CGFloat = 12 @State private var windowCountPublic: Int = TransportConfig.uiWindowInitialCountPublic @State private var windowCountPrivate: [PeerID: Int] = [:] + @State private var topChromeHeight: CGFloat = 0 + @State private var bottomChromeHeight: CGFloat = 0 @ThemedPalette private var palette @@ -466,21 +468,48 @@ struct ContentView: View { } } - /// Matrix: classic opaque bars with dividers. Glass: full-bleed message - /// list scrolling underneath floating chrome panels (safe-area insets), - /// so the translucency gains usable space instead of losing it. + /// Matrix: classic opaque bars with dividers. Glass on iOS 17+/macOS 14+: + /// full-bleed message list scrolling underneath floating chrome overlays + /// with explicit scroll content margins, avoiding SwiftUI `.safeAreaInset` + /// double top-insetting on iOS while preserving full-bleed translucency. + /// Older OS versions without `.contentMargins` keep single-level + /// `.safeAreaInset` so programmatic `scrollTo` targets still clear the bar. @ViewBuilder private var mainContent: some View { if usesGlassLayout { - publicMessageList - .safeAreaInset(edge: .top, spacing: 0) { - headerView - } - .safeAreaInset(edge: .bottom, spacing: 0) { - if selectedPrivatePeerID == nil { - composerView + if #available(iOS 17.0, macOS 14.0, *) { + publicMessageList + .overlay(alignment: .top) { + headerView + .background(ChromeHeightReader(edge: .top)) } - } + .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 + } + } + } else { + publicMessageList + .safeAreaInset(edge: .top, spacing: 0) { + headerView + } + .safeAreaInset(edge: .bottom, spacing: 0) { + if selectedPrivatePeerID == nil { + composerView + } + } + } } else { VStack(spacing: 0) { headerView @@ -522,6 +551,8 @@ struct ContentView: View { ) { ConnectivityStatusBanner(issue: issue) } + + NearbyNotesStripView() } // Hosted here rather than on the logo Text so the pending dialog // survives whatever happens to the header chrome. @@ -543,6 +574,24 @@ struct ContentView: View { } } + private var usesOverlayChrome: Bool { + guard usesGlassLayout else { return false } + if #available(iOS 17.0, macOS 14.0, *) { + return true + } + return false + } + + private var glassTopContentInset: CGFloat { + guard usesOverlayChrome else { return 0 } + return topChromeHeight > 0 ? topChromeHeight : headerHeight + 4 + } + + private var glassBottomContentInset: CGFloat { + guard usesOverlayChrome, selectedPrivatePeerID == nil else { return 0 } + return bottomChromeHeight > 0 ? bottomChromeHeight : 58 + } + private var publicMessageList: some View { PublicMessageListView( isAtBottom: $isAtBottomPublic, @@ -551,7 +600,9 @@ struct ContentView: View { imagePreviewURL: $imagePreviewURL, windowCountPublic: $windowCountPublic, showSidebar: $showSidebar, - isTextFieldFocused: $isTextFieldFocused + isTextFieldFocused: $isTextFieldFocused, + topContentInset: glassTopContentInset, + bottomContentInset: glassBottomContentInset ) } @@ -577,3 +628,32 @@ 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 948e2460..60dda0fb 100644 --- a/bitchat/Views/MessageListView.swift +++ b/bitchat/Views/MessageListView.swift @@ -48,7 +48,6 @@ struct PublicMessageListView: View { @EnvironmentObject private var publicChatModel: PublicChatModel @EnvironmentObject private var locationChannelsModel: LocationChannelsModel @EnvironmentObject private var appChromeModel: AppChromeModel - @ObservedObject private var nearbyNotes = NearbyNotesCounter.shared @Binding var isAtBottom: Bool @Binding var selectedMessageSender: String? @@ -57,12 +56,12 @@ struct PublicMessageListView: View { @Binding var windowCountPublic: Int @Binding var showSidebar: Bool var isTextFieldFocused: FocusState.Binding + var topContentInset: CGFloat = 0 + var bottomContentInset: CGFloat = 0 /// Whether this instance holds the nearby-notes counter active (mesh /// public timeline only); balanced against activate/deactivate. @State private var holdsNotesCounter = false - @Environment(\.appTheme) private var theme - @ThemedPalette private var palette var body: some View { MessageListContentView( @@ -71,6 +70,8 @@ struct PublicMessageListView: View { contextKey: publicChatModel.activeChannel.contextKey, selectedPublicChannel: locationChannelsModel.selectedChannel, bluetoothCanScan: bluetoothCanScan, + topContentInset: topContentInset, + bottomContentInset: bottomContentInset, liveMessages: { _ in publicChatModel.messages }, liveContextKey: { _ in publicChatModel.activeChannel.contextKey }, liveWindowCount: { _ in windowCountPublic }, @@ -82,17 +83,6 @@ struct PublicMessageListView: View { showSidebar: $showSidebar, isTextFieldFocused: isTextFieldFocused ) - // Keep the scroll view as the direct body under ContentView's - // safeAreaInsets (no wrapping VStack): notesHereStrip joins the top - // safe area instead so messages never receive double top insets. - .safeAreaInset(edge: .top, spacing: 0) { - // Notes pinned to this place stay visible while chatting — a - // conversation starting must not hide what's left here. - if case .mesh = locationChannelsModel.selectedChannel, - nearbyNotes.noteCount > 0 { - notesHereStrip - } - } .onAppear { updateNotesCounterHold() } .onDisappear { releaseNotesCounterHold() } .onChange(of: locationChannelsModel.selectedChannel) { _ in updateNotesCounterHold() } @@ -107,38 +97,6 @@ struct PublicMessageListView: View { } } - /// Tappable strip above the mesh timeline while notes are pinned at this - /// place: opens the notices sheet on the geo tab. - private var notesHereStrip: some View { - let text: String = nearbyNotes.noteCount == 1 - ? String(localized: "content.empty.notes_one", comment: "Hint when exactly one note was left at this place") - : String( - format: String(localized: "content.empty.notes_many", comment: "Hint counting notes left at this place"), - locale: .current, - nearbyNotes.noteCount - ) - - return Button { - appChromeModel.presentNotices(geoTab: true) - } label: { - HStack(spacing: 6) { - Text(verbatim: "📍 \(text)") - .bitchatFont(size: 12) - .foregroundColor(palette.primary) - Spacer() - Image(systemName: "chevron.right") - .font(.bitchatSystem(size: 10)) - .foregroundColor(palette.secondary) - } - .padding(.horizontal, 12) - .padding(.vertical, 7) - .background(palette.secondary.opacity(0.08)) - .background(theme.usesGlassChrome ? AnyShapeStyle(.ultraThinMaterial) : AnyShapeStyle(palette.background)) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - } - /// The nearby-notes counter is held whenever the mesh public timeline is /// showing — the strip needs a live count before it can decide to exist. /// Holding is not subscribing: nothing hits the relays until an explicit @@ -161,6 +119,51 @@ struct PublicMessageListView: View { } } +/// Tappable strip beneath the header while notes are pinned at this place +/// on the mesh channel: opens the notices sheet on the geo tab. Hosted +/// inside `ContentView.headerView` rather than a nested `.safeAreaInset` +/// so the header chrome contributes a single measured top inset. +struct NearbyNotesStripView: View { + @EnvironmentObject private var locationChannelsModel: LocationChannelsModel + @EnvironmentObject private var appChromeModel: AppChromeModel + @ObservedObject private var nearbyNotes = NearbyNotesCounter.shared + @Environment(\.appTheme) private var theme + @ThemedPalette private var palette + + var body: some View { + if case .mesh = locationChannelsModel.selectedChannel, + nearbyNotes.noteCount > 0 { + let text: String = nearbyNotes.noteCount == 1 + ? String(localized: "content.empty.notes_one", comment: "Hint when exactly one note was left at this place") + : String( + format: String(localized: "content.empty.notes_many", comment: "Hint counting notes left at this place"), + locale: .current, + nearbyNotes.noteCount + ) + + Button { + appChromeModel.presentNotices(geoTab: true) + } label: { + HStack(spacing: 6) { + Text(verbatim: "📍 \(text)") + .bitchatFont(size: 12) + .foregroundColor(palette.primary) + Spacer() + Image(systemName: "chevron.right") + .font(.bitchatSystem(size: 10)) + .foregroundColor(palette.secondary) + } + .padding(.horizontal, 12) + .padding(.vertical, 7) + .background(palette.secondary.opacity(0.08)) + .background(theme.usesGlassChrome ? AnyShapeStyle(.ultraThinMaterial) : AnyShapeStyle(palette.background)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + } +} + /// Private DM timeline host: observes only `PrivateInboxModel` so public /// channel messages, location updates, and nearby-note counts never invalidate /// an open direct-message timeline. @@ -183,6 +186,8 @@ struct PrivateMessageListView: View { contextKey: Self.contextKey(for: privatePeer), selectedPublicChannel: nil, bluetoothCanScan: false, + topContentInset: 0, + bottomContentInset: 0, liveMessages: { peer in privateInboxModel.messages(for: peer) }, liveContextKey: { peer in Self.contextKey(for: peer) }, liveWindowCount: { peer in @@ -224,6 +229,8 @@ private struct MessageListContentView: View { let contextKey: String let selectedPublicChannel: ChannelID? let bluetoothCanScan: Bool + let topContentInset: CGFloat + let bottomContentInset: CGFloat let liveMessages: (PeerID?) -> [BitchatMessage] let liveContextKey: (PeerID?) -> String let liveWindowCount: (PeerID?) -> Int @@ -298,7 +305,9 @@ private struct MessageListContentView: View { ScrollViewReader { proxy in ScrollView { if isEmptyPublic { - publicEmptyState(fillHeight: emptyStateViewportHeight) + publicEmptyState( + fillHeight: max(0, emptyStateViewportHeight - topContentInset - bottomContentInset) + ) } else { VStack(alignment: .leading, spacing: 0) { LazyVStack(alignment: .leading, spacing: 0) { @@ -370,6 +379,7 @@ private struct MessageListContentView: View { } } } + .modifier(ScrollChromeInsetsModifier(top: topContentInset, bottom: bottomContentInset)) .background { if isEmptyPublic { GeometryReader { geometry in @@ -390,6 +400,7 @@ private struct MessageListContentView: View { .overlay(alignment: .bottomTrailing) { if !isAtBottom && !messageItems.isEmpty { jumpToLatestPill(proxy: proxy) + .padding(.bottom, bottomContentInset) } } .onOpenURL(perform: handleOpenURL) @@ -411,6 +422,7 @@ private struct MessageListContentView: View { // mark the row callbacks are checked against) before any row // reports in. Expansion waits until the scroll below has // brought the newest row on screen. + bottomRowID = nil bottomSettledContextKey = nil scrollToBottom(on: proxy, privatePeer: privatePeer) } @@ -478,6 +490,10 @@ private struct MessageListContentView: View { cancelFollowScroll() } } + // Reset UIScrollView state when switching channels or DMs so a deep + // scroll offset from a populated room never carries over into a + // shorter or empty timeline on iOS. + .id(contextKey) .environment(\.openURL, OpenURLAction { url in guard MessageListExternalURLPolicy.isAllowed(url) else { return .discarded @@ -962,6 +978,24 @@ private struct MessageRowView: View, Equatable { } } +private struct ScrollChromeInsetsModifier: ViewModifier { + let top: CGFloat + let bottom: CGFloat + + @ViewBuilder + func body(content: Content) -> some View { + if #available(iOS 17.0, macOS 14.0, *) { + content + .contentMargins(.top, top, for: .scrollContent) + .contentMargins(.bottom, bottom, for: .scrollContent) + .contentMargins(.top, top, for: .scrollIndicators) + .contentMargins(.bottom, bottom, for: .scrollIndicators) + } else { + content + } + } +} + private extension ChannelID { var contextKey: String { switch self { diff --git a/bitchatTests/ViewSmokeTests.swift b/bitchatTests/ViewSmokeTests.swift index 5b0e9e6f..e3d9a850 100644 --- a/bitchatTests/ViewSmokeTests.swift +++ b/bitchatTests/ViewSmokeTests.swift @@ -24,7 +24,8 @@ private func makeSmokeViewModel() -> (viewModel: ChatViewModel, transport: MockT keychain: keychain, idBridge: idBridge, identityManager: identityManager, - transport: transport + transport: transport, + locationManager: makeSmokeLocationManager() ) return (viewModel, transport, identityManager) @@ -73,10 +74,9 @@ private func makeSmokeLocationManager() -> LocationChannelManager { @MainActor private func makeSmokeFeatureModels(for viewModel: ChatViewModel) -> SmokeFeatureModels { - let locationManager = makeSmokeLocationManager() let conversations = viewModel.conversations let publicChatModel = PublicChatModel(conversations: conversations) - let locationChannelsModel = LocationChannelsModel(manager: locationManager) + let locationChannelsModel = LocationChannelsModel(manager: viewModel.locationManager) let privateInboxModel = PrivateInboxModel(conversations: conversations) let appChromeModel = AppChromeModel( chatViewModel: viewModel, @@ -837,7 +837,14 @@ struct ViewSmokeTests { featureModels: featureModels ) let host = UIHostingController(rootView: rootView) - let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 393, height: 852)) + let windowScene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first + let window: UIWindow + if let windowScene { + window = UIWindow(windowScene: windowScene) + window.frame = windowScene.coordinateSpace.bounds + } else { + window = UIWindow(frame: CGRect(x: 0, y: 0, width: 393, height: 852)) + } window.rootViewController = host window.makeKeyAndVisible() host.view.frame = window.bounds @@ -852,6 +859,9 @@ struct ViewSmokeTests { host.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 330, right: 0) host.view.setNeedsLayout() host.view.layoutIfNeeded() + _ = await TestHelpers.waitUntil { + featureModels.publicChatModel.activeChannel == .location(channel) + } try? await Task.sleep(nanoseconds: 100_000_000) // Now deliver two system messages (matching the Tor restart screenshot). @@ -873,10 +883,13 @@ struct ViewSmokeTests { try? await Task.sleep(nanoseconds: 80_000_000) viewModel.conversations.append(second, to: .geohash("ez")) // Let followToBottom + 50ms retry settle. - try? await Task.sleep(nanoseconds: 120_000_000) + try? await Task.sleep(nanoseconds: 150_000_000) host.view.setNeedsLayout() host.view.layoutIfNeeded() + #expect(featureModels.publicChatModel.activeChannel == .location(channel)) + #expect(featureModels.publicChatModel.messages.count == 2) + func findScrollView(in view: UIView) -> UIScrollView? { if let sv = view as? UIScrollView { return sv } for subview in view.subviews { @@ -885,34 +898,61 @@ struct ViewSmokeTests { return nil } - let scrollView = findScrollView(in: host.view) - #expect(scrollView != nil) - if let scrollView { + func assertSingleTopInset(for hostController: UIHostingController, label: String) { + let scrollView = findScrollView(in: hostController.view) + #expect(scrollView != nil, "\(label): expected UIScrollView") + guard let scrollView else { return } + let frameTopInWindow = scrollView.superview?.convert(scrollView.frame.origin, to: window).y ?? scrollView.frame.origin.y let contentZeroInWindow = scrollView.convert(CGPoint.zero, to: window).y - let topInset = scrollView.adjustedContentInset.top - let expectedMaxTop = host.view.safeAreaInsets.top + 80 + let hostSafeTop = hostController.view.safeAreaInsets.top + let expectedMinTop = hostSafeTop + 40 + let expectedMaxTop = hostSafeTop + 80 + #expect( - frameTopInWindow <= host.view.safeAreaInsets.top + 1, - "ScrollView frame should extend behind top safeAreaInset (frameTop=\(frameTopInWindow), hostSafeTop=\(host.view.safeAreaInsets.top), topInset=\(topInset), contentOffset.y=\(scrollView.contentOffset.y), contentZeroInWindow=\(contentZeroInWindow))" + frameTopInWindow <= hostSafeTop + 1, + "\(label): ScrollView frame should extend full-bleed behind the floating header (frameTop=\(frameTopInWindow), hostSafeTop=\(hostSafeTop))" ) #expect( - contentZeroInWindow <= expectedMaxTop, - "First message top (\(contentZeroInWindow)) exceeded header budget (\(expectedMaxTop)); frameTop=\(frameTopInWindow), topInset=\(topInset), contentOffset.y=\(scrollView.contentOffset.y), hostSafeTop=\(host.view.safeAreaInsets.top)" + scrollView.safeAreaInsets.top <= hostSafeTop + 1, + "\(label): ScrollView must not receive stacked safeAreaInsets from nested .safeAreaInset modifiers (scrollSafeTop=\(scrollView.safeAreaInsets.top), hostSafeTop=\(hostSafeTop))" + ) + #expect( + contentZeroInWindow >= expectedMinTop && contentZeroInWindow <= expectedMaxTop, + "\(label): First message top (\(contentZeroInWindow)) outside single-header range [\(expectedMinTop), \(expectedMaxTop)] (adjustedContentInset=\(scrollView.adjustedContentInset), contentInset=\(scrollView.contentInset), contentOffset=\(scrollView.contentOffset), contentSize=\(scrollView.contentSize))" ) - // Also verify the actual rendered content subview inside UIScrollView - // is not vertically centered or pushed halfway down. - let renderedContentMinY = scrollView.subviews - .filter { $0.bounds.height > 1 && $0.bounds.width > 100 } - .map { scrollView.convert($0.frame.origin, to: window).y } - .min() - if let renderedContentMinY { - #expect( - renderedContentMinY <= expectedMaxTop + 16, - "Rendered content subview top (\(renderedContentMinY)) was pushed down (expected <= \(expectedMaxTop + 16)); contentSize=\(scrollView.contentSize), contentOffset=\(scrollView.contentOffset), adjustedContentInset=\(scrollView.adjustedContentInset)" - ) - } } + + assertSingleTopInset(for: host, label: "#ez with 2 system messages + keyboard") + + // Also verify fresh launch -> banner dismissed -> empty #mesh -> 1 message + keyboard. + let (meshViewModel, _, _) = makeSmokeViewModel() + let meshFeatureModels = makeSmokeFeatureModels(for: meshViewModel) + meshViewModel.bluetoothState = .poweredOff + let meshHost = UIHostingController(rootView: installSmokeEnvironment( + ContentView().environment(\.appTheme, .liquidGlass), + featureModels: meshFeatureModels + )) + window.rootViewController = meshHost + meshHost.view.frame = window.bounds + meshHost.view.setNeedsLayout() + meshHost.view.layoutIfNeeded() + try? await Task.sleep(nanoseconds: 120_000_000) + + meshViewModel.bluetoothState = .poweredOn + meshHost.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 330, right: 0) + meshViewModel.conversations.append(BitchatMessage( + id: "yo-1", + sender: "anon6990", + content: "Yo", + timestamp: Date(timeIntervalSince1970: 1_700_001_000), + isRelay: false + ), to: .mesh) + try? await Task.sleep(nanoseconds: 150_000_000) + meshHost.view.setNeedsLayout() + meshHost.view.layoutIfNeeded() + + assertSingleTopInset(for: meshHost, label: "fresh #mesh after banner dismissal + 1 message + keyboard") window.isHidden = true } #endif