From cb69ad9e4f21b25954d76f4ce1b406f882dafecc Mon Sep 17 00:00:00 2001 From: klopez4212 Date: Thu, 12 Nov 2026 19:00:58 +0000 Subject: [PATCH] Adapt iPhone Duo layouts, rail navigation, and native sheets (#8568) Duo keeps conversations and Settings details open across closed, book and flat postures. Book mode splits at the fold; flattening restores the sidebar. Native rail controls, full-width navigation backdrops and sheet-local safe areas keep content aligned. Ordinary iPhones remain single-pane in portrait and landscape; tablet and Duo split layouts remain enabled. Includes the recovered preview's matching pane widths, Buzz empty-pane mark, stable Settings chevrons, Bestie pane routing and Duo-only upward New menu attachment. Current main's Activity redesign, Search content fade and unread-navigation button are retained. Menu selection checks sit beside their labels. Shared mobile changes remain in scope: the native iOS status editor, Appearance preview layout, avatar crop preservation, onboarding footer layout, profile/invite sheet geometry and nested conversation navigation. This PR is not exclusively Duo-gated. Nested navigator observers preserve recording cancellation and navigation callbacks; crop resizing preserves the selected image region. iOS 27.1 APIs remain compile-time and runtime gated. Validation on the reconciled source: Flutter analysis, Activity/Home journeys, the full mobile test suite, file-size checks and Swift package tests. The iPhone single-pane fix was also exercised on an iPhone 18 Pro simulator before reconciliation. Fresh hosted CI and physical-device confirmation of the reconciled build are separate and remain pending. --------- Signed-off-by: kenny lopez Signed-off-by: Tom Brow Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 Co-authored-by: Tom Brow Co-authored-by: Tom Brow --- .github/workflows/_ci-flake.yml | 4 +- .../buzz-relay/src/membership_cache/tests.rs | 10 + .../NativePhotoZoomTests.swift | 36 + mobile/ios/Runner.xcodeproj/project.pbxproj | 4 + mobile/ios/Runner/AppDelegate.swift | 68 ++ .../ios/Runner/ConcentricSheetSurface.swift | 50 +- mobile/ios/Runner/IosNavigationBar.swift | 289 ++++++- .../ios/Runner/JumpToLatestGlassButton.swift | 32 +- .../ios/Runner/NativeAttachmentPopover.swift | 6 +- .../NativeAttachmentPopoverCoordinator.swift | 20 +- .../Runner/NativePhotoZoomCoordinator.swift | 98 ++- .../ios/Runner/NativeProfileTextEditor.swift | 62 +- mobile/ios/Runner/NativeStatusEditor.swift | 238 ++++++ .../ProfileSetupRecoveryTests.swift | 131 ++++ mobile/ios/RunnerTests/RunnerTests.swift | 476 +++++++++--- .../lib/features/activity/activity_page.dart | 53 +- .../activity_page/header_actions.dart | 11 +- mobile/lib/features/agents/agents_page.dart | 303 +++++--- .../channels/bestie_conversation.dart | 20 +- .../channels/channel_actions_sheet.dart | 6 +- .../channels/channel_detail_page.dart | 26 +- .../channels/channel_detail_page/banners.dart | 2 +- .../channel_detail_page/empty_messages.dart | 19 + .../channel_detail_page/message_list.dart | 50 +- .../lib/features/channels/channels_page.dart | 54 +- .../channels/channels_page/channel_tile.dart | 251 +++--- .../channels_page/community_switcher.dart | 198 +++-- .../channels/channels_page/sections.dart | 273 ++++--- .../channels/channels_page/skeleton.dart | 10 +- mobile/lib/features/channels/compose_bar.dart | 2 + .../compose_bar/compose_bar_widget.dart | 1 + .../compose_bar/ios_attachment_popover.dart | 15 +- mobile/lib/features/channels/me/me_page.dart | 62 +- .../features/channels/media_viewer_page.dart | 48 +- .../media_viewer_page/image_controls.dart | 32 +- .../channels/native_photo_zoom_preview.dart | 5 + .../features/channels/thread_detail_page.dart | 4 +- .../voice_note_composer_recorder.dart | 18 +- mobile/lib/features/home/home_page.dart | 303 ++++++-- .../home/home_screen_shortcut_host.dart | 4 +- .../home/messages_navigation_bar.dart | 74 +- .../features/invites/invite_create_page.dart | 150 +++- .../invite_link_section.dart | 14 +- mobile/lib/features/pairing/pairing_page.dart | 14 +- .../pairing_page/pairing_welcome_view.dart | 52 +- .../features/pairing/pairing_qr_scanner.dart | 146 +++- .../dynamic_island_portal.dart | 27 +- .../pairing_qr_scanner/fallback_scanner.dart | 41 +- .../pairing_qr_scanner/scanner_camera.dart | 98 ++- .../profile/animated_avatar_capture.dart | 1 + .../review_controls.dart | 68 +- .../features/profile/profile_edit_page.dart | 85 ++- .../features/profile/set_status_sheet.dart | 187 ++++- .../features/profile/user_profile_sheet.dart | 39 +- mobile/lib/features/search/search_page.dart | 301 +++++--- .../search/search_page/message_tile.dart | 18 +- .../lib/features/settings/settings_page.dart | 259 +++++-- .../settings_page/notifications_section.dart | 30 +- .../settings_page/profile_section.dart | 52 +- .../settings/theme_option_sheets.dart | 55 +- .../features/settings/theme_picker_page.dart | 32 +- .../theme_preview_sheet.dart | 271 ++++--- .../widgets/adaptive_conversation_pane.dart | 601 +++++++++++++++ .../shared/widgets/app_route_observer.dart | 19 + .../shared/widgets/avatar_editor_options.dart | 105 +++ .../widgets/avatar_editor_options_scope.dart | 19 + .../widgets/avatar_image_source_controls.dart | 41 +- .../lib/shared/widgets/buzz_setting_menu.dart | 4 +- .../lib/shared/widgets/buzz_sheet_header.dart | 10 +- .../widgets/concentric_sheet_surface.dart | 88 ++- .../covered_route_keyboard_insets.dart | 14 +- mobile/lib/shared/widgets/duo_toolbar.dart | 177 +++++ .../widgets/duo_workspace_scaffold.dart | 48 ++ .../shared/widgets/emoji_avatar_controls.dart | 48 +- .../lib/shared/widgets/frosted_app_bar.dart | 226 ++++-- .../lib/shared/widgets/frosted_scaffold.dart | 34 +- .../widgets/ios_message_create_button.dart | 28 +- .../shared/widgets/ios_navigation_bar.dart | 46 +- .../widgets/ios_navigation_metrics.dart | 81 ++ .../shared/widgets/modal_presentation.dart | 193 ++++- .../shared/widgets/navigation_backdrop.dart | 3 + .../shared/widgets/onboarding_step_page.dart | 341 +++++---- .../widgets/profile_avatar_crop_page.dart | 145 ++-- mobile/pubspec.lock | 8 + mobile/pubspec.yaml | 1 + .../features/activity/activity_page_test.dart | 51 +- .../features/age_gate/age_gate_app_test.dart | 3 +- .../features/agents/agents_sheet_test.dart | 123 +++ .../channels/channel_detail_page_test.dart | 306 +++++++- .../features/channels/channels_page_test.dart | 266 ++++++- .../channels/default_agent_launcher_test.dart | 23 +- .../channels/me/me_chat_assistant_test.dart | 86 +++ .../media_viewer_page/image_rail_test.dart | 131 ++++ mobile/test/features/home/home_page_test.dart | 411 +++++++++- .../invites/invite_create_page_test.dart | 116 +++ .../fullscreen_onboarding_test.dart | 46 ++ .../onboarding/internal_build_entry_test.dart | 6 + .../features/pairing/pairing_page_test.dart | 38 + .../pairing/pairing_qr_scanner_test.dart | 172 ++++- .../profile_avatar_crop_cancel_test.dart | 105 +++ .../profile_avatar_crop_resize_test.dart | 126 +++ .../profile/profile_edit_page_test.dart | 182 ++++- .../profile/set_status_sheet_test.dart | 168 ++++ .../features/search/search_page_test.dart | 84 ++ .../settings/builderlab_account_row_test.dart | 52 +- .../settings/connection_section_test.dart | 15 + .../features/settings/settings_page_test.dart | 213 +++++- .../settings/theme_picker_page_test.dart | 170 +++++ .../shared/push/push_root_isolation_test.dart | 20 +- .../push/push_unconfigured_build_test.dart | 2 + .../adaptive_conversation_pane_test.dart | 716 ++++++++++++++++++ .../adaptive_conversation_recording_test.dart | 149 ++++ .../widgets/buzz_setting_menu_test.dart | 10 + .../shared/widgets/frosted_app_bar_test.dart | 321 ++++++++ .../widgets/ios_navigation_bar_test.dart | 25 + .../widgets/modal_presentation_test.dart | 209 +++++ 116 files changed, 10118 insertions(+), 1815 deletions(-) create mode 100644 mobile/ios/Runner/NativeStatusEditor.swift create mode 100644 mobile/lib/shared/widgets/adaptive_conversation_pane.dart create mode 100644 mobile/lib/shared/widgets/avatar_editor_options.dart create mode 100644 mobile/lib/shared/widgets/avatar_editor_options_scope.dart create mode 100644 mobile/lib/shared/widgets/duo_toolbar.dart create mode 100644 mobile/lib/shared/widgets/duo_workspace_scaffold.dart create mode 100644 mobile/test/features/channels/media_viewer_page/image_rail_test.dart create mode 100644 mobile/test/features/profile/profile_avatar_crop_cancel_test.dart create mode 100644 mobile/test/features/profile/profile_avatar_crop_resize_test.dart create mode 100644 mobile/test/shared/widgets/adaptive_conversation_pane_test.dart create mode 100644 mobile/test/shared/widgets/adaptive_conversation_recording_test.dart diff --git a/.github/workflows/_ci-flake.yml b/.github/workflows/_ci-flake.yml index ff527ddb7d..c411abf50b 100644 --- a/.github/workflows/_ci-flake.yml +++ b/.github/workflows/_ci-flake.yml @@ -287,7 +287,9 @@ jobs: needs: [flake-select] if: needs.flake-select.outputs.dart != '' runs-on: ubuntu-latest - timeout-minutes: 30 + # Large mobile changes take about three minutes per repetition, plus SDK + # setup. Allow all ten repetitions to finish with runner variance. + timeout-minutes: 45 permissions: contents: read steps: diff --git a/crates/buzz-relay/src/membership_cache/tests.rs b/crates/buzz-relay/src/membership_cache/tests.rs index c55ddf7973..0f7aad2af3 100644 --- a/crates/buzz-relay/src/membership_cache/tests.rs +++ b/crates/buzz-relay/src/membership_cache/tests.rs @@ -510,6 +510,16 @@ async fn ttl_reclaims_idle_snapshots_and_invalidation_preserves_only_active_read "an active reader owns the old allocation" ); drop(entry); + // Moka reclaims invalidated entries through epoch-based maintenance; + // dropping the reader does not synchronously collect the cache's copy. + tokio::time::timeout(Duration::from_secs(5), async { + while weak.upgrade().is_some() { + cache.entries.run_pending_tasks(); + tokio::task::yield_now().await; + } + }) + .await + .expect("invalidated snapshot must be reclaimed after its last reader"); assert!( weak.upgrade().is_none(), "last reader must release the allocation" diff --git a/mobile/ios/NativeControlTests/NativePhotoZoomTests.swift b/mobile/ios/NativeControlTests/NativePhotoZoomTests.swift index 074399ccdf..18cfd378ce 100644 --- a/mobile/ios/NativeControlTests/NativePhotoZoomTests.swift +++ b/mobile/ios/NativeControlTests/NativePhotoZoomTests.swift @@ -71,12 +71,48 @@ struct NativePhotoZoomTests { viewer.updateFrame(data, at: 0) precondition(closedPhoto.image === closedImage, "Closed viewers must ignore continuing frames") print("PASS: native photo window, stale responses, eviction and teardown") + railJourney(data: data) videoJourney(data: data) loaderJourney() } } @available(iOS 18.0, *) + @MainActor static func railJourney(data: Data) { + let viewer = NativePhotoZoomViewController(image: UIImage(data: data)!, + labels: ["One", "Two"], initialIndex: 0, canReply: true, canMore: true, canDelete: false) + viewer.loadViewIfNeeded() + viewer.view.frame = CGRect(x: 0, y: 0, width: 951, height: 669) + let pager = viewer.children.compactMap { $0 as? UIPageViewController }.first! + let buttons = ["Close photo", "Reply in thread", "More image actions"].map { label in + descendants(viewer.view).compactMap { $0 as? UIButton }.first { $0.accessibilityLabel == label }! + } + let indicator = descendants(viewer.view).compactMap { $0 as? UIPageControl }.first! + let pageContainer = indicator.superview!.superview!.superview! + let page = pager.viewControllers!.first! + for left in [false, true] { + let centerX: CGFloat = left ? 48 : 903 + viewer.sourceRailGeometry = (viewer.view.bounds.size, centerX) + viewer.layoutGallery(insets: UIEdgeInsets(top: 0, left: left ? 76 : 0, bottom: 0, right: left ? 0 : 76)) + precondition(pager.view.frame == viewer.view.bounds, "Native gallery must span the full Duo window") + pageContainer.layoutIfNeeded() + let indicatorFrame = indicator.convert(indicator.bounds, to: viewer.view) + precondition(abs(indicatorFrame.midX - pager.view.frame.midX) < 0.5, "Photo indicator must share the full-width photo center on either rail side") + for (slot, button) in buttons.enumerated() { + precondition(left ? button.center.x <= 76 : button.center.x >= 875, "Every action is centered inside the rail") + precondition(button.center.x == (left ? 54 : 897), "Native actions must match the channel rail's inward-aligned centerline") + precondition(button.bounds.width >= 44 && button.bounds.height >= 44, "Retain accessible hit targets") + if slot > 0 { precondition(button.frame.minY > buttons[slot - 1].frame.maxY, "Close, Reply, More must not overlap") } + } + } + precondition(buttons[1].frame.minY > 669 - 140 && buttons[2].frame.maxY == 669 - 12, "Reply and More must anchor to the bottom of the rail") + viewer.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + viewer.layoutGallery(insets: UIEdgeInsets(top: 59, left: 0, bottom: 34, right: 0)) + precondition(buttons[0].frame.maxY < buttons[1].frame.minY, "Ordinary phones retain top Close and bottom actions") + precondition(pager.viewControllers!.first === page, "Folding must retain the selected native page") + print("PASS: native gallery rail sides, full viewport, targets and compact transition") + } + @available(iOS 18.0, *) @MainActor static func videoJourney(data: Data) { let path = CommandLine.arguments[1] let viewer = NativePhotoZoomViewController(image: UIImage(data: data)!, diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index c4e27d48eb..f082ce75a8 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -41,6 +41,7 @@ 4A71C0152F40B00100A17E01 /* HuddleMediaPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A71C0162F40B00100A17E01 /* HuddleMediaPlugin.swift */; }; 4A71C0172F40C00100A17E01 /* HuddleAudioEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A71C0182F40C00100A17E01 /* HuddleAudioEngine.swift */; }; 4A71C0192F40D00100A17E01 /* NativeProfileTextEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A71C01A2F40D00100A17E01 /* NativeProfileTextEditor.swift */; }; + F84390190000000000000001 /* NativeStatusEditor.swift in Sources */ = {isa = PBXBuildFile; fileRef = F84390190000000000000002 /* NativeStatusEditor.swift */; }; 7B81D0192F40D00100A17E01 /* NativeCommunityEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B81D01A2F40D00100A17E01 /* NativeCommunityEntry.swift */; }; 7B81D0192F40D00100A17E91 /* NativeProfileSetup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B81D01A2F40D00100A17E91 /* NativeProfileSetup.swift */; }; 4A71C01B2F40E00100A17E01 /* NativeSkinToneControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A71C01C2F40E00100A17E01 /* NativeSkinToneControl.swift */; }; @@ -143,6 +144,7 @@ 4A71C0162F40B00100A17E01 /* HuddleMediaPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HuddleMediaPlugin.swift; sourceTree = ""; }; 4A71C0182F40C00100A17E01 /* HuddleAudioEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HuddleAudioEngine.swift; sourceTree = ""; }; 4A71C01A2F40D00100A17E01 /* NativeProfileTextEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeProfileTextEditor.swift; sourceTree = ""; }; + F84390190000000000000002 /* NativeStatusEditor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeStatusEditor.swift; sourceTree = ""; }; 7B81D01A2F40D00100A17E01 /* NativeCommunityEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeCommunityEntry.swift; sourceTree = ""; }; 7B81D01A2F40D00100A17E91 /* NativeProfileSetup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeProfileSetup.swift; sourceTree = ""; }; 4A71C01C2F40E00100A17E01 /* NativeSkinToneControl.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeSkinToneControl.swift; sourceTree = ""; }; @@ -328,6 +330,7 @@ C0AF00000000000000000012 /* NativeAddMembersSheet.swift */, C0AF00000000000000000072 /* NativeCreateChannelSheet.swift */, 4A71C01A2F40D00100A17E01 /* NativeProfileTextEditor.swift */, + F84390190000000000000002 /* NativeStatusEditor.swift */, 7B81D01A2F40D00100A17E01 /* NativeCommunityEntry.swift */, 7B81D01A2F40D00100A17E91 /* NativeProfileSetup.swift */, 4A71C01C2F40E00100A17E01 /* NativeSkinToneControl.swift */, @@ -678,6 +681,7 @@ C0AF00000000000000000011 /* NativeAddMembersSheet.swift in Sources */, C0AF00000000000000000071 /* NativeCreateChannelSheet.swift in Sources */, 4A71C0192F40D00100A17E01 /* NativeProfileTextEditor.swift in Sources */, + F84390190000000000000001 /* NativeStatusEditor.swift in Sources */, 7B81D0192F40D00100A17E01 /* NativeCommunityEntry.swift in Sources */, 7B81D0192F40D00100A17E91 /* NativeProfileSetup.swift in Sources */, 4A71C01B2F40E00100A17E01 /* NativeSkinToneControl.swift in Sources */, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 9475342aa6..7680ea2bef 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -467,7 +467,75 @@ import os.log result: @escaping FlutterResult ) { switch call.method { + case "cameraCutoutFrame": + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), + let scene = UIApplication.shared.connectedScenes + .compactMap({ $0 as? UIWindowScene }) + .first(where: { $0.activationState == .foregroundActive }), + let window = scene.windows.first(where: { $0.isKeyWindow }) { + if window.reservedRegions(kind: .division).contains(where: { $0.isActive }) { + result(nil) + return + } + let bounds = window.bounds + // Closed Duo displays may omit Flutter display features. UIKit still + // owns the physical occlusion; remove its interactive clearance. + for region in window.reservedRegions(kind: .occlusion) where region.isActive { + let rect = region.frame.inset(by: region.margins) + let isCamera = abs(rect.width - rect.height) < 1 + && rect.minX > 0 && rect.minY > 0 + && rect.maxX < bounds.width && rect.maxY < bounds.height + && rect.width < bounds.width / 4 + guard rect.width > 0, rect.height > 0, isCamera else { continue } + let values: [Double] = [ + Double(rect.minX), Double(rect.minY), Double(rect.width), + Double(rect.height), Double(bounds.width), Double(bounds.height) + ] + result(values) + return + } + } + #endif + result(nil) + case "previewRotationQuarterTurns": + // The plugin reads connectedScenes.first, which can be the inactive + // cover scene on Duo. Resolve the angle against the visible preview host. + if #available(iOS 17.0, *), + let scene = UIApplication.shared.connectedScenes + .compactMap({ $0 as? UIWindowScene }) + .first(where: { $0.activationState == .foregroundActive }), + let window = scene.windows.first(where: { $0.isKeyWindow }), + let camera = AVCaptureDevice.DiscoverySession( + deviceTypes: [.builtInTripleCamera, .builtInDualCamera, .builtInWideAngleCamera], + mediaType: .video, position: .back + ).devices.first { + let coordinator = AVCaptureDevice.RotationCoordinator(device: camera, previewLayer: window.layer) + let angle = coordinator.videoRotationAngleForHorizonLevelPreview + let orientation = call.arguments as? String + let legacyAngle: CGFloat + switch orientation { + case "landscapeLeft": legacyAngle = 180 + case "landscapeRight": legacyAngle = 0 + case "portraitDown": legacyAngle = 270 + default: legacyAngle = 90 + } + result(Int(((angle - legacyAngle) / 90).rounded())) + return + } + result(0) case "usesDynamicIslandQrScannerPortal": + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), + let scene = UIApplication.shared.connectedScenes + .compactMap({ $0 as? UIWindowScene }) + .first(where: { $0.activationState == .foregroundActive }), + let window = scene.windows.first(where: { $0.isKeyWindow }), + window.reservedRegions(kind: .division).contains(where: { $0.isActive }) { + result(false) + return + } + #endif result( UIDevice.current.userInterfaceIdiom == .phone && usesDynamicIslandQrScannerPortal( diff --git a/mobile/ios/Runner/ConcentricSheetSurface.swift b/mobile/ios/Runner/ConcentricSheetSurface.swift index 02fe9d0be3..cce6834e9f 100644 --- a/mobile/ios/Runner/ConcentricSheetSurface.swift +++ b/mobile/ios/Runner/ConcentricSheetSurface.swift @@ -30,6 +30,7 @@ final class ConcentricSheetSurfaceFactory: NSObject, FlutterPlatformViewFactory final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { private let rootView: UIView private let surfaceView: UIView + private let independentCorners: Bool private let channel: FlutterMethodChannel private let corners: String private let usesGlass: Bool @@ -47,9 +48,10 @@ final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { let minimumRadius = (arguments?["minimumRadius"] as? NSNumber)?.doubleValue ?? 24 corners = arguments?["corners"] as? String ?? "all" topRadius = (arguments?["topRadius"] as? NSNumber)?.doubleValue + independentCorners = (arguments?["independentCorners"] as? NSNumber)?.boolValue == true usesGlass = (arguments?["usesGlass"] as? NSNumber)?.boolValue == true - rootView = UIView(frame: frame) + rootView = ConcentricSurfaceRootView(frame: frame) rootView.isUserInteractionEnabled = false rootView.isOpaque = !usesGlass && backdropColorValue != nil rootView.backgroundColor = backdropColorValue.map { Self.color(from: $0) } ?? .clear @@ -84,12 +86,20 @@ final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { applyInterfaceStyle(from: arguments?["brightness"]) applyCornerConfiguration(minimumRadius: minimumRadius, capsule: arguments?["capsule"] as? Bool == true) + (rootView as? ConcentricSurfaceRootView)?.onLayout = { [weak self] in + guard let self else { return } + self.channel.invokeMethod("cornerRadiiChanged", arguments: self.cornerRadii()) + } + channel.setMethodCallHandler { [weak self] call, result in guard let self else { result(nil) return } switch call.method { + case "getCornerRadii": + self.rootView.layoutIfNeeded() + result(self.cornerRadii()) case "updateColors": guard let arguments = call.arguments as? [String: Any], @@ -172,6 +182,15 @@ final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { return } let radius = UICornerRadius.containerConcentric(minimum: minimumRadius) + if independentCorners { + surfaceView.cornerConfiguration = .corners( + topLeftRadius: corners == "bottom" ? nil : topRadius.map { .fixed($0) } ?? radius, + topRightRadius: corners == "bottom" ? nil : topRadius.map { .fixed($0) } ?? radius, + bottomLeftRadius: radius, + bottomRightRadius: radius + ) + return + } surfaceView.cornerConfiguration = corners == "bottom" ? .uniformBottomRadius( @@ -197,6 +216,24 @@ final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { } } + private func cornerRadii() -> [String: CGFloat] { + if #available(iOS 26.0, *) { + return [ + "topLeft": surfaceView.effectiveRadius(corner: .topLeft), + "topRight": surfaceView.effectiveRadius(corner: .topRight), + "bottomLeft": surfaceView.effectiveRadius(corner: .bottomLeft), + "bottomRight": surfaceView.effectiveRadius(corner: .bottomRight), + ] + } + let radius = surfaceView.layer.cornerRadius + return [ + "topLeft": corners == "bottom" ? 0 : radius, + "topRight": corners == "bottom" ? 0 : radius, + "bottomLeft": radius, + "bottomRight": radius, + ] + } + private func applyInterfaceStyle(from value: Any?) { switch value as? String { case "dark": @@ -216,3 +253,14 @@ final class ConcentricSheetSurfacePlatformView: NSObject, FlutterPlatformView { return UIColor(red: red, green: green, blue: blue, alpha: alpha) } } + +/// Reading effective radii during layout lets UIKit invalidate the geometry +/// when the enclosing display or presentation changes. +private final class ConcentricSurfaceRootView: UIView { + var onLayout: (() -> Void)? + + override func layoutSubviews() { + super.layoutSubviews() + onLayout?() + } +} diff --git a/mobile/ios/Runner/IosNavigationBar.swift b/mobile/ios/Runner/IosNavigationBar.swift index f3d1f3b2cc..12c08b7c43 100644 --- a/mobile/ios/Runner/IosNavigationBar.swift +++ b/mobile/ios/Runner/IosNavigationBar.swift @@ -1,6 +1,9 @@ import Flutter import UIKit +// UIKit 9127.0.85 is the iOS 27.1 SDK with Duo APIs. SDK checks must +// surround runtime availability checks: older SDKs cannot resolve these symbols. + /// Each Flutter route owns a UIKit navigation controller. Its private scroll /// view mirrors the Flutter viewport so UIKit performs the large-title layout. final class IosNavigationBarFactory: NSObject, FlutterPlatformViewFactory { @@ -340,6 +343,17 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { private let channel: FlutterMethodChannel private var offset: CGFloat = 0 private var controlBackground = UIColor.secondarySystemBackground + private var foldRefresh: DispatchWorkItem? + private var standaloneControl = false + private var standaloneLargeTitle = false + private var standaloneSurface: UIView? + private var horizontalControls = false + private var headerLeading: UIView? + private var headerTrailing: UIView? + private var paneTitle: UIView? + private var titleInsetLeft: CGFloat = 0 + private var titleInsetRight: CGFloat = 0 + private var alignCollapsedTitleToLeading = false private var alwaysFrosted = false private var backdropOnly = false private var usesSystemScrollEdge = false @@ -362,6 +376,8 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { private var floatingTitle: NavigationTitleView? private var titleMaxWidth: CGFloat? private var floatingTitleLift: CGFloat = 0 + private var portraitTopPadding: CGFloat = 0 + private var centerTitleInPane = false init(frame: CGRect, id: Int64, args: Any?, messenger: FlutterBinaryMessenger, parent: UIViewController?) { container = NavigationClipView(frame: frame) @@ -402,11 +418,46 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { result(nil) } configure(args as? [String: Any] ?? [:]) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), standaloneControl { + container.addInteraction(UIHingeInteraction { [weak self] _, _ in + guard let self else { return } + self.container.setNeedsLayout() + // Reserved divisions settle shortly after the physical hinge does. + self.foldRefresh?.cancel() + let refresh = DispatchWorkItem { [weak self] in self?.container.setNeedsLayout() } + self.foldRefresh = refresh + DispatchQueue.main.asyncAfter(deadline: .now() + 1.2, execute: refresh) + }) + } + #endif } func view() -> UIView { container } private func layout() { + if standaloneLargeTitle, let scroll = standaloneSurface as? UIScrollView, + let label = scroll.subviews.compactMap({ $0 as? UILabel }).first { + scroll.frame = container.bounds + let width = max(0, scroll.bounds.width - 32) + let size = label.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)) + // Match the pane's 44-point navigation row plus its 24-point top spacing. + label.frame = CGRect(x: 16, y: flutterSafeTop + 68, width: width, height: size.height) + scroll.contentSize = CGSize(width: scroll.bounds.width, height: label.frame.maxY + 24) + return + } + if standaloneControl { + reportRailGeometry() + if let surface = standaloneSurface { + let size = surface.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) + surface.frame = CGRect(x: (container.bounds.width - size.width) / 2, + y: (container.bounds.height - size.height) / 2, + width: size.width, height: size.height) + surface.layoutIfNeeded() + reportAvatarBounds() + } + return + } // Only the bar is exposed by the platform-view clip. A full viewport is // needed for UIKit's scroll-edge and large-title calculations. guard !measuring else { return } @@ -419,11 +470,18 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { let automaticTop = container.safeAreaInsets.top // An empty native bar supplies the same edge geometry beneath a custom // Flutter header. Place its lower edge at the end of that header so the - // system fade protects the filters as well as the status area. + // system fade protects the filters as well as the status area. Duo may + // collapse the native row to zero; do not subtract a phone-sized row. let protectedTop = backdropOnly - ? max(flutterSafeTop, container.bounds.height - max(44, navigation.navigationBar.bounds.height)) + ? max(flutterSafeTop, container.bounds.height - navigation.navigationBar.bounds.height) : flutterSafeTop - let requiredTop = max(0, protectedTop - automaticTop) + // Duo can collapse the native horizontal control row to zero because its + // controls live in the side rail. Flutter still reserves a 44-point row + // plus 24 points of breathing room. Give expanded titles that same space. + let compact = (metrics?["compactHeight"] as? CGFloat) ?? 44 + let paneTitleClearance = alignCollapsedTitleToLeading + ? max(44, compact) + 24 - compact : 0 + let requiredTop = max(0, protectedTop + paneTitleClearance - automaticTop) if abs(navigation.additionalSafeAreaInsets.top - requiredTop) > 0.5 { navigation.additionalSafeAreaInsets.top = requiredTop } @@ -439,11 +497,12 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { // beneath the entire control area, not just the status indicators. let glassBackedControls: Bool if #available(iOS 26.0, *) { - glassBackedControls = content.navigationItem.titleView is NavigationTitleView || floatingTitle != nil + glassBackedControls = content.navigationItem.titleView is NavigationTitleView || paneTitle is NavigationTitleView || floatingTitle != nil } else { glassBackedControls = false } - let statusOnly = alwaysFrosted && !navigation.navigationBar.prefersLargeTitles && glassBackedControls + let statusOnly = alwaysFrosted && !centerTitleInPane && paneTitle == nil && !horizontalControls + && !navigation.navigationBar.prefersLargeTitles && glassBackedControls let height = statusOnly ? min(container.bounds.height, statusHeight > 0 ? statusHeight + 6 : 0) : container.bounds.height @@ -453,13 +512,48 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { materialFade.frame = material.bounds materialFade.locations = statusOnly ? [0, NSNumber(value: Double(max(0, height - 12) / max(1, height))), 1] - : (navigation.navigationBar.prefersLargeTitles ? [0, 0.55, 1] : [0, 0.85, 1]) + : [0, 0.55, 1] CATransaction.commit() + if let title = paneTitle { + let titleWidth = max(0, container.bounds.width - titleInsetLeft - titleInsetRight) + let center = titleInsetLeft + titleWidth / 2 + var availableWidth = max(0, titleWidth - 32) + if horizontalControls && !alignCollapsedTitleToLeading { + let leadingWidth = headerLeading?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width ?? 0 + let trailingWidth = headerTrailing?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width ?? 0 + let leftEdge = titleInsetLeft + 16 + leadingWidth + let rightEdge = container.bounds.width - titleInsetRight - 20 - trailingWidth + availableWidth = max(0, min(center - leftEdge, rightEdge - center) * 2 - 16) + } + let size = title.sizeThatFits(CGSize(width: availableWidth, height: 44)) + title.frame = CGRect(x: alignCollapsedTitleToLeading + ? navigation.navigationBar.layoutMargins.left + : titleInsetLeft + (titleWidth - size.width) / 2, + y: alignCollapsedTitleToLeading + ? flutterSafeTop + 24 + (44 - size.height) / 2 + : (container.bounds.height - size.height) / 2, + width: size.width, height: size.height) + title.layoutIfNeeded() + } + if horizontalControls { + // These native glass groups belong to the Flutter pane, whose bounds + // already exclude the rail. Avoid UINavigationBar reserving it again. + for (surface, trailing) in [(headerLeading, false), (headerTrailing, true)] { + guard let surface else { continue } + let size = surface.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) + surface.frame = CGRect(x: trailing ? container.bounds.width - titleInsetRight - 20 - size.width : titleInsetLeft + 16, + y: navigation.navigationBar.prefersLargeTitles + ? max(12, flutterSafeTop + 24 + (44 - size.height) / 2) + : max(12, (container.bounds.height - size.height) / 2), + width: size.width, height: size.height) + surface.layoutIfNeeded() + } + } if let title = floatingTitle { let available = max(0, container.bounds.width - 48) let width = min(title.intrinsicContentSize.width, min(available, titleMaxWidth ?? available)) title.frame = CGRect(x: (container.bounds.width - width) / 2, - y: flutterSafeTop + 56 - floatingTitleLift, width: width, height: 44) + y: flutterSafeTop + portraitTopPadding + 56 - floatingTitleLift, width: width, height: 44) // This overlay is outside UINavigationBar, which normally lays out the // effect content after constraining its title. Apply that pass here too. title.layoutIfNeeded() @@ -468,6 +562,49 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { reportAvatarBounds() } + private func reportRailGeometry() { + #if canImport(UIKit, _version: 9127.0.85) + guard #available(iOS 27.1, *), let window = container.window else { return } + let inset = window.safeAreaInsets + let right = inset.right > 0 && inset.left == 0 + let left = inset.left > 0 && inset.right == 0 + guard inset.top == 0, right || left else { return } + let strip = CGRect(x: right ? window.bounds.width - inset.right : 0, + y: 0, width: right ? inset.right : inset.left, + height: window.bounds.height) + // Reserved-region frames include interactive margins. Remove those + // before finding the hardware axis; the safe-area strip is asymmetric. + let regions = window.reservedRegions(kind: .occlusion) + .filter { $0.isActive && $0.frame.intersects(strip) && $0.frame.midY < window.bounds.midY } + .sorted { $0.frame.minY < $1.frame.minY } + // Some hosts don't expose occlusions. The full safe-area inset includes + // content clearance; use UIKit's outer layout margin for the control, + // rather than centering it in that asymmetric inset. + guard let root = window.rootViewController else { return } + // Read the unobstructed edge: the strip-side margin has already been + // expanded to the safe area, while Flutter's controller reports a zero + // systemMinimumLayoutMargins despite its view's actual UIKit margins. + let margins = root.view.layoutMargins + let outerMargin = right ? margins.left : margins.right + let marginCenter = right ? window.bounds.width - outerMargin - 28 : outerMargin + 28 + let center = regions.first.map { $0.frame.inset(by: $0.margins).midX } ?? marginCenter + guard strip.contains(CGPoint(x: center, y: strip.midY)) else { return } + let division = window.reservedRegions(kind: .division) + .first { $0.isActive && $0.frame.height >= window.bounds.height - 1 + && $0.frame.minX > 0 && $0.frame.maxX < window.bounds.width } + let fold: Any = division.map { region -> Any in + [region.frame.minX, region.frame.minY, region.frame.width, region.frame.height] + } ?? NSNull() + let values: [String: Any] = ["bookDivision": fold, "centerX": center, + "topClearance": regions.map { $0.frame.maxY }.max() as Any? ?? NSNull(), + "windowWidth": window.bounds.width, + "windowHeight": window.bounds.height] + DispatchQueue.main.async { [weak self] in + self?.channel.invokeMethod("railGeometry", arguments: values) + } + #endif + } + private func reportAvatarBounds() { guard let avatar = trackedAvatar, avatar.window != nil, avatar.bounds.width > 0 else { return } avatar.layoutIfNeeded() @@ -484,6 +621,8 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { } private func configure(_ args: [String: Any]) { + titleInsetLeft = max(0, (args["titleInsetLeft"] as? NSNumber)?.doubleValue ?? 0) + titleInsetRight = max(0, (args["titleInsetRight"] as? NSNumber)?.doubleValue ?? 0) controlBackground = Self.color(args["controlBackground"]) flutterSafeTop = (args["safeTop"] as? NSNumber)?.doubleValue ?? 0 floatingTitleLift = args["titleHasAnimatedPortrait"] as? Bool == true ? 14 : 0 @@ -493,6 +632,58 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { material.overrideUserInterfaceStyle = navigation.overrideUserInterfaceStyle // Let the ultra-thin system material provide its own adaptive tint. material.contentView.backgroundColor = .clear + standaloneControl = args["standaloneControl"] as? Bool == true + standaloneLargeTitle = args["standaloneLargeTitle"] as? Bool == true + standaloneSurface?.removeFromSuperview() + standaloneSurface = nil + horizontalControls = args["horizontalControls"] as? Bool == true + centerTitleInPane = args["centerTitleInPane"] as? Bool == true + portraitTopPadding = CGFloat((args["portraitTopPadding"] as? NSNumber)?.doubleValue ?? 0) + paneTitle?.removeFromSuperview() + paneTitle = nil + alignCollapsedTitleToLeading = args["alignCollapsedTitleToLeading"] as? Bool == true + headerLeading?.removeFromSuperview() + headerTrailing?.removeFromSuperview() + headerLeading = nil + headerTrailing = nil + navigation.view.isHidden = standaloneControl || standaloneLargeTitle + || (horizontalControls && args["largeTitle"] as? Bool != true) + if standaloneLargeTitle { + container.overrideUserInterfaceStyle = navigation.overrideUserInterfaceStyle + material.isHidden = true + container.clipsToBounds = true + let scroll = UIScrollView() + scroll.contentInsetAdjustmentBehavior = .never + let label = UILabel() + let font = UIFont.preferredFont(forTextStyle: .largeTitle) + label.font = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor, size: 0) + label.adjustsFontForContentSizeCategory = true + label.text = args["title"] as? String + label.textColor = Self.color(args["foreground"]) + label.numberOfLines = 0 + label.lineBreakMode = .byWordWrapping + label.accessibilityTraits = .header + scroll.addSubview(label) + standaloneSurface = scroll + container.addSubview(scroll) + container.setNeedsLayout() + return + } + if standaloneControl { + material.isHidden = true + container.clipsToBounds = false + container.overrideUserInterfaceStyle = navigation.overrideUserInterfaceStyle + navigation.navigationBar.tintColor = Self.color(args["foreground"]) + trackedAvatar = nil + reportedAvatarFrame = nil + if let leading = args["leading"] as? [String: Any], + let surface = makeControlGroup([leading]).customView { + standaloneSurface = surface + container.addSubview(surface) + } + container.setNeedsLayout() + return + } let bar = navigation.navigationBar let color = Self.color(args["foreground"]) bar.tintColor = color @@ -505,7 +696,11 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { let largeTitle = args["largeTitle"] as? Bool == true alwaysFrosted = args["alwaysFrosted"] as? Bool == true if #available(iOS 26.0, *) { - if #available(iOS 27.0, *) { usesSystemScrollEdge = true } + if #available(iOS 27.0, *) { + // All headers use the same native soft scroll edge. Custom titles + // also retain material, like large titles, when embedding clips it. + usesSystemScrollEdge = true + } content.scrollView.topEdgeEffect.style = .soft content.scrollView.topEdgeEffect.isHidden = !usesSystemScrollEdge } @@ -515,6 +710,7 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { // Keep the graduated material throughout that transition so partial // scrolling never leaves the title and status area unprotected. material.isHidden = usesSystemScrollEdge && !largeTitle + && args["centerTitleInPane"] as? Bool != true && !backdropOnly // Let the native fade extend past the bar without enlarging its hit area. // The mirrored content is transparent and the bottom edge is hidden. container.clipsToBounds = !usesSystemScrollEdge @@ -589,10 +785,38 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { compactTitle.layer.mask = compactTitleMask if compactTitle.superview == nil { compactTitleContainer.addArrangedSubview(compactTitle) } compactTitleContainer.frame.size = compactTitle.intrinsicContentSize - item.titleView = compactTitleContainer + if alignCollapsedTitleToLeading { + // Duo's list title fades in place: the compact label uses the same + // leading margin as UIKit's expanded title, rather than recentering. + item.titleView = UIView() + compactTitleContainer.translatesAutoresizingMaskIntoConstraints = true + paneTitle = compactTitleContainer + container.addSubview(compactTitleContainer) + } else { + item.titleView = compactTitleContainer + } } else { item.titleView = nil } + if args["centerTitleInPane"] as? Bool == true, !largeTitle { + if let titleView = item.titleView { + item.titleView = nil + titleView.translatesAutoresizingMaskIntoConstraints = true + paneTitle = titleView + } else if let text = item.title, !text.isEmpty { + let label = UILabel() + label.text = text + label.font = .preferredFont(forTextStyle: .headline) + label.adjustsFontForContentSizeCategory = true + label.textColor = color + label.textAlignment = .center + label.lineBreakMode = .byTruncatingTail + label.accessibilityTraits = .header + paneTitle = label + } + item.title = nil + if let paneTitle { container.addSubview(paneTitle) } + } item.largeTitleDisplayMode = bar.prefersLargeTitles ? .always : .never trackedAvatar = nil reportedAvatarFrame = nil @@ -614,7 +838,21 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { groups.append([action]) } } - item.rightBarButtonItems = groups.reversed().map(makeControlGroup) + if horizontalControls { + item.leftBarButtonItems = nil + item.rightBarButtonItems = nil + if let leading = args["leading"] as? [String: Any] { + headerLeading = makeControlGroup([leading]).customView + } + if let actions = args["actions"] as? [[String: Any]], !actions.isEmpty { + headerTrailing = makeControlGroup(actions).customView + } + for surface in [headerLeading, headerTrailing].compactMap({ $0 }) { + container.addSubview(surface) + } + } else { + item.rightBarButtonItems = groups.reversed().map(makeControlGroup) + } if let metrics { channel.invokeMethod("metrics", arguments: metrics) } @@ -651,12 +889,16 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { var metrics: [String: Any] = ["compactHeight": compact] if large { metrics["expandedHeight"] = expandedBarHeight } self.metrics = metrics + // The first measurement may reveal a zero-height Duo control row. + // Reconcile its reserved title space on the next native layout pass. + if alignCollapsedTitleToLeading { container.setNeedsLayout() } DispatchQueue.main.async { [weak self] in self?.channel.invokeMethod("metrics", arguments: metrics) } } private func setScrollOffset(_ value: CGFloat) { + guard !standaloneControl && !standaloneLargeTitle else { return } guard value.isFinite else { return } // The mirror scroll view is finite. Past its end UIKit sees no content // under the bar and drops the scroll-edge blur, so a long chat whose @@ -746,7 +988,7 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { } private func makeControlGroup(_ actions: [[String: Any]]) -> UIBarButtonItem { - if actions.count == 1 { + if actions.count == 1 && !standaloneControl { let item = makeItem(actions[0]) // Let UIKit retain its navigation typography and sizing for text actions // such as Edit/Done, rather than inheriting UIButton's default styling. @@ -763,9 +1005,9 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { } else { surface.backgroundColor = controlBackground } - // Match the navigation bar's 44-point content height so single - // controls remain circular rather than being compressed vertically. - surface.layer.cornerRadius = 22 + // Use compact controls while retaining the 44-point minimum hit target. + let controlSize: CGFloat = standaloneControl ? 48 : 44 + surface.layer.cornerRadius = controlSize / 2 surface.layer.cornerCurve = .circular surface.clipsToBounds = true let stack = UIStackView() @@ -790,7 +1032,7 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { if #available(iOS 26.0, *) { button.cornerConfiguration = .capsule() } - button.layer.cornerRadius = 22 + button.layer.cornerRadius = controlSize / 2 button.layer.cornerCurve = .circular button.clipsToBounds = true } @@ -803,8 +1045,8 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { slot.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ - slot.widthAnchor.constraint(equalToConstant: item.image == nil && item.customView == nil ? max(44, button.intrinsicContentSize.width + 16) : 44), - slot.heightAnchor.constraint(equalToConstant: 44), + slot.widthAnchor.constraint(equalToConstant: item.image == nil && item.customView == nil ? max(controlSize, button.intrinsicContentSize.width + 16) : controlSize), + slot.heightAnchor.constraint(equalToConstant: controlSize), button.centerXAnchor.constraint(equalTo: slot.centerXAnchor), button.centerYAnchor.constraint(equalTo: slot.centerYAnchor) ]) @@ -823,6 +1065,11 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { stack.bottomAnchor.constraint(equalTo: surface.contentView.bottomAnchor) ]) let item = UIBarButtonItem(customView: surface) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), actions.allSatisfy({ $0["keepInHeaderOnDuo"] as? Bool == true }) { + item.axisBehavior = .horizontalOnly + } + #endif if #available(iOS 26.0, *) { item.hidesSharedBackground = true } return item } @@ -900,9 +1147,10 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { let button = UIButton(type: .custom) // UIKit adds the glass button's own padding around this custom view. // Match the 36-point image on both axes so that glass stays circular. - button.frame = CGRect(x: 0, y: 0, width: 36, height: 36) - button.widthAnchor.constraint(equalToConstant: 36).isActive = true - button.heightAnchor.constraint(equalToConstant: 36).isActive = true + let avatarTarget: CGFloat = standaloneControl ? 48 : 36 + button.frame = CGRect(x: 0, y: 0, width: avatarTarget, height: avatarTarget) + button.widthAnchor.constraint(equalToConstant: avatarTarget).isActive = true + button.heightAnchor.constraint(equalToConstant: avatarTarget).isActive = true button.setImage(item.image?.withAlignmentRectInsets(.zero), for: .normal) button.addAction(action, for: .touchUpInside) button.isEnabled = item.isEnabled @@ -935,6 +1183,7 @@ private final class IosNavigationBarView: NSObject, FlutterPlatformView { } deinit { + foldRefresh?.cancel() channel.setMethodCallHandler(nil) navigation.willMove(toParent: nil) navigation.view.removeFromSuperview() diff --git a/mobile/ios/Runner/JumpToLatestGlassButton.swift b/mobile/ios/Runner/JumpToLatestGlassButton.swift index a26129ee14..9b8c488088 100644 --- a/mobile/ios/Runner/JumpToLatestGlassButton.swift +++ b/mobile/ios/Runner/JumpToLatestGlassButton.swift @@ -41,6 +41,7 @@ private final class JumpToLatestGlassButton: UIButton { } final class NavigationGlassButton: UIButton { + var opensMenuAbove = false var hitTargetInsets = UIEdgeInsets.zero var pendingMenuAction: (() -> Void)? var menuVisibilityChanged: ((Bool) -> Void)? @@ -48,6 +49,13 @@ final class NavigationGlassButton: UIButton { weak var glassPreview: UIView? var onHighlightChanged: ((Bool) -> Void)? + override func menuAttachmentPoint(for configuration: UIContextMenuConfiguration) -> CGPoint { + guard opensMenuAbove else { + return super.menuAttachmentPoint(for: configuration) + } + return CGPoint(x: bounds.midX, y: bounds.minY) + } + override var isHighlighted: Bool { didSet { if oldValue != isHighlighted { onHighlightChanged?(isHighlighted) } @@ -342,10 +350,12 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { if arguments?["mergingNavigation"] as? Bool == true { let glass = MergingNavigationGlass(frame: containerView.bounds) + glass.vertical = arguments?["verticalNavigation"] as? Bool ?? false glass.autoresizingMask = [.flexibleWidth, .flexibleHeight] containerView.addSubview(glass) navigationGlass = glass glass.centerSurface.contentView.addSubview(button) + button.opensMenuAbove = !glass.vertical && arguments?["menuAbove"] as? Bool == true button.glassPreview = glass.centerSurface button.animateMenu = { [weak glass] visible, animator in glass?.setMenuOpen(visible, animator: animator) @@ -507,8 +517,11 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { ? UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { _ in } : NativeTabler.image($0, size: 24) } + var attributes: UIMenuElement.Attributes = [] + if item["enabled"] as? Bool != true { attributes.insert(.disabled) } + if item["destructive"] as? Bool == true { attributes.insert(.destructive) } let action = UIAction(title: item["label"] as? String ?? "", image: symbol, - attributes: item["enabled"] as? Bool == true ? [] : [.disabled], + attributes: attributes, state: item["checked"] as? Bool == true ? .on : .off) { [weak self] _ in let select = { [weak self] in self?.channel.invokeMethod("menuAction", arguments: item["id"]) @@ -587,7 +600,7 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { ) let pointSize: CGFloat = icon == "shutter" ? controlSize * Self.shutterIconRatio - : 24 + : (arguments?["iconSize"] as? NSNumber)?.doubleValue ?? 24 if icon == "shutter" { // The shutter is a solid disc, not Tabler's outlined circle glyph. buttonImage = UIGraphicsImageRenderer(size: CGSize(width: pointSize, height: pointSize)).image { _ in @@ -760,6 +773,7 @@ final class NativeSegmentedControlPlatformView: NSObject, FlutterPlatformView { /// Three native glass elements share a compositor so their surfaces merge. final class MergingNavigationGlass: UIView { + var vertical = false let leftSurface: UIVisualEffectView let centerSurface: UIVisualEffectView let rightSurface: UIVisualEffectView @@ -804,21 +818,23 @@ final class MergingNavigationGlass: UIView { // Use bounds/center rather than frame: side views may be transformed. leftSurface.bounds = CGRect(x: 0, y: 0, width: 56, height: 56) rightSurface.bounds = leftSurface.bounds - centerSurface.bounds = CGRect(x: 0, y: 0, width: 112, height: 56) - leftSurface.center = CGPoint(x: 28, y: bounds.midY) - rightSurface.center = CGPoint(x: bounds.width - 28, y: bounds.midY) + centerSurface.bounds = CGRect(x: 0, y: 0, width: vertical ? 56 : 112, height: 56) + leftSurface.center = vertical ? CGPoint(x: bounds.midX, y: 28) : CGPoint(x: 28, y: bounds.midY) + rightSurface.center = vertical ? CGPoint(x: bounds.midX, y: bounds.height - 28) : CGPoint(x: bounds.width - 28, y: bounds.midY) centerSurface.center = CGPoint(x: bounds.midX, y: bounds.midY) } func setMenuOpen(_ open: Bool, animator: UIContextMenuInteractionAnimating?) { layoutIfNeeded() - let movement = bounds.midX - 28 + let movement = (vertical ? bounds.midY : bounds.midX) - 28 + let dx = vertical ? 0 : movement + let dy = vertical ? movement : 0 let changes = { [weak self] in guard let self else { return } self.leftSurface.transform = open - ? CGAffineTransform(translationX: movement, y: 0).scaledBy(x: 0.9, y: 0.9) : .identity + ? CGAffineTransform(translationX: dx, y: dy).scaledBy(x: 0.9, y: 0.9) : .identity self.rightSurface.transform = open - ? CGAffineTransform(translationX: -movement, y: 0).scaledBy(x: 0.9, y: 0.9) : .identity + ? CGAffineTransform(translationX: -dx, y: -dy).scaledBy(x: 0.9, y: 0.9) : .identity } let opacity = { [weak self] in self?.leftSurface.alpha = open ? 0 : 1 diff --git a/mobile/ios/Runner/NativeAttachmentPopover.swift b/mobile/ios/Runner/NativeAttachmentPopover.swift index 048b52281d..2b62e5b86a 100644 --- a/mobile/ios/Runner/NativeAttachmentPopover.swift +++ b/mobile/ios/Runner/NativeAttachmentPopover.swift @@ -18,6 +18,7 @@ final class NativeAttachmentPopoverViewController: } private let channel: FlutterMethodChannel + private let cameraHorizontalOffset: CGFloat private let expandedWidth: CGFloat private let maximumMenuHeight: CGFloat private let expandedHeight = NativeAttachmentMenuLayout.maximumHeight @@ -63,10 +64,12 @@ final class NativeAttachmentPopoverViewController: init( channel: FlutterMethodChannel, expandedWidth: CGFloat, + cameraHorizontalOffset: CGFloat = 0, maximumMenuHeight: CGFloat = NativeAttachmentMenuLayout.maximumHeight ) { self.channel = channel self.expandedWidth = expandedWidth + self.cameraHorizontalOffset = cameraHorizontalOffset self.maximumMenuHeight = maximumMenuHeight super.init(nibName: nil, bundle: nil) preferredContentSize = NativeAttachmentMenuLayout.size( @@ -374,7 +377,8 @@ final class NativeAttachmentPopoverViewController: popover.sourceRect = NativeAttachmentPopoverAnchorLayout.sourceRect( anchorBounds: sourceView.bounds, keyboardDismissalOffset: self.keyboardDismissalOffset, - isExpanded: isExpanding + isExpanded: isExpanding, + horizontalOffset: nextSurface == .camera ? self.cameraHorizontalOffset : 0 ) } previousView?.alpha = 0 diff --git a/mobile/ios/Runner/NativeAttachmentPopoverCoordinator.swift b/mobile/ios/Runner/NativeAttachmentPopoverCoordinator.swift index 1d29029674..a785dfddba 100644 --- a/mobile/ios/Runner/NativeAttachmentPopoverCoordinator.swift +++ b/mobile/ios/Runner/NativeAttachmentPopoverCoordinator.swift @@ -29,10 +29,11 @@ enum NativeAttachmentPopoverAnchorLayout { static func sourceRect( anchorBounds: CGRect, keyboardDismissalOffset: CGFloat, - isExpanded: Bool + isExpanded: Bool, + horizontalOffset: CGFloat = 0 ) -> CGRect { anchorBounds.offsetBy( - dx: 0, + dx: horizontalOffset, dy: keyboardDismissalOffset + (isExpanded ? expandedVerticalOffset : 0) ) @@ -125,7 +126,15 @@ final class NativeAttachmentPopoverCoordinator: NSObject { height: CGFloat(truncating: height) ) DispatchQueue.main.async { [weak self] in - result(self?.presentPopover(sourceRect: sourceRect) ?? false) + let cameraCenterX = (arguments["cameraCenterX"] as? NSNumber).map { + CGFloat(truncating: $0) + } + result( + self?.presentPopover( + sourceRect: sourceRect, + cameraCenterX: cameraCenterX + ) ?? false + ) } case "dismiss": DispatchQueue.main.async { [weak self] in @@ -146,7 +155,7 @@ final class NativeAttachmentPopoverCoordinator: NSObject { } @MainActor - private func presentPopover(sourceRect: CGRect) -> Bool { + private func presentPopover(sourceRect: CGRect, cameraCenterX: CGFloat?) -> Bool { guard #available(iOS 26.0, *) else { return false } guard presentedController == nil else { return true } let rootViewController = @@ -199,7 +208,8 @@ final class NativeAttachmentPopoverCoordinator: NSObject { ) let controller = NativeAttachmentPopoverViewController( channel: channel, - expandedWidth: availableWidth + expandedWidth: availableWidth, + cameraHorizontalOffset: cameraCenterX.map { $0 - sourceRect.midX } ?? 0 ) controller.modalPresentationStyle = .popover controller.preferredTransition = .zoom { [weak anchorView] _ in diff --git a/mobile/ios/Runner/NativePhotoZoomCoordinator.swift b/mobile/ios/Runner/NativePhotoZoomCoordinator.swift index 67ca57a1f7..1f0666ecb8 100644 --- a/mobile/ios/Runner/NativePhotoZoomCoordinator.swift +++ b/mobile/ios/Runner/NativePhotoZoomCoordinator.swift @@ -68,6 +68,12 @@ final class NativePhotoZoomCoordinator { canDelete: args["canDelete"] as? Bool ?? false, videoIndices: Set(args["videoIndices"] as? [Int] ?? []) ) + if let center = args["railCenterX"] as? Double, + let width = args["railWindowWidth"] as? Double, + let height = args["railWindowHeight"] as? Double, + [center, width, height].allSatisfy({ $0.isFinite }), width > 0, height > 0 { + controller.sourceRailGeometry = (CGSize(width: width, height: height), CGFloat(center)) + } controller.request = { [weak self] method, index, action, completion in var payload: [String: Any] = ["session": session, "index": index] if let action { payload["action"] = action } @@ -149,7 +155,7 @@ private final class NativePhotoZoomViewController: UIViewController, UIPageViewC private let indicator = UIPageControl() private let close = UIButton(type: .system) private let navigationSizingBar = UINavigationBar() - private var closeCenterConstraint: NSLayoutConstraint? + private let pageContainer = UIView() private let reply = UIButton(type: .system) private let more = UIButton(type: .system) private let labels: [String] @@ -167,6 +173,7 @@ private final class NativePhotoZoomViewController: UIViewController, UIPageViewC var selectionFeedback = UISelectionFeedbackGenerator() private var paging = false private var acting = false + var sourceRailGeometry: (size: CGSize, centerX: CGFloat)? var onClose: ((String) -> Void)? var request: ((String, Int, String?, @escaping FlutterResult) -> Void)? var onSelection: ((UIImage?, [String: Any]?) -> Void)? @@ -211,7 +218,6 @@ private final class NativePhotoZoomViewController: UIViewController, UIPageViewC indicator.pageIndicatorTintColor = .gray indicator.accessibilityLabel = videoIndices.isEmpty ? "Photo" : "Attachment" indicator.addTarget(self, action: #selector(selectPage), for: .valueChanged) - let pageContainer = UIView() let pageSurface: UIVisualEffectView if #available(iOS 26.0, *) { let glass = UIGlassEffect(style: .regular) @@ -240,36 +246,72 @@ private final class NativePhotoZoomViewController: UIViewController, UIPageViewC indicator.topAnchor.constraint(equalTo: pageSurface.contentView.topAnchor), indicator.bottomAnchor.constraint(equalTo: pageSurface.contentView.bottomAnchor), ]) - let controls = UIStackView(arrangedSubviews: [reply, pageContainer, more]) - controls.axis = .horizontal; controls.alignment = .center; controls.spacing = 8 - view.addSubview(close); view.addSubview(controls) - pager.view.translatesAutoresizingMaskIntoConstraints = false + // Keep all controls in one hierarchy while the window folds or rotates. + // The photo surface can extend behind the rail without moving its pages. + for control in [close, reply, more, pageContainer] { view.addSubview(control) } pager.view.clipsToBounds = true - close.translatesAutoresizingMaskIntoConstraints = false - controls.translatesAutoresizingMaskIntoConstraints = false - let closeCenter = close.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) - closeCenterConstraint = closeCenter - NSLayoutConstraint.activate([ - // Match the existing gallery: fit photos between the toolbar bands. - pager.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 56), - pager.view.bottomAnchor.constraint(equalTo: controls.topAnchor, constant: -16), - pager.view.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), - pager.view.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), - closeCenter, - close.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), - close.widthAnchor.constraint(equalToConstant: 44), close.heightAnchor.constraint(equalToConstant: 44), - reply.widthAnchor.constraint(equalToConstant: 44), reply.heightAnchor.constraint(equalToConstant: 44), - more.widthAnchor.constraint(equalToConstant: 44), more.heightAnchor.constraint(equalToConstant: 44), - indicator.heightAnchor.constraint(greaterThanOrEqualToConstant: 44), - controls.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16), - controls.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16), - controls.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -12), - ]) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() - // Ask UIKit for its compact navigation height, including the current OS metrics. - closeCenterConstraint?.constant = navigationSizingBar.sizeThatFits(view.bounds.size).height / 2 + layoutGallery(insets: view.safeAreaInsets) + } + func layoutGallery(insets: UIEdgeInsets) { + let bounds = view.bounds + let right = insets.right > 0 && insets.left == 0 + let left = insets.left > 0 && insets.right == 0 + let inRail = insets.top == 0 && (right || left) + let safe = bounds.inset(by: insets) + let bottom = safe.maxY - 56 + let indicatorBounds = inRail ? bounds : safe + pageContainer.frame = CGRect(x: indicatorBounds.minX + 68, y: bottom, + width: max(0, indicatorBounds.width - 136), height: 44) + if inRail { + pager.view.frame = bounds + let width = right ? insets.right : insets.left + var centerX = right ? bounds.maxX - width / 2 : width / 2 + var top: CGFloat = min(bounds.width, bounds.height) >= 600 ? 110 : 170 + var railBottom = bounds.maxY - max(insets.bottom, 12) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *), let window = view.window { + let strip = CGRect(x: right ? window.bounds.maxX - width : 0, y: 0, + width: width, height: window.bounds.height) + let occlusions = window.reservedRegions(kind: .occlusion) + .filter { $0.isActive && $0.frame.intersects(strip) } + let regions = occlusions.filter { $0.frame.midY < window.bounds.midY } + .sorted { $0.frame.minY < $1.frame.minY } + let margins = window.rootViewController?.view.layoutMargins ?? .zero + let margin = right ? margins.left : margins.right + let axis = regions.first.map { $0.frame.inset(by: $0.margins).midX } + ?? (right ? window.bounds.maxX - margin - 28 : margin + 28) + centerX = view.convert(CGPoint(x: axis, y: 0), from: window).x + if let edge = occlusions.filter({ $0.frame.midY >= window.bounds.midY }).map({ $0.frame.minY }).min() { + railBottom = min(railBottom, view.convert(CGPoint(x: 0, y: edge), from: window).y - 12) + } + if let edge = regions.map({ $0.frame.maxY }).max() { + top = view.convert(CGPoint(x: 0, y: edge), from: window).y + 12 + } + } + #endif + // Reuse the app rail's measured axis while its window/side still match. + // Presentation can change UIKit's fallback margins under the modal. + if let source = sourceRailGeometry, source.size == bounds.size, + (left && (0...width).contains(source.centerX)) || + (right && (bounds.maxX - width...bounds.maxX).contains(source.centerX)) { + centerX = source.centerX + } + // Match IosNavigationMetrics.railCenter's inward optical alignment. + centerX += left ? 6 : -6 + close.frame = CGRect(x: centerX - 24, y: top + 6, width: 48, height: 48) + reply.frame = CGRect(x: centerX - 24, y: railBottom - 108, width: 48, height: 48) + more.frame = CGRect(x: centerX - 24, y: railBottom - 48, width: 48, height: 48) + } else { + pager.view.frame = CGRect(x: safe.minX, y: safe.minY + 56, + width: safe.width, height: max(0, bottom - 16 - safe.minY - 56)) + let centerY = safe.minY + navigationSizingBar.sizeThatFits(bounds.size).height / 2 + close.frame = CGRect(x: safe.maxX - 60, y: centerY - 22, width: 44, height: 44) + reply.frame = CGRect(x: safe.minX + 16, y: bottom, width: 44, height: 44) + more.frame = CGRect(x: safe.maxX - 60, y: bottom, width: 44, height: 44) + } } func shouldBeginDismissal(location: CGPoint, velocity: CGVector) -> Bool { !paging && !finishing && pager.view.frame.contains(location) diff --git a/mobile/ios/Runner/NativeProfileTextEditor.swift b/mobile/ios/Runner/NativeProfileTextEditor.swift index e0b0209b04..9e03473ba3 100644 --- a/mobile/ios/Runner/NativeProfileTextEditor.swift +++ b/mobile/ios/Runner/NativeProfileTextEditor.swift @@ -1,6 +1,9 @@ import Flutter import UIKit +// UIKit 9127.0.85 is the iOS 27.1 SDK with Duo APIs. SDK checks must +// surround runtime availability checks: older SDKs cannot resolve these symbols. + final class NativeProfileTextEditorCoordinator: NSObject, UIAdaptivePresentationControllerDelegate { @@ -28,6 +31,12 @@ final class NativeProfileTextEditorCoordinator: NSObject, _ call: FlutterMethodCall, result: @escaping FlutterResult ) { + if call.method == "presentStatus", let arguments = call.arguments as? [String: Any] { + DispatchQueue.main.async { [weak self] in + self?.presentStatus(arguments, result: result) + } + return + } guard call.method == "present" || call.method == "presentChannel" || call.method == "presentProject" else { result(FlutterMethodNotImplemented) return @@ -79,6 +88,39 @@ final class NativeProfileTextEditorCoordinator: NSObject, } } + @MainActor + private func presentStatus(_ arguments: [String: Any], result: @escaping FlutterResult) { + guard presentedController == nil else { + result(FlutterError(code: "already_presented", message: "An editor is already open.", details: nil)) + return + } + guard let presenter = topViewController(from: parentViewController ?? activeWindowRootViewController()) else { + result(FlutterError(code: "presentation_failed", message: "Unable to present status editor.", details: nil)) + return + } + let editor = NativeStatusEditorViewController( + configuration: arguments, + onChooseEmoji: { [weak self] completion in + self?.channel.invokeMethod("chooseStatusEmoji", arguments: nil) { value in + completion(value as? String) + } + }, + onCancel: { [weak self] in self?.finish(value: nil) }, + onSet: { [weak self] value in self?.finish(value: value) } + ) + let navigation = UINavigationController(rootViewController: editor) + navigation.overrideUserInterfaceStyle = arguments["brightness"] as? String == "dark" ? .dark : .light + if UIDevice.current.userInterfaceIdiom == .pad { + navigation.modalPresentationStyle = .formSheet + } + configureDuoPlacement(navigation, presenter: presenter) + pendingResult = result + presentedController = navigation + presenter.present(navigation, animated: true) { [weak self] in + navigation.presentationController?.delegate = self + } + } + @MainActor private func present( title: String, @@ -157,6 +199,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, navigationController.sheetPresentationController?.detents = [.large()] } + configureDuoPlacement(navigationController, presenter: presenter) pendingResult = result presentedController = navigationController presenter.present(navigationController, animated: true) { [weak self] in @@ -164,6 +207,17 @@ final class NativeProfileTextEditorCoordinator: NSObject, } } + @MainActor + private func configureDuoPlacement(_ navigation: UINavigationController, presenter: UIViewController) { + #if canImport(UIKit, _version: 9127.0.85) + guard #available(iOS 27.1, *) else { return } + let insets = presenter.view.safeAreaInsets + guard insets.top == 0, insets.left > 0 || insets.right > 0 else { return } + navigation.sheetPresentationController?.preferredPlacement = + presenter.view.effectiveUserInterfaceLayoutDirection == .rightToLeft ? .leading : .trailing + #endif + } + @MainActor private func finish(value: Any?) { guard let controller = presentedController else { @@ -216,7 +270,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, } } -private final class NativeProfileTextEditorViewController: +final class NativeProfileTextEditorViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate @@ -352,6 +406,12 @@ private final class NativeProfileTextEditorViewController: target: self, action: #selector(setTapped) ) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + navigationItem.leftBarButtonItem?.axisBehavior = .verticalPreferred + navigationItem.rightBarButtonItem?.axisBehavior = .verticalPreferred + } + #endif updateNavigation() } diff --git a/mobile/ios/Runner/NativeStatusEditor.swift b/mobile/ios/Runner/NativeStatusEditor.swift new file mode 100644 index 0000000000..dc521812ad --- /dev/null +++ b/mobile/ios/Runner/NativeStatusEditor.swift @@ -0,0 +1,238 @@ +import UIKit + +// UIKit 9127.0.85 is the iOS 27.1 SDK with Duo APIs. SDK checks must +// surround runtime availability checks: older SDKs cannot resolve these symbols. + +/// Status uses the same navigation-controller sheet as the profile text forms. +final class NativeStatusEditorViewController: UITableViewController, UITextFieldDelegate { + let statusField = UITextField() + let emojiField = StatusEmojiTextField() + let datePicker = UIDatePicker() + private let configuration: [String: Any] + private let onChooseEmoji: (@escaping (String?) -> Void) -> Void + private let onCancel: () -> Void + private let onSet: ([String: Any]) -> Void + private var duration: Int + private let durations = [3600, 28800, 86400, 604800] + private let durationLabels = ["1 hour", "8 hours", "1 day", "1 week", "Custom"] + private let presets = [("🗣️", "In a meeting"), ("🚌", "Commuting"), + ("🤒", "Out sick"), ("🏖️", "Vacationing"), ("🏠", "Working remotely")] + + init(configuration: [String: Any], onChooseEmoji: @escaping (@escaping (String?) -> Void) -> Void = { $0(nil) }, onCancel: @escaping () -> Void, + onSet: @escaping ([String: Any]) -> Void) { + self.configuration = configuration + self.onChooseEmoji = onChooseEmoji + self.onCancel = onCancel + self.onSet = onSet + duration = configuration["duration"] as? Int ?? 86400 + super.init(style: .insetGrouped) + title = "Set a status" + } + + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func viewDidLoad() { + super.viewDidLoad() + view.tintColor = .label + navigationController?.view.tintColor = .label + navigationController?.navigationBar.tintColor = .label + let pageColor = color("pageBackgroundArgb", fallback: .systemGroupedBackground) + tableView.backgroundColor = pageColor + // Space the form below the bar without moving UIKit’s native rail actions. + tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 16)) + NavigationTopEdge.configure(tableView, item: navigationItem) + navigationItem.leftBarButtonItem = UIBarButtonItem( + barButtonSystemItem: .close, target: self, action: #selector(cancel)) + navigationItem.leftBarButtonItem?.accessibilityLabel = "Close" + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Set", style: .done, target: self, action: #selector(save)) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + navigationItem.leftBarButtonItem?.axisBehavior = .verticalPreferred + navigationItem.rightBarButtonItem?.axisBehavior = .verticalPreferred + } + #endif + statusField.text = configuration["text"] as? String ?? "" + statusField.placeholder = "What’s your status?" + statusField.accessibilityLabel = "Status" + statusField.returnKeyType = .done + statusField.delegate = self + emojiField.text = configuration["emoji"] as? String ?? "" + emojiField.placeholder = "Emoji" + emojiField.accessibilityLabel = "Status emoji" + emojiField.autocorrectionType = .no + emojiField.autocapitalizationType = .none + emojiField.clearButtonMode = .whileEditing + for field in [statusField, emojiField] { + field.font = .preferredFont(forTextStyle: .body) + field.adjustsFontForContentSizeCategory = true + field.addTarget(self, action: #selector(changed), for: .editingChanged) + } + datePicker.tintColor = .label + datePicker.datePickerMode = .dateAndTime + datePicker.preferredDatePickerStyle = .compact + datePicker.minimumDate = Date().addingTimeInterval(300) + let expiration = configuration["expiresAt"] as? Double ?? Date().addingTimeInterval(86400).timeIntervalSince1970 + datePicker.date = max(Date(timeIntervalSince1970: expiration), datePicker.minimumDate ?? Date()) + datePicker.accessibilityLabel = "Custom expiration" + tableView.keyboardDismissMode = .interactive + changed() + } + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + if configuration["saveError"] as? Bool == true, !didShowError { + didShowError = true + let alert = UIAlertController(title: "Couldn’t save status", message: "Your changes are still here. Please try again.", preferredStyle: .alert) + alert.view.tintColor = .label + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } + } + + private var didShowError = false + + override func numberOfSections(in tableView: UITableView) -> Int { + configuration["hasExistingStatus"] as? Bool == true ? 4 : 3 + } + + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + switch section { + case 0: return 2 + case 1: return duration == 0 ? 2 : 1 + case 2: return presets.count + default: return 1 + } + } + + override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + section == 1 ? "Duration" : section == 2 ? "Quick statuses" : nil + } + + private func color(_ key: String, fallback: UIColor) -> UIColor { + guard let value = configuration[key] as? NSNumber else { return fallback } + let argb = value.uint32Value + return UIColor(red: CGFloat((argb >> 16) & 255) / 255, + green: CGFloat((argb >> 8) & 255) / 255, + blue: CGFloat(argb & 255) / 255, + alpha: CGFloat((argb >> 24) & 255) / 255) + } + + private func embed(_ content: UIView, in cell: UITableViewCell) { + content.translatesAutoresizingMaskIntoConstraints = false + cell.contentView.addSubview(content) + NSLayoutConstraint.activate([ + content.leadingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.leadingAnchor), + content.trailingAnchor.constraint(equalTo: cell.contentView.layoutMarginsGuide.trailingAnchor), + content.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 12), + content.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -12), + ]) + } + + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = UITableViewCell(style: .value1, reuseIdentifier: nil) + cell.backgroundColor = color("containerBackgroundArgb", fallback: .secondarySystemGroupedBackground) + cell.selectionStyle = .none + switch indexPath.section { + case 0: + if indexPath.row == 0 { + embed(statusField, in: cell) + } else { + let choose = UIButton(type: .system) + choose.setTitle("Choose emoji", for: .normal) + choose.addAction(UIAction { [weak self, weak choose] _ in + guard let self else { return } + self.view.endEditing(true) + choose?.isEnabled = false + choose?.setTitle("Loading…", for: .normal) + self.onChooseEmoji { [weak self, weak choose] value in + choose?.isEnabled = true + choose?.setTitle("Choose emoji", for: .normal) + guard let self, let value else { return } + self.emojiField.text = value + self.changed() + } + }, for: .touchUpInside) + let row = UIStackView(arrangedSubviews: [emojiField, choose]) + row.spacing = 12 + choose.setContentHuggingPriority(.required, for: .horizontal) + embed(row, in: cell) + } + case 1: + if indexPath.row == 1 { + embed(datePicker, in: cell) + } else { + cell.textLabel?.text = "Clear after" + let button = UIButton(type: .system) + let selected = durations.firstIndex(of: duration) ?? 4 + button.setTitle(durationLabels[selected], for: .normal) + button.accessibilityLabel = "Duration" + button.showsMenuAsPrimaryAction = true + button.menu = UIMenu(children: durationLabels.enumerated().map { index, label in + UIAction(title: label, state: index == selected ? .on : .off) { [weak self] _ in + guard let self else { return } + self.duration = index < self.durations.count ? self.durations[index] : 0 + self.tableView.reloadSections(IndexSet(integer: 1), with: .automatic) + } + }) + button.sizeToFit() + cell.accessoryView = button + } + case 2: + cell.textLabel?.text = "\(presets[indexPath.row].0) \(presets[indexPath.row].1)" + cell.accessibilityTraits.insert(.button) + cell.selectionStyle = .default + default: + cell.textLabel?.text = "Clear status" + cell.textLabel?.textColor = .systemRed + cell.accessibilityTraits.insert(.button) + cell.selectionStyle = .default + } + return cell + } + + override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + if indexPath.section == 2 { + emojiField.text = presets[indexPath.row].0 + statusField.text = presets[indexPath.row].1 + changed() + } else if indexPath.section == 3 { + submit(clear: true) + } + } + + @objc private func changed() { + navigationItem.rightBarButtonItem?.isEnabled = + !(statusField.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + || !(emojiField.text ?? "").isEmpty + } + + @objc private func cancel() { onCancel() } + @objc private func save() { + guard navigationItem.rightBarButtonItem?.isEnabled == true else { return } + submit(clear: false) + } + + private func submit(clear: Bool) { + onSet([ + "text": statusField.text ?? "", "emoji": emojiField.text ?? "", + "duration": duration, "clear": clear, + "expiresAt": duration == 0 ? datePicker.date.timeIntervalSince1970 + : Date().addingTimeInterval(TimeInterval(duration)).timeIntervalSince1970, + ]) + } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + save() + return true + } +} + +/// Open the system's complete emoji keyboard when it is enabled. +final class StatusEmojiTextField: UITextField { + override var textInputContextIdentifier: String? { "buzz.status.emoji" } + override var textInputMode: UITextInputMode? { + UITextInputMode.activeInputModes.first { $0.primaryLanguage == "emoji" } ?? super.textInputMode + } +} diff --git a/mobile/ios/RunnerTests/ProfileSetupRecoveryTests.swift b/mobile/ios/RunnerTests/ProfileSetupRecoveryTests.swift index 5e6c927e37..7cdbef365a 100644 --- a/mobile/ios/RunnerTests/ProfileSetupRecoveryTests.swift +++ b/mobile/ios/RunnerTests/ProfileSetupRecoveryTests.swift @@ -5,6 +5,114 @@ import XCTest @testable import Buzz final class ProfileSetupRecoveryTests: XCTestCase { + @MainActor + func testNativeEditorsPreferRightPaneOnlyWithDuoRail() async throws { + for duo in [false, true] { + for method in ["presentStatus", "present"] { + let messenger = ProfileSetupTestMessenger() + let parent = SheetPlacementPresenter() + parent.view = SheetPlacementView(duo: duo) + let coordinator = NativeProfileTextEditorCoordinator( + messenger: messenger, parentViewController: parent) + defer { withExtendedLifetime(coordinator) {} } + messenger.invoke(method, arguments: [ + "title": "Profile description", "initialValue": "", "placeholder": "", + "multiline": true, "brightness": "light", + "pageBackgroundArgb": 0xFFFFFFFF, "containerBackgroundArgb": 0xFFF0F0F0, + "containerCornerRadius": 16, + ]) + await withCheckedContinuation { continuation in + DispatchQueue.main.async { continuation.resume() } + } + let sheet = try XCTUnwrap(parent.captured?.sheetPresentationController) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + XCTAssertEqual(sheet.preferredPlacement, duo ? .trailing : .automatic) + } + #endif + XCTAssertEqual(sheet.detents.map(\.identifier), [.large]) + XCTAssertNil(sheet.sourceView) + } + } + } + + @MainActor + func testStatusFormPresetsCustomExpirationClearAndRailActions() throws { + var values: [[String: Any]] = [] + var cancelled = false + let expiration = Date().addingTimeInterval(172800) + let editor = NativeStatusEditorViewController( + configuration: ["text": "", "emoji": "", "duration": 0, + "expiresAt": expiration.timeIntervalSince1970, + "hasExistingStatus": true], + onChooseEmoji: { $0(":buzz:") }, + onCancel: { cancelled = true }, onSet: { values.append($0) }) + let navigation = UINavigationController(rootViewController: editor) + navigation.loadViewIfNeeded() + editor.loadViewIfNeeded() + for style in [UIUserInterfaceStyle.light, .dark] { + let traits = UITraitCollection(userInterfaceStyle: style) + XCTAssertEqual(editor.view.tintColor.resolvedColor(with: traits), UIColor.label.resolvedColor(with: traits)) + XCTAssertEqual(navigation.navigationBar.tintColor.resolvedColor(with: traits), UIColor.label.resolvedColor(with: traits)) + XCTAssertEqual(editor.datePicker.tintColor.resolvedColor(with: traits), UIColor.label.resolvedColor(with: traits)) + } + let cancel = try XCTUnwrap(editor.navigationItem.leftBarButtonItem) + let submit = try XCTUnwrap(editor.navigationItem.rightBarButtonItem) + XCTAssertEqual(cancel.accessibilityLabel, "Close") + XCTAssertFalse(submit.isEnabled) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + XCTAssertEqual(cancel.axisBehavior, .verticalPreferred) + XCTAssertEqual(submit.axisBehavior, .verticalPreferred) + } + #endif + XCTAssertEqual(editor.tableView(editor.tableView, numberOfRowsInSection: 1), 2) + editor.tableView(editor.tableView, didSelectRowAt: IndexPath(row: 0, section: 2)) + XCTAssertTrue(submit.isEnabled) + XCTAssertEqual(editor.statusField.text, "In a meeting") + let emojiCell = editor.tableView(editor.tableView, cellForRowAt: IndexPath(row: 1, section: 0)) + let chooseEmoji = try XCTUnwrap(descendants(emojiCell).compactMap { $0 as? UIButton }.first { $0.title(for: .normal) == "Choose emoji" }) + chooseEmoji.sendActions(for: .touchUpInside) + XCTAssertEqual(editor.emojiField.text, ":buzz:") + UIApplication.shared.sendAction(try XCTUnwrap(submit.action), to: submit.target, from: submit, for: nil) + XCTAssertEqual(values.last?["text"] as? String, "In a meeting") + XCTAssertEqual(values.last?["emoji"] as? String, ":buzz:") + XCTAssertEqual(try XCTUnwrap(values.last?["expiresAt"] as? Double), expiration.timeIntervalSince1970, accuracy: 1) + editor.tableView(editor.tableView, didSelectRowAt: IndexPath(row: 0, section: 3)) + XCTAssertEqual(values.last?["clear"] as? Bool, true) + UIApplication.shared.sendAction(try XCTUnwrap(cancel.action), to: cancel.target, from: cancel, for: nil) + XCTAssertTrue(cancelled) + } + + @MainActor + func testNativeProfileFieldsRetainCancelAndPreferVerticalControls() throws { + for multiline in [false, true] { + var cancelled = false + let editor = NativeProfileTextEditorViewController( + title: multiline ? "Profile description" : "Display name", + initialValue: "Original", placeholder: "Text", multiline: multiline, + pageBackgroundColor: .systemBackground, containerBackgroundColor: .secondarySystemBackground, + containerCornerRadius: 16, allowUnchangedSubmission: false, + channelDescription: nil, originalName: nil, originalDescription: nil, + canEditDetails: true, canEditCanvas: false, canvasContent: "", canvasLoaded: false, + isProjectEditor: false, onCancel: { cancelled = true }, onSet: { _ in } + ) + editor.loadViewIfNeeded() + let cancel = try XCTUnwrap(editor.navigationItem.leftBarButtonItem) + let submit = try XCTUnwrap(editor.navigationItem.rightBarButtonItem) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + XCTAssertEqual(cancel.axisBehavior, .verticalPreferred) + XCTAssertEqual(submit.axisBehavior, .verticalPreferred) + } + #endif + XCTAssertTrue(cancel.isEnabled) + XCTAssertFalse(submit.isEnabled) + UIApplication.shared.sendAction(try XCTUnwrap(cancel.action), to: cancel.target, from: cancel, for: nil) + XCTAssertTrue(cancelled) + } + } + @MainActor func testSelectedEditorIconsContrastInBothAppearances() throws { for dark in [false, true] { @@ -266,3 +374,26 @@ private final class ProfileSetupTestMessenger: NSObject, FlutterBinaryMessenger } } } + + +private final class SheetPlacementView: UIView { + let duo: Bool + init(duo: Bool) { + self.duo = duo + super.init(frame: CGRect(x: 0, y: 0, width: 932, height: 656)) + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + override var safeAreaInsets: UIEdgeInsets { + duo ? UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 84) + : UIEdgeInsets(top: 62, left: 0, bottom: 34, right: 0) + } +} + +private final class SheetPlacementPresenter: UIViewController { + var captured: UIViewController? + override func present(_ viewControllerToPresent: UIViewController, + animated: Bool, completion: (() -> Void)? = nil) { + captured = viewControllerToPresent + completion?() + } +} diff --git a/mobile/ios/RunnerTests/RunnerTests.swift b/mobile/ios/RunnerTests/RunnerTests.swift index 7cd26d0c41..b6d6c2abca 100644 --- a/mobile/ios/RunnerTests/RunnerTests.swift +++ b/mobile/ios/RunnerTests/RunnerTests.swift @@ -8,6 +8,91 @@ import XCTest class RunnerTests: XCTestCase { + @MainActor + func testSectionMenuKeepsDisabledSelectionAndDestructiveAttributes() throws { + let platform = NavigationGlassButtonFactory(messenger: NavigationTestMessenger()).create( + withFrame: CGRect(x: 0, y: 0, width: 44, height: 44), viewIdentifier: 999996, + arguments: ["icon": "more", "plain": true, "iconSize": 14, + "menu": [["id": 0, "label": "Move up", "enabled": false], + ["id": 1, "label": "Sort: Recent", "enabled": true, "checked": true], + ["id": 2, "label": "Delete section", "enabled": true, "destructive": true]]] + ) + let button = try XCTUnwrap(descendants(of: platform.view()).compactMap { $0 as? NavigationGlassButton }.first) + XCTAssertTrue(button.showsMenuAsPrimaryAction) + XCTAssertEqual(button.configuration?.image?.size.width, 14) + let group = try XCTUnwrap(button.menu?.children.first as? UIMenu) + let actions = group.children.compactMap { $0 as? UIAction } + XCTAssertEqual(actions.count, 3) + XCTAssertTrue(actions[0].attributes.contains(.disabled)) + XCTAssertEqual(actions[1].state, .on) + XCTAssertTrue(actions[2].attributes.contains(.destructive)) + } + + @MainActor + func testStaticPaneTitleKeepsLargeTypeAndWrapsWithinPane() throws { + let messenger = NavigationTestMessenger() + let parent = UIViewController() + let title = IosNavigationBarFactory(messenger: messenger, parent: parent).create( + withFrame: CGRect(x: 0, y: 0, width: 290, height: 669), viewIdentifier: 999991, + arguments: ["title": "Invite to community", "standaloneLargeTitle": true] + ) + let view = title.view() + parent.view.addSubview(view) + view.setNeedsLayout() + view.layoutIfNeeded() + let label = try XCTUnwrap(descendants(of: view).compactMap { $0 as? UILabel }.first { $0.text == "Invite to community" }) + XCTAssertEqual(label.numberOfLines, 0) + XCTAssertTrue(label.font.fontDescriptor.symbolicTraits.contains(.traitBold)) + XCTAssertEqual(label.font.pointSize, UIFont.preferredFont(forTextStyle: .largeTitle).pointSize) + XCTAssertTrue(label.accessibilityTraits.contains(.header)) + XCTAssertGreaterThan(label.bounds.height, label.font.lineHeight) + XCTAssertLessThanOrEqual(label.frame.maxX, view.bounds.width - 16) + view.frame.size.width = 200 + view.setNeedsLayout() + view.layoutIfNeeded() + XCTAssertLessThanOrEqual(label.frame.maxX, 184) + XCTAssertGreaterThan(label.bounds.height, label.font.lineHeight) + } + + @MainActor + func testHorizontalMenuAttachesAboveItsButton() { + let button = NavigationGlassButton(frame: CGRect(x: 0, y: 0, width: 112, height: 56)) + button.opensMenuAbove = true + let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil) + XCTAssertEqual(button.menuAttachmentPoint(for: configuration), CGPoint(x: 56, y: 0)) + } + + @MainActor + func testNavigationGlassMergesAndRestoresInBothDirections() async { + for vertical in [false, true] { + let glass = MergingNavigationGlass(frame: CGRect( + x: 0, y: 0, width: vertical ? 56 : 256, height: vertical ? 200 : 56 + )) + glass.vertical = vertical + glass.setNeedsLayout() + glass.layoutIfNeeded() + XCTAssertEqual(glass.centerSurface.bounds.width, vertical ? 56 : 112) + XCTAssertEqual(glass.centerSurface.center, CGPoint(x: glass.bounds.midX, y: glass.bounds.midY)) + glass.setMenuOpen(true, animator: nil) + let merged = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + glass.leftSurface.alpha == 0 && glass.rightSurface.alpha == 0 + }, object: nil) + await fulfillment(of: [merged], timeout: 2) + XCTAssertEqual(glass.leftSurface.transform.tx, vertical ? 0 : 100, accuracy: 0.01) + XCTAssertEqual(glass.leftSurface.transform.ty, vertical ? 72 : 0, accuracy: 0.01) + XCTAssertEqual(glass.rightSurface.transform.tx, vertical ? 0 : -100, accuracy: 0.01) + XCTAssertEqual(glass.rightSurface.transform.ty, vertical ? -72 : 0, accuracy: 0.01) + glass.setMenuOpen(false, animator: nil) + glass.setMenuOpen(true, animator: nil) + glass.setMenuOpen(false, animator: nil) + let restored = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + glass.leftSurface.alpha == 1 && glass.rightSurface.alpha == 1 && + glass.leftSurface.transform == .identity && glass.rightSurface.transform == .identity + }, object: nil) + await fulfillment(of: [restored], timeout: 2) + } + } + @MainActor func testRejectedCommunityEntryPresentationCompletesAndAllowsRetry() async throws { let messenger = NavigationTestMessenger() @@ -46,6 +131,7 @@ class RunnerTests: XCTestCase { let messenger = NavigationTestMessenger() let parent = UIViewController() let window = UIWindow(frame: UIScreen.main.bounds) + window.windowScene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) window.rootViewController = parent window.makeKeyAndVisible() defer { window.isHidden = true } @@ -65,10 +151,11 @@ class RunnerTests: XCTestCase { XCTAssertFalse(scroll.topEdgeEffect.isHidden) XCTAssertTrue(scroll.bottomEdgeEffect.isHidden) let material = try XCTUnwrap(bar.view().subviews.first as? UIVisualEffectView) - XCTAssertTrue(material.isHidden) + XCTAssertFalse(material.isHidden, "Custom headers retain the same material as large-title headers") // Filter collapse changes the protected area without moving the Flutter // controls or adding a second accessibility owner. - let compactHeight = bar.view().safeAreaInsets.top + navigation.navigationBar.bounds.height + // Flutter reserves at least 44 points even when Duo hides the native row. + let compactHeight = bar.view().safeAreaInsets.top + max(44, navigation.navigationBar.bounds.height) for height in [compactHeight + 48, compactHeight] { bar.view().frame.size.height = height bar.view().setNeedsLayout() @@ -81,21 +168,113 @@ class RunnerTests: XCTestCase { @MainActor func testNativeSheetTopEdgeIsSoftWithoutAnOpaqueNavigationFill() throws { guard #available(iOS 26.0, *) else { return } - let picker = NativeAddMembersViewController( - state: ["users": [], "selected": [], "query": "", "loading": false], - loadAvatar: { _, _, reply in reply(nil) }, - send: { _, _ in } + let sheets: [UITableViewController] = [ + NativeAddMembersViewController( + state: ["users": [], "selected": [], "query": "", "loading": false], + loadAvatar: { _, _, reply in reply(nil) }, + send: { _, _ in } + ), + NativeStatusEditorViewController(configuration: [:], onCancel: {}, onSet: { _ in }), + ] + for sheet in sheets { + sheet.loadViewIfNeeded() + let scroll = sheet.tableView! + let item = sheet.navigationItem + XCTAssertEqual(scroll.topEdgeEffect.style, .soft) + XCTAssertTrue(scroll.bottomEdgeEffect.isHidden) + let appearance = try XCTUnwrap(item.standardAppearance) + XCTAssertLessThan(appearance.backgroundColor?.cgColor.alpha ?? 0, 1) + XCTAssertEqual(item.scrollEdgeAppearance, appearance) + XCTAssertEqual(item.compactAppearance, appearance) + XCTAssertEqual(item.compactScrollEdgeAppearance, appearance) + } + } + + @MainActor + func testListHeaderActionsAlignToPaneWhileLargeTitleRemainsVisible() throws { + let parent = UIViewController() + let window = UIWindow(windowScene: try XCTUnwrap( + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)) + window.rootViewController = parent + window.makeKeyAndVisible() + defer { window.isHidden = true } + let factory = IosNavigationBarFactory(messenger: NavigationTestMessenger(), parent: parent) + let bar = factory.create( + withFrame: CGRect(x: 0, y: 0, width: 400, height: 164), + viewIdentifier: 999995, + arguments: [ + "title": "Inbox", "largeTitle": true, "horizontalControls": true, + "alignCollapsedTitleToLeading": true, + "actions": [ + ["id": "filter", "label": "Filter inbox", "symbol": "line.3.horizontal.decrease", + "enabled": true, "keepInHeaderOnDuo": true], + ["id": "options", "label": "Inbox options", "symbol": "ellipsis", + "enabled": true, "keepInHeaderOnDuo": true], + ], + ]) + parent.view.addSubview(bar.view()) + let navigation = try XCTUnwrap(parent.children.first as? UINavigationController) + for width: CGFloat in [320, 400] { + bar.view().frame.size.width = width + bar.view().setNeedsLayout() + bar.view().layoutIfNeeded() + XCTAssertFalse(navigation.view.isHidden) + let material = try XCTUnwrap(descendants(of: bar.view()).first { + $0.accessibilityIdentifier == "navigation-scroll-material" + }) + XCTAssertFalse(material.isHidden, "Large pane titles retain the graduated native material") + if #available(iOS 27.0, *) { + let scroll = try XCTUnwrap(navigation.topViewController?.view as? UIScrollView) + XCTAssertFalse(scroll.topEdgeEffect.isHidden) + XCTAssertEqual(scroll.topEdgeEffect.style, .soft) + } + XCTAssertTrue(navigation.navigationBar.prefersLargeTitles) + let button = try XCTUnwrap(descendants(of: bar.view()).compactMap { $0 as? UIButton } + .first { $0.accessibilityLabel == "Inbox options" }) + let frame = button.convert(button.bounds, to: bar.view()) + XCTAssertEqual(frame.maxX, width - 20, accuracy: 1) + XCTAssertLessThan(frame.maxY, 90) + // Flutter shrinks the header as Inbox scrolls. Its compact title must + // stay centered on the action row instead of the whole shrinking view. + for height: CGFloat in [164, 100, 68] { + bar.view().frame.size.height = height + bar.view().setNeedsLayout() + bar.view().layoutIfNeeded() + let title = try XCTUnwrap(descendants(of: bar.view()).compactMap { $0 as? UILabel } + .filter { $0.text == "Inbox" && !$0.isDescendant(of: navigation.view) }.first) + XCTAssertEqual(title.convert(title.bounds, to: bar.view()).midY, + button.convert(button.bounds, to: bar.view()).midY, accuracy: 1) + } + } + } + + + @MainActor + func testConcentricSurfaceReportsEachResolvedCornerAfterLayout() throws { + guard #available(iOS 26.0, *) else { return } + let messenger = NavigationTestMessenger() + let platformView = ConcentricSheetSurfacePlatformView( + frame: CGRect(x: 0, y: 0, width: 400, height: 300), + viewIdentifier: 73, + messenger: messenger, + arguments: ["independentCorners": true] ) - picker.loadViewIfNeeded() - let scroll = picker.tableView! - let item = picker.navigationItem - XCTAssertEqual(scroll.topEdgeEffect.style, .soft) - XCTAssertTrue(scroll.bottomEdgeEffect.isHidden) - let appearance = try XCTUnwrap(item.standardAppearance) - XCTAssertLessThan(appearance.backgroundColor?.cgColor.alpha ?? 0, 1) - XCTAssertEqual(item.scrollEdgeAppearance, appearance) - XCTAssertEqual(item.compactAppearance, appearance) - XCTAssertEqual(item.compactScrollEdgeAppearance, appearance) + let root = platformView.view() + let surface = try XCTUnwrap(root.subviews.first) + XCTAssertEqual(surface.layer.cornerCurve, .continuous) + for radii: [CGFloat] in [[24, 24, 62, 48], [48, 62, 24, 24]] { + surface.cornerConfiguration = .corners( + topLeftRadius: .fixed(radii[0]), topRightRadius: .fixed(radii[1]), + bottomLeftRadius: .fixed(radii[2]), bottomRightRadius: .fixed(radii[3]) + ) + root.setNeedsLayout() + root.layoutIfNeeded() + let reported = try XCTUnwrap(messenger.cornerRadii) + XCTAssertEqual(reported["topLeft"], radii[0]) + XCTAssertEqual(reported["topRight"], radii[1]) + XCTAssertEqual(reported["bottomLeft"], radii[2]) + XCTAssertEqual(reported["bottomRight"], radii[3]) + } } @@ -302,6 +481,17 @@ class RunnerTests: XCTestCase { XCTAssertEqual(label.traitCollection.userInterfaceStyle, dark ? .dark : .light) } } + var paneArguments = arguments + paneArguments["safeTop"] = 0 + paneArguments["centerTitleInPane"] = true + paneArguments["portraitTopPadding"] = 12 + paneArguments["alwaysFrosted"] = true + messenger.configure(paneArguments) + bar.view().layoutIfNeeded() + let paneTitle = try XCTUnwrap(bar.view().subviews.compactMap { $0 as? NavigationTitleView }.first) + XCTAssertEqual(paneTitle.frame.minY, 12 + 56) + let paneMaterial = try XCTUnwrap(bar.view().subviews.first as? UIVisualEffectView) + XCTAssertEqual(paneMaterial.frame, bar.view().bounds, "Portrait panes retain the full native navigation backdrop") var animatedArguments = arguments animatedArguments["titleHasAnimatedPortrait"] = true messenger.configure(animatedArguments) @@ -707,44 +897,91 @@ class RunnerTests: XCTestCase { } @MainActor - func testConversationUsesNativeSoftEdgeWithoutExpandingHitArea() throws { + func testDuoConversationUsesNativeSoftEdgeWithoutExpandingHitArea() throws { let parent = UIViewController() let window = UIWindow(frame: UIScreen.main.bounds) + window.windowScene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) window.rootViewController = parent window.makeKeyAndVisible() + parent.view.backgroundColor = .systemRed defer { window.isHidden = true } let messenger = NavigationTestMessenger() let factory = IosNavigationBarFactory(messenger: messenger, parent: parent) let bar = factory.create( withFrame: CGRect(x: 0, y: 0, width: window.bounds.width, height: 120), viewIdentifier: 999993, - arguments: ["title": "general", "subtitle": "36 members", "alwaysFrosted": true]) + arguments: ["title": "general", "subtitle": "36 members", "alwaysFrosted": true, "centerTitleInPane": true]) parent.view.addSubview(bar.view()) - let navigation = try XCTUnwrap(parent.children.first as? UINavigationController) let material = try XCTUnwrap(bar.view().subviews.first as? UIVisualEffectView) for offset in [0.0, 52.0, 0.0] { + let left = offset == 52 ? 76.0 : 0.0 + let right = 76 - left + messenger.configure(["title": "A longer conversation title", "subtitle": "36 members", "alwaysFrosted": true, + "centerTitleInPane": true, "titleInsetLeft": left, "titleInsetRight": right, + "horizontalControls": true, + "actions": [["id": "project", "label": "Project", "symbol": "doc", "enabled": true], + ["id": "agent", "label": "Agent", "symbol": "person", "enabled": true]]]) messenger.scroll(to: offset) bar.view().setNeedsLayout() bar.view().layoutIfNeeded() + XCTAssertFalse(material.isHidden) + let fade = try XCTUnwrap(material.layer.mask as? CAGradientLayer) + XCTAssertEqual(fade.locations?[1].doubleValue, 0.55) if #available(iOS 27.0, *) { + let navigation = try XCTUnwrap(parent.children.first as? UINavigationController) let scroll = try XCTUnwrap(navigation.topViewController?.view as? UIScrollView) - XCTAssertEqual(scroll.topEdgeEffect.style, .soft) XCTAssertFalse(scroll.topEdgeEffect.isHidden) - XCTAssertTrue(scroll.bottomEdgeEffect.isHidden) - XCTAssertTrue(material.isHidden, "Do not stack a uniform blur over the native fade") - XCTAssertFalse(bar.view().clipsToBounds) - XCTAssertEqual(scroll.contentOffset.y, offset, accuracy: 0.5) - XCTAssertFalse(bar.view().point(inside: CGPoint(x: 20, y: 121), with: nil)) - } else if #available(iOS 26.0, *) { - let safeTop = navigation.view.safeAreaInsets.top - XCTAssertEqual(material.frame.height, safeTop > 0 ? safeTop + 6 : 0, accuracy: 0.5) - XCTAssertFalse(material.isHidden) - } else { - XCTAssertEqual(material.frame.height, bar.view().bounds.height, accuracy: 0.5) - XCTAssertFalse(material.isHidden) + XCTAssertEqual(scroll.topEdgeEffect.style, .soft) } + XCTAssertEqual(material.frame, bar.view().bounds) XCTAssertEqual(material.alpha, 1) - XCTAssertNotNil(navigation.topViewController?.navigationItem.titleView as? NavigationTitleView) + XCTAssertFalse(bar.view().point(inside: CGPoint(x: 20, y: 121), with: nil)) + let title = try XCTUnwrap(descendants(of: bar.view()).first { $0 is NavigationTitleView }) + XCTAssertEqual(title.frame.midX, left + (bar.view().bounds.width - left - right) / 2, accuracy: 0.5) + let project = try XCTUnwrap(descendants(of: bar.view()).first { $0.accessibilityLabel == "Project" }) + let projectFrame = project.convert(project.bounds, to: bar.view()) + XCTAssertLessThanOrEqual(title.frame.maxX, projectFrame.minX) + let agent = try XCTUnwrap(descendants(of: bar.view()).first { $0.accessibilityLabel == "Agent" }) + XCTAssertLessThanOrEqual(agent.convert(agent.bounds, to: bar.view()).maxX, + bar.view().bounds.width - right) + // Verify actual material pixels beneath the rail, not just edge flags. + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + let renderer = UIGraphicsImageRenderer(size: CGSize(width: 16, height: 16), format: format) + func pixels() throws -> Data { + let image = renderer.image { context in + context.cgContext.translateBy(x: -(left > 0 ? 8 : window.bounds.width - 24), y: -8) + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + return try XCTUnwrap(try XCTUnwrap(image.cgImage).dataProvider?.data) as Data + } + let protected = try pixels() + material.isHidden = true + let unprotected = try pixels() + material.isHidden = false + XCTAssertNotEqual(protected, unprotected, "The blur must remain visible beneath either rail") + } + } + + @MainActor + func testStandaloneRailObservesBookPosture() throws { + for standalone in [false, true] { + let parent = UIViewController() + let bar = IosNavigationBarFactory( + messenger: NavigationTestMessenger(), parent: parent + ).create(withFrame: CGRect(x: 0, y: 0, width: 48, height: 48), + viewIdentifier: 999989, + arguments: ["standaloneControl": standalone]) + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.1, *) { + XCTAssertEqual( + bar.view().interactions.contains { $0 is UIHingeInteraction }, standalone) + } else { + XCTAssertTrue(bar.view().interactions.isEmpty) + } + #else + XCTAssertTrue(bar.view().interactions.isEmpty) + #endif } } @@ -853,82 +1090,92 @@ class RunnerTests: XCTestCase { guard !UIAccessibility.isReduceMotionEnabled else { throw XCTSkip("The system has disabled transition animation") } - let parent = UIViewController() - let window = UIWindow(frame: UIScreen.main.bounds) - window.windowScene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) - window.rootViewController = parent - window.makeKeyAndVisible() - defer { window.isHidden = true } - let messenger = NavigationTestMessenger() - let bar = IosNavigationBarFactory(messenger: messenger, parent: parent).create( - withFrame: CGRect(x: 0, y: 0, width: window.bounds.width, height: 180), - viewIdentifier: 999992, arguments: ["title": "Home", "largeTitle": true]) - parent.view.addSubview(bar.view()) - parent.view.layoutIfNeeded() - try await Task.sleep(nanoseconds: 200_000_000) - let navigation = try XCTUnwrap(parent.children.first as? UINavigationController) - let metrics = try XCTUnwrap(messenger.metrics) - let expanded = try XCTUnwrap(metrics["expandedHeight"] as? Double) - let compact = try XCTUnwrap(metrics["compactHeight"] as? Double) - let boundary = expanded - compact + for leadingTitle in [false, true] { + let parent = UIViewController() + let window = UIWindow(frame: UIScreen.main.bounds) + window.windowScene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) + window.rootViewController = parent + window.makeKeyAndVisible() + defer { window.isHidden = true } + let messenger = NavigationTestMessenger() + let bar = IosNavigationBarFactory(messenger: messenger, parent: parent).create( + withFrame: CGRect(x: 0, y: 0, width: window.bounds.width, height: 180), + viewIdentifier: 999992, arguments: ["title": "Home", "largeTitle": true, "alignCollapsedTitleToLeading": leadingTitle]) + parent.view.addSubview(bar.view()) + parent.view.layoutIfNeeded() + try await Task.sleep(nanoseconds: 200_000_000) + let navigation = try XCTUnwrap(parent.children.first as? UINavigationController) + let metrics = try XCTUnwrap(messenger.metrics) + let expanded = try XCTUnwrap(metrics["expandedHeight"] as? Double) + let compact = try XCTUnwrap(metrics["compactHeight"] as? Double) + let boundary = expanded - compact - func labels(in view: UIView) -> [UILabel] { - let own = (view as? UILabel).map { [$0] } ?? [] - return own + view.subviews.flatMap { labels(in: $0) } + func labels(in view: UIView) -> [UILabel] { + let own = (view as? UILabel).map { [$0] } ?? [] + return own + view.subviews.flatMap { labels(in: $0) } + } + func visibleOpacity(of view: UIView) -> Float { + guard !view.isHidden else { return 0 } + let opacity = view.layer.presentation()?.opacity ?? Float(view.alpha) + let maskOpacity = view.layer.mask.map { $0.presentation()?.opacity ?? $0.opacity } ?? 1 + return opacity * maskOpacity * (view.superview.map { visibleOpacity(of: $0) } ?? 1) + } + let title = try XCTUnwrap(labels(in: navigation.view) + .filter { $0.text == "Home" }.max { $0.font.pointSize < $1.font.pointSize }) + let centeredTitle = try XCTUnwrap(labels(in: bar.view()).filter { $0.text == "Home" && $0 !== title }.min { $0.font.pointSize < $1.font.pointSize }) + let initialTitleX = title.convert(title.bounds, to: bar.view()).minX + if leadingTitle { + XCTAssertGreaterThanOrEqual(title.convert(title.bounds, to: bar.view()).minY, 44, + "Expanded pane titles must clear the reserved header row") + } + let initialTitleY = title.convert(title.bounds, to: parent.view).minY + XCTAssertEqual(title.textColor.cgColor.alpha, 1, accuracy: 0.01) + messenger.scroll(to: boundary * 0.7) + XCTAssertGreaterThan(title.textColor.cgColor.alpha, 0.1) + XCTAssertLessThan(title.textColor.cgColor.alpha, 0.6, "The actual large text must fade before it collapses") + // Flutter also resizes the platform view every scroll frame. Exercise that + // layout, which could invalidate a snapshot-only header transition. + bar.view().frame.size.height -= boundary * 0.7 + bar.view().setNeedsLayout() + bar.view().layoutIfNeeded() + XCTAssertLessThan(title.textColor.cgColor.alpha, 0.6) + messenger.scroll(to: boundary) + // The host app can hold the main thread past the whole fade, so check the + // animation itself rather than sampling its presentation mid-flight. + let mask = try XCTUnwrap(centeredTitle.layer.mask) + XCTAssertFalse(mask.bounds.isEmpty) + XCTAssertEqual(mask.opacity, 1) + let fade = try XCTUnwrap(mask.animation(forKey: "titleFade") as? CABasicAnimation, + "Collapsing must fade the compact title in") + XCTAssertEqual(fade.keyPath, "opacity") + XCTAssertEqual((fade.fromValue as? NSNumber)?.floatValue, 0) + XCTAssertEqual((fade.toValue as? NSNumber)?.floatValue, 1) + // A band around the 0.18 s design value: a near-zero duration is a snap. + XCTAssertGreaterThanOrEqual(fade.duration, 0.1) + XCTAssertLessThanOrEqual(fade.duration, 0.5) + XCTAssertEqual(title.textColor.cgColor.alpha, 0, accuracy: 0.01) + if leadingTitle { + XCTAssertEqual(centeredTitle.convert(centeredTitle.bounds, to: bar.view()).minX, initialTitleX, accuracy: 0.5) + } + messenger.scroll(to: boundary * 0.7) + XCTAssertNil(mask.animation(forKey: "titleFade"), "Reversing must cancel the fade") + try await Task.sleep(nanoseconds: 240_000_000) + XCTAssertEqual(visibleOpacity(of: centeredTitle), 0, accuracy: 0.01) + XCTAssertGreaterThan(title.textColor.cgColor.alpha, 0.1) + messenger.scroll(to: boundary) + try await Task.sleep(nanoseconds: 240_000_000) + XCTAssertEqual(visibleOpacity(of: centeredTitle), 1, accuracy: 0.01) + XCTAssertEqual(navigation.navigationBar.frame.height, compact, accuracy: 0.5) + messenger.scroll(to: 0) + bar.view().frame.size.height += boundary * 0.7 + bar.view().setNeedsLayout() + bar.view().layoutIfNeeded() + try await Task.sleep(nanoseconds: 240_000_000) + XCTAssertEqual(title.textColor.cgColor.alpha, 1, accuracy: 0.01) + XCTAssertEqual(visibleOpacity(of: centeredTitle), 0, accuracy: 0.01) + XCTAssertEqual(navigation.navigationBar.frame.height, expanded, accuracy: 0.5) + XCTAssertEqual(title.convert(title.bounds, to: parent.view).minY, initialTitleY, accuracy: 0.5) } - func visibleOpacity(of view: UIView) -> Float { - guard !view.isHidden else { return 0 } - let opacity = view.layer.presentation()?.opacity ?? Float(view.alpha) - let maskOpacity = view.layer.mask.map { $0.presentation()?.opacity ?? $0.opacity } ?? 1 - return opacity * maskOpacity * (view.superview.map { visibleOpacity(of: $0) } ?? 1) - } - let title = try XCTUnwrap(labels(in: navigation.view) - .filter { $0.text == "Home" }.max { $0.font.pointSize < $1.font.pointSize }) - let centeredTitle = try XCTUnwrap(navigation.topViewController?.navigationItem.titleView?.subviews.compactMap { $0 as? UILabel }.first) - let initialTitleY = title.convert(title.bounds, to: parent.view).minY - XCTAssertEqual(title.textColor.cgColor.alpha, 1, accuracy: 0.01) - messenger.scroll(to: boundary * 0.7) - XCTAssertGreaterThan(title.textColor.cgColor.alpha, 0.1) - XCTAssertLessThan(title.textColor.cgColor.alpha, 0.6, "The actual large text must fade before it collapses") - // Flutter also resizes the platform view every scroll frame. Exercise that - // layout, which could invalidate a snapshot-only header transition. - bar.view().frame.size.height -= boundary * 0.7 - bar.view().setNeedsLayout() - bar.view().layoutIfNeeded() - XCTAssertLessThan(title.textColor.cgColor.alpha, 0.6) - messenger.scroll(to: boundary) - // The host app can hold the main thread past the whole fade, so check the - // animation itself rather than sampling its presentation mid-flight. - let mask = try XCTUnwrap(centeredTitle.layer.mask) - XCTAssertFalse(mask.bounds.isEmpty) - XCTAssertEqual(mask.opacity, 1) - let fade = try XCTUnwrap(mask.animation(forKey: "titleFade") as? CABasicAnimation, - "Collapsing must fade the compact title in") - XCTAssertEqual(fade.keyPath, "opacity") - XCTAssertEqual((fade.fromValue as? NSNumber)?.floatValue, 0) - XCTAssertEqual((fade.toValue as? NSNumber)?.floatValue, 1) - // A band around the 0.18 s design value: a near-zero duration is a snap. - XCTAssertGreaterThanOrEqual(fade.duration, 0.1) - XCTAssertLessThanOrEqual(fade.duration, 0.5) - XCTAssertEqual(title.textColor.cgColor.alpha, 0, accuracy: 0.01) - messenger.scroll(to: boundary * 0.7) - XCTAssertNil(mask.animation(forKey: "titleFade"), "Reversing must cancel the fade") - try await Task.sleep(nanoseconds: 240_000_000) - XCTAssertEqual(visibleOpacity(of: centeredTitle), 0, accuracy: 0.01) - XCTAssertGreaterThan(title.textColor.cgColor.alpha, 0.1) - messenger.scroll(to: boundary) - try await Task.sleep(nanoseconds: 240_000_000) - XCTAssertEqual(visibleOpacity(of: centeredTitle), 1, accuracy: 0.01) - XCTAssertEqual(navigation.navigationBar.frame.height, compact, accuracy: 0.5) - messenger.scroll(to: 0) - bar.view().frame.size.height += boundary * 0.7 - bar.view().setNeedsLayout() - bar.view().layoutIfNeeded() - try await Task.sleep(nanoseconds: 240_000_000) - XCTAssertEqual(title.textColor.cgColor.alpha, 1, accuracy: 0.01) - XCTAssertEqual(visibleOpacity(of: centeredTitle), 0, accuracy: 0.01) - XCTAssertEqual(navigation.navigationBar.frame.height, expanded, accuracy: 0.5) - XCTAssertEqual(title.convert(title.bounds, to: parent.view).minY, initialTitleY, accuracy: 0.5) } @MainActor @@ -1316,6 +1563,19 @@ class RunnerTests: XCTestCase { ) } + func testDuoCameraAnchorMovesToComposerCenter() { + let anchor = CGRect(x: 0, y: 0, width: 44, height: 44) + XCTAssertEqual( + NativeAttachmentPopoverAnchorLayout.sourceRect( + anchorBounds: anchor, + keyboardDismissalOffset: 200, + isExpanded: true, + horizontalOffset: 180 + ), + anchor.offsetBy(dx: 180, dy: 240) + ) + } + func testAttachmentMenuReturnsToKeyboardDismissedAnchor() { let anchorBounds = CGRect(x: 0, y: 0, width: 44, height: 44) @@ -2137,12 +2397,14 @@ private actor NativeEmojiDownloadProbe { } private final class NavigationTestMessenger: NSObject, FlutterBinaryMessenger { + var cornerRadii: [String: CGFloat]? var metrics: [String: Any]? var avatarBounds: [String: Any]? var actions: [String] = [] func send(onChannel channel: String, message: Data?) { guard let message else { return } let call = FlutterStandardMethodCodec.sharedInstance().decodeMethodCall(message) + if call.method == "cornerRadiiChanged" { cornerRadii = call.arguments as? [String: CGFloat] } if call.method == "metrics" { metrics = call.arguments as? [String: Any] } if call.method == "avatarBounds" { avatarBounds = call.arguments as? [String: Any] } if call.method == "action", let action = call.arguments as? String { actions.append(action) } diff --git a/mobile/lib/features/activity/activity_page.dart b/mobile/lib/features/activity/activity_page.dart index 646e3df19b..8288c99bc1 100644 --- a/mobile/lib/features/activity/activity_page.dart +++ b/mobile/lib/features/activity/activity_page.dart @@ -1,4 +1,5 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'dart:async'; import 'dart:math' show max; @@ -382,16 +383,19 @@ class ActivityPage extends HookConsumerWidget { : thread.parentId; if (!context.mounted) return; - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage( - channel: resolvedChannel, - initialMessageId: target.id, - initialThreadRootId: threadRootId, - initialThreadRouteBehavior: - InitialThreadRouteBehavior.replaceCurrentRoute, - ), + openConversationPane( + context, + target.id, + (_) => ChannelDetailPage( + channel: resolvedChannel, + initialMessageId: target.id, + initialThreadRootId: threadRootId, + initialThreadRouteBehavior: + ConversationPaneScope.maybeOf(context) == null + ? InitialThreadRouteBehavior.replaceCurrentRoute + : InitialThreadRouteBehavior.push, ), + reopen: true, ); } @@ -404,15 +408,18 @@ class ActivityPage extends HookConsumerWidget { ); return; } - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage( - channel: channel, - initialThreadRootId: draft.threadHeadId, - initialThreadRouteBehavior: - InitialThreadRouteBehavior.replaceCurrentRoute, - ), + openConversationPane( + context, + 'draft:${draft.channelId}:${draft.threadHeadId}', + (_) => ChannelDetailPage( + channel: channel, + initialThreadRootId: draft.threadHeadId, + initialThreadRouteBehavior: + ConversationPaneScope.maybeOf(context) == null + ? InitialThreadRouteBehavior.replaceCurrentRoute + : InitialThreadRouteBehavior.push, ), + reopen: true, ); } @@ -433,12 +440,12 @@ class ActivityPage extends HookConsumerWidget { ); return; } - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage( - channel: channel, - initialMessageId: target.eventId, - ), + openConversationPane( + context, + target.eventId, + (_) => ChannelDetailPage( + channel: channel, + initialMessageId: target.eventId, ), ); } diff --git a/mobile/lib/features/activity/activity_page/header_actions.dart b/mobile/lib/features/activity/activity_page/header_actions.dart index de0e9ccf8d..ec97c47a10 100644 --- a/mobile/lib/features/activity/activity_page/header_actions.dart +++ b/mobile/lib/features/activity/activity_page/header_actions.dart @@ -69,16 +69,11 @@ class _ActivityMenuButton extends StatelessWidget { surfaceKey: ValueKey(popoverKey), items: [ for (final entry in options.entries) - PopupMenuItem( + CheckedPopupMenuItem( value: entry.key, + checked: value == entry.key, height: Grid.xl, - child: Row( - children: [ - Expanded(child: Text(entry.value)), - if (value == entry.key) - const Icon(BuzzIcons.check, size: 16), - ], - ), + child: Text(entry.value), ), ], ); diff --git a/mobile/lib/features/agents/agents_page.dart b/mobile/lib/features/agents/agents_page.dart index c5d531c54d..49ec7e4ebc 100644 --- a/mobile/lib/features/agents/agents_page.dart +++ b/mobile/lib/features/agents/agents_page.dart @@ -1,6 +1,10 @@ import 'dart:async'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -136,114 +140,175 @@ class _AgentsNavigation extends HookConsumerWidget { if (identical(ModalRoute.of(context), _openAgentsRoute)) { _openAgentsNavigator = navigator; } - return NavigatorPopHandler( - onPopWithResult: (result) { - if (navigator.currentState?.canPop() ?? false) { - navigator.currentState!.pop(result); - } - }, - child: Navigator( - key: navigator, - observers: [heroController], - onGenerateRoute: (_) => MaterialPageRoute( - builder: (listContext) => Material( - color: context.colors.surface, - child: AgentsPage( - controller: controller, - draft: draft, - createOnOpen: createOnOpen, - onClose: () => Navigator.of(context).pop(), - onCreated: (pubkey) async { - // Only a first agent becomes Bestie; continue into its chat. - final scope = ref.read(meSyncProvider); - bool current() => - context.mounted && ref.read(meSyncProvider) == scope; - final Channel channel; - try { - if (await ref.read(defaultAgentProvider.future) != pubkey || - !current()) { - return; - } - channel = await ref - .read(channelActionsProvider) - .openDm(pubkeys: [pubkey]); - } catch (error) { - if (context.mounted) { - ScaffoldMessenger.maybeOf(context)?.showFeedbackSnackBar( - SnackBar( - content: Text( - 'Could not open the agent conversation. $error', + final toolbar = DuoToolbarScope.maybeOf(context); + return DuoToolbarScope( + strip: toolbar?.strip, + active: + (toolbar?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true), + child: NavigatorPopHandler( + onPopWithResult: (result) { + if (navigator.currentState?.canPop() ?? false) { + navigator.currentState!.pop(result); + } + }, + child: Navigator( + key: navigator, + observers: [heroController], + onGenerateRoute: (_) => MaterialPageRoute( + builder: (_) => _AgentsWorkspace( + child: Builder( + builder: (listContext) => Material( + color: context.colors.surface, + child: AgentsPage( + controller: controller, + draft: draft, + createOnOpen: createOnOpen, + onClose: () => Navigator.of(context).pop(), + onCreated: (pubkey) async { + // Only a first agent becomes Bestie; continue into its chat. + final scope = ref.read(meSyncProvider); + bool current() => + context.mounted && ref.read(meSyncProvider) == scope; + final Channel channel; + try { + if (await ref.read(defaultAgentProvider.future) != + pubkey || + !current()) { + return; + } + channel = await ref + .read(channelActionsProvider) + .openDm(pubkeys: [pubkey]); + } catch (error) { + if (context.mounted) { + ScaffoldMessenger.maybeOf( + context, + )?.showFeedbackSnackBar( + SnackBar( + content: Text( + 'Could not open the agent conversation. $error', + ), + ), + kind: ToastKind.error, + ); + } + return; + } + if (!current()) return; + // The welcome is local decoration; never let it block the chat. + try { + await saveBestieWelcome( + ref.read(savedPrefsProvider), + scope, + channel.id, + pubkey, + ); + ref.invalidate(bestieWelcomeProvider(channel.id)); + } catch (error) { + debugPrint('agents: Bestie welcome not saved: $error'); + } + // Close only the Agents stack, never a route opened above it. + if (!context.mounted || !current()) return; + if (ModalRoute.of(context)?.isCurrent ?? false) { + Navigator.of(context).pop(channel); + } + }, + onSelect: (pubkey) async { + final strip = DuoToolbarScope.maybeOf(listContext)?.strip; + final wide = + defaultTargetPlatform == TargetPlatform.iOS && + usesConversationPanes( + listContext, + strip: strip, + windowSize: + View.of(listContext).physicalSize / + View.of(listContext).devicePixelRatio, + ); + Widget profile({ + ValueChanged? onOpenChannel, + EdgeInsets contentPadding = EdgeInsets.zero, + }) => UserProfileSheet( + onOpenChannel: onOpenChannel, + embedded: onOpenChannel != null, + contentPadding: contentPadding, + pubkey: pubkey, + agentPresentation: true, + agentSubtitleIcon: + controller.agents.any( + (agent) => agent['agent_pubkey'] == pubkey, + ) + ? const AgentNavigationIcon(size: 16) + : null, + agentSubtitle: + controller.agents.any( + (agent) => agent['agent_pubkey'] == pubkey, + ) + ? 'Builderbot agent' + : agentLocationUnknown( + ref.read(activeCommunityProvider).asData?.value, + controller, + ) + ? null + : 'Manage on desktop', + primaryActionsSpacing: Grid.md, + contextualActions: (_) => + BestieAgentAction(pubkey: pubkey, compact: true), + agentIdentity: (_) => AgentIdentitySections( + pubkey: pubkey, + controller: controller, ), - ), - kind: ToastKind.error, - ); - } - return; - } - if (!current()) return; - // The welcome is local decoration; never let it block the chat. - try { - await saveBestieWelcome( - ref.read(savedPrefsProvider), - scope, - channel.id, - pubkey, - ); - ref.invalidate(bestieWelcomeProvider(channel.id)); - } catch (error) { - debugPrint('agents: Bestie welcome not saved: $error'); - } - // Close only the Agents stack, never a route opened above it. - if (!context.mounted || !current()) return; - if (ModalRoute.of(context)?.isCurrent ?? false) { - Navigator.of(context).pop(channel); - } - }, - onSelect: (pubkey) async { - final channel = await showBuzzModalBottomSheet( - context: listContext, - isScrollControlled: true, - showDragHandle: false, - showCloseButton: false, - padBottom: false, - builder: (_) => UserProfileSheet( - pubkey: pubkey, - agentPresentation: true, - agentSubtitleIcon: - controller.agents.any( - (agent) => agent['agent_pubkey'] == pubkey, - ) - ? const AgentNavigationIcon(size: 16) - : null, - agentSubtitle: - controller.agents.any( - (agent) => agent['agent_pubkey'] == pubkey, - ) - ? 'Builderbot agent' - : agentLocationUnknown( - ref.read(activeCommunityProvider).asData?.value, - controller, - ) - ? null - : 'Manage on desktop', - primaryActionsSpacing: Grid.md, - contextualActions: (_) => - BestieAgentAction(pubkey: pubkey, compact: true), - agentIdentity: (_) => AgentIdentitySections( - pubkey: pubkey, - controller: controller, - ), - agentSettings: (_) => DeleteAgentAction( - asSettingsRow: true, - controller: controller, - pubkey: pubkey, - ), + agentSettings: (_) => DeleteAgentAction( + asSettingsRow: true, + controller: controller, + pubkey: pubkey, + ), + ); + if (wide) { + await openConversationPane(listContext, pubkey, ( + paneContext, + ) { + final pane = DuoToolbarScope.maybeOf(paneContext)!; + return DuoToolbarScope( + strip: pane.strip, + active: pane.active, + child: FrostedScaffold( + appBar: const FrostedAppBar(), + body: SizedBox.expand( + child: DuoSheetCloseScope( + inRail: true, + child: profile( + contentPadding: pane.contentInsets, + onOpenChannel: (channel) { + if (context.mounted) { + Navigator.of(context).pop(channel); + } + }, + ), + ), + ), + ), + ); + }); + return; + } + final channel = await showBuzzModalBottomSheet( + context: listContext, + isScrollControlled: true, + showDragHandle: false, + showCloseButton: false, + showRailCloseButton: true, + padHorizontal: false, + padBottom: false, + builder: (_) => profile(), + ); + if (channel != null && context.mounted) { + Navigator.of(context).pop(channel); + } + }, ), - ); - if (channel != null && context.mounted) { - Navigator.of(context).pop(channel); - } - }, + ), + ), ), ), ), @@ -748,3 +813,29 @@ class AgentsPage extends HookConsumerWidget { /// Progress of opening a link's draft: waiting on gates, sign-in requested, /// sign-in seen running, or done. enum _DraftStep { wait, signInRequested, signingIn, done } + +class _AgentsWorkspace extends StatelessWidget { + const _AgentsWorkspace({required this.child}); + final Widget child; + + @override + Widget build(BuildContext context) => + defaultTargetPlatform != TargetPlatform.iOS + ? child + : AdaptiveConversationDestination( + emptyLabel: 'Select an agent', + preferredListWidth: + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null + ? 375 + : null, + listWidthFraction: + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null + ? null + : .5, + child: child, + ); +} diff --git a/mobile/lib/features/channels/bestie_conversation.dart b/mobile/lib/features/channels/bestie_conversation.dart index 6a6c2c3803..5ac2abbfbb 100644 --- a/mobile/lib/features/channels/bestie_conversation.dart +++ b/mobile/lib/features/channels/bestie_conversation.dart @@ -3,6 +3,7 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; import '../../shared/me/default_agent.dart'; import '../../shared/me/me_sync.dart'; import '../../shared/relay/relay.dart'; @@ -64,13 +65,18 @@ Future openBestieConversation( } // Only the lookup is guarded; an open conversation can be replaced. release(); - await Navigator.of(context).push( - MaterialPageRoute( - // Native glass and video layers must track the live route. - allowSnapshotting: false, - builder: (_) => ChannelDetailPage(channel: channel), - ), - ); + final pane = ConversationPaneScope.maybeOf(context); + if (pane != null) { + pane.open(channel.id, (_) => ChannelDetailPage(channel: channel)); + } else { + await Navigator.of(context).push( + MaterialPageRoute( + // Native glass and video layers must track the live route. + allowSnapshotting: false, + builder: (_) => ChannelDetailPage(channel: channel), + ), + ); + } } catch (error) { if (context.mounted) { ScaffoldMessenger.of(context).showFeedbackSnackBar( diff --git a/mobile/lib/features/channels/channel_actions_sheet.dart b/mobile/lib/features/channels/channel_actions_sheet.dart index c8894123eb..146024aedb 100644 --- a/mobile/lib/features/channels/channel_actions_sheet.dart +++ b/mobile/lib/features/channels/channel_actions_sheet.dart @@ -482,6 +482,8 @@ Future _confirmAndRun( required String confirmLabel, required Future Function() action, }) async { + final ownerNavigator = Navigator.of(sheetContext); + final ownerRoute = ModalRoute.of(sheetContext); final pageContext = Navigator.of(sheetContext, rootNavigator: true).context; final confirmed = await showBuzzDialog( context: pageContext, @@ -503,7 +505,9 @@ Future _confirmAndRun( if (confirmed != true) return; try { await action(); - if (pageContext.mounted) Navigator.of(pageContext).pop(true); + if (ownerNavigator.mounted && ownerRoute?.isCurrent == true) { + ownerNavigator.pop(true); + } } catch (error) { if (!pageContext.mounted) return; ScaffoldMessenger.of(pageContext).showFeedbackSnackBar( diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index 2d43ae3b20..77e7c5f1b9 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -1,8 +1,10 @@ +import '../../shared/widgets/duo_toolbar.dart'; import 'composer_geometry.dart'; import 'message_author_visibility.dart'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'message_swipe_reply.dart'; import 'bestie_welcome.dart'; import 'bestie_welcome_storage.dart'; @@ -165,6 +167,11 @@ enum InitialThreadRouteBehavior { replaceCurrentRoute, } +double _conversationHeaderHeight( + BuildContext context, { + double titleContentHeight = 0, +}) => frostedAppBarHeight(context, titleContentHeight: titleContentHeight); + class _ResolvedChannelDetailPage extends HookConsumerWidget { final Channel channel; @@ -540,7 +547,8 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { // it reads through it when it is shown again. final openReadActive = isAppInUse(useAppLifecycleState()) && - (ModalRoute.of(context)?.isCurrent ?? true); + (ModalRoute.of(context)?.isCurrent ?? true) && + ConversationPaneScope.isActiveOf(context); useEffect(() { if (!readState.isReady || !openReadActive || openReadTimestamp == null) { return null; @@ -661,6 +669,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { ); return FrostedScaffold( + extendHeaderUnderRail: true, foreground: !resolvedChannel.isForum && timelineEntries.isNotEmpty && @@ -672,7 +681,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { left: 0, right: 0, top: - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) + @@ -689,6 +698,15 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { resizeToAvoidBottomInset: !usesFixedAndroidImeViewport || resolvedChannel.isForum, appBar: FrostedAppBar( + nativeTitleInsets: duoContentInsetsOf(context), + automaticallyImplyLeading: + !ConversationPaneScope.isBaseRouteOf(context) || + !usesConversationPanes( + context, + windowSize: + View.of(context).physicalSize / + View.of(context).devicePixelRatio, + ), alwaysFrosted: true, nativeViewSuppressed: messageActionBackdropActive, nativeTitle: dmHeader.label, @@ -767,7 +785,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { null) Positioned( top: - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, @@ -813,7 +831,7 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { loading: SizedBox.shrink, error: (e, _) => Padding( padding: EdgeInsets.only( - top: frostedAppBarHeight( + top: _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ), diff --git a/mobile/lib/features/channels/channel_detail_page/banners.dart b/mobile/lib/features/channels/channel_detail_page/banners.dart index 8ee0e801a6..9616722f9c 100644 --- a/mobile/lib/features/channels/channel_detail_page/banners.dart +++ b/mobile/lib/features/channels/channel_detail_page/banners.dart @@ -131,7 +131,7 @@ class _MessageTimelineSkeleton extends StatelessWidget { physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.fromLTRB( Grid.gutter, - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) + diff --git a/mobile/lib/features/channels/channel_detail_page/empty_messages.dart b/mobile/lib/features/channels/channel_detail_page/empty_messages.dart index 4eebc54f71..a75f375aaa 100644 --- a/mobile/lib/features/channels/channel_detail_page/empty_messages.dart +++ b/mobile/lib/features/channels/channel_detail_page/empty_messages.dart @@ -33,3 +33,22 @@ class _EmptyMessages extends StatelessWidget { ); } } + +Widget _welcomeMessages( + BuildContext context, { + required double appBarTitleContentHeight, + required double composerBottomInset, + required List children, +}) => SingleChildScrollView( + padding: EdgeInsets.fromLTRB( + Grid.gutter, + _conversationHeaderHeight( + context, + titleContentHeight: appBarTitleContentHeight, + ) + + Grid.md, + Grid.gutter, + composerBottomInset + Grid.md, + ), + child: Column(children: children), +); diff --git a/mobile/lib/features/channels/channel_detail_page/message_list.dart b/mobile/lib/features/channels/channel_detail_page/message_list.dart index 3ab803c302..b0c291f87f 100644 --- a/mobile/lib/features/channels/channel_detail_page/message_list.dart +++ b/mobile/lib/features/channels/channel_detail_page/message_list.dart @@ -300,7 +300,7 @@ class _MessageList extends HookConsumerWidget { } final stickyTop = - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) + @@ -479,7 +479,7 @@ class _MessageList extends HookConsumerWidget { final visiblePageHeight = max( 0.0, viewportHeight - - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) - @@ -625,7 +625,7 @@ class _MessageList extends HookConsumerWidget { (navigationBottomInset / viewportHeight).clamp(0.0, 1.0) - 0.01; final topEdge = 1 - - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) / @@ -682,7 +682,8 @@ class _MessageList extends HookConsumerWidget { active: readStateReady && appInUse && - (ModalRoute.of(context)?.isCurrent ?? true), + (ModalRoute.of(context)?.isCurrent ?? true) && + ConversationPaneScope.isActiveOf(context), onDwell: readVisibleRows, keys: [channelId, readingContentKey(allMessages), navigationBottomInset], ); @@ -873,29 +874,20 @@ class _MessageList extends HookConsumerWidget { } if (entries.isEmpty) { if (welcomeAgent != null) { - return SingleChildScrollView( - padding: EdgeInsets.fromLTRB( - Grid.gutter, - frostedAppBarHeight( - context, - titleContentHeight: appBarTitleContentHeight, - ) + - Grid.md, - Grid.gutter, - composerBottomInset + Grid.md, - ), - child: Column( - children: [ - BestieWelcome(agent: welcomeAgent!), - ?hiddenHistory, - if (displayedTyping.isNotEmpty) - InlineAgentTyping( - channelId: channelId, - entries: displayedTyping, - knownAgents: workingAgents, - ), - ], - ), + return _welcomeMessages( + context, + appBarTitleContentHeight: appBarTitleContentHeight, + composerBottomInset: composerBottomInset, + children: [ + BestieWelcome(agent: welcomeAgent!), + ?hiddenHistory, + if (displayedTyping.isNotEmpty) + InlineAgentTyping( + channelId: channelId, + entries: displayedTyping, + knownAgents: workingAgents, + ), + ], ); } return hiddenHistory ?? const _EmptyMessages(); @@ -964,7 +956,7 @@ class _MessageList extends HookConsumerWidget { padding: EdgeInsets.only( left: Grid.gutter, right: Grid.gutter, - top: frostedAppBarHeight( + top: _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ), @@ -1171,7 +1163,7 @@ class _MessageList extends HookConsumerWidget { left: 0, right: 0, top: - frostedAppBarHeight( + _conversationHeaderHeight( context, titleContentHeight: appBarTitleContentHeight, ) + diff --git a/mobile/lib/features/channels/channels_page.dart b/mobile/lib/features/channels/channels_page.dart index b60bd5eb66..c07dc79ae2 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -1,5 +1,6 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'channel_unread.dart'; import '../../shared/widgets/collapsible_section_body.dart'; import '../../shared/me/me_sync.dart'; @@ -14,6 +15,8 @@ import 'dart:math' show max, min; import 'dart:ui'; import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show ScrollCacheExtent; import 'package:flutter/services.dart'; @@ -43,6 +46,7 @@ import '../../shared/widgets/buzz_setting_menu.dart'; import '../../shared/widgets/buzz_titled_sheet_layout.dart'; import '../../shared/widgets/ios_glass_navigation_action.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; +import '../../shared/widgets/ios_message_create_button.dart'; import '../../shared/widgets/frosted_app_bar.dart'; import '../../shared/widgets/frosted_scaffold.dart'; import '../../shared/widgets/modal_presentation.dart'; @@ -179,6 +183,12 @@ class ChannelsPage extends HookConsumerWidget { fontWeight: FontWeight.w600, color: navigationPrimaryForeground(context), ); + final nativeDuoTitle = + messagesFilters != null && + defaultTargetPlatform == TargetPlatform.iOS && + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null; final filterContentHeight = messagesFilters == null ? 0.0 : max(48.0, MediaQuery.textScalerOf(context).scale(16) * 1.4 + 16) + @@ -212,7 +222,9 @@ class ChannelsPage extends HookConsumerWidget { () { void updateHeaderTreatment() { final collapse = - messagesFilters == null || !channelsScrollController.hasClients + messagesFilters == null || + nativeDuoTitle || + !channelsScrollController.hasClients ? 0.0 : channelsScrollController.offset .clamp(0.0, filterContentHeight) @@ -232,7 +244,12 @@ class ChannelsPage extends HookConsumerWidget { return () => channelsScrollController.removeListener(updateHeaderTreatment); }, - [channelsScrollController, messagesFilters != null, filterContentHeight], + [ + channelsScrollController, + messagesFilters != null, + filterContentHeight, + nativeDuoTitle, + ], ); useEffect(() { final tabReselection = this.tabReselection; @@ -284,6 +301,17 @@ class ChannelsPage extends HookConsumerWidget { .toList(); Future openChannel(Channel channel) async { if (!context.mounted) return; + final pane = ConversationPaneScope.maybeOf(context); + if (pane != null) { + pane.open( + channel.id, + (_) => ChannelDetailPage( + channel: channel, + placement: ChannelRoutePlacement.ordinary, + ), + ); + return; + } await Navigator.of(context).push( MaterialPageRoute( builder: (_) => ChannelDetailPage( @@ -479,16 +507,24 @@ class ChannelsPage extends HookConsumerWidget { final role = ref.read(currentCommunityRoleProvider).unwrapPrevious(); final canInvite = role.hasError || canManageCommunityInvites(role.value); unawaited(HapticFeedback.selectionClick()); + Widget menu(BuildContext _) => _CommunityMenuSheet( + canInvite: canInvite, + onSwitchCommunity: openCommunityGrid, + invitePageBuilder: communityInvitePageBuilder, + appearancePageBuilder: communityAppearancePageBuilder, + ); + final window = MediaQueryData.fromView(View.of(context)); + final bounded = + defaultTargetPlatform == TargetPlatform.iOS && + window.size.shortestSide >= 600; showBuzzModalBottomSheet( context: context, + useRootNavigator: true, + useDuoFullWidth: !bounded, + constraints: bounded ? const BoxConstraints(maxWidth: 480) : null, showCloseButton: false, showDragHandle: true, - builder: (_) => _CommunityMenuSheet( - canInvite: canInvite, - onSwitchCommunity: openCommunityGrid, - invitePageBuilder: communityInvitePageBuilder, - appearancePageBuilder: communityAppearancePageBuilder, - ), + builder: menu, ); } @@ -611,7 +647,7 @@ class ChannelsPage extends HookConsumerWidget { appBar: FrostedAppBar( key: headerKey, onNativeReadyChanged: (ready) => nativeHeaderReady.value = ready, - nativeTitle: '', + nativeTitle: nativeDuoTitle ? 'Messages' : '', useNativeNavigation: messagesFilters == null, nativeViewSuppressed: headerNativeSuppressed, nativeLeading: messagesFilters != null diff --git a/mobile/lib/features/channels/channels_page/channel_tile.dart b/mobile/lib/features/channels/channels_page/channel_tile.dart index 54117a3546..d3a12e9721 100644 --- a/mobile/lib/features/channels/channels_page/channel_tile.dart +++ b/mobile/lib/features/channels/channels_page/channel_tile.dart @@ -35,133 +35,146 @@ class _ChannelTile extends ConsumerWidget { ? navigationMetadataForeground(context) : channelNavigationForeground(context); - return InkWell( - borderRadius: BorderRadius.circular(Radii.md), - onTap: onTap, - onLongPress: () => _showChannelActions(context, ref), - child: Padding( - padding: const EdgeInsets.only( - left: _kChannelSectionInset, - right: _kChannelSectionInset, - top: _kChannelRowVerticalPadding, - bottom: _kChannelRowVerticalPadding, - ), - child: Row( - children: [ - if (channel.isDm) ...[ - SizedBox( - width: _kChannelLeadingWidth, - child: Align( - alignment: Alignment.centerLeft, - child: _DmAvatar( - channel: channel, - currentPubkey: currentPubkey, - ), - ), - ), - const SizedBox(width: _kChannelLabelGap), - ] else ...[ - SizedBox( - width: _kChannelLeadingWidth, - child: Align( - alignment: Alignment.centerLeft, - child: Icon( - channel.visibility == 'private' - ? BuzzIcons.lock - : BuzzIcons.hash, - key: ValueKey('channel-icon-${channel.id}'), - size: _kChannelIconSize, - color: contentColor, - ), - ), - ), - const SizedBox(width: _kChannelLabelGap), - ], - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - ref.watch( - identityNameSourcesProvider.select( - (names) => resolveDmChannelDisplayLabel( - channel, - currentPubkey: currentPubkey, - names: names, - ), + final selected = + ConversationPaneScope.maybeOf(context)?.selectedId == channel.id; + return DecoratedBox( + decoration: BoxDecoration( + color: selected ? context.colors.primaryContainer : null, + borderRadius: BorderRadius.circular(Radii.md), + ), + child: Semantics( + selected: selected, + child: InkWell( + borderRadius: BorderRadius.circular(Radii.md), + onTap: onTap, + onLongPress: () => _showChannelActions(context, ref), + child: Padding( + padding: const EdgeInsets.only( + left: _kChannelSectionInset, + right: _kChannelSectionInset, + top: _kChannelRowVerticalPadding, + bottom: _kChannelRowVerticalPadding, + ), + child: Row( + children: [ + if (channel.isDm) ...[ + SizedBox( + width: _kChannelLeadingWidth, + child: Align( + alignment: Alignment.centerLeft, + child: _DmAvatar( + channel: channel, + currentPubkey: currentPubkey, ), ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: navigationChatTitleTextStyle.copyWith( - color: isMuted - ? contentColor - : channelNavigationForeground( - context, - unread: isUnread, + ), + const SizedBox(width: _kChannelLabelGap), + ] else ...[ + SizedBox( + width: _kChannelLeadingWidth, + child: Align( + alignment: Alignment.centerLeft, + child: Icon( + channel.visibility == 'private' + ? BuzzIcons.lock + : BuzzIcons.hash, + key: ValueKey('channel-icon-${channel.id}'), + size: _kChannelIconSize, + color: contentColor, + ), + ), + ), + const SizedBox(width: _kChannelLabelGap), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + ref.watch( + identityNameSourcesProvider.select( + (names) => resolveDmChannelDisplayLabel( + channel, + currentPubkey: currentPubkey, + names: names, ), - fontWeight: isUnread ? FontWeight.w600 : FontWeight.w400, + ), + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: navigationChatTitleTextStyle.copyWith( + color: isMuted + ? contentColor + : channelNavigationForeground( + context, + unread: isUnread, + ), + fontWeight: isUnread + ? FontWeight.w600 + : FontWeight.w400, + ), + ), + ], + ), + ), + if (hasAttention) ...[ + const SizedBox(width: Grid.xxs), + // The dot is the only sign of this state, so name it for + // screen readers; it merges into the row's label. + Semantics( + label: 'Needs your attention', + child: Container( + key: ValueKey('channel-attention-dot-${channel.id}'), + width: 6, + height: 6, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: context.colors.primary, + ), ), ), ], - ), - ), - if (hasAttention) ...[ - const SizedBox(width: Grid.xxs), - // The dot is the only sign of this state, so name it for - // screen readers; it merges into the row's label. - Semantics( - label: 'Needs your attention', - child: Container( - key: ValueKey('channel-attention-dot-${channel.id}'), - width: 6, - height: 6, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: context.colors.primary, - ), - ), - ), - ], - if (channel.isEphemeral) ...[ - const SizedBox(width: Grid.xxs), - _EphemeralBadge(channel: channel), - ], - if (isMuted) ...[ - const SizedBox(width: Grid.xxs), - SizedBox( - width: _kChannelIconSize, - child: Center( - child: Icon( - BuzzIcons.bellOff, - size: 12, - color: navigationMetadataForeground(context), - ), - ), - ), - ], - if (!channel.isMember && !channel.isDm) - Padding( - padding: const EdgeInsets.only(right: Grid.xxs), - child: Container( - padding: const EdgeInsets.symmetric( - horizontal: Grid.half + 2, - vertical: 3, - ), - decoration: BoxDecoration( - color: context.colors.primary.withValues(alpha: 0.1), - borderRadius: BorderRadius.circular(Radii.sm), - ), - child: Text( - 'Open', - style: context.textTheme.labelSmall?.copyWith( - color: context.colors.primary, - fontWeight: FontWeight.w600, + if (channel.isEphemeral) ...[ + const SizedBox(width: Grid.xxs), + _EphemeralBadge(channel: channel), + ], + if (isMuted) ...[ + const SizedBox(width: Grid.xxs), + SizedBox( + width: _kChannelIconSize, + child: Center( + child: Icon( + BuzzIcons.bellOff, + size: 12, + color: navigationMetadataForeground(context), + ), ), ), - ), - ), - ], + ], + if (!channel.isMember && !channel.isDm) + Padding( + padding: const EdgeInsets.only(right: Grid.xxs), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: Grid.half + 2, + vertical: 3, + ), + decoration: BoxDecoration( + color: context.colors.primary.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(Radii.sm), + ), + child: Text( + 'Open', + style: context.textTheme.labelSmall?.copyWith( + color: context.colors.primary, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ], + ), + ), ), ), ); diff --git a/mobile/lib/features/channels/channels_page/community_switcher.dart b/mobile/lib/features/channels/channels_page/community_switcher.dart index 6f959638b9..fcb550bc76 100644 --- a/mobile/lib/features/channels/channels_page/community_switcher.dart +++ b/mobile/lib/features/channels/channels_page/community_switcher.dart @@ -305,25 +305,35 @@ class CommunitySwitcherPage extends HookConsumerWidget { ); } + final ios = defaultTargetPlatform == TargetPlatform.iOS; + final toolbarScope = DuoToolbarScope.maybeOf(context); + final strip = ios + ? (toolbarScope == null + ? FoldGeometry.of(context).strip + : toolbarScope.strip) + : null; + final closeAction = IosNavigationAction( + label: 'Close community switcher', + symbol: 'xmark', + onPressed: () => Navigator.of(context).pop(), + ); + final editAction = IosNavigationAction( + label: isEditing.value ? 'Done' : 'Edit', + symbol: strip == null ? null : (isEditing.value ? 'checkmark' : 'pencil'), + onPressed: () => isEditing.value = !isEditing.value, + ); final header = FrostedAppBar( nativeTitle: '', automaticallyImplyLeading: false, - nativeLeading: IosNavigationAction( - label: 'Close community switcher', - symbol: 'xmark', - onPressed: () => Navigator.of(context).pop(), - ), - nativeActions: [ - IosNavigationAction( - label: isEditing.value ? 'Done' : 'Edit', - onPressed: () => isEditing.value = !isEditing.value, - ), - ], - leading: IconButton( - tooltip: 'Close community switcher', - onPressed: () => Navigator.of(context).pop(), - icon: const Icon(BuzzIcons.x), - ), + nativeLeading: strip == null ? closeAction : null, + nativeActions: strip == null ? [editAction] : [], + leading: strip != null + ? null + : IconButton( + tooltip: 'Close community switcher', + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(BuzzIcons.x), + ), actions: [ TextButton( key: const Key('community-switcher-edit'), @@ -418,78 +428,104 @@ class CommunitySwitcherPage extends HookConsumerWidget { final surface = FrostedScaffold( key: const Key('community-switcher-page'), appBar: header, - body: SafeArea(top: false, child: body), + body: SafeArea( + top: false, + left: strip == null, + right: strip == null, + child: body, + ), ); - return PopScope( - canPop: flight.value == null, - child: IgnorePointer( - ignoring: flight.value != null, - child: AnimatedBuilder( - animation: Listenable.merge([centering, controller, reveal]), - child: RepaintBoundary(child: surface), - builder: (context, child) { - final selected = flight.value; - final departure = _communityDepartureCurve.transform( - controller.value, - ); - final surfaceExit = Curves.easeOutCubic.transform(centering.value); - final centerProgress = _communityCenterCurve.transform( - centering.value, - ); - final screen = MediaQuery.sizeOf(context); - final center = Offset(screen.width / 2, screen.height / 2); - final destinationRect = landingBounds.value; - return Stack( - fit: StackFit.expand, - children: [ - if (selected != null) + return DuoToolbarPortal( + strip: strip, + active: + (toolbarScope?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true) && + flight.value == null, + actions: [closeAction, editAction], + child: PopScope( + canPop: flight.value == null, + child: IgnorePointer( + ignoring: flight.value != null, + child: AnimatedBuilder( + animation: Listenable.merge([centering, controller, reveal]), + child: RepaintBoundary( + child: strip == null + ? surface + : DuoToolbarScope( + strip: strip, + active: toolbarScope?.active ?? true, + child: surface, + ), + ), + builder: (context, child) { + final selected = flight.value; + final departure = _communityDepartureCurve.transform( + controller.value, + ); + final surfaceExit = Curves.easeOutCubic.transform( + centering.value, + ); + final centerProgress = _communityCenterCurve.transform( + centering.value, + ); + final screen = MediaQuery.sizeOf(context); + final center = Offset(screen.width / 2, screen.height / 2); + final destinationRect = landingBounds.value; + return Stack( + fit: StackFit.expand, + children: [ + if (selected != null) + Opacity( + key: const Key('community-loading-backdrop'), + opacity: 1 - Curves.easeOutCubic.transform(reveal.value), + child: ColoredBox(color: context.colors.surface), + ), Opacity( - key: const Key('community-loading-backdrop'), - opacity: 1 - Curves.easeOutCubic.transform(reveal.value), - child: ColoredBox(color: context.colors.surface), + key: const Key('community-picker-opacity'), + opacity: 1 - surfaceExit, + child: Transform.scale( + scale: 1 + 0.04 * surfaceExit, + child: child, + ), ), - Opacity( - key: const Key('community-picker-opacity'), - opacity: 1 - surfaceExit, - child: Transform.scale( - scale: 1 + 0.04 * surfaceExit, - child: child, - ), - ), - if (selected != null && controller.value == 0) - Positioned( - top: center.dy + _communityCenteredAvatarSize / 2 + Grid.md, - left: 0, - right: 0, - child: Center( - child: RepaintBoundary( - child: BuzzLoadingIndicator( - key: const Key('community-switch-loading'), - size: 18, - color: context.colors.onSecondaryContainer, - semanticLabel: 'Loading ${selected.community.name}', + if (selected != null && controller.value == 0) + Positioned( + top: + center.dy + + _communityCenteredAvatarSize / 2 + + Grid.md, + left: 0, + right: 0, + child: Center( + child: RepaintBoundary( + child: BuzzLoadingIndicator( + key: const Key('community-switch-loading'), + size: 18, + color: context.colors.onSecondaryContainer, + semanticLabel: 'Loading ${selected.community.name}', + ), ), ), ), - ), - if (selected != null) - _CommunityFlyingAvatar( - avatar: flightAvatar, - origin: selected.origin.center, - destination: - destinationRect ?? - Rect.fromCenter( - center: center, - width: _communityCenteredAvatarSize, - height: _communityCenteredAvatarSize, - ), - centerProgress: centerProgress, - departure: departure, - ), - ], - ); - }, + if (selected != null) + _CommunityFlyingAvatar( + avatar: flightAvatar, + origin: selected.origin.center, + destination: + destinationRect ?? + Rect.fromCenter( + center: center, + width: _communityCenteredAvatarSize, + height: _communityCenteredAvatarSize, + ), + centerProgress: centerProgress, + departure: departure, + ), + ], + ); + }, + ), ), ), ); diff --git a/mobile/lib/features/channels/channels_page/sections.dart b/mobile/lib/features/channels/channels_page/sections.dart index 0f1f60d7df..9b02181862 100644 --- a/mobile/lib/features/channels/channels_page/sections.dart +++ b/mobile/lib/features/channels/channels_page/sections.dart @@ -134,77 +134,124 @@ class _CustomSectionHeader extends StatelessWidget { color: sectionColor, ), ), - Builder( - builder: (buttonContext) => _SectionOptionsButton( + if (_usesNativeSectionMenu(context)) + IosMessageCreateButton( key: ValueKey('section-menu-${section.id}'), - tooltip: '${section.name} options', - icon: Icon( - BuzzIcons.ellipsis, - size: 14, - color: navigationAccessoryForeground(context), + icon: 'more', + accessibilityLabel: '${section.name} options', + width: 44, + height: 44, + plain: true, + iconSize: 14, + foregroundColor: navigationAccessoryForeground(context), + selectedIndex: sortMode == ChannelSortMode.recent ? 3 : 4, + dividerBefore: const {3, 5}, + destructiveIndices: const {5}, + actions: [ + ( + label: 'Rename section', + symbol: 'pencil', + onPressed: onRename, + ), + ( + label: 'Move up', + symbol: 'arrow.up', + onPressed: isFirst ? null : onMoveUp, + ), + ( + label: 'Move down', + symbol: 'arrow.down', + onPressed: isLast ? null : onMoveDown, + ), + ( + label: 'Sort: Recent', + symbol: '', + onPressed: () => onSortModeChange(ChannelSortMode.recent), + ), + ( + label: 'Sort: A–Z', + symbol: '', + onPressed: () => onSortModeChange(ChannelSortMode.alpha), + ), + ( + label: 'Delete section', + symbol: 'trash', + onPressed: onDelete, + ), + ], + ) + else + Builder( + builder: (buttonContext) => _SectionOptionsButton( + key: ValueKey('section-menu-${section.id}'), + tooltip: '${section.name} options', + icon: Icon( + BuzzIcons.ellipsis, + size: 14, + color: navigationAccessoryForeground(context), + ), + onPressed: () async { + final value = await showAnchoredPopover( + context: buttonContext, + width: 216, + alignment: AnchoredPopoverAlignment.end, + surfaceKey: ValueKey('section-popover-${section.id}'), + items: [ + const PopupMenuItem( + value: 'rename', + padding: _sectionMenuItemPadding, + child: _SectionMenuItemContent( + icon: BuzzIcons.pencil, + label: 'Rename section', + ), + ), + PopupMenuItem( + value: 'move_up', + enabled: !isFirst, + padding: _sectionMenuItemPadding, + child: const _SectionMenuItemContent( + icon: BuzzIcons.arrowUp, + label: 'Move up', + ), + ), + PopupMenuItem( + value: 'move_down', + enabled: !isLast, + padding: _sectionMenuItemPadding, + child: const _SectionMenuItemContent( + icon: BuzzIcons.arrowDown, + label: 'Move down', + ), + ), + ..._sortMenuItems(sortMode), + PopupMenuItem( + value: 'delete', + padding: _sectionMenuItemPadding, + child: _SectionMenuItemContent( + icon: BuzzIcons.trash2, + label: 'Delete section', + color: context.colors.error, + ), + ), + ], + ); + switch (value) { + case 'rename': + onRename(); + case 'move_up': + onMoveUp(); + case 'move_down': + onMoveDown(); + case _kSortRecentMenuValue: + onSortModeChange(ChannelSortMode.recent); + case _kSortAlphaMenuValue: + onSortModeChange(ChannelSortMode.alpha); + case 'delete': + onDelete(); + } + }, ), - onPressed: () async { - final value = await showAnchoredPopover( - context: buttonContext, - width: 216, - alignment: AnchoredPopoverAlignment.end, - surfaceKey: ValueKey('section-popover-${section.id}'), - items: [ - const PopupMenuItem( - value: 'rename', - padding: _sectionMenuItemPadding, - child: _SectionMenuItemContent( - icon: BuzzIcons.pencil, - label: 'Rename section', - ), - ), - PopupMenuItem( - value: 'move_up', - enabled: !isFirst, - padding: _sectionMenuItemPadding, - child: const _SectionMenuItemContent( - icon: BuzzIcons.arrowUp, - label: 'Move up', - ), - ), - PopupMenuItem( - value: 'move_down', - enabled: !isLast, - padding: _sectionMenuItemPadding, - child: const _SectionMenuItemContent( - icon: BuzzIcons.arrowDown, - label: 'Move down', - ), - ), - ..._sortMenuItems(sortMode), - PopupMenuItem( - value: 'delete', - padding: _sectionMenuItemPadding, - child: _SectionMenuItemContent( - icon: BuzzIcons.trash2, - label: 'Delete section', - color: context.colors.error, - ), - ), - ], - ); - switch (value) { - case 'rename': - onRename(); - case 'move_up': - onMoveUp(); - case 'move_down': - onMoveDown(); - case _kSortRecentMenuValue: - onSortModeChange(ChannelSortMode.recent); - case _kSortAlphaMenuValue: - onSortModeChange(ChannelSortMode.alpha); - case 'delete': - onDelete(); - } - }, ), - ), ], ), ), @@ -288,18 +335,7 @@ PopupMenuItem _sortMenuItem({ required String value, required String label, required bool selected, -}) => PopupMenuItem( - value: value, - child: Row( - children: [ - Expanded(child: Text(label)), - if (selected) - const Icon(BuzzIcons.check, key: ValueKey('sort-selected-check')) - else - const SizedBox(width: 24), - ], - ), -); +}) => CheckedPopupMenuItem(value: value, checked: selected, child: Text(label)); List> _sortMenuItems( ChannelSortMode current, { @@ -473,31 +509,58 @@ class _SectionHeader extends StatelessWidget { ), ), if (sortMode case final mode?) ...[ - Builder( - builder: (buttonContext) => _SectionOptionsButton( + if (_usesNativeSectionMenu(context)) + IosMessageCreateButton( key: ValueKey('sort-menu-$label'), - tooltip: '$label options', - icon: Icon( - BuzzIcons.ellipsis, - size: 14, - color: navigationAccessoryForeground(context), + icon: 'more', + accessibilityLabel: '$label options', + width: 44, + height: 44, + plain: true, + iconSize: 14, + foregroundColor: navigationAccessoryForeground(context), + selectedIndex: mode == ChannelSortMode.recent ? 0 : 1, + actions: [ + ( + label: 'Sort: Recent', + symbol: '', + onPressed: () => + onSortModeChange?.call(ChannelSortMode.recent), + ), + ( + label: 'Sort: A–Z', + symbol: '', + onPressed: () => + onSortModeChange?.call(ChannelSortMode.alpha), + ), + ], + ) + else + Builder( + builder: (buttonContext) => _SectionOptionsButton( + key: ValueKey('sort-menu-$label'), + tooltip: '$label options', + icon: Icon( + BuzzIcons.ellipsis, + size: 14, + color: navigationAccessoryForeground(context), + ), + onPressed: () async { + final value = await showAnchoredPopover( + context: buttonContext, + width: 216, + alignment: AnchoredPopoverAlignment.end, + surfaceKey: ValueKey('sort-popover-$label'), + items: _sortMenuItems(mode, showDivider: false), + ); + if (value == _kSortRecentMenuValue) { + onSortModeChange?.call(ChannelSortMode.recent); + } else if (value == _kSortAlphaMenuValue) { + onSortModeChange?.call(ChannelSortMode.alpha); + } + }, ), - onPressed: () async { - final value = await showAnchoredPopover( - context: buttonContext, - width: 216, - alignment: AnchoredPopoverAlignment.end, - surfaceKey: ValueKey('sort-popover-$label'), - items: _sortMenuItems(mode, showDivider: false), - ); - if (value == _kSortRecentMenuValue) { - onSortModeChange?.call(ChannelSortMode.recent); - } else if (value == _kSortAlphaMenuValue) { - onSortModeChange?.call(ChannelSortMode.alpha); - } - }, ), - ), ], ], ), @@ -562,6 +625,12 @@ class _SectionChevron extends StatelessWidget { } } +bool _usesNativeSectionMenu(BuildContext context) => + defaultTargetPlatform == TargetPlatform.iOS && + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null; + class _SectionOptionsButton extends StatelessWidget { const _SectionOptionsButton({ super.key, diff --git a/mobile/lib/features/channels/channels_page/skeleton.dart b/mobile/lib/features/channels/channels_page/skeleton.dart index 57de6ed777..4e82cb1c05 100644 --- a/mobile/lib/features/channels/channels_page/skeleton.dart +++ b/mobile/lib/features/channels/channels_page/skeleton.dart @@ -94,10 +94,12 @@ class _ChannelSkeletonSection extends StatelessWidget { ), ), const SizedBox(width: _kChannelLabelGap), - SkeletonBar( - key: Key('channels-skeleton-row-label-$index'), - width: widths[index], - height: 16, + Flexible( + child: SkeletonBar( + key: Key('channels-skeleton-row-label-$index'), + width: widths[index], + height: 16, + ), ), ], ), diff --git a/mobile/lib/features/channels/compose_bar.dart b/mobile/lib/features/channels/compose_bar.dart index 1702c05739..6b35bdd8ab 100644 --- a/mobile/lib/features/channels/compose_bar.dart +++ b/mobile/lib/features/channels/compose_bar.dart @@ -9,6 +9,8 @@ import 'dart:math' as math; import 'dart:ui' show FlutterView; import 'package:camera/camera.dart' as camera; +import 'package:duo_kit/duo_kit.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; diff --git a/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart b/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart index 18c4be9b5a..a623f19644 100644 --- a/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart +++ b/mobile/lib/features/channels/compose_bar/compose_bar_widget.dart @@ -974,6 +974,7 @@ class ComposeBar extends HookConsumerWidget { iosAttachmentPopover .present( sourceContext: triggerContext, + composerContext: sendSurfaceKey.currentContext ?? context, onCapture: (image) => retainAndQueueImages([image]), onChoosePhotos: retainAndQueueImages, onAllPhotos: () => chooseAttachment(() async { diff --git a/mobile/lib/features/channels/compose_bar/ios_attachment_popover.dart b/mobile/lib/features/channels/compose_bar/ios_attachment_popover.dart index bd4ba9e5de..efea37b362 100644 --- a/mobile/lib/features/channels/compose_bar/ios_attachment_popover.dart +++ b/mobile/lib/features/channels/compose_bar/ios_attachment_popover.dart @@ -42,6 +42,7 @@ class _IOSAttachmentPopoverCoordinator { Future present({ required Object owner, required BuildContext sourceContext, + required BuildContext composerContext, required Future Function(XFile image) onCapture, required Future Function(List photos) onChoosePhotos, required VoidCallback onAllPhotos, @@ -80,7 +81,7 @@ class _IOSAttachmentPopoverCoordinator { } if (!identical(_activeOwner, owner)) return false; final supported = supportResult == true; - if (!supported || !sourceContext.mounted) { + if (!supported || !sourceContext.mounted || !composerContext.mounted) { _clearOwner(owner); return false; } @@ -91,6 +92,15 @@ class _IOSAttachmentPopoverCoordinator { return false; } final origin = renderObject.localToGlobal(Offset.zero); + final composerBox = composerContext.findRenderObject(); + final isDuo = + (DuoToolbarScope.maybeOf(composerContext)?.strip ?? + FoldGeometry.of(composerContext).strip) != + null; + final cameraCenterX = + isDuo && composerBox is RenderBox && composerBox.hasSize + ? composerBox.localToGlobal(Offset(composerBox.size.width / 2, 0)).dx + : null; _didPresent = true; final didPresent = @@ -99,6 +109,7 @@ class _IOSAttachmentPopoverCoordinator { 'y': origin.dy, 'width': renderObject.size.width, 'height': renderObject.size.height, + 'cameraCenterX': ?cameraCenterX, }) ?? false; if (!identical(_activeOwner, owner)) return false; @@ -186,6 +197,7 @@ class _IOSAttachmentPopoverCoordinator { class _IOSAttachmentPopoverController { Future present({ required BuildContext sourceContext, + required BuildContext composerContext, required Future Function(XFile image) onCapture, required Future Function(List photos) onChoosePhotos, required VoidCallback onAllPhotos, @@ -195,6 +207,7 @@ class _IOSAttachmentPopoverController { }) => _iosAttachmentPopoverCoordinator.present( owner: this, sourceContext: sourceContext, + composerContext: composerContext, onCapture: onCapture, onChoosePhotos: onChoosePhotos, onAllPhotos: onAllPhotos, diff --git a/mobile/lib/features/channels/me/me_page.dart b/mobile/lib/features/channels/me/me_page.dart index e3edc5fa01..aee4b4fb91 100644 --- a/mobile/lib/features/channels/me/me_page.dart +++ b/mobile/lib/features/channels/me/me_page.dart @@ -1,5 +1,7 @@ import 'dart:convert'; + import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -176,32 +178,46 @@ class MePage extends HookConsumerWidget { a.lastMessageAt ?? a.createdAt, ), ); - Widget row(Channel channel) => _MeChatRow( - channelId: channel.id, - name: channel.name, - isUnread: unreadIds.contains(channel.id), - onTap: () => Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => - ChannelDetailPage(channel: channel, personalChat: true), + Widget row(Channel channel) { + final pane = ConversationPaneScope.maybeOf(context); + final selected = pane?.selectedId == channel.id; + return DecoratedBox( + decoration: BoxDecoration( + color: selected ? context.colors.primaryContainer : null, + borderRadius: BorderRadius.circular(Radii.md), ), - ), - onLongPress: () => showChannelDetailsSheet( - context: context, - channel: channel, - currentPubkey: viewer, - onMemberTap: (context, pubkey) => showUserProfileSheet( - context, - pubkey, - names: channelIdentityNamesProvider(channel.id), - contextualActions: (_) => ChannelMemberProfileActions( - channel: channel, - pubkey: pubkey, + child: Semantics( + selected: selected, + child: _MeChatRow( + channelId: channel.id, + name: channel.name, + isUnread: unreadIds.contains(channel.id), + onLongPress: () => showChannelDetailsSheet( + context: context, + channel: channel, + currentPubkey: viewer, + onMemberTap: (context, pubkey) => showUserProfileSheet( + context, + pubkey, + names: channelIdentityNamesProvider(channel.id), + contextualActions: (_) => ChannelMemberProfileActions( + channel: channel, + pubkey: pubkey, + ), + ), + personalChat: true, + ), + onTap: () => openConversationPane( + context, + channel.id, + (_) => + ChannelDetailPage(channel: channel, personalChat: true), + ), ), ), - personalChat: true, - ), - ); + ); + } + final inventorySlivers = [ SliverPadding( padding: EdgeInsets.fromLTRB( diff --git a/mobile/lib/features/channels/media_viewer_page.dart b/mobile/lib/features/channels/media_viewer_page.dart index 2a03ce4baf..7f0737fa98 100644 --- a/mobile/lib/features/channels/media_viewer_page.dart +++ b/mobile/lib/features/channels/media_viewer_page.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'dart:io'; import 'dart:ui' show ImageFilter; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; @@ -19,6 +20,7 @@ import '../../shared/theme/theme.dart'; import '../../shared/widgets/buzz_loading_indicator.dart'; import '../../shared/widgets/concentric_sheet_surface.dart'; import '../../shared/widgets/page_indicator.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; import '../../shared/widgets/ios_navigation_bar.dart'; import '../../shared/widgets/navigation_backdrop.dart'; @@ -465,6 +467,13 @@ class MediaImageViewerPage extends HookConsumerWidget { onMore?.call(context, images[currentIndex.value].url); } + final toolbarScope = DuoToolbarScope.maybeOf(context); + final strip = defaultTargetPlatform == TargetPlatform.iOS + ? (toolbarScope == null + ? FoldGeometry.of(context).strip + : toolbarScope.strip) + : null; + final inRail = strip != null; final viewportHeight = MediaQuery.sizeOf(context).height; final dragProgress = (dragOffset.value / viewportHeight).clamp(0.0, 1.0); final imageScale = 1 - (dragProgress * 0.1); @@ -487,7 +496,37 @@ class MediaImageViewerPage extends HookConsumerWidget { ), ), body: Stack( + fit: StackFit.expand, children: [ + Theme( + data: ThemeData.dark(), + child: DuoToolbarPortal( + strip: strip, + active: + (toolbarScope?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true), + actions: [ + IosNavigationAction( + label: 'Close image viewer', + symbol: 'xmark', + onPressed: () => unawaited(dismiss()), + ), + if (onReply != null) + IosNavigationAction( + label: 'Reply in thread', + symbol: 'arrowshape.turn.up.left', + onPressed: () => unawaited(replyInThread()), + ), + if (onMore != null) + IosNavigationAction( + label: 'More image actions', + symbol: 'ellipsis', + onPressed: showMoreActions, + ), + ], + child: const SizedBox.shrink(), + ), + ), Positioned.fill( child: Transform.translate( offset: Offset(0, dragOffset.value), @@ -504,7 +543,9 @@ class MediaImageViewerPage extends HookConsumerWidget { itemBuilder: (context, index) { final image = images[index]; return Padding( - padding: _mediaViewerPadding(context), + padding: inRail + ? EdgeInsets.zero + : _mediaViewerPadding(context), child: LayoutBuilder( builder: (context, constraints) { final viewerSize = _imageViewerSize( @@ -590,6 +631,7 @@ class MediaImageViewerPage extends HookConsumerWidget { opacity: chromeOpacity, child: SafeArea( child: _MediaViewerBottomControls( + showActions: !inRail, images: images, currentIndex: currentIndex.value, onSelect: (index) { @@ -612,7 +654,9 @@ class MediaImageViewerPage extends HookConsumerWidget { ), ), ), - if (defaultTargetPlatform == TargetPlatform.iOS) + if (inRail) + const SizedBox.shrink() + else if (defaultTargetPlatform == TargetPlatform.iOS) Positioned( top: 0, left: 0, diff --git a/mobile/lib/features/channels/media_viewer_page/image_controls.dart b/mobile/lib/features/channels/media_viewer_page/image_controls.dart index c4e8102efa..aeb18846ce 100644 --- a/mobile/lib/features/channels/media_viewer_page/image_controls.dart +++ b/mobile/lib/features/channels/media_viewer_page/image_controls.dart @@ -1,6 +1,7 @@ part of '../media_viewer_page.dart'; class _MediaViewerBottomControls extends StatelessWidget { + final bool showActions; final List images; final int currentIndex; final ValueChanged onSelect; @@ -8,6 +9,7 @@ class _MediaViewerBottomControls extends StatelessWidget { final VoidCallback? onMore; const _MediaViewerBottomControls({ + this.showActions = true, required this.images, required this.currentIndex, required this.onSelect, @@ -22,13 +24,14 @@ class _MediaViewerBottomControls extends StatelessWidget { child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ - _MediaViewerCircleButton( - key: const ValueKey('message-media-image-viewer-reply-thread'), - icon: BuzzIcons.messageSquareReply, - tooltip: 'Reply in thread', - onPressed: onReply, - ), - const SizedBox(width: Grid.xxs), + if (showActions) + _MediaViewerCircleButton( + key: const ValueKey('message-media-image-viewer-reply-thread'), + icon: BuzzIcons.messageSquareReply, + tooltip: 'Reply in thread', + onPressed: onReply, + ), + if (showActions) const SizedBox(width: Grid.xxs), Expanded( child: images.length > 1 ? Theme( @@ -47,13 +50,14 @@ class _MediaViewerBottomControls extends StatelessWidget { ) : const SizedBox(height: 56), ), - const SizedBox(width: Grid.xxs), - _MediaViewerCircleButton( - key: const ValueKey('message-media-image-viewer-more-actions'), - icon: BuzzIcons.ellipsis, - tooltip: 'More image actions', - onPressed: onMore, - ), + if (showActions) const SizedBox(width: Grid.xxs), + if (showActions) + _MediaViewerCircleButton( + key: const ValueKey('message-media-image-viewer-more-actions'), + icon: BuzzIcons.ellipsis, + tooltip: 'More image actions', + onPressed: onMore, + ), ], ), ); diff --git a/mobile/lib/features/channels/native_photo_zoom_preview.dart b/mobile/lib/features/channels/native_photo_zoom_preview.dart index 33b455419d..34676636e6 100644 --- a/mobile/lib/features/channels/native_photo_zoom_preview.dart +++ b/mobile/lib/features/channels/native_photo_zoom_preview.dart @@ -7,6 +7,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import '../../shared/relay/media_image.dart'; +import '../../shared/widgets/ios_navigation_metrics.dart'; /// Message-scoped actions shared with the Flutter gallery. class NativePhotoActions { @@ -82,6 +83,7 @@ class NativePhotoZoomPreview { if (!context.mounted) return false; final configuration = createLocalImageConfiguration(context); final reduceMotion = MediaQuery.disableAnimationsOf(context); + final railMetrics = IosNavigationMetrics.of(context); final loads = _PhotoWindow(configuration, initialIndex, ( index, bytes, @@ -172,6 +174,9 @@ class NativePhotoZoomPreview { 'canMore': actions != null, 'canDelete': actions?.canDelete ?? false, 'reduceMotion': reduceMotion, + 'railCenterX': railMetrics.railCenterX, + 'railWindowWidth': railMetrics.windowSize?.width, + 'railWindowHeight': railMetrics.windowSize?.height, }); if (posterLoad != null && !cachedPoster) { unawaited( diff --git a/mobile/lib/features/channels/thread_detail_page.dart b/mobile/lib/features/channels/thread_detail_page.dart index b54fce0bae..ca70430636 100644 --- a/mobile/lib/features/channels/thread_detail_page.dart +++ b/mobile/lib/features/channels/thread_detail_page.dart @@ -1,4 +1,5 @@ import 'message_author_visibility.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'message_swipe_reply.dart'; import '../../shared/widgets/ios_scroll_to_top.dart'; import 'message_footer_layout.dart'; @@ -806,7 +807,8 @@ class ThreadDetailPage extends HookConsumerWidget { threadViewportVisible && readStateReady && appInUse && - (ModalRoute.of(context)?.isCurrent ?? true), + (ModalRoute.of(context)?.isCurrent ?? true) && + ConversationPaneScope.isActiveOf(context), onDwell: readVisibleReplies, keys: [threadHead.id, readingContentKey(allMsgs), navigationBottomInset], ); diff --git a/mobile/lib/features/channels/voice_note_composer_recorder.dart b/mobile/lib/features/channels/voice_note_composer_recorder.dart index deb60e11f3..0c418139b3 100644 --- a/mobile/lib/features/channels/voice_note_composer_recorder.dart +++ b/mobile/lib/features/channels/voice_note_composer_recorder.dart @@ -64,11 +64,23 @@ class VoiceNoteComposerRecorder extends HookConsumerWidget { return subscription.close; }, [recorder, onCancel]); - final route = ModalRoute.of(context); + // A root presentation covers nested composers without pushing on their + // local navigator. Observe every enclosing route so either path cancels. + final routes = >[]; + BuildContext? routeContext = context; + while (routeContext != null) { + final route = ModalRoute.of(routeContext); + if (route != null) routes.add(route); + routeContext = routeContext + .findAncestorStateOfType() + ?.context; + } useEffect(() { - if (route != null) voiceNoteRouteObserver.subscribe(routeAware, route); + for (final route in routes) { + voiceNoteRouteObserver.subscribe(routeAware, route); + } return () => voiceNoteRouteObserver.unsubscribe(routeAware); - }, [routeAware, route]); + }, [routeAware, ...routes]); Future finish() async { if (!isStarted.value || isStopping.value || error.value != null) return; diff --git a/mobile/lib/features/home/home_page.dart b/mobile/lib/features/home/home_page.dart index a6de3581f3..3613d70eae 100644 --- a/mobile/lib/features/home/home_page.dart +++ b/mobile/lib/features/home/home_page.dart @@ -1,3 +1,9 @@ +import 'package:duo_kit/duo_kit.dart'; + +import '../../shared/widgets/adaptive_conversation_pane.dart'; +import '../../shared/widgets/duo_workspace_scaffold.dart'; +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/ios_navigation_metrics.dart'; import '../../shared/widgets/android_expanding_menu_button.dart'; import 'package:flutter/material.dart'; @@ -57,6 +63,21 @@ class HomePage extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + final communityId = ref.watch( + activeCommunityProvider.select((value) => value.value?.id), + ); + final conversations = useMemoized(ConversationPaneController.new, [ + communityId, + ]); + useEffect(() => conversations.dispose, [conversations]); + useListenable(conversations); + final strip = FoldGeometry.of(context).strip; + final wide = usesConversationPanes(context, strip: strip); + final sidebarWidth = + defaultTargetPlatform == TargetPlatform.iOS && strip != null + ? 375.0 + : null; + final showWorkspaceNavigation = wide || conversations.selectedId == null; final route = ModalRoute.of(context); final coveringProgress = useAnimation( route?.secondaryAnimation ?? kAlwaysDismissedAnimation, @@ -80,7 +101,13 @@ class HomePage extends HookConsumerWidget { final reducedMotion = MediaQuery.disableAnimationsOf(context); void openSearch() => Navigator.of(context).push( BottomUpPageRoute( - builder: (_) => const CoveredRouteKeyboardInsets(child: SearchPage()), + builder: (_) => CoveredRouteKeyboardInsets( + child: AdaptiveConversationDestination( + preferredListWidth: sidebarWidth, + listToolbarSlots: 1, + child: const SearchPage(), + ), + ), reducedMotion: reducedMotion, ), ); @@ -99,7 +126,10 @@ class HomePage extends HookConsumerWidget { final solo = mePageBuilder?.call(context, newChat, newWorkspace); void openInbox() => Navigator.of(context).push( BottomUpPageRoute( - builder: (_) => const ActivityPage(), + builder: (_) => AdaptiveConversationDestination( + preferredListWidth: sidebarWidth, + child: const ActivityPage(), + ), reducedMotion: reducedMotion, ), ); @@ -277,92 +307,201 @@ class HomePage extends HookConsumerWidget { }, ); final bottom = mobileTabBarBottom(context); - return Scaffold( - resizeToAvoidBottomInset: false, - // Register the floating controls with Scaffold so snackbars clear them. - extendBody: true, - bottomNavigationBar: Padding( - padding: EdgeInsets.only(bottom: bottom), - child: SizedBox( - height: mobileTabBarHeight, - child: - defaultTargetPlatform != TargetPlatform.iOS || - nativeControlsVisible - ? Center( - child: MessagesNavigationBar( - onSearch: openSearch, - agent: defaultAgentBuilder(context), - creationActions: [ - ( - label: 'New chat', - symbol: 'square.and.pencil', - onPressed: newChat.value, - ), - ( - label: 'New workspace', - symbol: 'workspace', - onPressed: newWorkspace.value, - ), - ( - label: 'New DM', - symbol: 'bubble.left', - onPressed: newDm.value, - ), - ( - label: 'New channel', - symbol: 'number', - onPressed: newChannel.value, - ), - ], - ), - ) - : null, - ), + Widget navigationBar(Axis axis) => MessagesNavigationBar( + axis: axis, + onSearch: openSearch, + agent: ConversationPaneScope( + controller: conversations, + child: Builder(builder: defaultAgentBuilder), ), - body: Stack( - children: [ - if (defaultTargetPlatform == TargetPlatform.iOS) - HomeScreenShortcutHost( - newChat: newChat, - newDm: newDm, - onAgents: onAgents, - openBestieConversation: openBestieConversation, - ), - MediaQuery( - data: MediaQuery.of(context).copyWith( - padding: MediaQuery.paddingOf(context).copyWith( - bottom: - MediaQuery.paddingOf(context).bottom + - mobileTabBarHeight + - mobileTabBarBottomGap, + creationActions: [ + ( + label: 'New chat', + symbol: 'square.and.pencil', + onPressed: newChat.value, + ), + ( + label: 'New workspace', + symbol: 'workspace', + onPressed: newWorkspace.value, + ), + (label: 'New DM', symbol: 'bubble.left', onPressed: newDm.value), + (label: 'New channel', symbol: 'number', onPressed: newChannel.value), + ], + ); + return DuoWorkspaceScaffold( + navigationBuilder: (context, placement) => + wide || + !showWorkspaceNavigation || + !nativeControlsVisible || + communitySurfaceProgress.value != 0 + ? const SizedBox.shrink() + : Transform.translate( + offset: Offset( + IosNavigationMetrics.of(context).railCenter( + MediaQuery.sizeOf(context), + strip!.rect.center.dx, + ) - + strip.rect.center.dx, + 0, ), - viewPadding: MediaQuery.viewPaddingOf(context).copyWith( - bottom: - MediaQuery.viewPaddingOf(context).bottom + - mobileTabBarHeight + - mobileTabBarBottomGap, + child: SafeArea( + bottom: false, + child: Padding( + // Match the compact composer's safe-area gutter and its + // downward resting offset in _ComposerDockFrame. + padding: EdgeInsets.only( + bottom: + (MediaQuery.viewPaddingOf(context).bottom + + Grid.xxs - + Grid.twelve - + Grid.quarter) + .clamp(0.0, double.infinity), + ), + child: Align( + alignment: Alignment.bottomCenter, + child: navigationBar(Axis.vertical), + ), + ), ), ), - child: Opacity( - key: const Key('home-community-surface-visibility'), - // The switcher uses a transparent route for its avatar flight. - // Keep Home laid out, but do not paint it through UIKit glass. - opacity: communitySurfaceProgress.value == 0 ? 1 : 0, - child: messages, - ), - ), - Positioned( - left: 0, - right: 0, - bottom: 0, - child: IgnorePointer( - child: MobileTabFooterBackdrop( - height: mobileTabFooterBackdropHeight(context), - tint: context.controlSurface, + body: Scaffold( + resizeToAvoidBottomInset: false, + extendBody: true, + bottomNavigationBar: strip == null && showWorkspaceNavigation + ? Padding( + padding: EdgeInsets.only(bottom: bottom), + child: SizedBox( + height: mobileTabBarHeight, + child: + (defaultTargetPlatform != TargetPlatform.iOS || + nativeControlsVisible) + ? Center(child: navigationBar(Axis.horizontal)) + : null, + ), + ) + : null, + body: Stack( + children: [ + if (defaultTargetPlatform == TargetPlatform.iOS) + ConversationPaneScope( + controller: conversations, + child: HomeScreenShortcutHost( + newChat: newChat, + newDm: newDm, + onAgents: onAgents, + openBestieConversation: openBestieConversation, + ), + ), + MediaQueryOverride( + transform: (media) => media.copyWith( + padding: media.padding.copyWith( + bottom: + media.padding.bottom + + (strip == null && showWorkspaceNavigation + ? mobileTabBarHeight + mobileTabBarBottomGap + : 0), + ), + viewPadding: media.viewPadding.copyWith( + bottom: + media.viewPadding.bottom + + (strip == null && showWorkspaceNavigation + ? mobileTabBarHeight + mobileTabBarBottomGap + : 0), + ), + ), + child: Opacity( + key: const Key('home-community-surface-visibility'), + // The switcher uses a transparent route for its avatar flight. + // Keep Home laid out, but do not paint it through UIKit glass. + opacity: communitySurfaceProgress.value == 0 ? 1 : 0, + child: AdaptiveConversationPane( + controller: conversations, + strip: strip, + preferredListWidth: sidebarWidth, + emptyContent: strip == null + ? null + : Image.asset( + 'assets/images/buzz-icon.png', + width: 80, + color: Theme.of(context).colorScheme.onSurfaceVariant, + colorBlendMode: BlendMode.srcIn, + semanticLabel: 'Buzz', + ), + list: wide && strip != null + ? Builder( + builder: (paneContext) { + final paneMedia = MediaQuery.of(paneContext); + final insets = + DuoToolbarScope.maybeOf( + paneContext, + )?.contentInsets ?? + EdgeInsets.zero; + return Stack( + fit: StackFit.expand, + children: [ + MediaQuery( + data: paneMedia.copyWith( + padding: paneMedia.padding.copyWith( + bottom: + paneMedia.padding.bottom + + mobileTabBarHeight + + mobileTabBarBottomGap, + ), + viewPadding: paneMedia.viewPadding.copyWith( + bottom: + paneMedia.viewPadding.bottom + + mobileTabBarHeight + + mobileTabBarBottomGap, + ), + ), + child: messages, + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + child: IgnorePointer( + child: MobileTabFooterBackdrop( + height: mobileTabFooterBackdropHeight( + paneContext, + ), + tint: paneContext.controlSurface, + ), + ), + ), + if (nativeControlsVisible) + Positioned( + left: insets.left, + right: insets.right, + bottom: mobileTabBarBottom(paneContext), + height: mobileTabBarHeight, + child: Center( + child: navigationBar(Axis.horizontal), + ), + ), + ], + ); + }, + ) + : messages, + ), ), ), - ), - ], + if (strip == null && showWorkspaceNavigation) + Positioned( + left: 0, + right: 0, + bottom: 0, + child: IgnorePointer( + child: MobileTabFooterBackdrop( + height: mobileTabFooterBackdropHeight(context), + tint: context.controlSurface, + ), + ), + ), + ], + ), ), ); } diff --git a/mobile/lib/features/home/home_screen_shortcut_host.dart b/mobile/lib/features/home/home_screen_shortcut_host.dart index 144f4595e6..066376ba19 100644 --- a/mobile/lib/features/home/home_screen_shortcut_host.dart +++ b/mobile/lib/features/home/home_screen_shortcut_host.dart @@ -8,6 +8,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../shared/me/default_agent.dart'; import '../../shared/profile/user_cache_provider.dart'; import '../../shared/shortcuts/home_screen_shortcuts.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; /// Publishes Home's app icon quick actions and runs a tapped one. /// @@ -117,7 +118,8 @@ class HomeScreenShortcutHost extends HookConsumerWidget { (route) => route.isFirst || (route is ModalRoute && - route.popDisposition == RoutePopDisposition.doNotPop), + route.popDisposition == RoutePopDisposition.doNotPop && + !popCompactConversationDestination(route)), ); } // Drop the tap when a screen kept Home covered or opened over it diff --git a/mobile/lib/features/home/messages_navigation_bar.dart b/mobile/lib/features/home/messages_navigation_bar.dart index a90f229b3d..69aca5fcf4 100644 --- a/mobile/lib/features/home/messages_navigation_bar.dart +++ b/mobile/lib/features/home/messages_navigation_bar.dart @@ -18,7 +18,9 @@ class MessagesNavigationBar extends HookWidget { required this.onSearch, required this.creationActions, required this.agent, + this.axis = Axis.horizontal, }); + final Axis axis; final VoidCallback onSearch; final Widget agent; final List<({String label, String symbol, VoidCallback? onPressed})> @@ -27,6 +29,68 @@ class MessagesNavigationBar extends HookWidget { @override Widget build(BuildContext context) { final menuOpen = useState(false); + useEffect(() { + menuOpen.value = false; + return null; + }, [axis]); + if (axis == Axis.vertical) { + return SizedBox( + width: 56, + height: 168 + Grid.xs * 2, + child: Stack( + children: [ + IosMessageCreateButton( + key: const ValueKey('vertical-create-menu'), + mergingNavigation: true, + navigationAxis: Axis.vertical, + onMenuVisibilityChanged: (visible) => menuOpen.value = visible, + actions: creationActions, + dividerBefore: const {2}, + sectionTitles: const {0: 'Solo', 2: 'Team'}, + accessibilityLabel: 'New', + width: 56, + height: 168 + Grid.xs * 2, + plain: false, + ), + Positioned( + top: 0, + width: 56, + height: 56 + Grid.xs / 2, + child: ClipRect( + child: Align( + alignment: Alignment.topCenter, + child: _MenuNudge( + axis: Axis.vertical, + offset: menuOpen.value ? 56 + Grid.xs : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: _search(context), + ), + ), + ), + ), + Positioned( + bottom: 0, + width: 56, + height: 56 + Grid.xs / 2, + child: ClipRect( + child: Align( + alignment: Alignment.bottomCenter, + child: _MenuNudge( + axis: Axis.vertical, + offset: menuOpen.value ? -56 - Grid.xs : 0, + menuOpen: menuOpen.value, + alignment: Alignment.center, + child: NavigationGlassGroup(child: agent), + ), + ), + ), + ), + ], + ), + ); + } + if (defaultTargetPlatform == TargetPlatform.iOS) { return SizedBox( width: 256, @@ -34,6 +98,7 @@ class MessagesNavigationBar extends HookWidget { child: Stack( children: [ IosMessageCreateButton( + key: const ValueKey('horizontal-create-menu'), mergingNavigation: true, onMenuVisibilityChanged: (visible) => menuOpen.value = visible, actions: creationActions, @@ -120,11 +185,13 @@ class MessagesNavigationBar extends HookWidget { class _MenuNudge extends StatelessWidget { const _MenuNudge({ required this.offset, + this.axis = Axis.horizontal, required this.menuOpen, required this.alignment, required this.child, }); final double offset; + final Axis axis; final bool menuOpen; final Alignment alignment; final Widget child; @@ -143,8 +210,11 @@ class _MenuNudge extends StatelessWidget { duration: duration, curve: Curves.easeOutCubic, transformAlignment: alignment, - transform: Matrix4.translationValues(offset, 0, 0) - ..scaleByDouble(scale, scale, 1, 1), + transform: Matrix4.translationValues( + axis == Axis.horizontal ? offset : 0, + axis == Axis.vertical ? offset : 0, + 0, + )..scaleByDouble(scale, scale, 1, 1), child: child, ), ), diff --git a/mobile/lib/features/invites/invite_create_page.dart b/mobile/lib/features/invites/invite_create_page.dart index 30812a9e0b..12bec8970b 100644 --- a/mobile/lib/features/invites/invite_create_page.dart +++ b/mobile/lib/features/invites/invite_create_page.dart @@ -2,6 +2,11 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'dart:async'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/ios_navigation_bar.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:buzz/shared/theme/buzz_icons.dart'; @@ -25,40 +30,145 @@ part 'invite_create_page/invite_link_section.dart'; part 'invite_create_page/person_invite_section.dart'; /// A page for authorized community members to create and send invitations. -class CommunityInvitePage extends ConsumerWidget { +class CommunityInvitePage extends HookConsumerWidget { /// Creates the community invitation page. const CommunityInvitePage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final roleAsync = ref.watch(currentCommunityRoleProvider); - return FrostedScaffold( - useUtilitySurfaceTheme: true, - appBar: const FrostedAppBar( - centerTitle: true, - nativeLargeTitle: true, - title: Text('Invite to community'), + final bodyKey = useMemoized(GlobalKey.new); + final optionsNavigator = useMemoized(() => GlobalKey()); + final scope = DuoToolbarScope.maybeOf(context); + final strip = scope?.strip ?? FoldGeometry.of(context).strip; + final split = + defaultTargetPlatform == TargetPlatform.iOS && + strip != null && + usesConversationPanes(context, strip: strip); + final form = roleAsync.when( + loading: () => const Center( + child: BuzzLoadingIndicator( + size: 48, + semanticLabel: 'Checking community permissions', + ), ), - body: roleAsync.when( - loading: () => const Center( - child: BuzzLoadingIndicator( - size: 48, - semanticLabel: 'Checking community permissions', + error: (_, _) => _InvitePermissionError( + onRetry: () => ref.invalidate(communityMembershipProvider), + ), + data: (role) => canManageCommunityInvites(role) + ? _CommunityInviteBody(role: role!, split: split) + : const _InvitePermissionDenied(), + ); + final body = KeyedSubtree( + key: bodyKey, + child: LayoutBuilder( + builder: (context, constraints) => MediaQuery( + data: MediaQuery.of(context).copyWith( + size: constraints.biggest, + padding: split + ? MediaQuery.paddingOf(context).copyWith(left: 0, right: 0) + : null, + viewPadding: split + ? MediaQuery.viewPaddingOf(context).copyWith(left: 0, right: 0) + : null, + ), + child: NavigatorPopHandler( + onPopWithResult: (_) => optionsNavigator.currentState!.pop(), + child: Navigator( + key: optionsNavigator, + pages: [MaterialPage(child: form)], + onDidRemovePage: (_) {}, + ), ), ), - error: (_, _) => _InvitePermissionError( - onRetry: () => ref.invalidate(communityMembershipProvider), + ), + ); + if (!split) { + return FrostedScaffold( + useUtilitySurfaceTheme: true, + appBar: const FrostedAppBar( + centerTitle: true, + nativeLargeTitle: true, + title: Text('Invite to community'), + ), + body: body, + ); + } + return Theme( + data: utilitySurfaceThemeData(Theme.of(context)), + child: DuoToolbarScope( + strip: strip, + active: scope?.active ?? true, + child: Scaffold( + body: Padding( + padding: EdgeInsets.only( + left: strip.side == FoldStripSide.left ? strip.width : 0, + right: strip.side == FoldStripSide.right ? strip.width : 0, + ), + child: Row( + children: [ + SizedBox( + width: 375.0.clamp( + 0.0, + (MediaQuery.sizeOf(context).width - strip.width - 1) / 2, + ), + child: DuoToolbarPortal( + strip: strip, + active: + (scope?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true), + actions: [ + if (Navigator.canPop(context)) + IosNavigationAction( + label: 'Back', + symbol: 'chevron.backward', + onPressed: () { + final local = optionsNavigator.currentState; + if (local?.canPop() ?? false) { + local!.pop(); + } else { + Navigator.of(context).maybePop(); + } + }, + ), + ], + child: const SizedBox.expand( + key: ValueKey('invite-title-pane'), + child: IosNavigationBar( + title: 'Invite to community', + standaloneLargeTitle: true, + ), + ), + ), + ), + VerticalDivider( + width: 1, + thickness: 1, + color: context.colors.outlineVariant, + ), + Expanded( + child: SafeArea( + left: false, + right: false, + child: SizedBox.expand( + key: const ValueKey('invite-controls-pane'), + child: body, + ), + ), + ), + ], + ), + ), ), - data: (role) => canManageCommunityInvites(role) - ? _CommunityInviteBody(role: role!) - : const _InvitePermissionDenied(), ), ); } } class _CommunityInviteBody extends StatelessWidget { - const _CommunityInviteBody({required this.role}); + const _CommunityInviteBody({required this.role, this.split = false}); + + final bool split; final CommunityMemberRole role; @@ -67,7 +177,9 @@ class _CommunityInviteBody extends StatelessWidget { return ListView( padding: EdgeInsets.fromLTRB( 0, - frostedAppBarHeight(context, nativeLargeTitle: true) + Grid.xs, + split + ? Grid.sm + : frostedAppBarHeight(context, nativeLargeTitle: true) + Grid.xs, 0, Grid.lg, ), diff --git a/mobile/lib/features/invites/invite_create_page/invite_link_section.dart b/mobile/lib/features/invites/invite_create_page/invite_link_section.dart index a9ca97f4be..9a97241560 100644 --- a/mobile/lib/features/invites/invite_create_page/invite_link_section.dart +++ b/mobile/lib/features/invites/invite_create_page/invite_link_section.dart @@ -170,11 +170,15 @@ void _showInviteOptionSheet({ showBuzzModalBottomSheet( context: context, showDragHandle: true, - builder: (_) => _InviteOptionSheet( - title: title, - value: value, - options: options, - onSelected: onSelected, + useDuoFullWidth: false, + isScrollControlled: true, + builder: (_) => SingleChildScrollView( + child: _InviteOptionSheet( + title: title, + value: value, + options: options, + onSelected: onSelected, + ), ), ); } diff --git a/mobile/lib/features/pairing/pairing_page.dart b/mobile/lib/features/pairing/pairing_page.dart index 11f6e02444..7032faddf5 100644 --- a/mobile/lib/features/pairing/pairing_page.dart +++ b/mobile/lib/features/pairing/pairing_page.dart @@ -172,7 +172,10 @@ class PairingPage extends HookConsumerWidget { Future openScanner() async { unawaited(HapticFeedback.selectionClick()); - final usesDynamicIslandPortal = await usesDynamicIslandQrScannerPortal(); + final cameraFrame = await resolveDuoQrScannerCameraFrame(context); + if (!context.mounted) return; + final usesDynamicIslandPortal = + cameraFrame != null || await usesDynamicIslandQrScannerPortal(); if (!context.mounted) { return; } @@ -186,6 +189,7 @@ class PairingPage extends HookConsumerWidget { try { code = await showDynamicIslandPairingQrScanner( context, + cameraFrame: cameraFrame, onProgress: (value) { if (context.mounted) islandScannerProgress.value = value; }, @@ -372,6 +376,14 @@ class PairingPage extends HookConsumerWidget { backgroundColor: Colors.transparent, appBar: pairingAppBar, body: SafeArea( + minimum: websiteWelcome + ? EdgeInsets.symmetric( + horizontal: math.max( + MediaQuery.paddingOf(context).left, + MediaQuery.paddingOf(context).right, + ), + ) + : EdgeInsets.zero, child: ValueListenableBuilder( valueListenable: islandScannerProgress, builder: (context, progress, child) => ExcludeFocus( diff --git a/mobile/lib/features/pairing/pairing_page/pairing_welcome_view.dart b/mobile/lib/features/pairing/pairing_page/pairing_welcome_view.dart index d63d271472..7c8a0c185e 100644 --- a/mobile/lib/features/pairing/pairing_page/pairing_welcome_view.dart +++ b/mobile/lib/features/pairing/pairing_page/pairing_welcome_view.dart @@ -414,29 +414,37 @@ class _PairingWelcomeView extends HookWidget { alignment: Alignment.bottomCenter, children: [ for (var page = 1; page < 5; page++) - ExcludeFocus( - excluding: page != selectedPage, - child: ExcludeSemantics( + Positioned( + // Only the visible panel determines the footer height. + left: page == selectedPage ? null : 0, + right: page == selectedPage ? null : 0, + bottom: page == selectedPage ? null : 0, + child: ExcludeFocus( excluding: page != selectedPage, - child: IgnorePointer( - ignoring: page != selectedPage, - child: AnimatedSlide( - key: ValueKey('welcome-panel-$page'), - offset: Offset( - page == selectedPage - ? 0 - : page == 1 - ? -1 - : 1, - 0, - ), - duration: revealDuration, - curve: page == selectedPage - ? Curves.easeOutQuad - : Curves.easeOutCubic.flipped, - child: SizedBox( - width: double.infinity, - child: actions(page), + child: ExcludeSemantics( + excluding: page != selectedPage, + child: IgnorePointer( + ignoring: page != selectedPage, + child: AnimatedSlide( + key: ValueKey( + 'welcome-panel-$page', + ), + offset: Offset( + page == selectedPage + ? 0 + : page == 1 + ? -1 + : 1, + 0, + ), + duration: revealDuration, + curve: page == selectedPage + ? Curves.easeOutQuad + : Curves.easeOutCubic.flipped, + child: SizedBox( + width: double.infinity, + child: actions(page), + ), ), ), ), diff --git a/mobile/lib/features/pairing/pairing_qr_scanner.dart b/mobile/lib/features/pairing/pairing_qr_scanner.dart index 95891855ef..69461f5c0d 100644 --- a/mobile/lib/features/pairing/pairing_qr_scanner.dart +++ b/mobile/lib/features/pairing/pairing_qr_scanner.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:math' as math; import 'dart:ui' show lerpDouble; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; @@ -19,6 +20,60 @@ part 'pairing_qr_scanner/scanner_camera.dart'; const _qrScannerPlatformChannel = MethodChannel('buzz/qr_scanner'); +/// The closed Duo camera cutout. Unfolded displays use the drawer scanner. +Rect? duoQrScannerCameraFrame(BuildContext context) { + if (defaultTargetPlatform != TargetPlatform.iOS) return null; + final fold = FoldGeometry.of(context); + if (fold.division != null) return null; + + for (final rect in fold.occlusions) { + if (rect.width > 0 && + (rect.width - rect.height).abs() < 1 && + rect.left > 0 && + rect.top > 0 && + rect.right < fold.size.width && + rect.bottom < fold.size.height && + (fold.strip?.rect.contains(rect.center) ?? false)) { + return rect; + } + } + return null; +} + +/// Resolves the cover camera even when Flutter publishes no display features. +Future resolveDuoQrScannerCameraFrame(BuildContext context) async { + if (FoldGeometry.of(context).division != null) return null; + final reported = duoQrScannerCameraFrame(context); + if (reported != null || defaultTargetPlatform != TargetPlatform.iOS) { + return reported; + } + final size = MediaQuery.sizeOf(context); + try { + final values = await _qrScannerPlatformChannel.invokeListMethod( + 'cameraCutoutFrame', + ); + if (!context.mounted || + MediaQuery.sizeOf(context) != size || + values == null || + values.length != 6 || + values.any((value) => !value.isFinite) || + (values[4] - size.width).abs() > 1 || + (values[5] - size.height).abs() > 1) { + return null; + } + return Rect.fromLTWH( + values[0].toDouble(), + values[1].toDouble(), + values[2].toDouble(), + values[3].toDouble(), + ); + } on PlatformException { + return null; + } on MissingPluginException { + return null; + } +} + /// Returns whether the current iPhone should use the Dynamic Island scanner. /// /// Android, iPad, and iPhones without a Dynamic Island always use the standard @@ -48,6 +103,7 @@ Future usesDynamicIslandQrScannerPortal() async { Future showDynamicIslandPairingQrScanner( BuildContext context, { ValueChanged? onProgress, + Rect? cameraFrame, }) { return Navigator.of(context).push( PageRouteBuilder( @@ -56,8 +112,11 @@ Future showDynamicIslandPairingQrScanner( barrierDismissible: false, transitionDuration: Duration.zero, reverseTransitionDuration: Duration.zero, - pageBuilder: (_, _, _) => - _DynamicIslandQrScannerPortal(onProgress: onProgress), + pageBuilder: (_, _, _) => _DynamicIslandQrScannerPortal( + onProgress: onProgress, + cameraFrame: cameraFrame, + sourceSize: MediaQuery.sizeOf(context), + ), ), ); } @@ -108,6 +167,7 @@ class DynamicIslandQrScannerGeometry { const DynamicIslandQrScannerGeometry({ required this.viewport, required this.safeAreaTop, + this.cameraFrame, }); /// The full logical-pixel size available to the portal route. @@ -116,6 +176,9 @@ class DynamicIslandQrScannerGeometry { /// The top safe-area inset reported by iOS. final double safeAreaTop; + /// The Duo camera cutout; null retains the Dynamic Island geometry. + final Rect? cameraFrame; + static const _collapsedWidth = 120.0; static const _collapsedHeight = 36.0; static const _fallbackTop = 11.0; @@ -129,15 +192,50 @@ class DynamicIslandQrScannerGeometry { _fallbackTop + math.max(0, safeAreaTop - _referenceSafeAreaTop); /// The portal frame before the opening animation starts. - Rect get collapsedFrame => Rect.fromLTWH( - (viewport.width - _collapsedWidth) / 2, - top, - _collapsedWidth, - _collapsedHeight, - ); + Rect get collapsedFrame { + final camera = cameraFrame; + if (camera != null) { + // Match the cover's active-camera pill seen on-device: four points + // beyond the cutout at the outer end and 22 points toward the content. + final onBottom = camera.center.dy > viewport.height / 2; + return Rect.fromLTRB( + camera.left, + camera.top - (onBottom ? 22 : 4), + camera.right, + camera.bottom + (onBottom ? 4 : 22), + ); + } + return Rect.fromLTWH( + (viewport.width - _collapsedWidth) / 2, + top, + _collapsedWidth, + _collapsedHeight, + ); + } /// The square camera frame after the opening animation completes. Rect get expandedFrame { + final camera = cameraFrame == null ? null : collapsedFrame; + if (camera != null) { + final onRight = camera.center.dx > viewport.width / 2; + final onBottom = camera.center.dy > viewport.height / 2; + final horizontalRoom = onRight + ? camera.right - _edgeMargin + : viewport.width - _edgeMargin - camera.left; + final verticalRoom = onBottom + ? camera.bottom - _edgeMargin + : viewport.height - _edgeMargin - camera.top; + final size = math.min(420.0, math.min(horizontalRoom, verticalRoom)); + final left = onRight ? camera.right - size : camera.left; + final desiredTop = camera.center.dy > viewport.height / 2 + ? camera.bottom - size + : camera.top; + final top = desiredTop.clamp( + _edgeMargin, + viewport.height - _edgeMargin - size, + ); + return Rect.fromLTWH(left, top, size, size); + } final maxHeight = math.max( _collapsedHeight, viewport.height - top - _edgeMargin, @@ -153,7 +251,7 @@ class DynamicIslandQrScannerGeometry { final end = expandedFrame; return Rect.fromLTRB( lerpDouble(start.left, end.left, t)!, - top, + lerpDouble(start.top, end.top, t)!, lerpDouble(start.right, end.right, t)!, lerpDouble(start.bottom, end.bottom, t)!, ); @@ -162,14 +260,34 @@ class DynamicIslandQrScannerGeometry { /// Returns the portal corner radius at [progress]. double cornerRadiusAt(double progress) { final t = progress.clamp(0.0, 1.0); - return lerpDouble(_collapsedHeight / 2, _expandedCornerRadius, t)!; + return lerpDouble( + collapsedFrame.shortestSide / 2, + _expandedCornerRadius, + t, + )!; + } + + /// Keeps the camera-side corner concentric with a circular Duo cutout. + BorderRadius borderRadiusAt(double progress) { + final radius = Radius.circular(cornerRadiusAt(progress)); + final camera = cameraFrame; + if (camera == null || (camera.width - camera.height).abs() >= 1) { + return BorderRadius.all(radius); + } + final anchor = Radius.circular(camera.shortestSide / 2); + final right = camera.center.dx > viewport.width / 2; + final bottom = camera.center.dy > viewport.height / 2; + return BorderRadius.only( + topLeft: !right && !bottom ? anchor : radius, + topRight: right && !bottom ? anchor : radius, + bottomLeft: !right && bottom ? anchor : radius, + bottomRight: right && bottom ? anchor : radius, + ); } /// Returns the camera opacity after its delayed entrance. double scannerOpacityAt(double progress) { - return ((progress - _scannerFadeStart) / (1 - _scannerFadeStart)).clamp( - 0.0, - 1.0, - ); + final fadeStart = cameraFrame == null ? _scannerFadeStart : 0.35; + return ((progress - fadeStart) / (1 - fadeStart)).clamp(0.0, 1.0); } } diff --git a/mobile/lib/features/pairing/pairing_qr_scanner/dynamic_island_portal.dart b/mobile/lib/features/pairing/pairing_qr_scanner/dynamic_island_portal.dart index c2f8647a21..3ee9eab071 100644 --- a/mobile/lib/features/pairing/pairing_qr_scanner/dynamic_island_portal.dart +++ b/mobile/lib/features/pairing/pairing_qr_scanner/dynamic_island_portal.dart @@ -3,10 +3,17 @@ part of '../pairing_qr_scanner.dart'; // A smooth, non-bouncy spring inspired by Apple's public motion guidance; // these are our timings, not private Dynamic Island animation constants. const _dynamicIslandOpenDuration = Duration(milliseconds: 230); -const _dynamicIslandCloseDuration = Duration(milliseconds: 230); +const _dynamicIslandCloseDuration = Duration(milliseconds: 180); class _DynamicIslandQrScannerPortal extends HookWidget { - const _DynamicIslandQrScannerPortal({this.onProgress}); + const _DynamicIslandQrScannerPortal({ + this.onProgress, + this.cameraFrame, + required this.sourceSize, + }); + + final Rect? cameraFrame; + final Size sourceSize; final ValueChanged? onProgress; @@ -85,7 +92,9 @@ class _DynamicIslandQrScannerPortal extends HookWidget { ) .orCancel; } - if (closing && context.mounted) await finish(null); + if (closing && context.mounted) { + await finish(null); + } } on TickerCanceled { // A dismissal, motion-setting change, or unmount can retarget the spring. } @@ -98,7 +107,6 @@ class _DynamicIslandQrScannerPortal extends HookWidget { void closePortal() { if (isClosing.value || hasHandledResult.value) return; hasHandledResult.value = true; - unawaited(_setDynamicIslandScannerStatusBarHidden(false)); isClosing.value = true; } @@ -133,6 +141,9 @@ class _DynamicIslandQrScannerPortal extends HookWidget { final geometry = DynamicIslandQrScannerGeometry( viewport: constraints.biggest, safeAreaTop: MediaQuery.viewPaddingOf(context).top, + cameraFrame: + duoQrScannerCameraFrame(context) ?? + (constraints.biggest == sourceSize ? cameraFrame : null), ); return Stack( @@ -163,16 +174,14 @@ class _DynamicIslandQrScannerPortal extends HookWidget { key: const ValueKey( 'dynamic-island-qr-scanner-portal', ), - borderRadius: BorderRadius.circular( - geometry.cornerRadiusAt(progress), - ), + borderRadius: geometry.borderRadiusAt(progress), child: ColoredBox( color: Colors.black, child: Stack( fit: StackFit.expand, children: [ - // Start warming the camera on the first frame, - // and keep it mounted throughout dismissal. + // Warm the camera during opening; dispose only + // after the closing morph has finished. Opacity( opacity: scannerOpacity, child: _QrScannerCamera( diff --git a/mobile/lib/features/pairing/pairing_qr_scanner/fallback_scanner.dart b/mobile/lib/features/pairing/pairing_qr_scanner/fallback_scanner.dart index 52fd263ca5..30f7cd7558 100644 --- a/mobile/lib/features/pairing/pairing_qr_scanner/fallback_scanner.dart +++ b/mobile/lib/features/pairing/pairing_qr_scanner/fallback_scanner.dart @@ -117,8 +117,10 @@ class FallbackPairingQrScanner extends HookWidget { controller: controller, onDetect: handleDetection, ), - const IgnorePointer( - child: _FallbackQrScannerViewfinder(), + const Positioned.fill( + child: IgnorePointer( + child: _FallbackQrScannerViewfinder(), + ), ), ], ), @@ -209,23 +211,37 @@ class _FallbackQrScannerViewfinder extends StatelessWidget { Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { - final size = math.min( - constraints.maxWidth - (Grid.xl * 2), - constraints.maxHeight - 240, + final topInset = MediaQuery.paddingOf(context).top; + final exposedHeight = math.max( + 0.0, + constraints.maxHeight - topInset - _fallbackScannerSheetPeekHeight, + ); + final center = Offset( + constraints.maxWidth / 2, + topInset + exposedHeight / 2, + ); + final size = math.max( + 0.0, + math.min(constraints.maxWidth - (Grid.xl * 2), exposedHeight - 240), ); return Stack( fit: StackFit.expand, children: [ CustomPaint( + key: const ValueKey('fallback-qr-scanner-mask'), painter: _FallbackQrScannerViewfinderPainter( - viewfinderSize: math.max(0, size), + viewfinderSize: size, + center: center, ), ), Align( alignment: Alignment.center, child: Transform.translate( - offset: Offset(0, (size / 2) + Grid.md), + offset: Offset( + 0, + center.dy - constraints.maxHeight / 2 + (size / 2) + Grid.md, + ), child: Text( 'Scan a QR code', style: context.textTheme.bodyMedium?.copyWith( @@ -243,14 +259,18 @@ class _FallbackQrScannerViewfinder extends StatelessWidget { } class _FallbackQrScannerViewfinderPainter extends CustomPainter { - const _FallbackQrScannerViewfinderPainter({required this.viewfinderSize}); + const _FallbackQrScannerViewfinderPainter({ + required this.viewfinderSize, + required this.center, + }); final double viewfinderSize; + final Offset center; @override void paint(Canvas canvas, Size size) { final rect = Rect.fromCenter( - center: size.center(Offset.zero), + center: center, width: viewfinderSize, height: viewfinderSize, ); @@ -277,6 +297,7 @@ class _FallbackQrScannerViewfinderPainter extends CustomPainter { @override bool shouldRepaint(_FallbackQrScannerViewfinderPainter oldDelegate) { - return oldDelegate.viewfinderSize != viewfinderSize; + return oldDelegate.viewfinderSize != viewfinderSize || + oldDelegate.center != center; } } diff --git a/mobile/lib/features/pairing/pairing_qr_scanner/scanner_camera.dart b/mobile/lib/features/pairing/pairing_qr_scanner/scanner_camera.dart index 36fb196700..efc3b3b876 100644 --- a/mobile/lib/features/pairing/pairing_qr_scanner/scanner_camera.dart +++ b/mobile/lib/features/pairing/pairing_qr_scanner/scanner_camera.dart @@ -33,6 +33,28 @@ class _QrScannerCamera extends HookWidget { }, [controller]); final state = cameraState.value; final ready = state.isInitialized && state.isRunning; + final fold = FoldGeometry.of(context); + final correction = useFuture( + useMemoized(() async { + if (defaultTargetPlatform != TargetPlatform.iOS || + fold.strip == null || + !ready) { + return 0; + } + try { + return await _qrScannerPlatformChannel.invokeMethod( + 'previewRotationQuarterTurns', + state.deviceOrientation.name, + ) ?? + 0; + } on PlatformException { + return 0; + } on MissingPluginException { + return 0; + } + }, [ready, fold.size, fold.strip?.rect, state.deviceOrientation]), + preserveState: false, + ); return AnimatedOpacity( key: const ValueKey('qr-camera-ready-fade'), opacity: ready || state.error != null ? 1 : 0, @@ -40,46 +62,50 @@ class _QrScannerCamera extends HookWidget { ? Duration.zero : const Duration(milliseconds: 230), curve: Curves.easeOut, - child: MobileScanner( - controller: controller, - fit: BoxFit.cover, - errorBuilder: (context, error) { - final message = switch (error.errorCode) { - MobileScannerErrorCode.permissionDenied => - 'Camera permission is required to scan QR codes.\n\n' - 'Please grant camera access in your device settings.', - _ => - 'Could not start camera: ' - "${error.errorDetails?.message ?? 'unknown error'}", - }; - return ColoredBox( - color: Colors.black, - child: Center( - child: Padding( - padding: const EdgeInsets.all(Grid.sm), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - BuzzIcons.cameraOff, - size: 48, - color: Colors.white.withValues(alpha: 0.72), - ), - const SizedBox(height: Grid.xs), - Text( - message, - textAlign: TextAlign.center, - style: context.textTheme.bodyMedium?.copyWith( + child: RotatedBox( + key: const ValueKey('qr-camera-orientation'), + quarterTurns: state.error == null ? correction.data ?? 0 : 0, + child: MobileScanner( + controller: controller, + fit: BoxFit.cover, + errorBuilder: (context, error) { + final message = switch (error.errorCode) { + MobileScannerErrorCode.permissionDenied => + 'Camera permission is required to scan QR codes.\n\n' + 'Please grant camera access in your device settings.', + _ => + 'Could not start camera: ' + "${error.errorDetails?.message ?? 'unknown error'}", + }; + return ColoredBox( + color: Colors.black, + child: Center( + child: Padding( + padding: const EdgeInsets.all(Grid.sm), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + BuzzIcons.cameraOff, + size: 48, color: Colors.white.withValues(alpha: 0.72), ), - ), - ], + const SizedBox(height: Grid.xs), + Text( + message, + textAlign: TextAlign.center, + style: context.textTheme.bodyMedium?.copyWith( + color: Colors.white.withValues(alpha: 0.72), + ), + ), + ], + ), ), ), - ), - ); - }, - onDetect: onDetect, + ); + }, + onDetect: onDetect, + ), ), ); } diff --git a/mobile/lib/features/profile/animated_avatar_capture.dart b/mobile/lib/features/profile/animated_avatar_capture.dart index 2aec77c320..24b916c69d 100644 --- a/mobile/lib/features/profile/animated_avatar_capture.dart +++ b/mobile/lib/features/profile/animated_avatar_capture.dart @@ -17,6 +17,7 @@ import 'package:path_provider/path_provider.dart'; import '../../shared/emoji/emoji_avatar.dart'; import '../../shared/relay/relay.dart'; import '../../shared/theme/theme.dart'; +import '../../shared/widgets/avatar_editor_options.dart'; import '../../shared/widgets/buzz_loading_indicator.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; import 'avatar_background_grid.dart'; diff --git a/mobile/lib/features/profile/animated_avatar_capture/review_controls.dart b/mobile/lib/features/profile/animated_avatar_capture/review_controls.dart index 851d5fe468..dff9a3c570 100644 --- a/mobile/lib/features/profile/animated_avatar_capture/review_controls.dart +++ b/mobile/lib/features/profile/animated_avatar_capture/review_controls.dart @@ -49,49 +49,37 @@ class _AnimatedReviewNav extends StatelessWidget { final VoidCallback? onRetake; @override - Widget build(BuildContext context) => Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: AvatarEditorOptionButton( - icon: BuzzIcons.userRound, - iosIcon: IosGlassNavigationIcon.person, - label: 'You', - selected: selected == _AnimatedReviewSection.person, - onTap: () => onSelected(_AnimatedReviewSection.person), - ), + Widget build(BuildContext context) => AvatarEditorOptions( + centered: false, + dividerBefore: 3, + options: [ + AvatarEditorOptionButton( + icon: BuzzIcons.userRound, + iosIcon: IosGlassNavigationIcon.person, + label: 'You', + selected: selected == _AnimatedReviewSection.person, + onTap: () => onSelected(_AnimatedReviewSection.person), ), - const SizedBox(width: Grid.half), - Expanded( - child: AvatarEditorOptionButton( - icon: BuzzIcons.palette, - iosIcon: IosGlassNavigationIcon.palette, - label: 'Background', - selected: selected == _AnimatedReviewSection.color, - onTap: () => onSelected(_AnimatedReviewSection.color), - ), + AvatarEditorOptionButton( + icon: BuzzIcons.palette, + iosIcon: IosGlassNavigationIcon.palette, + label: 'Background', + selected: selected == _AnimatedReviewSection.color, + onTap: () => onSelected(_AnimatedReviewSection.color), ), - const SizedBox(width: Grid.half), - Expanded( - child: AvatarEditorOptionButton( - icon: BuzzIcons.galleryThumbnails, - iosIcon: IosGlassNavigationIcon.frame, - label: 'Frame', - selected: selected == _AnimatedReviewSection.poster, - onTap: () => onSelected(_AnimatedReviewSection.poster), - ), + AvatarEditorOptionButton( + icon: BuzzIcons.galleryThumbnails, + iosIcon: IosGlassNavigationIcon.frame, + label: 'Frame', + selected: selected == _AnimatedReviewSection.poster, + onTap: () => onSelected(_AnimatedReviewSection.poster), ), - const SizedBox(width: Grid.half), - Container(width: 1, height: 64, color: context.colors.outlineVariant), - const SizedBox(width: Grid.half), - Expanded( - child: AvatarEditorOptionButton( - icon: BuzzIcons.camera, - iosIcon: IosGlassNavigationIcon.camera, - label: 'Retake', - selected: false, - onTap: onRetake, - ), + AvatarEditorOptionButton( + icon: BuzzIcons.camera, + iosIcon: IosGlassNavigationIcon.camera, + label: 'Retake', + selected: false, + onTap: onRetake, ), ], ); diff --git a/mobile/lib/features/profile/profile_edit_page.dart b/mobile/lib/features/profile/profile_edit_page.dart index 7388be3a2d..b0a45374b7 100644 --- a/mobile/lib/features/profile/profile_edit_page.dart +++ b/mobile/lib/features/profile/profile_edit_page.dart @@ -1,5 +1,6 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'dart:async'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -12,11 +13,13 @@ import '../../shared/profile/user_profile.dart'; import '../../shared/relay/relay.dart'; import '../../shared/emoji/emoji_data_provider.dart'; import '../../shared/theme/theme.dart'; +import '../../shared/widgets/avatar_editor_options_scope.dart'; import '../../shared/widgets/app_list.dart'; import '../../shared/widgets/app_list_card.dart'; import '../../shared/widgets/buzz_loading_indicator.dart'; import '../../shared/widgets/frosted_app_bar.dart'; import '../../shared/widgets/frosted_scaffold.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import '../../shared/widgets/ios_glass_navigation_action.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; import '../../shared/widgets/modal_presentation.dart'; @@ -52,6 +55,16 @@ class ProfileEditPage extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final reduceMotion = MediaQuery.disableAnimationsOf(context); + final directWideDuoEditor = useMemoized( + () => + startInPhotoEditor && + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null && + (View.of(context).physicalSize / View.of(context).devicePixelRatio) + .shortestSide >= + 600, + ); final profileAsync = ref.watch(profileProvider); final profile = profileAsync.asData?.value; final profileHydrated = profileAsync.hasValue; @@ -70,12 +83,13 @@ class ProfileEditPage extends HookConsumerWidget { final isImageCameraActive = useState(false); final avatarMode = useState(ProfileAvatarMode.image); final avatarTransition = useAnimationController( + initialValue: directWideDuoEditor ? 1 : 0, duration: reduceMotion ? Duration.zero : const Duration(milliseconds: 200), ); useEffect(() { - if (!startInPhotoEditor) return null; + if (!startInPhotoEditor || directWideDuoEditor) return null; WidgetsBinding.instance.addPostFrameCallback((_) { if (context.mounted) unawaited(avatarTransition.forward(from: 0)); }); @@ -168,7 +182,7 @@ class ProfileEditPage extends HookConsumerWidget { return; } isClosingAvatar.value = true; - await avatarTransition.reverse(); + if (!directWideDuoEditor) await avatarTransition.reverse(); if (!context.mounted) return; if (startInPhotoEditor) { Navigator.of(context).pop(); @@ -368,36 +382,43 @@ class ProfileEditPage extends HookConsumerWidget { height: constraints.maxHeight < 600 ? 700 : constraints.maxHeight, - child: ProfileAvatarEditor( - key: const ValueKey('profile-avatar-editor-page'), - currentAvatarUrl: profile?.avatarUrl, - fallbackInitial: profile?.initial ?? '?', - draft: activeDraft, - mode: avatarMode.value, - transition: avatarTransition, - onModeChanged: (nextMode) => - avatarMode.value = nextMode, - onDraftChanged: (draft) { - avatarDraft.value = draft; - avatarDraftMode.value = draft == null - ? null - : avatarMode.value; - }, - onAnimatedPrepareChanged: (prepare) { - prepareAnimatedAvatar.value = prepare; - canPrepareAnimatedAvatar.value = prepare != null; - if (avatarMode.value == - ProfileAvatarMode.animated) { - avatarDraft.value = null; - avatarDraftMode.value = null; - } - }, - onImageCameraActiveChanged: (active) { - isImageCameraActive.value = active; - }, - animatedCaptureBuilder: - animatedAvatarCaptureBuilder, - imageCaptureBuilder: imageAvatarCaptureBuilder, + child: AvatarEditorOptionsScope( + interactive: + profileHydrated && + !isSavingAvatar.value && + !isClosingAvatar.value, + child: ProfileAvatarEditor( + key: const ValueKey('profile-avatar-editor-page'), + currentAvatarUrl: profile?.avatarUrl, + fallbackInitial: profile?.initial ?? '?', + draft: activeDraft, + mode: avatarMode.value, + transition: avatarTransition, + onModeChanged: (nextMode) => + avatarMode.value = nextMode, + onDraftChanged: (draft) { + avatarDraft.value = draft; + avatarDraftMode.value = draft == null + ? null + : avatarMode.value; + }, + onAnimatedPrepareChanged: (prepare) { + prepareAnimatedAvatar.value = prepare; + canPrepareAnimatedAvatar.value = + prepare != null; + if (avatarMode.value == + ProfileAvatarMode.animated) { + avatarDraft.value = null; + avatarDraftMode.value = null; + } + }, + onImageCameraActiveChanged: (active) { + isImageCameraActive.value = active; + }, + animatedCaptureBuilder: + animatedAvatarCaptureBuilder, + imageCaptureBuilder: imageAvatarCaptureBuilder, + ), ), ), ), diff --git a/mobile/lib/features/profile/set_status_sheet.dart b/mobile/lib/features/profile/set_status_sheet.dart index 5114c987d2..ef54337a31 100644 --- a/mobile/lib/features/profile/set_status_sheet.dart +++ b/mobile/lib/features/profile/set_status_sheet.dart @@ -1,4 +1,9 @@ +import 'dart:async'; + +import 'package:duo_kit/duo_kit.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import 'package:flutter/cupertino.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -42,16 +47,129 @@ enum _StatusDuration { final Duration? duration; } -void showSetStatusSheet(BuildContext context, {UserStatus? currentStatus}) { - showBuzzModalBottomSheet( +bool _nativeStatusEditorOpen = false; + +Future showSetStatusSheet( + BuildContext context, { + UserStatus? currentStatus, +}) async { + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.iOS) { + if (_nativeStatusEditorOpen) return; + _nativeStatusEditorOpen = true; + try { + await _showNativeStatusEditor(context, currentStatus); + return; + } on MissingPluginException { + // Keep the portable editor available on hosts without the iOS plugin. + if (!context.mounted) return; + } finally { + _nativeStatusEditorOpen = false; + } + } + if (!context.mounted) return; + await showBuzzModalBottomSheet( context: context, isScrollControlled: true, showCloseButton: false, + showRailCloseButton: true, showDragHandle: false, builder: (_) => _SetStatusSheet(currentStatus: currentStatus), ); } +Future _showNativeStatusEditor( + BuildContext context, + UserStatus? currentStatus, +) async { + const channel = MethodChannel('buzz/profile_text_editor'); + final container = ProviderScope.containerOf(context, listen: false); + final notifier = container.read(userStatusProvider.notifier); + final sheetTheme = utilitySurfaceThemeData(Theme.of(context)); + final currentExpiration = currentStatus?.expirationDateTime; + var draft = { + 'text': currentStatus?.text ?? '', + 'emoji': currentStatus?.emoji ?? '', + 'duration': currentExpiration == null ? 86400 : 0, + 'expiresAt': currentExpiration == null + ? null + : currentExpiration.millisecondsSinceEpoch / 1000, + 'hasExistingStatus': currentStatus != null && !currentStatus.isEmpty, + 'brightness': sheetTheme.brightness.name, + 'pageBackgroundArgb': sheetTheme.colorScheme.surface.toARGB32(), + 'containerBackgroundArgb': sheetTheme.colorScheme.surfaceContainerHighest + .toARGB32(), + }; + channel.setMethodCallHandler((call) async { + if (call.method != 'chooseStatusEmoji' || !context.mounted) return null; + // Resolve the palette before opening the picker: its Flutter loading + // surface would otherwise sit underneath this native presentation. + await container.read(customEmojiPaletteProvider.future); + if (!context.mounted) return null; + final selection = Completer(); + showEmojiPicker( + context: context, + onSelect: (emoji) { + if (!selection.isCompleted) selection.complete(emoji); + }, + onDismiss: () { + if (!selection.isCompleted) selection.complete(null); + }, + ); + return selection.future; + }); + try { + while (context.mounted) { + final value = await channel.invokeMapMethod( + 'presentStatus', + draft, + ); + if (value == null) return; + final expiration = _nativeStatusExpiration(value['expiresAt']); + if (value['clear'] != true && expiration == null) { + // Preserve the edit, but replace the invalid date with the default preset + // so pressing Set again can recover without resubmitting the bad value. + draft = { + ...draft, + ...value, + 'duration': 86400, + 'expiresAt': null, + 'saveError': true, + }; + continue; + } + try { + if (value['clear'] == true) { + await notifier.clearStatus(); + } else { + await notifier.setStatus( + value['text'] as String, + value['emoji'] as String, + expiresAt: expiration, + ); + } + return; + } catch (_) { + // Reopen with the exact submitted draft, just like the native text forms. + // The error belongs to this editor, so it remains visible above the sheet. + draft = {...draft, ...value, 'saveError': true}; + } + } + } finally { + channel.setMethodCallHandler(null); + } +} + +DateTime? _nativeStatusExpiration(Object? value) { + // Validate before multiplying or rounding untrusted method-channel input. + if (value is! num || + !value.isFinite || + value < -8640000000000 || + value > 8640000000000) { + return null; + } + return DateTime.fromMillisecondsSinceEpoch((value * 1000).round()); +} + class _SetStatusSheet extends HookConsumerWidget { const _SetStatusSheet({this.currentStatus}); @@ -427,42 +545,49 @@ Future _showNativeDateTimePicker( if (defaultTargetPlatform == TargetPlatform.iOS) { var selected = safeInitial; - return showCupertinoModalPopup( - context: context, - builder: (pickerContext) => Material( - color: context.colors.surface, - child: SafeArea( - top: false, - child: Padding( - padding: const EdgeInsets.only(bottom: Grid.half), - child: SizedBox( - height: 300, - child: Column( - children: [ - Align( - alignment: Alignment.centerRight, - child: TextButton( - onPressed: () => - Navigator.of(pickerContext).pop(selected), - child: const Text('Done'), - ), + Widget picker(BuildContext pickerContext) => Material( + color: context.colors.surface, + child: SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.only(bottom: Grid.half), + child: SizedBox( + height: 300, + child: Column( + children: [ + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: () => Navigator.of(pickerContext).pop(selected), + child: const Text('Done'), ), - Expanded( - child: CupertinoDatePicker( - mode: CupertinoDatePickerMode.dateAndTime, - minimumDate: minimum, - initialDateTime: safeInitial, - use24hFormat: MediaQuery.alwaysUse24HourFormatOf(context), - onDateTimeChanged: (value) => selected = value, - ), + ), + Expanded( + child: CupertinoDatePicker( + mode: CupertinoDatePickerMode.dateAndTime, + minimumDate: minimum, + initialDateTime: safeInitial, + use24hFormat: MediaQuery.alwaysUse24HourFormatOf(context), + onDateTimeChanged: (value) => selected = value, ), - ], - ), + ), + ], ), ), ), ), ); + final strip = + DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip; + if (strip != null) { + return showBuzzModalBottomSheet( + context: context, + title: 'Custom expiration', + builder: picker, + ); + } + return showCupertinoModalPopup(context: context, builder: picker); } final lastDate = now.add(const Duration(days: 365)); diff --git a/mobile/lib/features/profile/user_profile_sheet.dart b/mobile/lib/features/profile/user_profile_sheet.dart index 05074406ac..eb92cedefc 100644 --- a/mobile/lib/features/profile/user_profile_sheet.dart +++ b/mobile/lib/features/profile/user_profile_sheet.dart @@ -70,6 +70,15 @@ void showUserProfileSheet( class UserProfileSheet extends HookConsumerWidget { final String pubkey; + /// Opens a conversation from an embedded profile without popping its pane. + final ValueChanged? onOpenChannel; + + /// Uses the available pane height instead of the modal sheet height cap. + final bool embedded; + + /// Insets the profile controls while artwork fills the surrounding pane. + final EdgeInsets contentPadding; + /// Agent artwork treatment within the profile sheet. final bool agentPresentation; final String? agentSubtitle; @@ -99,6 +108,9 @@ class UserProfileSheet extends HookConsumerWidget { const UserProfileSheet({ super.key, required this.pubkey, + this.onOpenChannel, + this.embedded = false, + this.contentPadding = EdgeInsets.zero, this.agentPresentation = false, this.agentSubtitle, this.agentSubtitleIcon, @@ -198,7 +210,11 @@ class UserProfileSheet extends HookConsumerWidget { .read(channelActionsProvider) .openDm(pubkeys: [pk], waitForChannelList: false); if (!context.mounted) return; - Navigator.of(context).pop(channel); + if (onOpenChannel != null) { + onOpenChannel!(channel); + } else { + Navigator.of(context).pop(channel); + } } catch (_) { // Silently fail — user tapped but DM open failed. if (context.mounted) isOpeningDirectMessage.value = false; @@ -207,7 +223,9 @@ class UserProfileSheet extends HookConsumerWidget { final content = ConstrainedBox( constraints: BoxConstraints( - maxHeight: MediaQuery.sizeOf(context).height * 0.7, + maxHeight: embedded + ? double.infinity + : MediaQuery.sizeOf(context).height * 0.7, ), child: Column( mainAxisSize: MainAxisSize.min, @@ -526,12 +544,17 @@ class UserProfileSheet extends HookConsumerWidget { return AgentArtworkPanel( imageUrl: avatarUrl, borderRadius: BorderRadius.zero, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - BuzzSheetHeader(leading: headerLeading), - Flexible(child: SafeArea(top: false, child: content)), - ], + child: SafeArea( + top: false, + bottom: false, + minimum: contentPadding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BuzzSheetHeader(leading: headerLeading), + Flexible(child: SafeArea(top: false, child: content)), + ], + ), ), ); } diff --git a/mobile/lib/features/search/search_page.dart b/mobile/lib/features/search/search_page.dart index cd852c94cf..68aef2733b 100644 --- a/mobile/lib/features/search/search_page.dart +++ b/mobile/lib/features/search/search_page.dart @@ -1,7 +1,14 @@ import '../../shared/widgets/top_edge_fade.dart'; + import 'dart:async'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; + +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/navigation_backdrop.dart'; +import '../../shared/widgets/ios_navigation_bar.dart'; + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -130,7 +137,7 @@ class SearchPage extends HookConsumerWidget { void closeSearch() { focusNode.unfocus(); - Navigator.of(context).maybePop(); + Navigator.of(context).pop(); } void runRecentSearch(String query) { @@ -143,124 +150,166 @@ class SearchPage extends HookConsumerWidget { ref.read(searchProvider.notifier).search(query); } - return Scaffold( - backgroundColor: context.colors.surface, - resizeToAvoidBottomInset: false, - body: SafeArea( - bottom: false, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Padding( - padding: const EdgeInsets.fromLTRB( - Grid.gutter, - Grid.half, - Grid.gutter, - Grid.xxs, - ), - child: Row( - children: [ - if (!embedded) ...[ - if (nativeIos) - IosGlassNavigationButton( - key: const Key('search-close'), - icon: IosGlassNavigationIcon.close, - semanticLabel: 'Close search', - onPressed: closeSearch, - controlSize: 48, - foregroundColor: searchPrimaryColor, - ) - else - SizedBox.square( - key: const Key('search-close'), - dimension: 48, - child: IconButton( - tooltip: 'Close search', - onPressed: closeSearch, - style: IconButton.styleFrom( - backgroundColor: searchSurfaceColor, - foregroundColor: searchPrimaryColor, - ), - icon: const Icon( - BuzzIcons.x, - size: buzzSearchControlIconSize, - ), - ), - ), - const SizedBox(width: Grid.xxs), - ], - Expanded( - child: SizedBox( - key: const Key('search-field-container'), - height: fieldHeight, - child: ConcentricSheetSurface( - enabled: nativeIos, - usesGlass: true, - providesSheetSurface: false, - padding: EdgeInsets.zero, - color: searchSurfaceColor, - minimumRadius: fieldHeight / 2, - contentClipRadius: fieldHeight / 2, - child: BuzzSearchField( - controller: textController, - focusNode: focusNode, - hintText: 'Search', - iconColor: searchPrimaryColor, - inputColor: searchPrimaryColor, - placeholderColor: searchPlaceholderColor, - surfaceColor: nativeIos - ? Colors.transparent - : searchSurfaceColor, - isEditing: false, - reduceMotion: true, - motionDuration: Duration.zero, - onTap: activateSearch, - onChanged: (value) => - ref.read(searchProvider.notifier).search(value), - onSubmitted: (value) { - final query = value.trim(); - if (query.isNotEmpty) { - ref - .read(recentSearchesProvider.notifier) - .record(query); - } - }, - ), - ), - ), + final toolbar = DuoToolbarScope.maybeOf(context); + final hasStrip = toolbar?.strip != null; + final compactDuo = hasStrip && isCompactDuoWindow(context); + return DuoToolbarPortal( + strip: toolbar?.strip, + active: + !embedded && + (toolbar?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true), + actions: [ + IosNavigationAction( + label: 'Close search', + symbol: 'xmark', + onPressed: closeSearch, + ), + ], + child: Scaffold( + backgroundColor: context.colors.surface, + resizeToAvoidBottomInset: false, + body: SafeArea( + left: !hasStrip, + right: !hasStrip, + top: !hasStrip, + bottom: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + NavigationBackdrop( + active: hasStrip, + suppressNativeView: !hasStrip, + child: Padding( + padding: EdgeInsets.only( + top: hasStrip ? MediaQuery.paddingOf(context).top : 0, + left: toolbar?.contentInsets.left ?? 0, + right: toolbar?.contentInsets.right ?? 0, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: EdgeInsets.fromLTRB( + Grid.gutter, + compactDuo ? Grid.xs : Grid.half, + Grid.gutter, + Grid.xxs, + ), + child: Row( + children: [ + if (!embedded && !hasStrip) ...[ + if (nativeIos) + IosGlassNavigationButton( + key: const Key('search-close'), + icon: IosGlassNavigationIcon.close, + semanticLabel: 'Close search', + onPressed: closeSearch, + controlSize: 48, + foregroundColor: searchPrimaryColor, + ) + else + SizedBox.square( + key: const Key('search-close'), + dimension: 48, + child: IconButton( + tooltip: 'Close search', + onPressed: closeSearch, + style: IconButton.styleFrom( + backgroundColor: searchSurfaceColor, + foregroundColor: searchPrimaryColor, + ), + icon: const Icon( + BuzzIcons.x, + size: buzzSearchControlIconSize, + ), + ), + ), + const SizedBox(width: Grid.xxs), + ], + Expanded( + child: SizedBox( + key: const Key('search-field-container'), + height: fieldHeight, + child: ConcentricSheetSurface( + enabled: nativeIos, + usesGlass: true, + providesSheetSurface: false, + padding: EdgeInsets.zero, + color: searchSurfaceColor, + minimumRadius: fieldHeight / 2, + contentClipRadius: fieldHeight / 2, + child: BuzzSearchField( + controller: textController, + focusNode: focusNode, + hintText: 'Search', + iconColor: searchPrimaryColor, + inputColor: searchPrimaryColor, + placeholderColor: searchPlaceholderColor, + surfaceColor: nativeIos + ? Colors.transparent + : searchSurfaceColor, + isEditing: false, + reduceMotion: true, + motionDuration: Duration.zero, + onTap: activateSearch, + onChanged: (value) => ref + .read(searchProvider.notifier) + .search(value), + onSubmitted: (value) { + final query = value.trim(); + if (query.isNotEmpty) { + ref + .read( + recentSearchesProvider.notifier, + ) + .record(query); + } + }, + ), + ), + ), + ), + ], + ), + ), + SizedBox( + key: const ValueKey('search-header-filters'), + height: filtersHeight, + child: FilterChipBar<_SearchFilter>( + useNativeGlass: nativeIos, + expandItems: true, + visualDensity: const VisualDensity(horizontal: -2), + chipVerticalPadding: _searchFilterChipVerticalPadding, + barVerticalPadding: _searchFilterBarVerticalPadding, + selected: activeFilter.value, + onSelected: (filter) => activeFilter.value = filter, + items: [ + for (final filter in _SearchFilter.values) + FilterChipItem(id: filter, label: filter.label), + ], + ), + ), + const SizedBox(height: Grid.xxs), + ], ), - ], - ), - ), - SizedBox( - key: const ValueKey('search-header-filters'), - height: filtersHeight, - child: FilterChipBar<_SearchFilter>( - useNativeGlass: nativeIos, - expandItems: true, - visualDensity: const VisualDensity(horizontal: -2), - chipVerticalPadding: _searchFilterChipVerticalPadding, - barVerticalPadding: _searchFilterBarVerticalPadding, - selected: activeFilter.value, - onSelected: (filter) => activeFilter.value = filter, - items: [ - for (final filter in _SearchFilter.values) - FilterChipItem(id: filter, label: filter.label), - ], - ), - ), - const SizedBox(height: Grid.xxs), - Expanded( - child: TopEdgeFade( - child: _SearchBody( - state: searchState, - filter: activeFilter.value, - currentPubkey: currentPubkey, - onRecentSearchSelected: runRecentSearch, ), ), - ), - ], + Expanded( + child: Padding( + padding: toolbar?.contentInsets ?? EdgeInsets.zero, + child: TopEdgeFade( + child: _SearchBody( + state: searchState, + filter: activeFilter.value, + currentPubkey: currentPubkey, + onRecentSearchSelected: runRecentSearch, + ), + ), + ), + ), + ], + ), ), ), ); @@ -670,12 +719,12 @@ class _PeopleSection extends ConsumerWidget { .read(channelActionsProvider) .openDm(pubkeys: [user.pubkey], waitForChannelList: false); if (!context.mounted) return; - await Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage( - channel: channel, - placement: ChannelRoutePlacement.ordinary, - ), + await openConversationPane( + context, + channel.id, + (_) => ChannelDetailPage( + channel: channel, + placement: ChannelRoutePlacement.ordinary, ), ); }, @@ -743,10 +792,10 @@ extension on _SearchFilter { Future _openSearchChannel(BuildContext context, Channel channel) async { try { if (!context.mounted) return; - await Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage(channel: channel), - ), + await openConversationPane( + context, + channel.id, + (_) => ChannelDetailPage(channel: channel), ); } catch (_) { if (!context.mounted) return; diff --git a/mobile/lib/features/search/search_page/message_tile.dart b/mobile/lib/features/search/search_page/message_tile.dart index f6c87e16f1..fd1747acec 100644 --- a/mobile/lib/features/search/search_page/message_tile.dart +++ b/mobile/lib/features/search/search_page/message_tile.dart @@ -199,15 +199,15 @@ class _MessageTile extends ConsumerWidget { if (channel == null || !context.mounted) return; if (hit.kind == 45001) { - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ForumThreadPage( - channelId: channel.id, - postEventId: hit.eventId, - currentPubkey: currentPubkey, - isMember: channel.isMember, - isArchived: channel.isArchived, - ), + openConversationPane( + context, + hit.eventId, + (_) => ForumThreadPage( + channelId: channel.id, + postEventId: hit.eventId, + currentPubkey: currentPubkey, + isMember: channel.isMember, + isArchived: channel.isArchived, ), ); } else { diff --git a/mobile/lib/features/settings/settings_page.dart b/mobile/lib/features/settings/settings_page.dart index 64750a2724..7600223f00 100644 --- a/mobile/lib/features/settings/settings_page.dart +++ b/mobile/lib/features/settings/settings_page.dart @@ -1,8 +1,11 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; + import 'dart:async'; import 'package:buzz/shared/crypto/event_signing.dart'; import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -28,6 +31,8 @@ import '../../shared/widgets/app_list.dart'; import '../../shared/widgets/app_list_card.dart'; import '../../shared/widgets/frosted_app_bar.dart'; import '../../shared/widgets/frosted_scaffold.dart'; +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/bottom_up_page_route.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; import '../../shared/widgets/immediate_page_route.dart'; @@ -73,90 +78,198 @@ class SettingsPage extends HookConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final packageInfoFuture = useMemoized(() => PackageInfo.fromPlatform()); final packageInfo = useFuture(packageInfoFuture); - final topSectionHeight = frostedAppBarHeight( - context, - bottomHeight: Grid.xxs, - ); + final strip = FoldGeometry.of(context).strip; + final avatarFirst = + defaultTargetPlatform == TargetPlatform.iOS && strip != null; + final topSectionHeight = avatarFirst + ? (usesConversationPanes(context, strip: strip) ? 0.0 : Grid.sm) + : frostedAppBarHeight(context, bottomHeight: Grid.xxs); - // Keep feedback local even while Home is mounted during the transition. - return ScaffoldMessenger( - child: FrostedScaffold( + final wide = usesConversationPanes(context, strip: strip); + + final sections = <(String, Widget)>[ + ('Status', _StatusSection(onSetStatus: onSetStatus)), + ( + 'Profile', + _ProfileSection( + profileEditPageBuilder: profileEditPageBuilder, + onEditDisplayName: onEditDisplayName, + onEditProfileDescription: onEditProfileDescription, + ), + ), + if (_notificationsVisible(ref)) + ('Notifications', const _NotificationsSection()), + ( + 'Connection', + _ConnectionSection( + identityRecoveryPageBuilder: identityRecoveryPageBuilder, + ), + ), + if (HostedEnvironment.enabled) + ('Account', const _BuilderlabAccountSection()), + ]; + Widget detail(String name, Widget section) => Builder( + builder: (detailContext) => FrostedScaffold( useUtilitySurfaceTheme: true, appBar: FrostedAppBar( - nativeTitle: 'Settings', - nativeLeading: IosNavigationAction( - label: 'Close settings', - symbol: 'xmark', - onPressed: () => Navigator.of(context).pop(), + nativeTitle: name, + title: Text(name), + automaticallyImplyLeading: !usesConversationPanes( + detailContext, + windowSize: + View.of(detailContext).physicalSize / + View.of(detailContext).devicePixelRatio, ), - automaticallyImplyLeading: false, - horizontalInset: Grid.gutter, - leading: Theme.of(context).platform == TargetPlatform.iOS - ? IosGlassNavigationButton( - key: const ValueKey('settings-ios-glass-close'), - icon: IosGlassNavigationIcon.close, - semanticLabel: 'Close settings', - onPressed: () { - unawaited(HapticFeedback.lightImpact()); - Navigator.of(context).pop(); - }, - foregroundColor: navigationPrimaryForeground(context), - ) - : SizedBox( - width: Grid.xl, - height: Grid.xl, - child: IconButton( - tooltip: 'Close settings', - onPressed: () { - unawaited(HapticFeedback.lightImpact()); - Navigator.of(context).pop(); - }, - color: navigationPrimaryForeground(context), - icon: const Icon(BuzzIcons.x), - ), - ), - bottomHeight: Grid.xxs, - bottom: const SizedBox.expand(), ), body: ListView( padding: EdgeInsets.only( - top: topSectionHeight, - bottom: MediaQuery.paddingOf(context).bottom + Grid.xs, + top: frostedAppBarHeight(detailContext), + bottom: MediaQuery.paddingOf(detailContext).bottom + Grid.xs, ), - children: [ - profileHeader, - _StatusSection(onSetStatus: onSetStatus), - _ProfileSection( - profileEditPageBuilder: profileEditPageBuilder, - onEditDisplayName: onEditDisplayName, - onEditProfileDescription: onEditProfileDescription, - ), - const _NotificationsSection(), - _ConnectionSection( - identityRecoveryPageBuilder: identityRecoveryPageBuilder, - ), - if (HostedEnvironment.enabled) const _BuilderlabAccountSection(), - // An internal build's only way out of its organization, rarely - // needed, so it sits last. - if (OrganizationEnvironment.enabled) - AppListCard( - verticalPadding: Grid.twelve, + children: [section], + ), + ), + ); + final controller = useMemoized(ConversationPaneController.new); + useEffect(() => controller.dispose, [controller]); + useEffect( + () { + if (wide && + (controller.selectedId == null || + (controller.selectedId == 'Notifications' && + !sections.any( + (section) => section.$1 == 'Notifications', + )))) { + final section = sections.first; + controller.open( + section.$1, + (_) => detail(section.$1, section.$2), + animate: false, + ); + } + return null; + }, + [ + wide, + controller.selectedId, + sections.map((section) => section.$1).join(','), + ], + ); + useListenable(controller); + // Keep feedback local even while Home is mounted during the transition. + return Theme( + data: utilitySurfaceThemeData(Theme.of(context)), + child: AdaptiveConversationDestination( + preferredListWidth: avatarFirst ? 375 : null, + emptyLabel: 'Select a setting', + listToolbarSlots: 1, + controller: controller, + persistentSelection: sections.any( + (section) => section.$1 == controller.selectedId, + ), + child: Builder( + builder: (paneContext) => ScaffoldMessenger( + child: FrostedScaffold( + useUtilitySurfaceTheme: true, + appBar: FrostedAppBar( + nativeTitle: avatarFirst ? '' : 'Settings', + railOnly: avatarFirst, + nativeLeading: IosNavigationAction( + label: 'Close settings', + symbol: 'xmark', + onPressed: () => Navigator.of(context).pop(), + ), + automaticallyImplyLeading: false, + horizontalInset: Grid.gutter, + leading: Theme.of(context).platform == TargetPlatform.iOS + ? IosGlassNavigationButton( + key: const ValueKey('settings-ios-glass-close'), + icon: IosGlassNavigationIcon.close, + semanticLabel: 'Close settings', + onPressed: () { + unawaited(HapticFeedback.lightImpact()); + Navigator.of(context).pop(); + }, + foregroundColor: navigationPrimaryForeground(context), + ) + : SizedBox( + width: Grid.xl, + height: Grid.xl, + child: IconButton( + tooltip: 'Close settings', + onPressed: () { + unawaited(HapticFeedback.lightImpact()); + Navigator.of(context).pop(); + }, + color: navigationPrimaryForeground(context), + icon: const Icon(BuzzIcons.x), + ), + ), + bottomHeight: Grid.xxs, + bottom: const SizedBox.expand(), + ), + body: ListView( + padding: EdgeInsets.only( + top: topSectionHeight, + bottom: MediaQuery.paddingOf(context).bottom + Grid.xs, + ), children: [ - AppListRow( - key: const Key('settings-sign-out'), - icon: BuzzIcons.logOut, - title: 'Sign out', - titleColor: context.colors.error, - onTap: () => confirmOrganizationSignOut(context, ref), - ), + profileHeader, + if (wide) + AppListCard( + dividerIndent: Grid.xs, + verticalPadding: Grid.twelve, + children: [ + for (final section in sections) + AppListRow( + title: section.$1, + trailing: const _RowChevron(), + onTap: () => controller.open( + section.$1, + (_) => detail(section.$1, section.$2), + animate: false, + ), + ), + ], + ) + else ...[ + _StatusSection(onSetStatus: onSetStatus), + _ProfileSection( + profileEditPageBuilder: profileEditPageBuilder, + onEditDisplayName: onEditDisplayName, + onEditProfileDescription: onEditProfileDescription, + ), + const _NotificationsSection(), + _ConnectionSection( + identityRecoveryPageBuilder: identityRecoveryPageBuilder, + ), + ], + if (!wide && HostedEnvironment.enabled) + const _BuilderlabAccountSection(), + // An internal build's only way out of its organization, rarely + // needed, so it sits last. + if (OrganizationEnvironment.enabled) + AppListCard( + verticalPadding: Grid.twelve, + children: [ + AppListRow( + key: const Key('settings-sign-out'), + icon: BuzzIcons.logOut, + title: 'Sign out', + titleColor: context.colors.error, + onTap: () => confirmOrganizationSignOut(context, ref), + ), + ], + ), + if (packageInfo.hasData) + _VersionFooter( + version: packageInfo.data!.version, + buildNumber: packageInfo.data!.buildNumber, + ), ], ), - if (packageInfo.hasData) - _VersionFooter( - version: packageInfo.data!.version, - buildNumber: packageInfo.data!.buildNumber, - ), - ], + ), + ), ), ), ); diff --git a/mobile/lib/features/settings/settings_page/notifications_section.dart b/mobile/lib/features/settings/settings_page/notifications_section.dart index 5173c3cb42..5d30246e1d 100644 --- a/mobile/lib/features/settings/settings_page/notifications_section.dart +++ b/mobile/lib/features/settings/settings_page/notifications_section.dart @@ -1,29 +1,33 @@ part of '../settings_page.dart'; +bool _notificationsVisible(WidgetRef ref) { + if (defaultTargetPlatform != TargetPlatform.iOS) return false; + final community = ref.watch(activeCommunityProvider).value; + if (community == null) return false; + final setup = ref.watch(buzzPushSetupStatusProvider); + final capability = ref.watch(currentRelayPushDescriptorProvider); + return (!capability.isLoading && + !capability.hasError && + capability.value != null) || + community.pushNotificationsEnabled || + community.pushSubscriptionState.pendingTombstoneGeneration != null || + setup.hasError; +} + class _NotificationsSection extends ConsumerWidget { const _NotificationsSection(); @override Widget build(BuildContext context, WidgetRef ref) { - if (defaultTargetPlatform != TargetPlatform.iOS) { - return const SizedBox.shrink(); - } - final community = ref.watch(activeCommunityProvider).value; - if (community == null) return const SizedBox.shrink(); + if (!_notificationsVisible(ref)) return const SizedBox.shrink(); + final community = ref.watch(activeCommunityProvider).value!; final setup = ref.watch(buzzPushSetupStatusProvider); final capability = ref.watch(currentRelayPushDescriptorProvider); final hasCapability = !capability.isLoading && !capability.hasError && capability.value != null; - final optOutPending = - community.pushSubscriptionState.pendingTombstoneGeneration != null; - if (!hasCapability && - !community.pushNotificationsEnabled && - !optOutPending && - !setup.hasError) { - return const SizedBox.shrink(); - } + final canToggle = hasCapability || community.pushNotificationsEnabled; void setEnabled(bool enabled) { diff --git a/mobile/lib/features/settings/settings_page/profile_section.dart b/mobile/lib/features/settings/settings_page/profile_section.dart index 8fa2a62df9..dc14f5483d 100644 --- a/mobile/lib/features/settings/settings_page/profile_section.dart +++ b/mobile/lib/features/settings/settings_page/profile_section.dart @@ -41,9 +41,55 @@ class _ProfileSection extends StatelessWidget { trailing: const _RowChevron(), onTap: () { unawaited(HapticFeedback.selectionClick()); - Navigator.of( - context, - ).push(immediatePageRoute(builder: profileEditPageBuilder)); + final scope = DuoToolbarScope.maybeOf(context); + final strip = scope?.strip ?? FoldGeometry.of(context).strip; + if (strip == null) { + Navigator.of( + context, + ).push(immediatePageRoute(builder: profileEditPageBuilder)); + return; + } + final windowSize = + View.of(context).physicalSize / View.of(context).devicePixelRatio; + final pane = ConversationPaneScope.maybeOf(context); + // From the compact all-settings list, the editor is the initial + // detail. An existing Profile detail must remain beneath the editor. + if (windowSize.shortestSide < 600 && + pane != null && + pane.selectedId == null) { + pane.open('settings-photo', profileEditPageBuilder, animate: false); + return; + } + Widget editor(BuildContext routeContext) { + final routeScope = DuoToolbarScope.maybeOf(routeContext); + final routeStrip = + routeScope?.strip ?? FoldGeometry.of(routeContext).strip; + return DuoToolbarScope( + strip: routeStrip, + active: routeScope?.active ?? true, + leadingSlots: routeScope?.leadingSlots ?? 0, + contentInsets: + routeScope?.contentInsets ?? + EdgeInsets.only( + left: routeStrip?.side == FoldStripSide.left + ? routeStrip!.width + : 0, + right: routeStrip?.side == FoldStripSide.right + ? routeStrip!.width + : 0, + ), + child: profileEditPageBuilder(routeContext), + ); + } + + Navigator.of(context).push( + windowSize.shortestSide < 600 + ? immediatePageRoute(builder: editor) + : BottomUpPageRoute( + reducedMotion: MediaQuery.disableAnimationsOf(context), + builder: editor, + ), + ); }, ), ], diff --git a/mobile/lib/features/settings/theme_option_sheets.dart b/mobile/lib/features/settings/theme_option_sheets.dart index a05cf85952..6d8e2beb23 100644 --- a/mobile/lib/features/settings/theme_option_sheets.dart +++ b/mobile/lib/features/settings/theme_option_sheets.dart @@ -7,6 +7,8 @@ import 'package:buzz/shared/theme/buzz_icons.dart'; import '../../shared/theme/theme.dart'; import '../../shared/widgets/modal_presentation.dart'; +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; const appearanceModeOptions = <({ThemeMode mode, String label, IconData icon})>[ (mode: ThemeMode.light, label: 'Light', icon: BuzzIcons.sun), @@ -27,6 +29,9 @@ Future showAccentColorPickerSheet({ title: 'Chat color', showDragHandle: true, builder: (_) => _AccentColorPicker( + compact: + DuoToolbarScope.maybeOf(context)?.strip != null && + usesConversationPanes(context), colorScheme: colorScheme, initialIndex: selectedIndex, onSelected: onSelected, @@ -36,11 +41,13 @@ Future showAccentColorPickerSheet({ class _AccentColorPicker extends HookWidget { const _AccentColorPicker({ required this.colorScheme, + required this.compact, required this.initialIndex, required this.onSelected, }); final ColorScheme colorScheme; + final bool compact; final int initialIndex; final ValueChanged onSelected; @@ -56,26 +63,34 @@ class _AccentColorPicker extends HookWidget { Grid.gutter, Grid.xs, ), - child: GridView.builder( - key: const ValueKey('accent-selection-grid'), - shrinkWrap: true, - primary: false, - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 4, - crossAxisSpacing: Grid.xxs, - mainAxisSpacing: Grid.xs, - ), - itemCount: chatColorChoices.length, - itemBuilder: (context, index) => _AccentSheetOption( - index: index, - color: chatColorForScheme(colorScheme, index), - selected: selected.value == index, - onTap: () { - unawaited(HapticFeedback.selectionClick()); - selected.value = index; - onSelected(index); - }, + child: Align( + heightFactor: 1, + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: compact ? 320 : double.infinity, + ), + child: GridView.builder( + key: const ValueKey('accent-selection-grid'), + shrinkWrap: true, + primary: false, + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 4, + crossAxisSpacing: Grid.xxs, + mainAxisSpacing: Grid.xs, + ), + itemCount: chatColorChoices.length, + itemBuilder: (context, index) => _AccentSheetOption( + index: index, + color: chatColorForScheme(colorScheme, index), + selected: selected.value == index, + onTap: () { + unawaited(HapticFeedback.selectionClick()); + selected.value = index; + onSelected(index); + }, + ), + ), ), ), ), diff --git a/mobile/lib/features/settings/theme_picker_page.dart b/mobile/lib/features/settings/theme_picker_page.dart index 12664d48cf..39d51ed360 100644 --- a/mobile/lib/features/settings/theme_picker_page.dart +++ b/mobile/lib/features/settings/theme_picker_page.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -11,6 +12,10 @@ import '../../shared/community/community_icon_provider.dart'; import '../../shared/community/community_provider.dart'; import '../../shared/theme/theme.dart'; import '../../shared/widgets/avatar_image.dart'; +import '../../shared/widgets/duo_toolbar.dart'; +import '../../shared/widgets/adaptive_conversation_pane.dart'; +import '../../shared/widgets/mobile_tab_footer_backdrop.dart'; +import '../../shared/widgets/ios_navigation_metrics.dart'; import '../../shared/widgets/frosted_app_bar.dart'; import '../../shared/widgets/frosted_scaffold.dart'; import '../../shared/widgets/ios_glass_navigation_action.dart'; @@ -20,13 +25,32 @@ import 'theme_option_sheets.dart'; part 'theme_picker_page/theme_home_preview.dart'; part 'theme_picker_page/theme_preview_sheet.dart'; -String _themeLabelFor(ThemeColors theme, ThemeMode mode) => - mode == ThemeMode.system ? pairedThemeLabel(theme.name) : theme.displayName; - /// Appearance preview with draft mode and chat color, applied with Set. class ThemePickerPage extends StatelessWidget { const ThemePickerPage({super.key}); @override - Widget build(BuildContext context) => const _ThemePreviewExperience(); + Widget build(BuildContext context) { + final parent = DuoToolbarScope.maybeOf(context); + final strip = parent == null + ? FoldGeometry.of(context).strip + : parent.strip; + final insets = + parent?.contentInsets ?? + EdgeInsets.only( + left: strip?.side == FoldStripSide.left ? strip!.width : 0, + right: strip?.side == FoldStripSide.right ? strip!.width : 0, + ); + return DuoToolbarScope( + strip: strip, + active: parent?.active ?? true, + contentInsets: insets, + child: MediaQuery.removePadding( + context: context, + removeLeft: insets.left > 0, + removeRight: insets.right > 0, + child: const _ThemePreviewExperience(), + ), + ); + } } diff --git a/mobile/lib/features/settings/theme_picker_page/theme_preview_sheet.dart b/mobile/lib/features/settings/theme_picker_page/theme_preview_sheet.dart index 5828ed8996..0b28889a1a 100644 --- a/mobile/lib/features/settings/theme_picker_page/theme_preview_sheet.dart +++ b/mobile/lib/features/settings/theme_picker_page/theme_preview_sheet.dart @@ -9,6 +9,7 @@ class _ThemePreviewExperience extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + final inRail = DuoToolbarScope.maybeOf(context)?.strip != null; final stored = ref.read(communityThemeProvider); final draftMode = useState(stored.mode); final draftAccent = useState(chatColorIndex(stored.accent)); @@ -32,6 +33,13 @@ class _ThemePreviewExperience extends HookConsumerWidget { draftMode.value = _appearanceOrder[(index + 1) % _appearanceOrder.length]; } + void chooseColor() => showAccentColorPickerSheet( + context: context, + colorScheme: selectedBaseScheme, + selectedIndex: draftAccent.value, + onSelected: (index) => draftAccent.value = index, + ); + void applySelection() { unawaited(HapticFeedback.mediumImpact()); ref @@ -53,7 +61,7 @@ class _ThemePreviewExperience extends HookConsumerWidget { Navigator.of(context).pop(); } - return FrostedScaffold( + final scaffold = FrostedScaffold( useUtilitySurfaceTheme: true, appBar: FrostedAppBar( automaticallyImplyLeading: false, @@ -72,6 +80,7 @@ class _ThemePreviewExperience extends HookConsumerWidget { actions: [_ThemePreviewSetButton(onPressed: applySelection)], ), body: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox(height: frostedAppBarHeight(context)), Expanded( @@ -80,58 +89,149 @@ class _ThemePreviewExperience extends HookConsumerWidget { mode: draftMode.value, accentIndex: draftAccent.value, platformBrightness: platformBrightness, - titleHorizontalOffset: 0, ), ), - SafeArea( - top: false, - minimum: const EdgeInsets.only(bottom: Grid.xs), - child: Padding( - padding: const EdgeInsets.fromLTRB( - Grid.gutter, - Grid.twelve, - Grid.gutter, - 0, + if (inRail) SizedBox(height: frostedAppBarHeight(context)), + if (!inRail) + SafeArea( + top: false, + minimum: const EdgeInsets.only(bottom: Grid.xs), + child: Padding( + padding: const EdgeInsets.fromLTRB( + Grid.gutter, + Grid.twelve, + Grid.gutter, + 0, + ), + child: Row( + children: [ + SizedBox( + width: 64, + child: _PreviewSheetCircleAction( + key: const ValueKey( + 'theme-preview-accent-action-button', + ), + semanticLabel: 'Chat color', + color: chatColorForScheme( + selectedBaseScheme, + draftAccent.value, + ), + onTap: chooseColor, + ), + ), + Expanded( + child: Text( + appearanceModeLabel(draftMode.value), + textAlign: TextAlign.center, + ), + ), + SizedBox( + width: 64, + child: _AppearanceCycleAction( + mode: draftMode.value, + reduceMotion: reduceMotion, + onTap: cycleAppearance, + ), + ), + ], + ), ), + ), + ], + ), + ); + final portal = useMemoized(() => OverlayPortalController()..show()); + return OverlayPortal( + overlayLocation: OverlayChildLocation.rootOverlay, + controller: portal, + overlayChildBuilder: (context) { + final scope = DuoToolbarScope.maybeOf(context); + final strip = scope?.strip; + if (strip == null) return const SizedBox.shrink(); + final window = + View.of(context).physicalSize / View.of(context).devicePixelRatio; + final wide = usesConversationPanes( + context, + strip: strip, + windowSize: window, + ); + final controls = [ + _PreviewSheetCircleAction( + key: const ValueKey('theme-preview-accent-action-button'), + semanticLabel: 'Chat color', + color: chatColorForScheme(selectedBaseScheme, draftAccent.value), + onTap: chooseColor, + ), + _AppearanceCycleAction( + mode: draftMode.value, + reduceMotion: reduceMotion, + onTap: cycleAppearance, + ), + ]; + if (wide) { + return Positioned( + left: strip.side == FoldStripSide.left ? strip.width : 0, + right: strip.side == FoldStripSide.right ? strip.width : 0, + bottom: mobileTabBarBottom(context), + height: mobileTabBarHeight, + child: Offstage( + offstage: + !(scope?.active ?? true) || + !(ModalRoute.isCurrentOf(context) ?? true), child: Row( + key: const ValueKey('theme-preview-bottom-row'), + mainAxisAlignment: MainAxisAlignment.center, children: [ - SizedBox( - width: 64, - child: _PreviewSheetCircleAction( - key: const ValueKey('theme-preview-accent-action-button'), - semanticLabel: 'Chat color', - color: chatColorForScheme( - selectedBaseScheme, - draftAccent.value, - ), - onTap: () => showAccentColorPickerSheet( - context: context, - colorScheme: selectedBaseScheme, - selectedIndex: draftAccent.value, - onSelected: (index) => draftAccent.value = index, - ), - ), - ), - Expanded( - child: Text( - appearanceModeLabel(draftMode.value), - textAlign: TextAlign.center, - ), - ), - SizedBox( - width: 64, - child: _AppearanceCycleAction( - mode: draftMode.value, - reduceMotion: reduceMotion, - onTap: cycleAppearance, - ), - ), + controls[0], + const SizedBox(width: Grid.xs), + controls[1], ], ), ), + ); + } + return Positioned( + left: + IosNavigationMetrics.of( + context, + ).railCenter(window, strip.rect.center.dx) - + 32, + top: strip.rect.bottom - strip.bottomClearance - 132, + width: 64, + child: Offstage( + offstage: + !(scope?.active ?? true) || + !(ModalRoute.isCurrentOf(context) ?? true), + child: Column( + key: const ValueKey('theme-preview-rail-bottom'), + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + height: 60, + child: _PreviewSheetCircleAction( + key: const ValueKey('theme-preview-accent-action-button'), + semanticLabel: 'Chat color', + color: chatColorForScheme( + selectedBaseScheme, + draftAccent.value, + ), + onTap: chooseColor, + ), + ), + SizedBox( + height: 60, + child: _AppearanceCycleAction( + mode: draftMode.value, + reduceMotion: reduceMotion, + onTap: cycleAppearance, + ), + ), + ], + ), ), - ], - ), + ); + }, + child: scaffold, ); } } @@ -142,85 +242,40 @@ class _ThemePreviewPage extends StatelessWidget { required this.mode, required this.accentIndex, required this.platformBrightness, - required this.titleHorizontalOffset, }); final ThemeColors theme; final ThemeMode mode; final int accentIndex; final Brightness platformBrightness; - final double titleHorizontalOffset; @override Widget build(BuildContext context) => Padding( - padding: const EdgeInsets.fromLTRB(Grid.gutter, Grid.xxs, Grid.gutter, 0), + padding: EdgeInsets.fromLTRB( + Grid.gutter, + Grid.xxs, + Grid.gutter, + DuoToolbarScope.maybeOf(context)?.strip != null ? Grid.xxs : 0, + ), child: DecoratedBox( key: ValueKey('theme-preview-page-${theme.name}'), decoration: BoxDecoration( color: context.colors.surfaceContainerLow, borderRadius: BorderRadius.circular(Radii.container), ), - child: LayoutBuilder( - builder: (context, constraints) { - const previewWidth = 858.0; - const previewHeight = 852.0; - final availableWidth = constraints.maxWidth - Grid.xs * 2; - final availableHeight = constraints.maxHeight - Grid.xs * 2; - final widthScale = availableWidth / previewWidth; - final heightScale = availableHeight / previewHeight; - final scale = widthScale < heightScale ? widthScale : heightScale; - final previewTop = - (constraints.maxHeight - previewHeight * scale) / 2; - final desiredTitleBottom = - constraints.maxHeight - previewTop + Grid.md; - final landscapeTitleBottom = - constraints.maxHeight - Grid.xs - Grid.lg; - final titleBottom = - heightScale < widthScale && - desiredTitleBottom > landscapeTitleBottom - ? landscapeTitleBottom - : desiredTitleBottom; - - return Stack( - children: [ - Positioned.fill( - child: Padding( - padding: const EdgeInsets.all(Grid.xs), - child: FittedBox( - key: ValueKey('theme-full-preview-${theme.name}'), - fit: BoxFit.contain, - alignment: Alignment.center, - child: _ThemeDevicePairPreview( - theme: theme, - mode: mode, - accentIndex: accentIndex, - platformBrightness: platformBrightness, - ), - ), - ), - ), - Positioned( - left: Grid.xs, - right: Grid.xs, - bottom: titleBottom, - child: Transform.translate( - key: ValueKey('theme-preview-name-motion-${theme.name}'), - offset: Offset(titleHorizontalOffset, 0), - child: Text( - _themeLabelFor(theme, mode), - key: ValueKey('theme-preview-name-${theme.name}'), - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - style: context.textTheme.titleSmall?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - ), - ), - ], - ); - }, + child: Padding( + padding: const EdgeInsets.all(Grid.xs), + child: FittedBox( + key: ValueKey('theme-full-preview-${theme.name}'), + fit: BoxFit.contain, + alignment: Alignment.center, + child: _ThemeDevicePairPreview( + theme: theme, + mode: mode, + accentIndex: accentIndex, + platformBrightness: platformBrightness, + ), + ), ), ), ); diff --git a/mobile/lib/shared/widgets/adaptive_conversation_pane.dart b/mobile/lib/shared/widgets/adaptive_conversation_pane.dart new file mode 100644 index 0000000000..b16c0e0dcd --- /dev/null +++ b/mobile/lib/shared/widgets/adaptive_conversation_pane.dart @@ -0,0 +1,601 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:duo_kit/duo_kit.dart'; + +import 'duo_toolbar.dart'; +import 'app_route_observer.dart'; +import 'covered_route_keyboard_insets.dart'; +import 'ios_navigation_metrics.dart'; +import 'duo_workspace_scaffold.dart'; + +import '../theme/theme.dart'; + +/// Duo uses the phone navigation model in portrait, even on its large display. +/// Callers inside a pane supply the full window size. +bool usesConversationPanes( + BuildContext context, { + FoldStrip? strip, + Size? windowSize, +}) { + final size = windowSize ?? MediaQuery.sizeOf(context); + final rail = strip ?? FoldGeometry.of(context).strip; + // The portrait Duo status cluster becomes a tall top inset, not a side + // strip. Keep that phone layout compact without excluding ordinary iPads. + final phoneStatusCluster = MediaQuery.viewPaddingOf(context).top > 50; + if (defaultTargetPlatform == TargetPlatform.iOS && + size.height >= size.width && + (rail != null || phoneStatusCluster || size.shortestSide < 600)) { + return false; + } + final bookDivision = bookDivisionOf(context); + // A landscape phone is wide enough for the breakpoint, but not for two + // usable panes. Fold geometry keeps Duo eligible in its supported poses. + if (size.shortestSide < 600 && rail == null && bookDivision == null) { + return false; + } + return bookDivision != null || size.width - (rail?.width ?? 0) >= 640; +} + +/// The active vertical fold, in window coordinates, when held like a book. +Rect? bookDivisionOf(BuildContext context) { + final geometry = FoldGeometry.of(context); + final division = geometry.division; + if (division != null && + division.axis == Axis.vertical && + division.isHalfOpened) { + return division.bounds; + } + final native = IosNavigationMetrics.of(context); + return native.windowSize == geometry.size ? native.bookDivision : null; +} + +final _compactPaneNavigators = Expando>(); + +/// Unwinds a compact destination for a shortcut, without bypassing page vetoes. +/// Returns false for other layouts or when a nested page refuses to close. +bool popCompactConversationDestination(Route route) { + final navigator = _compactPaneNavigators[route]?.currentState; + if (navigator == null) return false; + var cleared = false; + navigator.popUntil((nested) { + if (nested.popDisposition == RoutePopDisposition.doNotPop) return true; + cleared = nested.isFirst; + return cleared; + }); + return cleared; +} + +/// Selection belongs to the workspace, rather than to a particular display pose. +class ConversationPaneController extends ChangeNotifier { + String? selectedId; + WidgetBuilder? detailBuilder; + bool animateSelection = true; + int _request = 0; + // Deep-link requests may target the same item after its nested route popped. + // A fresh page identity reruns initialization without clearing the selection + // when Navigator removes the previous page. + LocalKey get selectionKey => ValueKey((selectedId, _request)); + + void open( + String id, + WidgetBuilder builder, { + bool animate = true, + bool reopen = false, + }) { + if (id == selectedId && !reopen) return; + if (reopen) _request++; + selectedId = id; + detailBuilder = builder; + animateSelection = animate; + notifyListeners(); + } + + void clear() { + if (selectedId == null) return; + selectedId = null; + detailBuilder = null; + notifyListeners(); + } +} + +class ConversationPaneScope + extends InheritedNotifier { + const ConversationPaneScope({ + required ConversationPaneController controller, + required super.child, + this.active = true, + super.key, + }) : super(notifier: controller); + + final bool active; + + /// Only the selected page owns the pane's implicit root navigation. + /// Imperatively pushed pages retain ordinary Back navigation. + static bool isBaseRouteOf(BuildContext context) { + final controller = maybeOf(context); + final settings = ModalRoute.of(context)?.settings; + return controller?.selectedId != null && + settings is Page && + settings.key == controller!.selectionKey; + } + + static bool isActiveOf(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType() + ?.active ?? + true; + + @override + bool updateShouldNotify(ConversationPaneScope oldWidget) => + active != oldWidget.active || super.updateShouldNotify(oldWidget); + + static ConversationPaneController? maybeOf(BuildContext context) => context + .dependOnInheritedWidgetOfExactType() + ?.notifier; +} + +/// Keeps both the list and its detail navigator mounted across compact/regular +/// layouts, so opening or closing Duo does not recreate the composer or thread. +class AdaptiveConversationPane extends HookConsumerWidget { + const AdaptiveConversationPane({ + required this.controller, + required this.list, + this.active = true, + this.strip, + this.emptyLabel = 'Select a conversation', + this.emptyContent, + this.listWidthFraction, + this.preferredListWidth, + this.persistentSelection = false, + this.listToolbarSlots = 0, + super.key, + }); + + final bool persistentSelection; + + /// Rail slots reserved for workspace controls that stay active in wide mode. + final int listToolbarSlots; + + /// Optional list share of the usable width; defaults to the compact sidebar. + final double? listWidthFraction; + + /// Preferred sidebar width, capped at half the usable area for narrow windows. + final double? preferredListWidth; + final String emptyLabel; + final Widget? emptyContent; + final FoldStrip? strip; + final ConversationPaneController controller; + final Widget list; + final bool active; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final routeObserver = useMemoized(appRouteObserver.createNestedObserver); + final navigator = useMemoized(() => GlobalKey()); + final ownerRoute = ModalRoute.of(context); + useEffect(() { + return () { + if (ownerRoute != null && + _compactPaneNavigators[ownerRoute] == navigator) { + _compactPaneNavigators[ownerRoute] = null; + } + }; + }, [ownerRoute, navigator]); + // The compact detail route that fully covers the list. While a detail + // pushes, pops or follows a back swipe, the list stays painted beneath it. + final coveringDetail = useValueNotifier?>(null); + return ConversationPaneScope( + controller: controller, + active: active && (ModalRoute.isCurrentOf(context) ?? true), + child: ListenableBuilder( + listenable: controller, + builder: (context, _) => LayoutBuilder( + builder: (context, constraints) { + final stripWidth = strip?.width ?? 0; + final leftInset = strip?.side == FoldStripSide.left + ? stripWidth + : 0.0; + final rightInset = strip?.side == FoldStripSide.right + ? stripWidth + : 0.0; + final contentWidth = constraints.maxWidth - stripWidth; + final wide = usesConversationPanes(context, strip: strip); + final book = wide ? bookDivisionOf(context) : null; + final selected = controller.selectedId; + if (ownerRoute != null) { + _compactPaneNavigators[ownerRoute] = + active && !wide && selected != null ? navigator : null; + } + // Pane surfaces meet at the fold so their header backdrops remain + // continuous. Content insets below keep controls out of its bounds. + final listWidth = book != null + ? book.center.dx - leftInset + : wide + ? listWidthFraction == null + ? preferredListWidth?.clamp( + 0.0, + (contentWidth - 1) / 2, + ) ?? + (contentWidth / 3).clamp(280.0, 360.0) + : (contentWidth - 1) * listWidthFraction! + : constraints.maxWidth; + final detailLeft = + book?.center.dx ?? (wide ? listWidth + leftInset + 1 : 0.0); + return TweenAnimationBuilder( + tween: Tween(end: Offset(listWidth, detailLeft)), + duration: wide && !MediaQuery.disableAnimationsOf(context) + ? const Duration(milliseconds: 240) + : Duration.zero, + curve: Curves.easeInOutCubic, + builder: (context, geometry, _) { + final listWidth = geometry.dx; + final detailLeft = geometry.dy; + final detailWidth = constraints.maxWidth - detailLeft; + return Stack( + fit: StackFit.expand, + children: [ + Positioned( + left: 0, + top: 0, + bottom: 0, + width: wide ? listWidth + leftInset : listWidth, + child: ValueListenableBuilder( + valueListenable: coveringDetail, + builder: (context, covering, list) => Offstage( + offstage: + !wide && + selected != null && + (covering?.isActive ?? false), + child: list, + ), + child: _CoveredList( + covered: !wide && selected != null, + child: MediaQueryOverride( + transform: (media) => media.copyWith( + size: Size(listWidth, constraints.maxHeight), + ), + child: DuoToolbarScope( + strip: strip, + contentInsets: EdgeInsets.only( + left: leftInset, + right: wide + ? (book?.width ?? 0) / 2 + : rightInset, + ), + active: + active && + (selected == null || + (wide && + (persistentSelection || + listToolbarSlots > 0))) && + (ModalRoute.isCurrentOf(context) ?? true), + child: list, + ), + ), + ), + ), + ), + Positioned( + left: detailLeft, + top: 0, + bottom: 0, + width: detailWidth, + child: Offstage( + offstage: !wide && selected == null, + child: TickerMode( + enabled: wide || selected != null, + child: MediaQueryOverride( + transform: (media) => media.copyWith( + size: Size(detailWidth, constraints.maxHeight), + ), + child: DuoToolbarScope( + strip: strip, + leadingSlots: wide ? listToolbarSlots : 0, + contentInsets: EdgeInsets.only( + left: wide ? (book?.width ?? 0) / 2 : leftInset, + right: rightInset, + ), + active: + active && + selected != null && + (ModalRoute.isCurrentOf(context) ?? true), + child: Semantics( + container: true, + explicitChildNodes: true, + child: PopScope( + canPop: + !active || + selected == null || + (wide && persistentSelection), + onPopInvokedWithResult: (didPop, result) { + if (!didPop && + active && + selected != null && + !(wide && persistentSelection)) { + navigator.currentState!.maybePop(result); + } + }, + child: ExcludeFocus( + excluding: selected == null, + child: NavigatorPopHandler( + enabled: wide && persistentSelection, + onPopWithResult: (result) => + navigator.currentState!.pop(result), + child: Navigator( + requestFocus: selected != null, + key: navigator, + observers: [routeObserver], + pages: [ + if (!(wide && + persistentSelection && + selected != null)) + MaterialPage( + key: const ValueKey( + 'conversation-placeholder', + ), + // Compact panes show the list + // through this page while a + // detail pushes or pops. + child: !wide + ? const SizedBox.shrink() + : Material( + color: context + .colors + .surface, + child: Center( + child: + emptyContent ?? + Text( + emptyLabel, + textAlign: + TextAlign + .center, + style: Theme.of(context) + .textTheme + .bodyLarge + ?.copyWith( + color: Theme.of( + context, + ).colorScheme.onSurfaceVariant, + decoration: + TextDecoration + .none, + ), + ), + ), + ), + ), + if (selected != null) + if (controller.animateSelection) + MaterialPage( + key: controller.selectionKey, + child: _CoveringDetail( + covering: coveringDetail, + builder: + controller.detailBuilder!, + ), + ) + else + _ImmediateDetailPage( + key: controller.selectionKey, + builder: (_) => _CoveringDetail( + covering: coveringDetail, + builder: + controller.detailBuilder!, + ), + ), + ], + onDidRemovePage: (page) { + if (page.key == + controller.selectionKey) { + controller.clear(); + } + }, + ), + ), + ), + ), + ), + ), + ), + ), + ), + ), + if (wide) + Positioned( + left: listWidth + leftInset, + top: 0, + bottom: 0, + width: 1, + child: IgnorePointer( + child: ColoredBox( + color: context.colors.outlineVariant, + ), + ), + ), + ], + ); + }, + ); + }, + ), + ), + ); + } +} + +/// Hides the compact list from input, focus and screen readers while a +/// detail sits above it, even during a transition that still paints it. +class _CoveredList extends StatelessWidget { + const _CoveredList({required this.covered, required this.child}); + + final bool covered; + final Widget child; + + @override + Widget build(BuildContext context) => TickerMode( + enabled: !covered, + child: IgnorePointer( + ignoring: covered, + child: ExcludeFocus( + excluding: covered, + child: ExcludeSemantics( + excluding: covered, + // A detail's keyboard must not relayout the list it covers. The + // scope keeps the detail's focus from counting as the list's own. + child: FocusScope( + child: CoveredRouteKeyboardInsets(isCovered: covered, child: child), + ), + ), + ), + ), + ); +} + +/// Derives [child]'s [MediaQuery] in a leaf, so the caller's build does not +/// depend on every field (keyboard insets change on each animation frame). +class MediaQueryOverride extends StatelessWidget { + const MediaQueryOverride({ + required this.transform, + required this.child, + super.key, + }); + + final MediaQueryData Function(MediaQueryData) transform; + final Widget child; + + @override + Widget build(BuildContext context) => + MediaQuery(data: transform(MediaQuery.of(context)), child: child); +} + +/// Reports its route as [covering] once the route fully covers the compact +/// list, and withdraws it while the route pushes, pops or follows a back swipe. +class _CoveringDetail extends HookWidget { + const _CoveringDetail({required this.covering, required this.builder}); + + final ValueNotifier?> covering; + final WidgetBuilder builder; + + @override + Widget build(BuildContext context) { + final route = ModalRoute.of(context); + final navigator = Navigator.of(context); + useEffect(() { + if (route == null) return null; + void sync() { + final settled = + route.animation?.status != AnimationStatus.forward && + route.animation?.status != AnimationStatus.reverse && + !navigator.userGestureInProgress; + if (settled && route.isCurrent) { + covering.value = route; + } else if (covering.value == route) { + covering.value = null; + } + } + + void syncStatus(AnimationStatus _) => sync(); + route.animation?.addStatusListener(syncStatus); + navigator.userGestureInProgressNotifier.addListener(sync); + // An immediate route can settle before these listeners attach. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (context.mounted) sync(); + }); + return () { + route.animation?.removeStatusListener(syncStatus); + navigator.userGestureInProgressNotifier.removeListener(sync); + }; + }, [route, navigator]); + return builder(context); + } +} + +/// Allows a detail with its own shared-element motion to own the transition. +class _ImmediateDetailPage extends Page { + const _ImmediateDetailPage({required this.builder, super.key}); + final WidgetBuilder builder; + + @override + Route createRoute(BuildContext context) => PageRouteBuilder( + settings: this, + transitionDuration: Duration.zero, + reverseTransitionDuration: Duration.zero, + pageBuilder: (context, _, _) => builder(context), + ); +} + +/// Opens a result in its workspace's detail pane, or an ordinary pushed route. +Future openConversationPane( + BuildContext context, + String selectionId, + WidgetBuilder builder, { + bool reopen = false, +}) async { + final pane = ConversationPaneScope.maybeOf(context); + if (pane != null) { + pane.open(selectionId, builder, reopen: reopen); + } else { + await Navigator.of(context).push(MaterialPageRoute(builder: builder)); + } +} + +/// A list/detail workspace for destinations such as Search and Inbox. +class AdaptiveConversationDestination extends HookConsumerWidget { + const AdaptiveConversationDestination({ + required this.child, + this.emptyLabel = 'Select a conversation', + this.listWidthFraction, + this.controller, + this.persistentSelection = false, + this.listToolbarSlots = 0, + this.preferredListWidth, + super.key, + }); + + /// Optional list share of the usable width; defaults to the compact sidebar. + final ConversationPaneController? controller; + final bool persistentSelection; + + /// Rail slots reserved for workspace controls that stay active in wide mode. + final int listToolbarSlots; + + /// Preferred sidebar width, capped to preserve room for its detail pane. + final double? preferredListWidth; + final double? listWidthFraction; + final String emptyLabel; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final ownedController = useMemoized(ConversationPaneController.new); + useEffect(() => ownedController.dispose, [ownedController]); + final controller = this.controller ?? ownedController; + final strip = FoldGeometry.of(context).strip; + return ColoredBox( + color: context.colors.surface, + child: DuoWorkspaceScaffold( + navigationBuilder: (_, _) => const SizedBox.shrink(), + body: MediaQueryOverride( + transform: (media) => media.removePadding( + removeLeft: strip?.side == FoldStripSide.left, + removeRight: strip?.side == FoldStripSide.right, + ), + child: AdaptiveConversationPane( + active: DuoToolbarScope.maybeOf(context)?.active ?? true, + controller: controller, + persistentSelection: persistentSelection, + listToolbarSlots: listToolbarSlots, + emptyLabel: emptyLabel, + listWidthFraction: listWidthFraction, + preferredListWidth: preferredListWidth, + strip: strip, + list: child, + ), + ), + ), + ); + } +} diff --git a/mobile/lib/shared/widgets/app_route_observer.dart b/mobile/lib/shared/widgets/app_route_observer.dart index b64730e7f5..708fc1175a 100644 --- a/mobile/lib/shared/widgets/app_route_observer.dart +++ b/mobile/lib/shared/widgets/app_route_observer.dart @@ -5,6 +5,11 @@ final appRouteObserver = AppRouteObserver(); /// Also reports reveals after the covering route has finished animating out. class AppRouteObserver extends RouteObserver> { + /// Creates a navigator-owned bridge to the shared route subscriptions. + /// Each nested navigator needs its own observer instance; Flutter observers + /// cannot be attached to more than one navigator at a time. + NavigatorObserver createNestedObserver() => _NestedAppRouteObserver(this); + final _revealListeners = , Set>{}; /// Registers a layout refresh for the end of a covering route's transition. @@ -39,3 +44,17 @@ class AppRouteObserver extends RouteObserver> { }); } } + +class _NestedAppRouteObserver extends NavigatorObserver { + _NestedAppRouteObserver(this.delegate); + + final AppRouteObserver delegate; + + @override + void didPush(Route route, Route? previousRoute) => + delegate.didPush(route, previousRoute); + + @override + void didPop(Route route, Route? previousRoute) => + delegate.didPop(route, previousRoute); +} diff --git a/mobile/lib/shared/widgets/avatar_editor_options.dart b/mobile/lib/shared/widgets/avatar_editor_options.dart new file mode 100644 index 0000000000..12e37499f9 --- /dev/null +++ b/mobile/lib/shared/widgets/avatar_editor_options.dart @@ -0,0 +1,105 @@ +import 'package:duo_kit/duo_kit.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; + +import '../theme/theme.dart'; +import 'avatar_editor_options_scope.dart'; +import 'duo_toolbar.dart'; +import 'ios_navigation_bar.dart'; + +/// Keeps phone options horizontal and projects Edit Photo options into Duo's rail. +class AvatarEditorOptions extends HookWidget { + const AvatarEditorOptions({ + required this.options, + this.centered = true, + this.dividerBefore, + super.key, + }); + + final List options; + final bool centered; + final int? dividerBefore; + + @override + Widget build(BuildContext context) { + final scope = AvatarEditorOptionsScope.maybeOf(context); + final toolbar = DuoToolbarScope.maybeOf(context); + final strip = toolbar?.strip ?? FoldGeometry.of(context).strip; + final inRail = + scope != null && + strip != null && + defaultTargetPlatform == TargetPlatform.iOS; + final portal = useMemoized(() => OverlayPortalController()..show()); + if (!inRail) { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (centered) const Spacer(), + for (var i = 0; i < options.length; i++) ...[ + if (i > 0) const SizedBox(width: Grid.half), + if (i == dividerBefore) ...[ + Container( + width: 1, + height: 64, + color: context.colors.outlineVariant, + ), + const SizedBox(width: Grid.half), + ], + Expanded(child: options[i]), + ], + if (centered) const Spacer(), + ], + ); + } + final active = + (ModalRoute.of(context)?.isCurrent ?? true) && + (toolbar?.active ?? true); + final window = MediaQueryData.fromView(View.of(context)); + final topClearance = + strip.isClearanceEstimated && window.size.shortestSide >= 600 + ? duoInnerDisplayEstimatedRailClearance + : strip.topClearance; + return OverlayPortal( + overlayLocation: OverlayChildLocation.rootOverlay, + controller: portal, + overlayChildBuilder: (context) => Positioned( + left: + IosNavigationMetrics.of( + context, + ).railCenter(window.size, strip.rect.center.dx) - + strip.width / 2, + width: strip.width, + top: strip.rect.top + topClearance + 120, + bottom: window.viewPadding.bottom + Grid.xxs, + child: Offstage( + offstage: !active, + child: IgnorePointer( + ignoring: !scope.interactive, + child: MediaQuery.removePadding( + context: context, + removeTop: true, + removeBottom: true, + child: Align( + alignment: Alignment.bottomCenter, + child: SingleChildScrollView( + child: Column( + key: const ValueKey('avatar-editor-side-options'), + mainAxisSize: MainAxisSize.min, + children: [ + for (var i = 0; i < options.length; i++) ...[ + if (i > 0) const SizedBox(height: Grid.xxs), + options[i], + ], + ], + ), + ), + ), + ), + ), + ), + ), + child: const SizedBox.shrink(), + ); + } +} diff --git a/mobile/lib/shared/widgets/avatar_editor_options_scope.dart b/mobile/lib/shared/widgets/avatar_editor_options_scope.dart new file mode 100644 index 0000000000..75ded7eb3c --- /dev/null +++ b/mobile/lib/shared/widgets/avatar_editor_options_scope.dart @@ -0,0 +1,19 @@ +import 'package:flutter/widgets.dart'; + +/// Enables side-rail options for the full-screen photo editor. +class AvatarEditorOptionsScope extends InheritedWidget { + const AvatarEditorOptionsScope({ + required this.interactive, + required super.child, + super.key, + }); + + final bool interactive; + + static AvatarEditorOptionsScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(AvatarEditorOptionsScope oldWidget) => + interactive != oldWidget.interactive; +} diff --git a/mobile/lib/shared/widgets/avatar_image_source_controls.dart b/mobile/lib/shared/widgets/avatar_image_source_controls.dart index 876be95bb7..bb09b61333 100644 --- a/mobile/lib/shared/widgets/avatar_image_source_controls.dart +++ b/mobile/lib/shared/widgets/avatar_image_source_controls.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import '../theme/theme.dart'; import '../theme/buzz_icons.dart'; import 'ios_glass_navigation_button.dart'; +import 'avatar_editor_options.dart'; import 'avatar_editor_option_button.dart'; /// Camera and photo-library actions shared by avatar editors. @@ -25,31 +25,24 @@ class AvatarImageSourceControls extends StatelessWidget { child: Column( children: [ const Spacer(), - Row( - children: [ - const Spacer(), - Expanded( - child: _ImageSourceOption( - key: const ValueKey('image-source-camera'), - icon: BuzzIcons.camera, - iosIcon: IosGlassNavigationIcon.camera, - label: 'Camera', - onTap: isPicking ? null : onCamera, - labelMaxWidth: 96, - ), + AvatarEditorOptions( + options: [ + _ImageSourceOption( + key: const ValueKey('image-source-camera'), + icon: BuzzIcons.camera, + iosIcon: IosGlassNavigationIcon.camera, + label: 'Camera', + onTap: isPicking ? null : onCamera, + labelMaxWidth: 96, ), - const SizedBox(width: Grid.half), - Expanded( - child: _ImageSourceOption( - key: const ValueKey('image-source-library'), - icon: BuzzIcons.images, - iosIcon: IosGlassNavigationIcon.photoLibrary, - label: 'Photo Library', - onTap: isPicking ? null : onLibrary, - labelMaxWidth: 104, - ), + _ImageSourceOption( + key: const ValueKey('image-source-library'), + icon: BuzzIcons.images, + iosIcon: IosGlassNavigationIcon.photoLibrary, + label: 'Photo Library', + onTap: isPicking ? null : onLibrary, + labelMaxWidth: 104, ), - const Spacer(), ], ), ], diff --git a/mobile/lib/shared/widgets/buzz_setting_menu.dart b/mobile/lib/shared/widgets/buzz_setting_menu.dart index f8b59ea76e..fc737ca4fe 100644 --- a/mobile/lib/shared/widgets/buzz_setting_menu.dart +++ b/mobile/lib/shared/widgets/buzz_setting_menu.dart @@ -153,8 +153,8 @@ class BuzzSettingMenu extends StatelessWidget { horizontal: Grid.twelve, ), ), - // A trailing check keeps labels flush with the menu's edge. - trailingIcon: option.value == value + // Keep selection beside the label, matching other checked menus. + leadingIcon: option.value == value ? Icon( Icons.check, size: 20, diff --git a/mobile/lib/shared/widgets/buzz_sheet_header.dart b/mobile/lib/shared/widgets/buzz_sheet_header.dart index 97bdedc459..dbd5dc41ff 100644 --- a/mobile/lib/shared/widgets/buzz_sheet_header.dart +++ b/mobile/lib/shared/widgets/buzz_sheet_header.dart @@ -6,6 +6,7 @@ import 'package:buzz/shared/theme/buzz_icons.dart'; import '../theme/theme.dart'; import 'buzz_navigation_metrics.dart'; +import 'duo_toolbar.dart'; import 'ios_glass_navigation_button.dart'; /// A titled sheet header with balanced actions and an exactly centered title. @@ -63,10 +64,11 @@ class BuzzSheetHeader extends StatelessWidget { ), ), ), - Align( - alignment: Alignment.bottomRight, - child: trailing ?? _SheetCloseButton(onClose: onClose), - ), + if (trailing != null || !DuoSheetCloseScope.of(context)) + Align( + alignment: Alignment.bottomRight, + child: trailing ?? _SheetCloseButton(onClose: onClose), + ), if (leading case final leading?) Align(alignment: Alignment.bottomLeft, child: leading), ], diff --git a/mobile/lib/shared/widgets/concentric_sheet_surface.dart b/mobile/lib/shared/widgets/concentric_sheet_surface.dart index 7e8e5bee36..36d5d5e56c 100644 --- a/mobile/lib/shared/widgets/concentric_sheet_surface.dart +++ b/mobile/lib/shared/widgets/concentric_sheet_surface.dart @@ -130,6 +130,58 @@ class ConcentricSheetSurface extends HookWidget { final surfaceColor = color ?? context.colors.surface; final brightness = context.theme.brightness; final nativeSurfaceChannel = useState(null); + final nativeCornerRadius = useState(null); + useEffect(() { + final channel = nativeSurfaceChannel.value; + if (channel == null) return null; + var active = true; + void updateRadii(dynamic value) { + if (!active || value is! Map) return; + double? radius(String key) { + final number = value[key]; + return number is num && number.isFinite && number >= 0 + ? number.toDouble() + : null; + } + + final topLeft = radius('topLeft'); + final topRight = radius('topRight'); + final bottomLeft = radius('bottomLeft'); + final bottomRight = radius('bottomRight'); + if (topLeft == null || + topRight == null || + bottomLeft == null || + bottomRight == null) { + return; + } + nativeCornerRadius.value = BorderRadius.only( + topLeft: Radius.circular(topLeft), + topRight: Radius.circular(topRight), + bottomLeft: Radius.circular(bottomLeft), + bottomRight: Radius.circular(bottomRight), + ); + } + + channel.setMethodCallHandler((call) async { + if (call.method == 'cornerRadiiChanged') updateRadii(call.arguments); + }); + // The platform view can lay out before Flutter installs its handler. + Future readInitialRadii() async { + try { + updateRadii(await channel.invokeMethod('getCornerRadii')); + } on MissingPluginException { + // Retain the fallback clip when the native view is unavailable. + } on PlatformException { + // A subsequent native layout can supply the geometry. + } + } + + unawaited(readInitialRadii()); + return () { + active = false; + channel.setMethodCallHandler(null); + }; + }, [nativeSurfaceChannel.value]); useEffect( () { final channel = nativeSurfaceChannel.value; @@ -214,6 +266,7 @@ class ConcentricSheetSurface extends HookWidget { 'minimumRadius': minimumRadius, 'capsule': capsule, 'corners': corners.name, + 'independentCorners': providesSheetSurface, if (providesSheetSurface && corners == ConcentricSurfaceCorners.all) 'topRadius': sheetTopRadius, @@ -236,27 +289,20 @@ class ConcentricSheetSurface extends HookWidget { ), ClipRSuperellipse( key: const ValueKey('concentric-sheet-content-clip'), - // UIKit's container-concentric corner resolves substantially - // larger than its minimum radius on an edge-inset iOS sheet. Keep - // the Flutter content inside that continuous outline; a 24pt - // circular clip still lets scrolling rows show through the native - // corner cutouts. - borderRadius: - nativeSurfaceSupported && - providesSheetSurface && - corners == ConcentricSurfaceCorners.all - ? BorderRadius.vertical( - top: const Radius.circular(sheetTopRadius), - bottom: Radius.circular( - contentClipRadius ?? _nativeContentClipRadius, - ), - ) - : _borderRadius( - contentClipRadius ?? - (nativeSurfaceSupported - ? _nativeContentClipRadius - : minimumRadius), - ), + // Match each resolved UIKit corner, including asymmetric display + // corners and changes when folding or rotating the device. + borderRadius: contentClipRadius != null + ? _borderRadius(contentClipRadius!) + : nativeSurfaceSupported + ? (nativeCornerRadius.value ?? + (providesSheetSurface && + corners == ConcentricSurfaceCorners.all + ? const BorderRadius.vertical( + top: Radius.circular(sheetTopRadius), + bottom: Radius.circular(_nativeContentClipRadius), + ) + : _borderRadius(_nativeContentClipRadius))) + : fallbackBorderRadius, clipBehavior: Clip.antiAlias, child: providesSheetSurface ? _ConcentricSheetSurfaceScope( diff --git a/mobile/lib/shared/widgets/covered_route_keyboard_insets.dart b/mobile/lib/shared/widgets/covered_route_keyboard_insets.dart index c73461ca16..70b594162e 100644 --- a/mobile/lib/shared/widgets/covered_route_keyboard_insets.dart +++ b/mobile/lib/shared/widgets/covered_route_keyboard_insets.dart @@ -23,14 +23,24 @@ import 'package:flutter_hooks/flutter_hooks.dart'; /// comes down to the held value, or as soon as focus is inside this route /// (the page raised its own keyboard and has to follow it). class CoveredRouteKeyboardInsets extends HookWidget { - const CoveredRouteKeyboardInsets({super.key, required this.child}); + const CoveredRouteKeyboardInsets({ + super.key, + required this.child, + this.isCovered, + }); final Widget child; + /// Overrides route currency for content covered within its own route, such + /// as a compact list beneath a nested detail navigator. + final bool? isCovered; + @override Widget build(BuildContext context) { final data = MediaQuery.of(context); - final current = ModalRoute.isCurrentOf(context) ?? true; + final current = isCovered == null + ? ModalRoute.isCurrentOf(context) ?? true + : !isCovered!; // Focus moving into the route must release the held values even when the // keyboard height is not changing at that moment. useListenable(FocusManager.instance); diff --git a/mobile/lib/shared/widgets/duo_toolbar.dart b/mobile/lib/shared/widgets/duo_toolbar.dart new file mode 100644 index 0000000000..e930d74e4b --- /dev/null +++ b/mobile/lib/shared/widgets/duo_toolbar.dart @@ -0,0 +1,177 @@ +import 'package:duo_kit/duo_kit.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import 'ios_navigation_bar.dart'; + +/// Rail top clearance on Duo's inner display until UIKit reports its regions. +/// The package estimate describes the cover display's taller status cluster. +const double duoInnerDisplayEstimatedRailClearance = 110; + +/// Whether Duo controls should use the compact cover arrangement. +bool isCompactDuoWindow(BuildContext context) { + // Subscribe to resizing even inside a pane whose MediaQuery is narrower. + MediaQuery.sizeOf(context); + final view = View.of(context); + return (view.physicalSize / view.devicePixelRatio).shortestSide < 600; +} + +/// Carries window geometry through the independently sized conversation panes. +class DuoToolbarScope extends InheritedWidget { + const DuoToolbarScope({ + required this.strip, + required this.active, + this.contentInsets = EdgeInsets.zero, + this.leadingSlots = 0, + required super.child, + super.key, + }); + + final FoldStrip? strip; + final bool active; + final EdgeInsets contentInsets; + + /// Space above detail actions for the workspace's persistent rail controls. + final int leadingSlots; + + static DuoToolbarScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(DuoToolbarScope oldWidget) => + strip != oldWidget.strip || + active != oldWidget.active || + contentInsets != oldWidget.contentInsets || + leadingSlots != oldWidget.leadingSlots; +} + +/// Content clearance for a pane, or a full-window route outside a pane. +EdgeInsets duoContentInsetsOf(BuildContext context) { + final pane = DuoToolbarScope.maybeOf(context); + if (pane != null) return pane.contentInsets; + final strip = FoldGeometry.of(context).strip; + return EdgeInsets.only( + left: strip?.side == FoldStripSide.left ? strip!.width : 0, + right: strip?.side == FoldStripSide.right ? strip!.width : 0, + ); +} + +/// Projects the current route's controls into the window's side strip. +/// The portal retains route ownership and inherited providers for callbacks. +class DuoToolbarPortal extends HookConsumerWidget { + const DuoToolbarPortal({ + required this.strip, + required this.active, + required this.actions, + required this.child, + super.key, + }); + + final FoldStrip? strip; + final bool active; + final List actions; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final portal = useMemoized(() => OverlayPortalController()..show()); + return OverlayPortal( + overlayLocation: OverlayChildLocation.rootOverlay, + controller: portal, + overlayChildBuilder: (context) { + final strip = this.strip; + if (strip == null || actions.isEmpty) { + return const SizedBox.shrink(); + } + final windowSize = + View.of(context).physicalSize / View.of(context).devicePixelRatio; + // The package fallback describes the cover display. The inner display's + // status cluster is shorter; keep this estimated until regions arrive. + final metrics = IosNavigationMetrics.of(context); + final measuredTop = metrics.windowSize == windowSize + ? metrics.railTopClearance + : null; + final actionOffset = + (DuoToolbarScope.maybeOf(context)?.leadingSlots ?? 0) * 60.0; + final topClearance = + (measuredTop != null + ? measuredTop + 12 + : strip.isClearanceEstimated && windowSize.shortestSide >= 600 + ? duoInnerDisplayEstimatedRailClearance + : strip.topClearance) + + actionOffset; + return Positioned( + left: + IosNavigationMetrics.of(context).railCenter( + View.of(context).physicalSize / + View.of(context).devicePixelRatio, + strip.rect.center.dx, + ) - + strip.width / 2, + top: strip.rect.top + topClearance, + width: strip.width, + child: Offstage( + offstage: !active, + child: MediaQuery.removePadding( + context: context, + removeTop: true, + removeBottom: true, + removeLeft: true, + removeRight: true, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: + (strip.rect.height - + topClearance - + strip.bottomClearance - + 220) + .clamp(0.0, double.infinity), + ), + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final action in actions) + SizedBox( + key: ValueKey('duo-toolbar-${action.label}'), + height: 60, + child: IosNavigationBar( + title: '', + standaloneControl: true, + leading: action, + ), + ), + ], + ), + ), + ), + ), + ), + ); + }, + child: child, + ); + } +} + +/// Marks sheets whose default Close action is supplied by the Duo rail. +class DuoSheetCloseScope extends InheritedWidget { + const DuoSheetCloseScope({ + required this.inRail, + required super.child, + super.key, + }); + + final bool inRail; + + static bool of(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType() + ?.inRail ?? + false; + + @override + bool updateShouldNotify(DuoSheetCloseScope oldWidget) => + inRail != oldWidget.inRail; +} diff --git a/mobile/lib/shared/widgets/duo_workspace_scaffold.dart b/mobile/lib/shared/widgets/duo_workspace_scaffold.dart new file mode 100644 index 0000000000..0cb9ec3825 --- /dev/null +++ b/mobile/lib/shared/widgets/duo_workspace_scaffold.dart @@ -0,0 +1,48 @@ +import 'dart:math' as math; + +import 'package:duo_kit/duo_kit.dart'; +import 'package:flutter/material.dart'; + +/// Keeps route surfaces full width; each pane reserves its controls separately. +class DuoWorkspaceScaffold extends StatelessWidget { + const DuoWorkspaceScaffold({ + required this.body, + required this.navigationBuilder, + super.key, + }); + + final Widget body; + final FoldNavigationBuilder navigationBuilder; + + @override + Widget build(BuildContext context) { + final strip = FoldGeometry.of(context).strip; + final placement = switch (strip?.side) { + FoldStripSide.left => FoldNavigationPlacement.left, + FoldStripSide.right => FoldNavigationPlacement.right, + null => FoldNavigationPlacement.bottom, + }; + return Stack( + fit: StackFit.expand, + children: [ + body, + if (strip != null) + Positioned.fromRect( + rect: strip.rect, + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + padding: EdgeInsets.only( + top: strip.topClearance, + bottom: math.max( + strip.bottomClearance, + MediaQuery.viewPaddingOf(context).bottom, + ), + ), + ), + child: navigationBuilder(context, placement), + ), + ), + ], + ); + } +} diff --git a/mobile/lib/shared/widgets/emoji_avatar_controls.dart b/mobile/lib/shared/widgets/emoji_avatar_controls.dart index 12cc8c5f27..9c521e35b9 100644 --- a/mobile/lib/shared/widgets/emoji_avatar_controls.dart +++ b/mobile/lib/shared/widgets/emoji_avatar_controls.dart @@ -9,6 +9,7 @@ import '../emoji/emoji_search.dart'; import '../theme/theme.dart'; import '../theme/buzz_icons.dart'; import 'avatar_background_grid.dart'; +import 'avatar_editor_options.dart'; import 'avatar_editor_option_button.dart'; import 'emoji_avatar_tile.dart'; import 'ios_glass_navigation_button.dart'; @@ -233,36 +234,27 @@ class EmojiAvatarControls extends HookConsumerWidget { : Offset(actionOffset, 0), child: Opacity( opacity: transitionProgress, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Spacer(), - Expanded( - child: AvatarEditorOptionButton( - key: const ValueKey('emoji-editor-background'), - icon: BuzzIcons.palette, - iosIcon: IosGlassNavigationIcon.palette, - label: 'Background', - selected: - activeSection == EmojiEditorSection.background, - onTap: () => - onSectionChanged(EmojiEditorSection.background), - labelMaxWidth: 96, - ), + child: AvatarEditorOptions( + options: [ + AvatarEditorOptionButton( + key: const ValueKey('emoji-editor-background'), + icon: BuzzIcons.palette, + iosIcon: IosGlassNavigationIcon.palette, + label: 'Background', + selected: activeSection == EmojiEditorSection.background, + onTap: () => + onSectionChanged(EmojiEditorSection.background), + labelMaxWidth: 96, ), - const SizedBox(width: Grid.half), - Expanded( - child: AvatarEditorOptionButton( - key: const ValueKey('emoji-editor-emoji'), - icon: BuzzIcons.smile, - iosIcon: IosGlassNavigationIcon.emoji, - label: 'Emoji', - selected: activeSection == EmojiEditorSection.emoji, - onTap: () => onSectionChanged(EmojiEditorSection.emoji), - labelMaxWidth: 80, - ), + AvatarEditorOptionButton( + key: const ValueKey('emoji-editor-emoji'), + icon: BuzzIcons.smile, + iosIcon: IosGlassNavigationIcon.emoji, + label: 'Emoji', + selected: activeSection == EmojiEditorSection.emoji, + onTap: () => onSectionChanged(EmojiEditorSection.emoji), + labelMaxWidth: 80, ), - const Spacer(), ], ), ), diff --git a/mobile/lib/shared/widgets/frosted_app_bar.dart b/mobile/lib/shared/widgets/frosted_app_bar.dart index 5e1d3ba08c..d535ff3637 100644 --- a/mobile/lib/shared/widgets/frosted_app_bar.dart +++ b/mobile/lib/shared/widgets/frosted_app_bar.dart @@ -1,3 +1,5 @@ +import 'package:duo_kit/duo_kit.dart'; +import 'duo_toolbar.dart'; import 'dart:math' show max; import 'package:flutter/material.dart'; @@ -38,9 +40,42 @@ double _barContentHeight( ? titleContentHeight : scaledTitleHeight; final accessibleHeight = Grid.xxs + effectiveTitleHeight + Grid.xxs; - return accessibleHeight > _kBarContentMinHeight - ? accessibleHeight + final strip = + DuoToolbarScope.maybeOf(context)?.strip ?? FoldGeometry.of(context).strip; + final minimumHeight = + defaultTargetPlatform == TargetPlatform.iOS && + strip != null && + !isCompactDuoWindow(context) + ? _nativeCompactHeight(context) : _kBarContentMinHeight; + return accessibleHeight > minimumHeight ? accessibleHeight : minimumHeight; +} + +/// Height for a compact title rail below the app bar's action row. +/// +/// The rail normally stays at 40dp, but grows with an accessible title rather +/// than clipping text at larger system text sizes. +double frostedAppBarLowerTitleHeight( + BuildContext context, { + TextStyle? titleStyle, +}) { + final style = _effectiveTitleStyle(context, titleStyle); + final scaledFontSize = MediaQuery.textScalerOf( + context, + ).scale(style.fontSize ?? 16); + final titleHeight = scaledFontSize * (style.height ?? 1); + return titleHeight > 40 ? titleHeight : 40; +} + +// Duo has no top status inset in the content panes. Reserve breathing room +// around the native 44-point controls instead of collapsing the header to them. +double _nativeCompactHeight(BuildContext context, [double titleHeight = 0]) { + final scope = DuoToolbarScope.maybeOf(context); + final strip = scope == null ? FoldGeometry.of(context).strip : scope.strip; + final height = IosNavigationMetrics.of(context).compactHeight; + return strip == null + ? max(height, titleHeight) + : max(height.clamp(44.0, double.infinity), titleHeight) + 24; } /// Returns the total height of the [FrostedAppBar] including safe area padding. @@ -58,10 +93,7 @@ double frostedAppBarHeight( }) { if (useNativeNavigation && defaultTargetPlatform == TargetPlatform.iOS) { return MediaQuery.paddingOf(context).top + - max( - IosNavigationMetrics.of(context).compactHeight, - titleContentHeight, - ) + + _nativeCompactHeight(context, titleContentHeight) + (nativeLargeTitle ? IosNavigationMetrics.of(context).largeTitleHeight : 0) + @@ -154,6 +186,9 @@ class FrostedAppBar extends StatelessWidget { /// Whether UIKit should expand the title at the top of the page. final bool nativeLargeTitle; + /// Aligns a full-width native backdrop title with the inset page content. + final EdgeInsets nativeTitleInsets; + /// Whether UIKit owns the title and actions. Custom Flutter layouts still /// use the native soft backdrop on iOS. final bool useNativeNavigation; @@ -173,6 +208,9 @@ class FrostedAppBar extends StatelessWidget { /// Uses a composable Flutter header while a backdrop covers the native view. final ValueListenable? nativeViewSuppressed; + /// Projects controls into Duo's rail without a header over the content. + final bool railOnly; + const FrostedAppBar({ super.key, this.nativeTitle, @@ -185,12 +223,14 @@ class FrostedAppBar extends StatelessWidget { this.nativeTitleRefreshing = false, this.onNativeTitlePressed, this.nativeLargeTitle = false, + this.nativeTitleInsets = EdgeInsets.zero, this.useNativeNavigation = true, this.nativeLayoutDuration = Duration.zero, this.nativeLeading, this.nativeActions, this.onNativeReadyChanged, this.nativeViewSuppressed, + this.railOnly = false, this.leading, this.automaticallyImplyLeading = true, this.title, @@ -222,9 +262,55 @@ class FrostedAppBar extends StatelessWidget { } Widget _build(BuildContext context, bool nativeSuppressed) { + final railInsets = duoContentInsetsOf(context); if (useNativeNavigation && defaultTargetPlatform == TargetPlatform.iOS && !nativeSuppressed) { + final toolbarScope = DuoToolbarScope.maybeOf(context); + final strip = toolbarScope == null + ? FoldGeometry.of(context).strip + : toolbarScope.strip; + final leadingAction = nativeLeading ?? _nativeAction(leading); + final onBack = + automaticallyImplyLeading && + leading == null && + Navigator.canPop(context) + ? () { + Navigator.of(context).maybePop(); + } + : null; + final trailingActions = + nativeActions ?? + actions.map(_nativeAction).whereType().toList(); + final stripActions = [ + if (leadingAction != null && !leadingAction.keepInHeaderOnDuo) + leadingAction + else if (leadingAction == null && onBack != null) + IosNavigationAction( + label: 'Back', + symbol: 'chevron.backward', + onPressed: onBack, + ), + ...trailingActions.where((action) => !action.keepInHeaderOnDuo), + ]; + final toolbarActive = + (toolbarScope?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true); + if (railOnly && strip != null) { + return Positioned( + top: 0, + left: 0, + right: 0, + child: DuoToolbarPortal( + strip: strip, + active: toolbarActive, + actions: stripActions, + child: NavigationBackdrop( + child: SizedBox(height: MediaQuery.paddingOf(context).top), + ), + ), + ); + } final offset = IosNavigationScrollScope.maybeOf(context); Widget buildNative(double scrollOffset) { // Scrolling tracks the finger directly; only the search focus change @@ -238,10 +324,7 @@ class FrostedAppBar extends StatelessWidget { : 0.0; final barHeight = MediaQuery.paddingOf(context).top + - max( - IosNavigationMetrics.of(context).compactHeight, - titleContentHeight, - ) + + _nativeCompactHeight(context, titleContentHeight) + extra; return AnimatedPositioned( duration: layoutDuration, @@ -250,60 +333,79 @@ class FrostedAppBar extends StatelessWidget { left: 0, right: 0, height: barHeight + bottomHeight, - child: Stack( - children: [ - Positioned( - top: 0, - left: 0, - right: 0, - height: barHeight, - child: IosNavigationBar( - onReadyChanged: onNativeReadyChanged, - title: - nativeTitle ?? - (title is Text ? (title as Text).data ?? '' : ''), - subtitle: nativeSubtitle, - ephemeralLabel: nativeEphemeralLabel, - titleAvatar: nativeTitleAvatar, - titleAvatars: nativeTitleAvatars, - titleMaxWidth: nativeTitleMaxWidth, - titlePresenceColor: nativeTitlePresenceColor, - titleRefreshing: nativeTitleRefreshing, - onTitlePressed: onNativeTitlePressed, - largeTitle: nativeLargeTitle, - alwaysFrosted: alwaysFrosted, - foregroundColor: iconColor, - leading: nativeLeading ?? _nativeAction(leading), - onBack: - automaticallyImplyLeading && - leading == null && - Navigator.canPop(context) - ? () => Navigator.of(context).maybePop() - : null, - actions: - nativeActions ?? - actions - .map(_nativeAction) - .whereType() - .toList(), - ), - ), - if (bottom != null) - AnimatedPositioned( - duration: layoutDuration, - curve: Curves.easeInOutCubic, - top: barHeight - bottomOverlap, + child: DuoToolbarPortal( + strip: strip, + active: toolbarActive, + actions: stripActions, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned( + top: 0, left: 0, right: 0, - height: bottomHeight + bottomOverlap, - child: bottomOverlap > 0 || bottom is SizedBox - ? bottom! - : ColoredBox( - color: context.colors.surface, - child: bottom!, - ), + height: barHeight, + child: IosNavigationBar( + centerTitleInPane: strip != null && !nativeLargeTitle, + titleInsets: nativeTitleInsets == EdgeInsets.zero + ? railInsets + : nativeTitleInsets, + alignCollapsedTitleToLeading: + strip != null && nativeLargeTitle, + horizontalControls: + strip != null && + ((leadingAction?.keepInHeaderOnDuo ?? false) || + trailingActions.any( + (action) => action.keepInHeaderOnDuo, + )), + onReadyChanged: onNativeReadyChanged, + title: + nativeTitle ?? + (title is Text ? (title as Text).data ?? '' : ''), + subtitle: nativeSubtitle, + ephemeralLabel: nativeEphemeralLabel, + titleAvatar: nativeTitleAvatar, + titleAvatars: nativeTitleAvatars, + titleMaxWidth: nativeTitleMaxWidth, + titlePresenceColor: nativeTitlePresenceColor, + titleRefreshing: nativeTitleRefreshing, + onTitlePressed: onNativeTitlePressed, + largeTitle: nativeLargeTitle, + alwaysFrosted: alwaysFrosted || strip != null, + foregroundColor: iconColor, + leading: + strip == null || + (leadingAction?.keepInHeaderOnDuo ?? false) + ? leadingAction + : null, + onBack: strip == null ? onBack : null, + actions: strip == null + ? trailingActions + : trailingActions + .where((action) => action.keepInHeaderOnDuo) + .toList(), + ), ), - ], + if (bottom != null) + AnimatedPositioned( + duration: layoutDuration, + curve: Curves.easeInOutCubic, + top: barHeight - bottomOverlap, + left: 0, + right: 0, + height: bottomHeight + bottomOverlap, + child: Padding( + padding: railInsets, + child: bottomOverlap > 0 || bottom is SizedBox + ? bottom! + : ColoredBox( + color: context.colors.surface, + child: bottom!, + ), + ), + ), + ], + ), ), ); } @@ -435,7 +537,7 @@ class FrostedAppBar extends StatelessWidget { final background = Container( key: const ValueKey('frosted-app-bar-background'), - padding: EdgeInsets.only(top: topPadding), + padding: railInsets.copyWith(top: topPadding), decoration: const BoxDecoration(), child: content, ); diff --git a/mobile/lib/shared/widgets/frosted_scaffold.dart b/mobile/lib/shared/widgets/frosted_scaffold.dart index 1b9f898d36..716cdca8cf 100644 --- a/mobile/lib/shared/widgets/frosted_scaffold.dart +++ b/mobile/lib/shared/widgets/frosted_scaffold.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'ios_navigation_bar.dart'; +import 'duo_toolbar.dart'; import 'ios_scroll_to_top.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; @@ -46,6 +47,9 @@ class FrostedScaffold extends HookWidget { /// Reserves the native large title above fixed controls. final bool nativePinnedBody; + /// Lets a conversation header span the rail while its body stays inset. + final bool extendHeaderUnderRail; + const FrostedScaffold({ super.key, required this.appBar, @@ -57,10 +61,14 @@ class FrostedScaffold extends HookWidget { this.backgroundGradient, this.useUtilitySurfaceTheme = false, this.nativePinnedBody = false, + this.extendHeaderUnderRail = false, }); @override Widget build(BuildContext context) { + final contentInsets = duoContentInsetsOf(context); + final fullWidthHeader = + extendHeaderUnderRail || contentInsets != EdgeInsets.zero; final scrollOffset = useValueNotifier(0.0); final pinnedController = useScrollController(keepScrollOffset: false); // A keyed page/tab owns both coordinated positions and their restoration @@ -217,12 +225,16 @@ class FrostedScaffold extends HookWidget { floatingActionButton: floatingActionButton, body: FrostedScrollUnderScope( isScrolledUnder: isScrolledUnder.value, - child: Stack( - children: _stackChildren( - observedBody, - pinnedController, - pinnedStorage, - pinnedKey, + child: Padding( + padding: fullWidthHeader ? EdgeInsets.zero : contentInsets, + child: Stack( + children: _stackChildren( + observedBody, + pinnedController, + pinnedStorage, + pinnedKey, + fullWidthHeader ? contentInsets : EdgeInsets.zero, + ), ), ), ), @@ -241,6 +253,7 @@ class FrostedScaffold extends HookWidget { ScrollController pinnedController, PageStorageBucket pinnedStorage, GlobalKey pinnedKey, + EdgeInsets bodyInsets, ) { final backdrop = backgroundGradient == null ? const [] @@ -280,10 +293,15 @@ class FrostedScaffold extends HookWidget { // content rather than only the fixed gradient. return [ ...backdrop, - bodyMotion, + Padding(padding: bodyInsets, child: bodyMotion), appBar, if (foreground != null) - Positioned.fill(child: DirectionalTransitionMotion(child: foreground!)), + Positioned.fill( + child: Padding( + padding: bodyInsets, + child: DirectionalTransitionMotion(child: foreground!), + ), + ), ]; } } diff --git a/mobile/lib/shared/widgets/ios_message_create_button.dart b/mobile/lib/shared/widgets/ios_message_create_button.dart index 7ed01526cf..02bc15aa21 100644 --- a/mobile/lib/shared/widgets/ios_message_create_button.dart +++ b/mobile/lib/shared/widgets/ios_message_create_button.dart @@ -10,6 +10,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../relay/relay.dart'; import '../theme/theme.dart'; import 'avatar_image.dart'; +import 'duo_toolbar.dart'; /// The four desktop creation destinations, presented by UIKit on iOS. class IosMessageCreateButton extends HookConsumerWidget { @@ -21,8 +22,11 @@ class IosMessageCreateButton extends HookConsumerWidget { this.avatarUrl, this.avatarInitial, this.dividerBefore = const {}, + this.destructiveIndices = const {}, this.sectionTitles = const {}, this.icon = 'plus', + this.iconSize, + this.foregroundColor, this.accessibilityLabel = 'Create', this.width = 64, this.height = 48, @@ -35,14 +39,18 @@ class IosMessageCreateButton extends HookConsumerWidget { this.showIconWithLabel = false, this.onMenuVisibilityChanged, this.mergingNavigation = false, + this.navigationAxis = Axis.horizontal, }); final Set dividerBefore; + final Set destructiveIndices; final Map sectionTitles; final String? label; final double? labelFontSize; final String? avatarUrl, avatarInitial; final String icon; + final double? iconSize; + final Color? foregroundColor; final String accessibilityLabel; final double width, height; final bool plain; @@ -65,6 +73,9 @@ class IosMessageCreateButton extends HookConsumerWidget { /// Hosts the Search/New/Bestie glass surfaces in one native container. final bool mergingNavigation; + /// Direction of the merged navigation surfaces. + final Axis navigationAxis; + final List<({String label, String symbol, VoidCallback? onPressed})> actions; @override @@ -77,7 +88,7 @@ class IosMessageCreateButton extends HookConsumerWidget { (route?.isCurrent ?? true) && coveringProgress == 0; final brightness = context.theme.brightness; - final foreground = context.colors.onSurface.toARGB32(); + final foreground = (foregroundColor ?? context.colors.onSurface).toARGB32(); // Only an avatar trigger fetches media, so only it depends on the relay. final media = avatarInitial == null ? null @@ -121,6 +132,7 @@ class IosMessageCreateButton extends HookConsumerWidget { { 'id': i, 'dividerBefore': dividerBefore.contains(i), + 'destructive': destructiveIndices.contains(i), 'sectionTitle': ?sectionTitles[i], 'label': actions[i].label, 'symbol': actions[i].symbol, @@ -130,6 +142,7 @@ class IosMessageCreateButton extends HookConsumerWidget { ]; final content = { 'icon': icon, + 'iconSize': ?iconSize, 'imageBytes': ?avatar, 'label': ?label, 'labelFontSize': ?labelFontSize, @@ -175,6 +188,7 @@ class IosMessageCreateButton extends HookConsumerWidget { channel.value, avatar, icon, + iconSize, label, labelFontSize, accessibilityLabel, @@ -183,6 +197,7 @@ class IosMessageCreateButton extends HookConsumerWidget { deferMenuActions, showIconWithLabel, ...dividerBefore, + ...destructiveIndices, ...sectionTitles.entries.expand((e) => [e.key, e.value]), ...actions.expand((a) => [a.label, a.symbol, a.onPressed != null]), brightness, @@ -208,9 +223,16 @@ class IosMessageCreateButton extends HookConsumerWidget { 'plain': plain, 'fillWidth': fillWidth, 'buttonCenterX': width / 2, - 'controlWidth': mergingNavigation ? 112.0 : width, + 'controlWidth': mergingNavigation && navigationAxis == Axis.horizontal + ? 112.0 + : width, 'mergingNavigation': mergingNavigation, - 'controlSize': height, + 'menuAbove': + mergingNavigation && + navigationAxis == Axis.horizontal && + DuoToolbarScope.maybeOf(context)?.strip != null, + 'verticalNavigation': navigationAxis == Axis.vertical, + 'controlSize': mergingNavigation ? 56.0 : height, 'hitTargetWidth': width, 'hitTargetHeight': height, 'brightness': brightness.name, diff --git a/mobile/lib/shared/widgets/ios_navigation_bar.dart b/mobile/lib/shared/widgets/ios_navigation_bar.dart index bb23b83d1c..bec49c99e5 100644 --- a/mobile/lib/shared/widgets/ios_navigation_bar.dart +++ b/mobile/lib/shared/widgets/ios_navigation_bar.dart @@ -39,8 +39,12 @@ class IosNavigationAction { this.plain = false, this.sharesBackground = true, + this.keepInHeaderOnDuo = false, }); + /// Keeps list controls beside their content when a Duo rail is present. + final bool keepInHeaderOnDuo; + final String label; final String? symbol; @@ -85,6 +89,7 @@ class IosNavigationAction { 'plain': plain, 'sharesBackground': sharesBackground, + 'keepInHeaderOnDuo': keepInHeaderOnDuo, 'children': [ for (var i = 0; i < children.length; i++) children[i]._encode('$id.$i'), ], @@ -138,6 +143,12 @@ class IosNavigationBar extends HookConsumerWidget { this.largeTitle = false, this.alwaysFrosted = false, this.backdropOnly = false, + this.standaloneControl = false, + this.standaloneLargeTitle = false, + this.horizontalControls = false, + this.centerTitleInPane = false, + this.titleInsets = EdgeInsets.zero, + this.alignCollapsedTitleToLeading = false, this.leading, this.actions = const [], this.onBack, @@ -167,6 +178,20 @@ class IosNavigationBar extends HookConsumerWidget { /// Paints only the native edge beneath custom Flutter header controls. final bool backdropOnly; + + /// Renders one glass control without navigation-bar overflow or safe areas. + final bool standaloneControl; + + /// A wrapping native large title for a static title pane. + final bool standaloneLargeTitle; + final bool horizontalControls; + + /// Centers compact titles within a pane that already excludes the Duo rail. + final bool centerTitleInPane; + + /// Content-area insets for a title whose backdrop spans the whole window. + final EdgeInsets titleInsets; + final bool alignCollapsedTitleToLeading; final IosNavigationAction? leading; final List actions; final VoidCallback? onBack; @@ -323,9 +348,11 @@ class IosNavigationBar extends HookConsumerWidget { }; } + final portraitTopPadding = centerTitleInPane ? 12.0 : 0.0; final payload = { 'title': title, 'titleMaxWidth': titleMaxWidth, + 'portraitTopPadding': portraitTopPadding, 'titleHasAnimatedPortrait': titleAvatars.length == 1 && DmHeaderPortrait.playsAnimation( @@ -348,6 +375,13 @@ class IosNavigationBar extends HookConsumerWidget { 'largeTitle': largeTitle, 'alwaysFrosted': alwaysFrosted, 'backdropOnly': backdropOnly, + 'standaloneControl': standaloneControl, + 'standaloneLargeTitle': standaloneLargeTitle, + 'horizontalControls': horizontalControls, + 'centerTitleInPane': centerTitleInPane, + 'titleInsetLeft': titleInsets.left, + 'titleInsetRight': titleInsets.right, + 'alignCollapsedTitleToLeading': alignCollapsedTitleToLeading, 'back': onBack != null, 'leading': leading == null ? null : encodeAction(leading!, 'leading'), 'actions': [ @@ -365,6 +399,15 @@ class IosNavigationBar extends HookConsumerWidget { final current = channel.value; if (current == null) return null; current.setMethodCallHandler((call) async { + if (call.method == 'railGeometry') { + if (context.mounted) { + IosNavigationMetrics.updateRail( + context, + call.arguments as Map, + ); + } + return; + } if (call.method == 'avatarBounds') { final values = call.arguments as Map; final box = viewKey.currentContext?.findRenderObject(); @@ -526,7 +569,8 @@ class IosNavigationBar extends HookConsumerWidget { if (titleAvatars.isNotEmpty) Positioned( top: - MediaQuery.viewPaddingOf(context).top - + MediaQuery.viewPaddingOf(context).top + + portraitTopPadding - (payload['titleHasAnimatedPortrait'] == true ? 4 : 0), left: 0, right: 0, diff --git a/mobile/lib/shared/widgets/ios_navigation_metrics.dart b/mobile/lib/shared/widgets/ios_navigation_metrics.dart index 6d7a731d72..85f55f7463 100644 --- a/mobile/lib/shared/widgets/ios_navigation_metrics.dart +++ b/mobile/lib/shared/widgets/ios_navigation_metrics.dart @@ -6,10 +6,87 @@ class IosNavigationMetrics { const IosNavigationMetrics({ this.compactHeight = 44, this.largeTitleHeight = 52, + this.railCenterX, + this.railTopClearance, + this.windowSize, + this.bookDivision, }); final double compactHeight; final double largeTitleHeight; + final double? railCenterX; + final double? railTopClearance; + final Size? windowSize; + final Rect? bookDivision; + + /// Aligns the shared rail with the status cluster in the reserved region. + double railCenter(Size size, double fallback) { + final center = windowSize == size ? railCenterX ?? fallback : fallback; + return center + (center < size.width / 2 ? 6 : -6); + } + + static void updateRail(BuildContext context, Map values) { + final notifier = _MetricsScope.of(context); + final center = (values['centerX'] as num?)?.toDouble(); + final width = (values['windowWidth'] as num?)?.toDouble(); + final height = (values['windowHeight'] as num?)?.toDouble(); + if (notifier == null || + center == null || + width == null || + height == null || + !center.isFinite || + !width.isFinite || + !height.isFinite || + center < 0 || + center > width || + width <= 0 || + height <= 0) { + return; + } + final size = Size(width, height); + final rawTop = (values['topClearance'] as num?)?.toDouble(); + final top = + rawTop != null && rawTop.isFinite && rawTop >= 0 && rawTop < height + ? rawTop + : null; + final rawDivision = values['bookDivision']; + Rect? division; + if (rawDivision is List && + rawDivision.length == 4 && + rawDivision.every((value) => value is num && value.isFinite)) { + final bounds = rawDivision + .map((value) => (value as num).toDouble()) + .toList(); + final candidate = Rect.fromLTWH( + bounds[0], + bounds[1], + bounds[2], + bounds[3], + ); + if (candidate.width >= 0 && + candidate.left > 0 && + candidate.right < width && + candidate.top <= 1 && + candidate.bottom >= height - 1) { + division = candidate; + } + } + final old = notifier.value; + if (old.railCenterX == center && + old.railTopClearance == top && + old.windowSize == size && + old.bookDivision == division) { + return; + } + notifier.value = IosNavigationMetrics( + compactHeight: old.compactHeight, + largeTitleHeight: old.largeTitleHeight, + railCenterX: center, + railTopClearance: top, + windowSize: size, + bookDivision: division, + ); + } static IosNavigationMetrics of(BuildContext context) => _MetricsScope.of(context)?.value ?? const IosNavigationMetrics(); @@ -31,6 +108,10 @@ class IosNavigationMetrics { notifier.value = IosNavigationMetrics( compactHeight: compact, largeTitleHeight: extra, + railCenterX: notifier.value.railCenterX, + railTopClearance: notifier.value.railTopClearance, + windowSize: notifier.value.windowSize, + bookDivision: notifier.value.bookDivision, ); } } diff --git a/mobile/lib/shared/widgets/modal_presentation.dart b/mobile/lib/shared/widgets/modal_presentation.dart index 54caebf961..56a3454be2 100644 --- a/mobile/lib/shared/widgets/modal_presentation.dart +++ b/mobile/lib/shared/widgets/modal_presentation.dart @@ -1,8 +1,11 @@ import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/material.dart'; import '../theme/theme.dart'; import 'buzz_sheet_header.dart'; +import 'duo_toolbar.dart'; +import 'ios_navigation_bar.dart'; import 'buzz_titled_sheet_layout.dart'; import 'concentric_sheet_surface.dart'; @@ -23,6 +26,10 @@ const buzzModalAnimationStyle = AnimationStyle( /// uses native concentric corners when available and paints a requested drag /// handle inside the shared header so its spacing is consistent on every /// platform. +/// Set [useDuoFullWidth] to false for a bounded sheet with local controls +/// in the nearest navigator (unless [useRootNavigator] is explicitly true). +/// Set [padHorizontal] to false when the content paints behind the Duo rail +/// and reserves its own horizontal safe area. /// Set [padBottom] to false when the content owns its bottom edge spacing. Future showBuzzModalBottomSheet({ required BuildContext context, @@ -38,12 +45,15 @@ Future showBuzzModalBottomSheet({ bool isScrollControlled = false, double scrollControlDisabledMaxHeightRatio = 9.0 / 16.0, bool useRootNavigator = false, + bool useDuoFullWidth = true, bool isDismissible = true, bool enableDrag = true, bool? showDragHandle, bool showCloseButton = true, + bool showRailCloseButton = false, bool useSafeArea = false, bool padBottom = true, + bool padHorizontal = true, RouteSettings? routeSettings, AnimationController? transitionAnimationController, Offset? anchorPoint, @@ -51,6 +61,11 @@ Future showBuzzModalBottomSheet({ bool? requestFocus, }) { final isIos = defaultTargetPlatform == TargetPlatform.iOS; + final startsFullWidth = + useDuoFullWidth && + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null; final theme = Theme.of(context); // Explicitly colored sheets (for example the dark Huddle drawer) own their // complete surface treatment. Standard utility sheets use the quieter page @@ -67,50 +82,140 @@ Future showBuzzModalBottomSheet({ return showModalBottomSheet( context: context, - builder: (sheetContext) => Theme( - data: sheetTheme, - child: Builder( - builder: (themedContext) => ConcentricSheetSurface( - enabled: isIos, - color: surfaceColor, - child: _SheetContent( - title: title, - showCloseButton: showCloseButton, - showDragHandle: showDragHandle == true, - surfaceColor: surfaceColor, - // Keep the entire scroll viewport above gesture navigation. The - // inner builder sees a consumed bottom inset, so sheet-local safe - // areas and scroll padding do not reserve that system inset twice. - child: SafeArea( - top: false, - left: false, - right: false, - bottom: padBottom, - child: Padding( - padding: EdgeInsets.only(bottom: padBottom ? Grid.half : 0), - child: Builder(builder: builder), + builder: (sheetContext) { + // Read the current window on every posture change. Keeping these values + // outside the builder leaves Close owned by a rail that may disappear. + final strip = + DuoToolbarScope.maybeOf(sheetContext)?.strip ?? + FoldGeometry.of(sheetContext).strip; + final fullWidth = strip != null && useDuoFullWidth; + final content = _SheetLocalSafeArea( + localize: strip != null && !fullWidth, + child: DuoToolbarScope( + strip: strip, + active: true, + child: DuoToolbarPortal( + strip: isIos && fullWidth ? strip : null, + active: ModalRoute.isCurrentOf(sheetContext) ?? true, + actions: [ + if (showCloseButton || showRailCloseButton) + IosNavigationAction( + label: 'Close ${title ?? 'sheet'}', + symbol: 'xmark', + onPressed: () => Navigator.of(sheetContext).pop(), + ), + ], + child: DuoSheetCloseScope( + inRail: + isIos && + fullWidth && + (showCloseButton || showRailCloseButton), + child: Theme( + data: sheetTheme, + child: Builder( + builder: (themedContext) => ConcentricSheetSurface( + enabled: isIos, + padding: fullWidth + ? EdgeInsets.zero + : const EdgeInsets.only( + left: Grid.xxs, + right: Grid.xxs, + bottom: Grid.xxs, + ), + color: surfaceColor, + child: SafeArea( + top: false, + bottom: false, + left: fullWidth && padHorizontal, + right: fullWidth && padHorizontal, + child: _SheetContent( + title: title, + showCloseButton: showCloseButton, + showDragHandle: showDragHandle == true, + surfaceColor: surfaceColor, + // Keep the entire scroll viewport above gesture navigation. The + // inner builder sees a consumed bottom inset, so sheet-local safe + // areas and scroll padding do not reserve that system inset twice. + child: SafeArea( + top: false, + left: false, + right: false, + bottom: padBottom, + child: Padding( + padding: EdgeInsets.only( + bottom: padBottom ? Grid.half : 0, + ), + child: Builder(builder: builder), + ), + ), + ), + ), + ), + ), ), ), ), ), - ), - ), + ); + if (!isIos || !useDuoFullWidth) return content; + // The route cannot change useSafeArea after presentation. Apply it here + // so rail-owned sheets can use the full window after unfolding. + final media = MediaQuery.of(sheetContext); + final window = MediaQueryData.fromView(View.of(sheetContext)); + return MediaQuery( + data: media.copyWith( + padding: media.padding.copyWith( + top: useSafeArea && !fullWidth + ? window.padding.top + : media.padding.top, + ), + ), + child: SafeArea( + top: useSafeArea && !fullWidth, + left: useSafeArea && !fullWidth, + right: useSafeArea && !fullWidth, + bottom: false, + child: Align( + alignment: Alignment.bottomCenter, + widthFactor: 1, + heightFactor: 1, + child: ConstrainedBox( + constraints: + constraints ?? + (fullWidth + ? const BoxConstraints(maxWidth: double.infinity) + : sheetTheme.bottomSheetTheme.constraints ?? + BoxConstraints( + maxWidth: sheetTheme.useMaterial3 + ? 640 + : double.infinity, + )), + child: content, + ), + ), + ), + ); + }, backgroundColor: isIos || title != null ? Colors.transparent : surfaceColor, barrierLabel: barrierLabel, elevation: elevation, shape: shape, clipBehavior: clipBehavior, - constraints: constraints, + // The route must permit expansion; the builder owns the live width cap. + constraints: isIos && useDuoFullWidth + ? const BoxConstraints(maxWidth: double.infinity) + : constraints, barrierColor: barrierColor, isScrollControlled: isScrollControlled, scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio, - useRootNavigator: useRootNavigator, + useRootNavigator: + (isIos && useDuoFullWidth) || startsFullWidth || useRootNavigator, isDismissible: isDismissible, enableDrag: enableDrag, // The shared header owns the handle so Android does not reserve a second // handle band above the title row and iOS keeps it inside its native inset. showDragHandle: false, - useSafeArea: useSafeArea, + useSafeArea: isIos && useDuoFullWidth ? false : useSafeArea, routeSettings: routeSettings, transitionAnimationController: transitionAnimationController, anchorPoint: anchorPoint, @@ -121,6 +226,40 @@ Future showBuzzModalBottomSheet({ ); } +/// Window insets only apply where they intersect a centered sheet's bounds. +class _SheetLocalSafeArea extends StatelessWidget { + const _SheetLocalSafeArea({required this.localize, required this.child}); + + final bool localize; + final Widget child; + + @override + Widget build(BuildContext context) { + if (!localize) return child; + return LayoutBuilder( + builder: (context, constraints) { + final media = MediaQuery.of(context); + final margin = (media.size.width - constraints.maxWidth) / 2; + EdgeInsets localInsets(EdgeInsets insets) => insets.copyWith( + left: (insets.left - margin).clamp(0.0, double.infinity), + right: (insets.right - margin).clamp(0.0, double.infinity), + ); + return DuoToolbarScope( + strip: null, + active: true, + child: MediaQuery( + data: media.copyWith( + padding: localInsets(media.padding), + viewPadding: localInsets(media.viewPadding), + ), + child: child, + ), + ); + }, + ); + } +} + class _SheetContent extends StatelessWidget { const _SheetContent({ required this.child, diff --git a/mobile/lib/shared/widgets/navigation_backdrop.dart b/mobile/lib/shared/widgets/navigation_backdrop.dart index 0820ef38cf..6ab52f2a86 100644 --- a/mobile/lib/shared/widgets/navigation_backdrop.dart +++ b/mobile/lib/shared/widgets/navigation_backdrop.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import '../theme/theme.dart'; import 'ios_navigation_bar.dart'; +import 'duo_toolbar.dart'; /// The shared top-edge treatment, independent of a header's controls. /// @@ -37,6 +38,8 @@ class NavigationBackdrop extends StatelessWidget { child: ExcludeSemantics( child: IosNavigationBar( title: '', + centerTitleInPane: + DuoToolbarScope.maybeOf(context)?.strip != null, backdropOnly: true, alwaysFrosted: true, ), diff --git a/mobile/lib/shared/widgets/onboarding_step_page.dart b/mobile/lib/shared/widgets/onboarding_step_page.dart index e1a58a44a8..472048817c 100644 --- a/mobile/lib/shared/widgets/onboarding_step_page.dart +++ b/mobile/lib/shared/widgets/onboarding_step_page.dart @@ -1,4 +1,6 @@ import 'dart:ui' show ImageFilter; +import 'package:duo_kit/duo_kit.dart'; +import 'duo_toolbar.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/semantics.dart'; @@ -36,13 +38,22 @@ class OnboardingStepPage extends StatelessWidget { Widget build(BuildContext context) { final theme = Theme.of(context); final ios = defaultTargetPlatform == TargetPlatform.iOS; + final scope = DuoToolbarScope.maybeOf(context); + final fold = FoldGeometry.of(context); + final size = MediaQuery.sizeOf(context); + final unfolded = + (!ios || size.width > size.height) && + (fold.division != null || size.shortestSide >= 600); + final strip = ios + ? (scope == null ? FoldGeometry.of(context).strip : scope.strip) + : null; final buttonStyle = FilledButton.styleFrom( backgroundColor: theme.colorScheme.primary, foregroundColor: theme.colorScheme.onPrimary, minimumSize: const Size.fromHeight(52), shape: const StadiumBorder(), ); - return Theme( + final page = Theme( data: theme.copyWith( filledButtonTheme: FilledButtonThemeData(style: buttonStyle), textButtonTheme: TextButtonThemeData( @@ -60,157 +71,186 @@ class OnboardingStepPage extends StatelessWidget { }, child: Scaffold( backgroundColor: theme.colorScheme.surface, - body: SafeArea( - top: !ios, - child: ExcludeFocus( - excluding: foregroundProgress > 0, - child: ExcludeSemantics( - excluding: foregroundProgress > 0, - child: IgnorePointer( - ignoring: foregroundProgress > 0, - child: Opacity( - key: const Key('scanner-welcome-opacity'), - opacity: 1 - foregroundProgress, - child: Transform.scale( - key: const Key('scanner-welcome-scale'), - scale: MediaQuery.disableAnimationsOf(context) - ? 1 - : 1 - .04 * foregroundProgress, - child: ImageFiltered( - enabled: - !MediaQuery.disableAnimationsOf(context) && - foregroundProgress > 0 && - foregroundProgress < 1, - imageFilter: ImageFilter.blur( - sigmaX: 16 * foregroundProgress, - sigmaY: 16 * foregroundProgress, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (ios) - SizedBox( - height: - MediaQuery.paddingOf(context).top + - IosNavigationMetrics.of( - context, - ).compactHeight, - child: IosNavigationBar( - title: '', - leading: onBack == null - ? null - : IosNavigationAction( - label: 'Back', - symbol: 'chevron.backward', - onPressed: onBack, - ), - ), - ) - else if (onBack != null) - NavigationBackdrop( - child: Align( - alignment: AlignmentDirectional.centerStart, - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: Grid.xxs, - ), - child: IconButton( - tooltip: 'Back', - onPressed: onBack, - icon: const BackButtonIcon(), - ), - ), - ), + body: Padding( + padding: EdgeInsets.symmetric( + horizontal: unfolded ? strip?.width ?? 0 : 0, + ), + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: strip == null || !unfolded ? double.infinity : 440, + ), + child: SafeArea( + left: strip == null || !unfolded, + right: strip == null || !unfolded, + top: !ios, + child: ExcludeFocus( + excluding: foregroundProgress > 0, + child: ExcludeSemantics( + excluding: foregroundProgress > 0, + child: IgnorePointer( + ignoring: foregroundProgress > 0, + child: Opacity( + key: const Key('scanner-welcome-opacity'), + opacity: 1 - foregroundProgress, + child: Transform.scale( + key: const Key('scanner-welcome-scale'), + scale: MediaQuery.disableAnimationsOf(context) + ? 1 + : 1 - .04 * foregroundProgress, + child: ImageFiltered( + enabled: + !MediaQuery.disableAnimationsOf(context) && + foregroundProgress > 0 && + foregroundProgress < 1, + imageFilter: ImageFilter.blur( + sigmaX: 16 * foregroundProgress, + sigmaY: 16 * foregroundProgress, ), - Expanded( - child: CustomScrollView( - keyboardDismissBehavior: - ScrollViewKeyboardDismissBehavior.onDrag, - slivers: [ - SliverFillRemaining( - hasScrollBody: false, - child: Padding( - padding: EdgeInsets.fromLTRB( - Grid.sm, - Grid.sm, - Grid.sm, - MediaQuery.viewInsetsOf( - context, - ).bottom > - 0 - ? keyboardBottomSpacing - : Grid.sm, - ), - child: Column( - crossAxisAlignment: - CrossAxisAlignment.stretch, - children: [ - GestureDetector( - key: onConnectionOptions == null - ? null - : const Key( - 'developer-pairing-trigger', - ), - excludeFromSemantics: true, - child: Semantics( - header: true, - namesRoute: true, - customSemanticsActions: - onConnectionOptions == null + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (ios && (strip == null || !unfolded)) + SizedBox( + height: + MediaQuery.paddingOf(context).top + + IosNavigationMetrics.of( + context, + ).compactHeight, + child: strip != null + ? const SizedBox.shrink() + : IosNavigationBar( + title: '', + leading: onBack == null ? null - : { - const CustomSemanticsAction( - label: - 'More connection options', - ): onConnectionOptions!, - }, - child: Text( - title, - style: OnboardingTypography - .title - .copyWith( - color: theme - .colorScheme - .onSurface, + : IosNavigationAction( + label: 'Back', + symbol: + 'chevron.backward', + onPressed: onBack, ), - ), + ), + ) + else if (!ios && onBack != null) + NavigationBackdrop( + child: Align( + alignment: + AlignmentDirectional.centerStart, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.xxs, + ), + child: IconButton( + tooltip: 'Back', + onPressed: onBack, + icon: const BackButtonIcon(), + ), + ), + ), + ), + Expanded( + child: CustomScrollView( + keyboardDismissBehavior: + ScrollViewKeyboardDismissBehavior + .onDrag, + slivers: [ + SliverFillRemaining( + hasScrollBody: false, + child: Padding( + padding: EdgeInsets.fromLTRB( + Grid.sm, + Grid.sm, + Grid.sm, + MediaQuery.viewInsetsOf( + context, + ).bottom > + 0 + ? keyboardBottomSpacing + : Grid.sm, + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.stretch, + children: [ + GestureDetector( + key: + onConnectionOptions == + null + ? null + : const Key( + 'developer-pairing-trigger', + ), + excludeFromSemantics: true, + child: Semantics( + header: true, + namesRoute: true, + customSemanticsActions: + onConnectionOptions == + null + ? null + : { + const CustomSemanticsAction( + label: + 'More connection options', + ): onConnectionOptions!, + }, + child: Text( + title, + style: + OnboardingTypography + .title + .copyWith( + color: theme + .colorScheme + .onSurface, + ), + ), + ), + ), + if (subtitle != null) ...[ + const SizedBox( + height: Grid.xs, + ), + Text( + subtitle!, + style: OnboardingTypography + .subtitle + .copyWith( + color: theme + .colorScheme + .onSurfaceVariant, + ), + ), + ], + const SizedBox(height: Grid.xs), + content, + const Spacer(), + if (actions.isNotEmpty) + const SizedBox( + height: Grid.sm, + ), + for ( + var i = 0; + i < actions.length; + i++ + ) ...[ + if (i > 0) + const SizedBox( + height: Grid.xxs, + ), + actions[i], + ], + ], ), ), - if (subtitle != null) ...[ - const SizedBox(height: Grid.xs), - Text( - subtitle!, - style: OnboardingTypography - .subtitle - .copyWith( - color: theme - .colorScheme - .onSurfaceVariant, - ), - ), - ], - const SizedBox(height: Grid.xs), - content, - const Spacer(), - if (actions.isNotEmpty) - const SizedBox(height: Grid.sm), - for ( - var i = 0; - i < actions.length; - i++ - ) ...[ - if (i > 0) - const SizedBox(height: Grid.xxs), - actions[i], - ], - ], - ), + ), + ], ), ), ], ), ), - ], + ), ), ), ), @@ -222,5 +262,22 @@ class OnboardingStepPage extends StatelessWidget { ), ), ); + if (strip == null) return page; + return DuoToolbarPortal( + strip: strip, + active: + (scope?.active ?? true) && + (ModalRoute.isCurrentOf(context) ?? true) && + foregroundProgress == 0, + actions: [ + if (onBack != null) + IosNavigationAction( + label: 'Back', + symbol: 'chevron.backward', + onPressed: onBack, + ), + ], + child: page, + ); } } diff --git a/mobile/lib/shared/widgets/profile_avatar_crop_page.dart b/mobile/lib/shared/widgets/profile_avatar_crop_page.dart index 76c06afcfd..73bc3a994e 100644 --- a/mobile/lib/shared/widgets/profile_avatar_crop_page.dart +++ b/mobile/lib/shared/widgets/profile_avatar_crop_page.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter/material.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter/services.dart'; @@ -8,6 +9,7 @@ import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:image/image.dart' as image; import '../theme/theme.dart'; +import 'duo_toolbar.dart'; import 'buzz_loading_indicator.dart'; import 'frosted_app_bar.dart'; import 'frosted_scaffold.dart'; @@ -39,7 +41,6 @@ class ProfileAvatarCropPage extends HookWidget { final dimensions = dimensionsData == null ? null : _ImageDimensions(dimensionsData[0], dimensionsData[1]); - final initializedForSize = useRef(null); final cropGeometry = useRef<_CropGeometry?>(null); final displaySize = useRef(null); final isClampingTransform = useRef(false); @@ -97,12 +98,60 @@ class ProfileAvatarCropPage extends HookWidget { return () => disposed = true; }, [imageBytes]); + final canCrop = + !isCropping.value && preparedBytes.value != null && dimensions != null; + Future finishCrop() async { + if (isCropping.value || + dimensions == null || + preparedBytes.value == null) { + return; + } + isCropping.value = true; + unawaited(HapticFeedback.lightImpact()); + try { + if (!context.mounted) return; + final geometry = cropGeometry.value; + if (geometry == null) return; + final cropped = await compute( + _cropAvatar, + _CropRequest( + bytes: preparedBytes.value!, + sourceWidth: dimensions.width, + sourceHeight: dimensions.height, + canvasWidth: geometry.canvasWidth, + canvasHeight: geometry.canvasHeight, + cropDiameter: geometry.cropDiameter, + transform: List.from(controller.value.storage), + ), + ); + if (context.mounted) { + Navigator.pop(context, cropped); + } + } finally { + if (context.mounted) isCropping.value = false; + } + } + + final strip = defaultTargetPlatform == TargetPlatform.iOS + ? (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) + : null; return Theme( data: AppTheme.dark(), child: FrostedScaffold( backgroundColor: Colors.black, appBar: FrostedAppBar( - useNativeNavigation: false, + nativeLeading: IosNavigationAction( + label: strip == null ? 'Back' : 'Cancel photo positioning', + symbol: strip == null ? 'chevron.backward' : 'xmark', + onPressed: isCropping.value ? null : () => Navigator.pop(context), + ), + nativeActions: [ + IosNavigationAction( + label: isCropping.value ? 'Saving…' : 'Done', + onPressed: canCrop ? finishCrop : null, + ), + ], horizontalInset: 0, alwaysFrosted: true, iconColor: Colors.white, @@ -115,19 +164,22 @@ class ProfileAvatarCropPage extends HookWidget { fontWeight: FontWeight.w600, ), ), - leading: Padding( - padding: const EdgeInsets.only(left: Grid.gutter), - child: Align( - widthFactor: 1, - alignment: Alignment.centerLeft, - child: _CropHeaderButton( - label: 'Back', - onPressed: isCropping.value - ? null - : () => Navigator.pop(context), - ), - ), - ), + automaticallyImplyLeading: false, + leading: strip != null + ? null + : Padding( + padding: const EdgeInsets.only(left: Grid.gutter), + child: Align( + widthFactor: 1, + alignment: Alignment.centerLeft, + child: _CropHeaderButton( + label: 'Back', + onPressed: isCropping.value + ? null + : () => Navigator.pop(context), + ), + ), + ), actions: [ Padding( padding: const EdgeInsets.only(right: Grid.gutter), @@ -135,45 +187,13 @@ class ProfileAvatarCropPage extends HookWidget { key: const ValueKey('avatar-crop-use-photo'), label: 'Done', loading: isCropping.value, - onPressed: - isCropping.value || - preparedBytes.value == null || - dimensions == null - ? null - : () async { - isCropping.value = true; - unawaited(HapticFeedback.lightImpact()); - try { - if (!context.mounted) return; - final geometry = cropGeometry.value; - if (geometry == null) return; - final cropped = await compute( - _cropAvatar, - _CropRequest( - bytes: preparedBytes.value!, - sourceWidth: dimensions.width, - sourceHeight: dimensions.height, - canvasWidth: geometry.canvasWidth, - canvasHeight: geometry.canvasHeight, - cropDiameter: geometry.cropDiameter, - transform: List.from( - controller.value.storage, - ), - ), - ); - if (context.mounted) Navigator.pop(context, cropped); - } finally { - if (context.mounted) isCropping.value = false; - } - }, + onPressed: canCrop ? finishCrop : null, ), ), ], ), body: Padding( - padding: EdgeInsets.only( - top: frostedAppBarHeight(context, useNativeNavigation: false), - ), + padding: EdgeInsets.only(top: frostedAppBarHeight(context)), child: loadError.value || dimensionsSnapshot.hasError ? const Center( child: Text( @@ -193,6 +213,7 @@ class ProfileAvatarCropPage extends HookWidget { final canvasWidth = constraints.maxWidth; final canvasHeight = math.max(1.0, constraints.maxHeight); final cropDiameter = math.min(canvasWidth, canvasHeight); + final previousGeometry = cropGeometry.value; cropGeometry.value = _CropGeometry( canvasWidth: canvasWidth, canvasHeight: canvasHeight, @@ -206,9 +227,7 @@ class ProfileAvatarCropPage extends HookWidget { ? cropDiameter : cropDiameter / aspect; displaySize.value = Size(displayWidth, displayHeight); - final canvasSize = Size(canvasWidth, canvasHeight); - if (initializedForSize.value != canvasSize) { - initializedForSize.value = canvasSize; + if (previousGeometry == null) { controller.value = Matrix4.identity() ..translateByDouble( (canvasWidth - displayWidth) / 2, @@ -216,6 +235,28 @@ class ProfileAvatarCropPage extends HookWidget { 0, 1, ); + } else if (previousGeometry.canvasWidth != canvasWidth || + previousGeometry.canvasHeight != canvasHeight || + previousGeometry.cropDiameter != cropDiameter) { + // Display dimensions scale with the crop diameter. Keep + // the same source-image point under the crop center and + // retain zoom, so the selected source rectangle survives. + final ratio = + cropDiameter / previousGeometry.cropDiameter; + final matrix = controller.value.clone(); + matrix.storage[12] = + canvasWidth / 2 - + (previousGeometry.canvasWidth / 2 - + matrix.storage[12]) * + ratio; + matrix.storage[13] = + canvasHeight / 2 - + (previousGeometry.canvasHeight / 2 - + matrix.storage[13]) * + ratio; + // The listener clamps against the new geometry. Scale is + // unchanged, so cropScale remains synchronized as well. + controller.value = matrix; } void movePhoto(Offset delta) { unawaited(HapticFeedback.selectionClick()); diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index bd2f85667d..5e97f5df7d 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -360,6 +360,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.7.12" + duo_kit: + dependency: "direct main" + description: + name: duo_kit + sha256: "212fb2cd8cd69d0aebec5631d259b026dacd5cd48746955a534f2a4a51cd145d" + url: "https://pub.dev" + source: hosted + version: "0.1.1" elliptic: dependency: transitive description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index ad01cef42b..c5ceff5895 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -52,6 +52,7 @@ dependencies: share_plus: ^13.3.0 local_auth: ^3.0.2 unorm_dart: ^0.3.3 + duo_kit: 0.1.1 flutter_cache_manager: ^3.5.0 file: ^7.0.1 path: ^1.9.1 diff --git a/mobile/test/features/activity/activity_page_test.dart b/mobile/test/features/activity/activity_page_test.dart index 96974e90cc..3a22c201b5 100644 --- a/mobile/test/features/activity/activity_page_test.dart +++ b/mobile/test/features/activity/activity_page_test.dart @@ -1,3 +1,4 @@ +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; @@ -129,6 +130,7 @@ void main() { }; Future buildTestable({ + bool withPane = false, HomeFeedResponse? feed, ActivityNotifier Function()? activityNotifier, Map? users, @@ -178,7 +180,11 @@ void main() { ).copyWith(textScaler: textScaler, padding: mediaPadding), child: child!, ), - home: ActivityPage(tabReselection: tabReselection), + home: withPane + ? AdaptiveConversationDestination( + child: ActivityPage(tabReselection: tabReselection), + ) + : ActivityPage(tabReselection: tabReselection), ), ); } @@ -367,10 +373,11 @@ void main() { expect(material.surfaceTintColor, Colors.transparent); expect(material.clipBehavior, Clip.antiAlias); - final items = tester.widgetList>( - find.byType(PopupMenuItem), + final items = tester.widgetList>( + find.byType(CheckedPopupMenuItem), ); expect(items, hasLength(3)); + expect(items.singleWhere((item) => item.checked).value, 'Anyone'); expect( items.every((item) => item.height >= Grid.xl), isTrue, @@ -1083,7 +1090,17 @@ void main() { participants: const ['Alice'], ); // A DM reply must still open its thread: the DM timeline hides replies. - for (final channelId in ['ch1', 'dm1']) { + for (final scenario in [ + (channel: 'ch1', wide: false), + (channel: 'dm1', wide: false), + (channel: 'ch1', wide: true), + ]) { + final channelId = scenario.channel; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = scenario.wide + ? const Size(1100, 800) + : const Size(800, 600); + addTearDown(tester.view.reset); final threadMention = FeedItem( id: 'reply-event', kind: 9, @@ -1107,7 +1124,11 @@ void main() { ); await tester.pumpWidget( - await buildTestable(feed: feed, channels: [...testChannels, dmChannel]), + await buildTestable( + withPane: scenario.wide, + feed: feed, + channels: [...testChannels, dmChannel], + ), ); await tester.pumpAndSettle(); @@ -1122,8 +1143,26 @@ void main() { expect(page.initialMessageId, 'reply-event'); expect( page.initialThreadRouteBehavior, - InitialThreadRouteBehavior.replaceCurrentRoute, + scenario.wide + ? InitialThreadRouteBehavior.push + : InitialThreadRouteBehavior.replaceCurrentRoute, ); + if (scenario.wide) { + final controller = ConversationPaneScope.maybeOf( + tester.element(find.byType(ChannelDetailPage)), + )!; + final previousKey = controller.selectionKey; + await tester.tap(find.byKey(const ValueKey('inbox-row-reply-event'))); + await tester.pumpAndSettle(); + expect(controller.selectedId, 'reply-event'); + expect(controller.selectionKey, isNot(previousKey)); + expect( + tester + .widget(find.byType(ChannelDetailPage)) + .initialThreadRootId, + threadIdParentDashReply, + ); + } await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpAndSettle(); } diff --git a/mobile/test/features/age_gate/age_gate_app_test.dart b/mobile/test/features/age_gate/age_gate_app_test.dart index 6e0076573c..eadec6ccda 100644 --- a/mobile/test/features/age_gate/age_gate_app_test.dart +++ b/mobile/test/features/age_gate/age_gate_app_test.dart @@ -279,7 +279,8 @@ void main() { expect(find.bySemanticsLabel('Checking age eligibility'), findsNothing); expect(find.byType(HomePage), findsOneWidget); - expect(find.byType(Navigator), findsOneWidget); + // Home may also host a nested conversation navigator. + expect(find.byType(MaterialApp), findsOneWidget); expect(relaySession.builds, 1); expect(requests, ageGatingEnabled ? 1 : 0); await tester.pump(); diff --git a/mobile/test/features/agents/agents_sheet_test.dart b/mobile/test/features/agents/agents_sheet_test.dart index 8a12b9eafc..1ab628f823 100644 --- a/mobile/test/features/agents/agents_sheet_test.dart +++ b/mobile/test/features/agents/agents_sheet_test.dart @@ -1,5 +1,7 @@ import 'package:flutter/services.dart'; +import 'package:buzz/shared/widgets/duo_toolbar.dart'; import 'package:buzz/shared/widgets/app_list_card.dart'; +import 'package:buzz/shared/widgets/agent_artwork_panel.dart'; import 'package:buzz/shared/agents/remote_agents.dart'; import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/me/default_agent.dart'; @@ -10,6 +12,7 @@ import 'package:buzz/features/agents/agents_page.dart'; import 'package:buzz/features/agents/agent_card.dart'; import 'package:buzz/features/profile/user_profile_sheet.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; import 'package:buzz/features/home/home_page.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -20,6 +23,126 @@ import '../../helpers/remote_agents_fixture.dart'; void main() { final existing = existingDesktopKeys.public; + testWidgets( + 'Duo keeps agent directory beside profile and Back clears detail', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + addTearDown(tester.view.reset); + try { + final h = await AgentsHarness.create(); + await h.open(tester, directory: [existing]); + expect(find.text('Select an agent'), findsOneWidget); + await tester.tap(find.byKey(ValueKey(existing))); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsNothing); + final profile = find.byType(UserProfileSheet); + expect(profile, findsOneWidget); + expect(find.byType(AgentCard).hitTestable(), findsOneWidget); + expect(tester.getRect(profile).left, closeTo(376, .01)); + expect(tester.getRect(profile).right, 951); + final artwork = find.descendant( + of: profile, + matching: find.byType(AgentArtworkPanel), + ); + expect(tester.getRect(artwork).right, 951); + for (final card + in find + .descendant(of: profile, matching: find.byType(AppListCard)) + .evaluate()) { + expect( + tester.getRect(find.byWidget(card.widget)).right, + lessThanOrEqualTo(875), + ); + } + expect( + tester + .getSize( + find + .descendant( + of: profile, + matching: find.byType(SingleChildScrollView), + ) + .first, + ) + .height, + greaterThan(500), + ); + expect(find.byKey(const ValueKey('duo-toolbar-Back')), findsOneWidget); + final profileElement = tester.element(profile); + tester.view.physicalSize = const Size(669, 951); + tester.view.padding = const FakeViewPadding(top: 82, bottom: 34); + tester.view.viewPadding = const FakeViewPadding(top: 82, bottom: 34); + await tester.pumpAndSettle(); + expect(profile, findsOneWidget); + expect(tester.element(profile), same(profileElement)); + expect(find.byType(AgentCard).hitTestable(), findsNothing); + tester.view.physicalSize = const Size(951, 669); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + await tester.pumpAndSettle(); + expect(tester.element(profile), same(profileElement)); + expect(find.byType(AgentCard).hitTestable(), findsOneWidget); + + tester.view.padding = const FakeViewPadding(left: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(left: 76, bottom: 21); + await tester.pumpAndSettle(); + expect(tester.getRect(profile).left, closeTo(452, .01)); + expect(tester.getRect(artwork).right, 951); + expect(tester.element(profile), same(profileElement)); + + Navigator.of(tester.element(profile)).pop(); + await tester.pumpAndSettle(); + expect(profile, findsNothing); + expect(find.text('Select an agent'), findsOneWidget); + expect(find.byType(AgentCard).hitTestable(), findsOneWidget); + tester.view.physicalSize = const Size(466, 678); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(ValueKey(existing))); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsOneWidget); + final sheetArtwork = find.descendant( + of: find.byType(UserProfileSheet), + matching: find.byType(AgentArtworkPanel), + ); + expect(tester.getRect(sheetArtwork).left, 0); + expect(tester.getRect(sheetArtwork).right, 466); + expect( + find.byKey(const ValueKey('duo-toolbar-Close agents')), + findsNothing, + ); + expect( + find.byKey(const ValueKey('duo-toolbar-Close sheet')), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('buzz-sheet-ios-glass-close')), + findsNothing, + ); + final sheetPortal = tester + .widgetList(find.byType(DuoToolbarPortal)) + .singleWhere( + (portal) => portal.actions.any((a) => a.label == 'Close sheet'), + ); + sheetPortal.actions.single.onPressed!(); + await tester.pumpAndSettle(); + expect(find.byType(UserProfileSheet), findsNothing); + expect( + find.byKey(const ValueKey('duo-toolbar-Close agents')), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + } finally { + debugDefaultTargetPlatformOverride = null; + } + }, + ); + testWidgets('agent profile sheet closes back to the full-page directory', ( tester, ) async { diff --git a/mobile/test/features/channels/channel_detail_page_test.dart b/mobile/test/features/channels/channel_detail_page_test.dart index 8c927d6ab0..2ff6393baf 100644 --- a/mobile/test/features/channels/channel_detail_page_test.dart +++ b/mobile/test/features/channels/channel_detail_page_test.dart @@ -1,3 +1,7 @@ +import 'package:buzz/features/activity/activity_page.dart'; +import 'package:buzz/features/activity/compose_drafts_provider.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'package:buzz/features/forum/forum_posts_view.dart'; import 'package:buzz/features/channels/me/me_chat_settings.dart'; import 'package:buzz/shared/widgets/dm_header_portrait.dart'; @@ -630,6 +634,139 @@ const _directoryAlice = const _directoryBob = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; void main() { + testWidgets('chat Back follows visibility of the conversation list', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + final controller = ConversationPaneController() + ..open( + 'chat', + (_) => ChannelDetailPage(channel: _testChannel), + animate: false, + ); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildTestable( + messages: const [], + home: AdaptiveConversationDestination( + controller: controller, + child: const Text('Conversation list'), + ), + ), + ); + await tester.pumpAndSettle(); + FrostedAppBar header() => + tester.widget(find.byType(FrostedAppBar)); + expect(find.text('Conversation list'), findsOneWidget); + expect(header().automaticallyImplyLeading, isFalse); + expect(header().nativeLargeTitle, isFalse); + final openNav = find.byWidgetPredicate( + (w) => w is IosNavigationBar && !w.standaloneControl, + ); + expect(tester.getRect(openNav).right, 951); + expect( + tester.getRect(openNav).left, + tester.getRect(find.byType(FrostedScaffold)).left, + ); + expect( + tester.widget(openNav).titleInsets, + const EdgeInsets.only(right: 76), + ); + for (final left in [false, true]) { + tester.view.physicalSize = const Size(466, 678); + tester.view.viewPadding = FakeViewPadding( + left: left ? 76 : 0, + right: left ? 0 : 76, + ); + tester.view.padding = tester.view.viewPadding; + await tester.pumpAndSettle(); + expect(header().nativeLargeTitle, isFalse); + expect(header().automaticallyImplyLeading, isTrue); + final nav = find.byWidgetPredicate( + (w) => w is IosNavigationBar && !w.standaloneControl, + ); + expect(tester.getRect(nav).left, 0); + expect(tester.getRect(nav).right, 466); + expect(tester.widget(nav).centerTitleInPane, isTrue); + expect( + tester.widget(nav).titleInsets, + EdgeInsets.only(left: left ? 76 : 0, right: left ? 0 : 76), + ); + } + tester.view.physicalSize = const Size(390, 800); + tester.view.viewPadding = const FakeViewPadding(bottom: 34); + tester.view.padding = const FakeViewPadding(bottom: 34); + await tester.pumpAndSettle(); + expect(find.text('Conversation list'), findsNothing); + expect(header().automaticallyImplyLeading, isTrue); + expect(header().nativeLargeTitle, isFalse); + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + expect(header().automaticallyImplyLeading, isFalse); + // A linked channel pushed over the pane root must keep a visible Back. + final detailNavigator = Navigator.of( + tester.element(find.byType(ChannelDetailPage)), + ); + unawaited( + detailNavigator.push( + MaterialPageRoute( + builder: (_) => ChannelDetailPage(channel: _testChannel), + ), + ), + ); + await tester.pumpAndSettle(); + expect(header().automaticallyImplyLeading, isTrue); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(header().automaticallyImplyLeading, isFalse); + final head = formatTimeline([ + _textMsg( + id: threadIdRoot, + pubkey: 'alice', + content: 'Thread root', + createdAt: 1000, + ), + ]).first; + unawaited( + Navigator.of(tester.element(find.byType(ChannelDetailPage))).push( + MaterialPageRoute( + builder: (_) => ThreadDetailPage( + threadHead: head, + allMessages: [head], + channelId: _channelId, + currentPubkey: null, + isMember: true, + isArchived: false, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(ThreadDetailPage), findsOneWidget); + expect(header().automaticallyImplyLeading, isTrue); + expect( + Navigator.of(tester.element(find.byType(ThreadDetailPage))).canPop(), + isTrue, + ); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(header().automaticallyImplyLeading, isFalse); + tester.view.physicalSize = const Size(466, 678); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = tester.view.viewPadding; + await tester.pumpWidget(_buildTestable(messages: const [])); + await tester.pumpAndSettle(); + expect(header().automaticallyImplyLeading, isTrue); + expect(header().nativeTitleInsets, const EdgeInsets.only(right: 76)); + expect( + tester.getRect(find.byType(ComposeBar)).right, + lessThanOrEqualTo(390), + ); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('Solo and channel headers show bounded roster portraits', ( tester, ) async { @@ -864,6 +1001,13 @@ void main() { 'Bestie DM preserves thread replies and ordinary sends: launcher=$fromLauncher', (tester) async { final sender = _RecordingOrdinarySender(); + final pane = ConversationPaneController(); + addTearDown(pane.dispose); + if (fromLauncher) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(1100, 800); + addTearDown(tester.view.reset); + } final dm = Channel( id: _channelId, name: 'Bestie', @@ -914,7 +1058,12 @@ void main() { ), ], home: fromLauncher - ? Scaffold(body: DefaultAgentLauncher(onChooseAgent: () {})) + ? AdaptiveConversationPane( + controller: pane, + list: Scaffold( + body: DefaultAgentLauncher(onChooseAgent: () {}), + ), + ) : ChannelDetailPage( channel: dm, initialMessageId: threadIdA, @@ -928,6 +1077,12 @@ void main() { await tester.pumpAndSettle(); } if (fromLauncher) { + expect(pane.selectedId, dm.id); + expect(find.byType(DefaultAgentLauncher), findsOneWidget); + expect( + tester.getRect(find.byType(ChannelDetailPage)).left, + greaterThan(0), + ); expect(find.byType(ThreadDetailPage), findsNothing); final row = find.byKey(const ValueKey('message-row-$threadIdRoot')); await tester.tap(row); @@ -5615,6 +5770,80 @@ void main() { ); }); + testWidgets( + 'Leave from details in the conversation pane keeps the list', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(402, 874); + addTearDown(tester.view.reset); + final pane = ConversationPaneController(); + addTearDown(pane.dispose); + final navigator = _RecordingNavigatorObserver(); + String? leftChannel; + final list = Builder( + builder: (_) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => pane.open( + _testChannel.id, + (_) => ChannelDetailPage(channel: _testChannel), + ), + child: const Text('Open conversation'), + ), + ), + ), + ); + await tester.pumpWidget( + _buildTestable( + messages: const [], + createChannelActions: (ref) => _FakeChannelActions( + ref, + onLeaveChannel: (id) async => leftChannel = id, + ), + navigatorObservers: [navigator], + home: AdaptiveConversationPane(controller: pane, list: list), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open conversation')); + await tester.pumpAndSettle(); + if (defaultTargetPlatform == TargetPlatform.iOS) { + tester + .widget(find.byType(IosNavigationBar)) + .onTitlePressed!(); + } else { + await tester.tap( + find.byKey(const ValueKey('channel-header-settings-trigger')), + ); + } + await tester.pumpAndSettle(); + await tester.drag( + find.byKey(const ValueKey('channel-details-page-list')), + const Offset(0, -300), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Leave channel').last); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FilledButton, 'Leave')); + await tester.pumpAndSettle(); + expect(leftChannel, _testChannel.id); + expect(tester.takeException(), isNull); + expect( + navigator.poppedRoutes.contains(navigator.pushedRoutes.first), + isFalse, + reason: + 'A channel lifecycle action must never pop the workspace root', + ); + expect(find.byType(ChannelDetailsPage), findsNothing); + expect(find.text('Open conversation'), findsOneWidget); + expect(find.byType(ChannelDetailPage), findsNothing); + }, + variant: TargetPlatformVariant({ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); + testWidgets('keeps manage sheet dismissible with a long canvas', ( tester, ) async { @@ -16540,6 +16769,74 @@ void main() { expect(find.byType(ThreadDetailPage), findsNothing); }); + testWidgets('Activity reopens a thread draft after Back', (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(1100, 800); + addTearDown(tester.view.reset); + final root = _textMsg( + id: threadIdRoot, + pubkey: 'alice', + content: 'Draft thread root', + ); + await tester.pumpWidget( + _buildTestable( + messages: [root], + relaySessionNotifier: _ReconnectingRelaySession( + initialStatus: SessionStatus.disconnected, + ), + threadReplies: const {threadIdRoot: []}, + users: const { + 'alice': UserProfile(pubkey: 'alice', displayName: 'Alice'), + }, + home: const AdaptiveConversationDestination(child: ActivityPage()), + ), + ); + await tester.pumpAndSettle(); + final drafts = ProviderScope.containerOf( + tester.element(find.byType(ActivityPage)), + ).read(composeDraftsProvider.notifier); + drafts.save( + key: '$_channelId:$threadIdRoot', + channelId: _channelId, + threadHeadId: threadIdRoot, + text: 'Retained thread draft', + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('activity-type-menu'))); + await tester.pumpAndSettle(); + await tester.tap( + find.ancestor( + of: find.descendant( + of: find.byKey(const ValueKey('activity-type-popover')), + matching: find.text('Drafts'), + ), + matching: find.byWidgetPredicate( + (widget) => widget is CheckedPopupMenuItem, + ), + ), + ); + await tester.pumpAndSettle(); + final draftRow = find.byKey( + ValueKey('draft-row-$_channelId:$threadIdRoot'), + ); + for (var attempt = 0; attempt < 2; attempt++) { + await tester.tap(draftRow); + await tester.pumpAndSettle(); + expect( + find.byType(ThreadDetailPage), + findsOneWidget, + reason: + 'Opening draft attempt $attempt must reach the thread composer', + ); + expect(find.text('Retained thread draft'), findsNWidgets(2)); + Navigator.of(tester.element(find.byType(ThreadDetailPage))).pop(); + await tester.pumpAndSettle(); + expect(find.byType(ThreadDetailPage), findsNothing); + expect(draftRow, findsOneWidget); + } + expect(tester.takeException(), isNull); + }); + testWidgets('replaces a temporary channel route for an initial thread', ( tester, ) async { @@ -21302,12 +21599,19 @@ class _FakeChannelActions extends ChannelActions { class _RecordingNavigatorObserver extends NavigatorObserver { final List> pushedRoutes = []; + final List> poppedRoutes = []; @override void didPush(Route route, Route? previousRoute) { super.didPush(route, previousRoute); pushedRoutes.add(route); } + + @override + void didPop(Route route, Route? previousRoute) { + super.didPop(route, previousRoute); + poppedRoutes.add(route); + } } class _HuddleRelayConfigNotifier extends RelayConfigNotifier { diff --git a/mobile/test/features/channels/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index 36b4472560..dbc7dc407f 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -28,6 +28,7 @@ import 'dart:io'; import 'dart:ui' as ui; import 'package:buzz/shared/widgets/buzz_sheet_header.dart'; +import 'package:buzz/shared/widgets/concentric_sheet_surface.dart'; import 'package:flutter/rendering.dart'; import 'package:buzz/shared/community/community_membership_provider.dart'; @@ -495,11 +496,22 @@ void main() { find.descendant(of: popover, matching: find.byType(PopupMenuDivider)), findsNothing, ); - final selectedCheck = find.byKey(const ValueKey('sort-selected-check')); + final selectedItem = find.ancestor( + of: find.text('Sort: A–Z'), + matching: find.byType(CheckedPopupMenuItem), + ); + expect( + tester.widget>(selectedItem).checked, + isTrue, + ); + final selectedCheck = find.descendant( + of: selectedItem, + matching: find.byIcon(Icons.done), + ); expect(selectedCheck, findsOneWidget); expect( tester.getCenter(selectedCheck).dx, - greaterThan(tester.getCenter(find.text('Sort: A–Z')).dx), + lessThan(tester.getTopLeft(find.text('Sort: A–Z')).dx), ); for (final label in ['general', 'Alice']) { @@ -1190,6 +1202,67 @@ void main() { ); expect(deleteText.style?.color, error); expect(deleteIcon.color, error); + Navigator.of(tester.element(popover)).pop(); + await tester.pumpAndSettle(); + + try { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + await tester.pumpWidget(const SizedBox.shrink()); + SharedPreferences.setMockInitialValues({}); + final duoPrefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + buildTestable( + realHome: true, + overrides: [ + savedPrefsProvider.overrideWithValue(duoPrefs), + channelsProvider.overrideWith(() => _FakeNotifier(testChannels)), + channelSectionsProvider.overrideWith( + () => _FakeChannelSectionsNotifier( + const ChannelSectionStore( + sections: [ + ChannelSection(id: 'section-1', name: 'Design', order: 0), + ], + ), + ), + ), + ], + ), + ); + await tester.pumpAndSettle(); + IosMessageCreateButton nativeMenu() => + tester.widget( + find.byKey(const Key('section-menu-section-1')), + ); + expect(nativeMenu().plain, isTrue); + expect(nativeMenu().iconSize, 14); + expect(nativeMenu().actions.map((action) => action.label), [ + 'Rename section', + 'Move up', + 'Move down', + 'Sort: Recent', + 'Sort: A–Z', + 'Delete section', + ]); + expect(nativeMenu().actions[1].onPressed, isNull); + expect(nativeMenu().actions[2].onPressed, isNull); + expect(nativeMenu().destructiveIndices, {5}); + final newMenu = find.byKey(const ValueKey('horizontal-create-menu')); + expect(newMenu, findsOneWidget); + nativeMenu().actions[4].onPressed!(); + await tester.pumpAndSettle(); + expect(nativeMenu().selectedIndex, 4); + expect(newMenu, findsOneWidget); + expect(find.byKey(const Key('section-popover-section-1')), findsNothing); + expect(ModalRoute.of(tester.element(newMenu))!.isCurrent, isTrue); + expect(tester.takeException(), isNull); + } finally { + debugDefaultTargetPlatformOverride = null; + } }); testWidgets('aligns the top, section, row, and skeleton label columns', ( @@ -1592,6 +1665,97 @@ void main() { } } + testWidgets( + 'community menu is a bounded bottom sheet when open and full width when compact', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + addTearDown(tester.view.resetPadding); + addTearDown(tester.view.resetViewPadding); + final community = Community( + id: 'alpha', + name: 'Alpha', + relayUrl: 'wss://alpha.example.com', + addedAt: DateTime(2025), + ); + await tester.pumpWidget( + buildTestable( + overrides: [ + channelsProvider.overrideWith(() => _FakeNotifier(testChannels)), + communityListProvider.overrideWith( + () => _FakeCommunityListNotifier([community]), + ), + activeCommunityProvider.overrideWith((ref) async => community), + ], + ), + ); + for (final size in [ + const Size(951, 669), + const Size(669, 951), + const Size(466, 678), + ]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + void openMenu() => tester + .widget(find.byType(FrostedAppBar)) + .nativeLeading! + .onPressed!(); + openMenu(); + await tester.pumpAndSettle(); + final dialog = find.byType(BottomSheet); + if (size.shortestSide >= 600) { + expect(dialog, findsOneWidget); + final surface = find.descendant( + of: dialog, + matching: find.byType(ConcentricSheetSurface), + ); + final rect = tester.getRect(surface); + final menuContext = tester.element( + find.byKey(const Key('community-switcher-sheet')), + ); + expect(MediaQuery.paddingOf(menuContext).right, 0); + final menu = tester.getRect( + find.byKey(const Key('community-switcher-sheet')), + ); + expect(menu.center.dx, closeTo(size.width / 2, 1)); + expect(rect.width, lessThanOrEqualTo(480)); + expect(rect.height, lessThan(size.height - 48)); + expect(rect.center.dx, closeTo(size.width / 2, 1)); + expect(rect.bottom, closeTo(size.height, 1)); + } else { + expect(dialog, findsOneWidget); + expect( + find.byKey(const Key('community-switcher-sheet')), + findsOneWidget, + ); + } + await tester.tapAt(const Offset(5, 5)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('community-switcher-sheet')), findsNothing); + openMenu(); + await tester.pumpAndSettle(); + await tester.drag(find.byType(BottomSheet), const Offset(0, 500)); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsNothing); + openMenu(); + await tester.pumpAndSettle(); + await tester.tap(find.text('Appearance')); + await tester.pumpAndSettle(); + expect(find.text('Appearance destination'), findsOneWidget); + expect(dialog, findsNothing); + Navigator.of(tester.element(find.text('Appearance destination'))).pop(); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + debugDefaultTargetPlatformOverride = null; + }, + ); + testWidgets('community settings hides invite for members', (tester) async { final community = Community( id: 'alpha', @@ -2115,16 +2279,31 @@ void main() { ); } - for (final nativeHeader in [false, true]) { + for (final (nativeHeader, duo) in [ + (false, false), + (true, false), + (true, true), + ]) { for (final reduceMotion in [false, true]) { testWidgets( - 'community selection holds enlarged until content loads (native header: $nativeHeader, reduced motion: $reduceMotion)', + 'community selection holds enlarged until content loads (native header: $nativeHeader, Duo: $duo, reduced motion: $reduceMotion)', (tester) async { debugDefaultTargetPlatformOverride = nativeHeader ? TargetPlatform.iOS : TargetPlatform.android; addTearDown(() => debugDefaultTargetPlatformOverride = null); - tester.view.physicalSize = const Size(390, 844); + tester.view.physicalSize = duo + ? const Size(466, 678) + : const Size(390, 844); + if (duo) { + tester.view.viewPadding = const FakeViewPadding( + right: 76, + bottom: 21, + ); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + addTearDown(tester.view.resetViewPadding); + addTearDown(tester.view.resetPadding); + } tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -2229,7 +2408,33 @@ void main() { await tester.tap(find.byKey(const Key('community-menu-switch'))); await tester.pumpAndSettle(); expect(progress.last, 1); - if (nativeHeader) { + if (duo) { + expect( + tester + .getCenter(find.byKey(const Key('community-switcher-title'))) + .dx, + 233, + ); + IosNavigationAction railAction(String label) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey('duo-toolbar-$label')), + matching: find.byType(IosNavigationBar), + ), + ) + .leading!; + expect(railAction('Close community switcher').symbol, 'xmark'); + expect(railAction('Edit').symbol, 'pencil'); + railAction('Edit').onPressed!(); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('community-switcher-remove-bravo')), + findsOneWidget, + ); + expect(railAction('Done').symbol, 'checkmark'); + railAction('Done').onPressed!(); + await tester.pumpAndSettle(); + } else if (nativeHeader) { var navigation = tester.widget( find.byType(IosNavigationBar).last, ); @@ -2271,11 +2476,23 @@ void main() { isTrue, ); } + if (duo) { + expect( + find.byKey(const ValueKey('duo-toolbar-Edit')), + findsNothing, + ); + expect( + find.byKey( + const ValueKey('duo-toolbar-Close community switcher'), + ), + findsNothing, + ); + } final origin = tester.getCenter(flyingAvatar); await tester.pump(const Duration(milliseconds: 105)); if (!reduceMotion) { final inFlight = tester.getCenter(flyingAvatar); - const center = Offset(195, 422); + final center = tester.view.physicalSize.center(Offset.zero); expect( (inFlight - center).distance, lessThan((origin - center).distance), @@ -2319,7 +2536,10 @@ void main() { initial.text.style?.decoration, anyOf(isNull, TextDecoration.none), ); - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); expect( tester.widget(flyingAvatar).transform.storage[0], 1.5, @@ -2350,7 +2570,10 @@ void main() { id == 'alpha' ? findsOneWidget : findsNothing, ); } - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); expect( tester.widget(flyingAvatar).transform.storage[0], 1.5, @@ -2368,7 +2591,10 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); if (!reduceMotion || nativeHeader) { - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); expect( find.byKey(const Key('community-switch-loading')), findsOneWidget, @@ -2378,7 +2604,10 @@ void main() { if (nativeHeader) { // Native images/layout may finish after the Flutter body. Keep the // hold, and use fresh bounds rather than the old community's slot. - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); final header = tester.widget( find.byWidgetPredicate( (widget) => @@ -2397,7 +2626,10 @@ void main() { await tester.pump(); // The loaded list and header are ready, but unread history and DM // labels must also settle before the background can be revealed. - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); final container = ProviderScope.containerOf( tester.element(find.byType(ChannelsPage)), ); @@ -2406,7 +2638,10 @@ void main() { unreadCatchUp.complete(); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(tester.getCenter(flyingAvatar), const Offset(195, 422)); + expect( + tester.getCenter(flyingAvatar), + tester.view.physicalSize.center(Offset.zero), + ); expect( tester .widget( @@ -2430,7 +2665,10 @@ void main() { await tester.pump(const Duration(milliseconds: 65)); expect(tester.getCenter(flyingAvatar).dx, lessThan(195)); await tester.pump(const Duration(milliseconds: 195)); - expect(tester.getCenter(flyingAvatar).dy, lessThan(422)); + expect( + tester.getCenter(flyingAvatar).dy, + lessThan(tester.view.physicalSize.height / 2), + ); expect( tester.getCenter(flyingAvatar).dy, greaterThan(destination.dy), diff --git a/mobile/test/features/channels/default_agent_launcher_test.dart b/mobile/test/features/channels/default_agent_launcher_test.dart index e76bb11e71..75f44dcfeb 100644 --- a/mobile/test/features/channels/default_agent_launcher_test.dart +++ b/mobile/test/features/channels/default_agent_launcher_test.dart @@ -13,6 +13,7 @@ import 'package:buzz/shared/me/default_agent_writer.dart'; import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/theme.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -93,6 +94,7 @@ void main() { }, ); + final paneVariant = ValueVariant({false, true}); testWidgets('a slow Bestie lookup does not open over a newer screen', ( tester, ) async { @@ -107,6 +109,8 @@ void main() { ); await saveDefaultAgent(scope, 'a' * 64); final actions = _SlowDmActions(); + final pane = ConversationPaneController(); + addTearDown(pane.dispose); SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); await tester.pumpWidget( @@ -121,7 +125,14 @@ void main() { ], child: MaterialApp( theme: AppTheme.light(), - home: Scaffold(body: DefaultAgentLauncher(onChooseAgent: () {})), + home: Scaffold( + body: paneVariant.currentValue! + ? ConversationPaneScope( + controller: pane, + child: DefaultAgentLauncher(onChooseAgent: () {}), + ) + : DefaultAgentLauncher(onChooseAgent: () {}), + ), ), ), ); @@ -163,9 +174,15 @@ void main() { await tester.tap(find.byType(IconButton)); await tester.pumpAndSettle(); expect(actions.calls, 2); - expect(find.byType(ChannelDetailPage), findsOneWidget); + if (paneVariant.currentValue!) { + expect(pane.selectedId, 'dm'); + expect(find.byType(ChannelDetailPage), findsNothing); + expect(find.byType(DefaultAgentLauncher), findsOneWidget); + } else { + expect(find.byType(ChannelDetailPage), findsOneWidget); + } await tester.pumpWidget(const SizedBox()); - }); + }, variant: paneVariant); } class _NoChannels extends ChannelsNotifier { diff --git a/mobile/test/features/channels/me/me_chat_assistant_test.dart b/mobile/test/features/channels/me/me_chat_assistant_test.dart index a9425e1817..45d1b9a629 100644 --- a/mobile/test/features/channels/me/me_chat_assistant_test.dart +++ b/mobile/test/features/channels/me/me_chat_assistant_test.dart @@ -2,6 +2,10 @@ import 'dart:async'; import 'dart:ui' show SemanticsAction; import 'package:buzz/features/channels/me/me_chat_assistant.dart'; +import 'package:buzz/features/channels/me/me_workspace_picker.dart'; +import 'package:buzz/shared/widgets/frosted_scaffold.dart'; +import 'package:buzz/shared/widgets/frosted_app_bar.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'package:buzz/features/channels/me/me_assistant_picker.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/shared/me/me_assistants.dart'; @@ -67,7 +71,89 @@ class _Harness extends HookConsumerWidget { } } +class _NativeHeaderHarness extends HookConsumerWidget { + const _NativeHeaderHarness(); + @override + Widget build(BuildContext context, WidgetRef ref) { + final workspace = useMeWorkspace(context, ref, enabled: false); + final assistant = useMeChatAssistant( + context, + ref, + enabled: false, + channelId: 'chat', + initial: null, + messages: const [], + ); + return FrostedScaffold( + appBar: FrostedAppBar( + nativeTitle: 'Solo chat', + nativeLeading: IosNavigationAction( + label: 'Back', + symbol: 'chevron.backward', + onPressed: () {}, + ), + nativeActions: [workspace.nativeAction, assistant.nativeAction], + ), + body: const SizedBox.expand(), + ); + } +} + void main() { + testWidgets('Solo controls stay in the upper rail across folds', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + tester.view.physicalSize = const Size(466, 678); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: const _NativeHeaderHarness(), + ), + ), + ); + await tester.pumpAndSettle(); + final bar = tester.widget(find.byType(FrostedAppBar)); + final labels = ['Back', ...bar.nativeActions!.map((a) => a.label)]; + double previousY = 0; + for (final label in labels) { + final control = find.byKey(ValueKey('duo-toolbar-$label')); + expect(control, findsOneWidget); + final rect = tester.getRect(control); + expect(rect.center.dx, greaterThan(390)); + expect(rect.center.dy, greaterThan(previousY)); + previousY = rect.center.dy; + } + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + previousY = 0; + for (final label in labels) { + final control = find.byKey(ValueKey('duo-toolbar-$label')); + expect(control, findsOneWidget); + final rect = tester.getRect(control); + expect(rect.center.dx, greaterThan(875)); + expect(rect.center.dy, greaterThan(previousY)); + expect(rect.bottom, lessThan(400)); + previousY = rect.center.dy; + } + final header = tester.widget( + find.byWidgetPredicate( + (w) => w is IosNavigationBar && !w.standaloneControl, + ), + ); + expect(header.actions, isEmpty); + tester.view.physicalSize = const Size(466, 678); + await tester.pumpAndSettle(); + for (final label in labels) { + expect(find.byKey(ValueKey('duo-toolbar-$label')), findsOneWidget); + } + expect(tester.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + for (final keyFallback in [false, true]) { final target = keyFallback ? '0123456789abcdef' * 4 : 'b'; // An unnamed agent reads as its compact npub, like every other picker. diff --git a/mobile/test/features/channels/media_viewer_page/image_rail_test.dart b/mobile/test/features/channels/media_viewer_page/image_rail_test.dart new file mode 100644 index 0000000000..5b4f2bc043 --- /dev/null +++ b/mobile/test/features/channels/media_viewer_page/image_rail_test.dart @@ -0,0 +1,131 @@ +import 'package:buzz/features/channels/media_viewer_page.dart'; +import 'package:buzz/shared/widgets/duo_toolbar.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +void main() { + testWidgets('photo gallery uses the Duo rail and full image surface', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(950, 670); + addTearDown(tester.view.reset); + final navigator = GlobalKey(); + final side = ValueNotifier(false); + addTearDown(side.dispose); + var replies = 0; + String? selected; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + navigatorKey: navigator, + builder: (context, child) => ValueListenableBuilder( + valueListenable: side, + builder: (context, left, _) => DuoToolbarScope( + active: true, + strip: FoldStrip( + side: left ? FoldStripSide.left : FoldStripSide.right, + rect: Rect.fromLTWH(left ? 0 : 870, 0, 80, 670), + topClearance: 110, + bottomClearance: 0, + isClearanceEstimated: false, + ), + child: child!, + ), + ), + home: const Scaffold(body: Text('Conversation')), + ), + ), + ); + void open() { + navigator.currentState!.push( + buildImageViewerRoute( + imageUrl: 'https://example.org/one.png', + heroTag: 'one', + galleryItems: const [ + MediaViewerImage( + url: 'https://example.org/one.png', + heroTag: 'one', + ), + MediaViewerImage( + url: 'https://example.org/two.png', + heroTag: 'two', + ), + ], + onReply: () => replies++, + onMore: (_, url) => selected = url, + ), + ); + } + + Finder rail(String label) => find.byKey(ValueKey('duo-toolbar-$label')); + void invoke(String label) { + tester + .widget( + find.descendant( + of: rail(label), + matching: find.byType(IosNavigationBar), + ), + ) + .leading! + .onPressed!(); + } + + open(); + await tester.pumpAndSettle(); + for (final left in [false, true]) { + side.value = left; + await tester.pumpAndSettle(); + double y = 0; + for (final label in [ + 'Close image viewer', + 'Reply in thread', + 'More image actions', + ]) { + final rect = tester.getRect(rail(label)); + expect(rect.center.dx, left ? lessThan(80) : greaterThan(870)); + expect(rect.top, greaterThan(y)); + y = rect.top; + } + expect( + tester.getRect( + find.byKey(const ValueKey('message-media-image-viewer-gesture:0')), + ), + const Rect.fromLTWH(0, 0, 950, 670), + ); + expect( + find.byKey(const ValueKey('message-media-image-viewer-reply-thread')), + findsNothing, + ); + expect( + find.byKey(const ValueKey('message-media-image-viewer-more-actions')), + findsNothing, + ); + } + await tester.drag( + find.byKey(const ValueKey('message-media-image-viewer-pages')), + const Offset(-800, 0), + ); + await tester.pumpAndSettle(); + invoke('More image actions'); + expect(selected, 'https://example.org/two.png'); + invoke('Reply in thread'); + await tester.pumpAndSettle(); + expect(replies, 1); + expect(rail('Close image viewer'), findsNothing); + open(); + await tester.pumpAndSettle(); + invoke('Close image viewer'); + await tester.pumpAndSettle(); + expect(find.text('Conversation'), findsOneWidget); + expect(replies, 1); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }); +} diff --git a/mobile/test/features/home/home_page_test.dart b/mobile/test/features/home/home_page_test.dart index aea7445d17..6de9e64cb9 100644 --- a/mobile/test/features/home/home_page_test.dart +++ b/mobile/test/features/home/home_page_test.dart @@ -1,3 +1,7 @@ +import 'package:buzz/shared/widgets/mobile_tab_footer_backdrop.dart'; +import 'package:buzz/shared/widgets/navigation_backdrop.dart'; +import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'dart:async'; import 'package:buzz/features/channels/default_agent_launcher.dart'; @@ -6,6 +10,8 @@ import 'package:buzz/features/channels/me/me_section.dart'; import 'package:buzz/features/activity/activity_page.dart'; import 'package:buzz/features/activity/inbox_unread_provider.dart'; import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_detail_page.dart'; +import 'package:buzz/features/profile/profile_edit_page.dart'; import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/shared/me/default_agent.dart'; import 'package:buzz/shared/relay/app_lifecycle_provider.dart'; @@ -17,7 +23,6 @@ import 'package:buzz/features/home/home_page.dart'; import 'package:buzz/features/home/messages_filters.dart'; import 'package:buzz/features/home/messages_navigation_bar.dart'; import 'package:buzz/shared/widgets/ios_message_create_button.dart'; -import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'package:buzz/features/search/search_page.dart'; import 'package:buzz/shared/theme/theme.dart'; @@ -98,6 +103,62 @@ void main() { ); } + testWidgets('every Home shortcut inherits the conversation controller', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + for (final scenario in [ + (size: const Size(1024, 768), rail: 0.0), + (size: const Size(466, 678), rail: 76.0), + (size: const Size(951, 669), rail: 76.0), + ]) { + tester.view.physicalSize = scenario.size; + tester.view.viewPadding = FakeViewPadding(right: scenario.rail); + tester.view.padding = tester.view.viewPadding; + await tester.pumpWidget(await buildHome()); + await tester.pumpAndSettle(); + final launcherContext = tester.element(find.byType(DefaultAgentLauncher)); + final controller = tester + .widget( + find.byType(AdaptiveConversationPane), + ) + .controller; + expect(ConversationPaneScope.maybeOf(launcherContext), same(controller)); + await tester.pumpWidget(const SizedBox.shrink()); + } + }); + + testWidgets('keyboard in a phone conversation does not rebuild Home', ( + tester, + ) async { + tester.view.physicalSize = const Size(402, 874); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + var homeBuilds = 0; + await tester.pumpWidget( + await buildHome(onNewChatAction: (_) => homeBuilds++), + ); + await tester.pumpAndSettle(); + tester + .widget(find.byType(AdaptiveConversationPane)) + .controller + .open( + 'sample', + (_) => const Scaffold(body: Text('Conversation content')), + ); + await tester.pumpAndSettle(); + expect(find.text('Conversation content'), findsOneWidget); + homeBuilds = 0; + + for (var frame = 1; frame <= 20; frame++) { + tester.view.viewInsets = FakeViewPadding(bottom: frame * 15.0); + await tester.pump(const Duration(milliseconds: 16)); + } + + expect(homeBuilds, 0); + }); + testWidgets('feedback clears floating navigation and wraps large text', ( tester, ) async { @@ -137,6 +198,262 @@ void main() { await tester.pumpAndSettle(); }); + testWidgets( + 'Duo Messages keeps its title and switcher aligned across folds', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + await tester.pumpWidget(await buildHome(longSolo: true)); + await tester.pumpAndSettle(); + final bar = find.byWidgetPredicate( + (widget) => widget is FrostedAppBar && widget.nativeTitle == 'Messages', + ); + expect(tester.widget(bar).nativeLargeTitle, isFalse); + expect(tester.getSize(bar).width, 375); + expect( + find.byWidgetPredicate((w) => w is Image && w.semanticLabel == 'Buzz'), + findsOneWidget, + ); + expect(tester.getTopLeft(bar).dy, 0); + final menu = find.byWidgetPredicate( + (widget) => + widget is IosMessageCreateButton && + widget.accessibilityLabel == 'Community menu', + ); + expect( + tester.getCenter(find.text('Messages')).dy, + tester.getCenter(menu).dy, + ); + expect( + tester.getCenter(menu).dy, + frostedAppBarHeight(tester.element(bar)) / 2, + ); + final originalHeaderRect = tester.getRect(bar); + final originalFiltersRect = tester.getRect(find.byType(MessagesFilters)); + expect( + originalFiltersRect.top - tester.getRect(menu).bottom, + lessThanOrEqualTo(12), + ); + final scrollable = find.byType(Scrollable).first; + await tester.drag(scrollable, const Offset(0, -250)); + await tester.pumpAndSettle(); + expect(tester.getRect(bar), originalHeaderRect); + expect(tester.getRect(find.byType(MessagesFilters)), originalFiltersRect); + expect( + tester.getCenter(find.text('Messages')).dy, + tester.getCenter(menu).dy, + ); + expect( + find.byWidgetPredicate( + (widget) => + widget is IosMessageCreateButton && + widget.accessibilityLabel == 'Community menu', + ), + findsOneWidget, + ); + expect(find.byType(MessagesFilters), findsOneWidget); + tester.view.physicalSize = const Size(466, 678); + await tester.pumpAndSettle(); + expect(tester.widget(bar).nativeLargeTitle, isFalse); + expect( + tester.getCenter(find.text('Messages')).dy, + tester.getCenter(menu).dy, + ); + final closedHeaderRect = tester.getRect(bar); + expect(closedHeaderRect.left, 0); + expect(closedHeaderRect.right, 466); + expect(tester.getRect(scrollable).right, lessThanOrEqualTo(390)); + expect(tester.getRect(menu).right, lessThanOrEqualTo(466 - 76)); + + final closedFiltersRect = tester.getRect(find.byType(MessagesFilters)); + expect( + closedFiltersRect.top - tester.getRect(menu).bottom, + lessThanOrEqualTo(12), + ); + await tester.drag(scrollable, const Offset(0, -200)); + await tester.pumpAndSettle(); + expect(tester.getRect(bar), closedHeaderRect); + expect(tester.getRect(find.byType(MessagesFilters)), closedFiltersRect); + tester.view.physicalSize = const Size(951, 669); + tester.view.viewPadding = const FakeViewPadding(left: 76); + tester.view.padding = const FakeViewPadding(left: 76); + await tester.pumpAndSettle(); + expect(tester.getRect(bar).left, 0); + expect(tester.getSize(bar).width, 375 + 76); + expect( + tester.getRect(find.text('Messages')).left, + greaterThanOrEqualTo(76), + ); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets('Duo rail retains unified Messages selection across folds', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(466, 678); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + await tester.pumpWidget(await buildHome(disableAnimations: true)); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byType(MessagesNavigationBar)) + .axis, + Axis.vertical, + ); + expect(tester.getCenter(find.byTooltip('Search')).dx, greaterThan(390)); + final create = tester.widget( + find.descendant( + of: find.byType(MessagesNavigationBar), + matching: find.byType(IosMessageCreateButton), + ), + ); + expect(create.mergingNavigation, isTrue); + expect(create.navigationAxis, Axis.vertical); + create.onMenuVisibilityChanged!(true); + await tester.pumpAndSettle(); + expect( + tester + .widget( + find + .ancestor( + of: find.byTooltip('Search'), + matching: find.byType(IgnorePointer), + ) + .first, + ) + .ignoring, + isTrue, + ); + create.onMenuVisibilityChanged!(false); + await tester.pumpAndSettle(); + expect( + tester + .widget( + find + .ancestor( + of: find.byTooltip('Search'), + matching: find.byType(IgnorePointer), + ) + .first, + ) + .ignoring, + isFalse, + ); + + // Dispatch the native control callback; widget tests do not run UIKit. + tester + .widget( + find.byWidgetPredicate( + (w) => w is IosGlassNavigationButton && w.label == 'Solo', + ), + ) + .onPressed!(); + await tester.pumpAndSettle(); + expect(find.text('Personal workspace'), findsOneWidget); + expect(find.text('General'), findsNothing); + final pane = ConversationPaneScope.maybeOf( + tester.element(find.text('Personal workspace')), + )!; + pane.open( + 'sample', + (_) => const Scaffold(body: Text('Conversation content')), + ); + await tester.pumpAndSettle(); + expect(find.text('Conversation content'), findsOneWidget); + expect(find.byType(MessagesNavigationBar), findsNothing); + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + expect(find.byType(MessagesNavigationBar), findsOneWidget); + expect(find.text('Conversation content'), findsOneWidget); + expect(pane.selectedId, 'sample'); + final openNavigation = find.byType(MessagesNavigationBar); + expect( + tester.widget(openNavigation).axis, + Axis.horizontal, + ); + final openBounds = tester.getRect(openNavigation); + expect(openBounds.left, greaterThanOrEqualTo(0)); + expect(openBounds.right, lessThanOrEqualTo(375)); + expect(openBounds.center.dx, 375 / 2); + expect(669 - openBounds.bottom, mobileTabBarBottomGap); + final openCreate = tester.widget( + find.descendant( + of: openNavigation, + matching: find.byType(IosMessageCreateButton), + ), + ); + expect(openCreate.navigationAxis, Axis.horizontal); + openCreate.onMenuVisibilityChanged!(true); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + openCreate.onMenuVisibilityChanged!(false); + await tester.pumpAndSettle(); + tester.widget(openNavigation).onSearch(); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(SearchPage)).width, 375); + tester.view.physicalSize = const Size(466, 678); + await tester.pumpAndSettle(); + final searchHeader = find.descendant( + of: find.byType(SearchPage), + matching: find.byType(NavigationBackdrop), + ); + final searchField = find.byKey(const Key('search-field-container')); + expect(tester.getRect(searchHeader).left, 0); + expect(tester.getRect(searchHeader).right, 466); + expect(tester.getRect(searchField).top, Grid.xs); + expect(tester.getRect(searchField).right, lessThanOrEqualTo(390)); + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(SearchPage)).width, 375); + expect(tester.getRect(searchField).top, Grid.half); + Navigator.of(tester.element(find.byType(SearchPage))).pop(); + await tester.pumpAndSettle(); + tester.view.physicalSize = const Size(669, 951); + tester.view.viewPadding = const FakeViewPadding(top: 82, bottom: 34); + tester.view.padding = const FakeViewPadding(top: 82, bottom: 34); + await tester.pumpAndSettle(); + expect(find.byType(MessagesNavigationBar), findsNothing); + expect(find.text('Personal workspace'), findsNothing); + expect(find.text('Conversation content'), findsOneWidget); + expect(pane.selectedId, 'sample'); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + expect(find.text('Personal workspace'), findsOneWidget); + expect(find.text('Conversation content'), findsOneWidget); + + tester.view.physicalSize = const Size(466, 678); + await tester.pumpAndSettle(); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Personal workspace'), findsOneWidget); + expect(find.text('General'), findsNothing); + expect(find.byType(MessagesNavigationBar), findsOneWidget); + tester.view.physicalSize = const Size(390, 844); + tester.view.viewPadding = const FakeViewPadding(bottom: 34); + tester.view.padding = const FakeViewPadding(bottom: 34); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byType(MessagesNavigationBar)) + .axis, + Axis.horizontal, + ); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }); + testWidgets( 'Messages filters its inventory and opens Search and Settings above it', (tester) async { @@ -361,6 +678,10 @@ void main() { testWidgets('app icon shortcuts name the Bestie and open each destination', ( tester, ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(402, 874); + addTearDown(tester.view.reset); + addTearDown(() => pendingHomeScreenShortcut.value = null); const channel = MethodChannel('buzz/home_screen_shortcuts'); final published = >[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( @@ -393,7 +714,10 @@ void main() { final bestie = 'b' * 64; final bestieUpdates = StreamController(); - addTearDown(bestieUpdates.close); + addTearDown(() async { + await tester.pumpWidget(const SizedBox()); + await bestieUpdates.close(); + }); bestieUpdates.add(bestie); ValueNotifier? chat; var homeBuilds = 0; @@ -501,6 +825,87 @@ void main() { reason: dmCalls.join(', '), ); + // Search uses a pane even on an ordinary phone. Drive the real search + // result and channel page, then dispatch each shortcut through the bridge. + Future openSearchResult() async { + tester + .widget(find.byType(MessagesNavigationBar)) + .onSearch(); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), '#'); + // Advance the production search debounce, then settle its results. + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('search-channel-row-channel')), + ); + await tester.pumpAndSettle(); + expect(find.byType(ChannelDetailPage), findsOneWidget); + } + + for (final shortcut in HomeScreenShortcut.values) { + await openSearchResult(); + final beforeChat = created; + final beforeBestie = opened.length; + final beforeDm = dmStates.length; + await tap(shortcut.type); + expect(find.byType(ChannelDetailPage), findsNothing); + expect(find.byType(SearchPage), findsNothing); + expect(pendingHomeScreenShortcut.value, isNull); + switch (shortcut) { + case HomeScreenShortcut.newChat: + expect(created, beforeChat + 1); + case HomeScreenShortcut.messageBestie: + expect(opened, hasLength(beforeBestie + 1)); + expect(opened.last, bestie); + case HomeScreenShortcut.newDm: + expect(dmStates.length, greaterThan(beforeDm)); + expect(nativeSession, isNotNull); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + dmBridge.name, + const StandardMethodCodec().encodeMethodCall( + MethodCall('closed', {'session': nativeSession}), + ), + (_) {}, + ); + await tester.pumpAndSettle(); + } + } + + // A real page veto, including one under another nested page, must not be + // mistaken for the pane's navigation-only Back interception. + await openSearchResult(); + final nested = Navigator.of(tester.element(find.byType(ChannelDetailPage))); + nested.push( + MaterialPageRoute( + builder: (_) => const ProfileEditPage(startInPhotoEditor: true), + ), + ); + await tester.pumpAndSettle(); + nested.push( + MaterialPageRoute( + builder: (_) => const Scaffold(body: Text('Above editor')), + ), + ); + await tester.pumpAndSettle(); + final beforeVeto = opened.length; + await tap('message-bestie'); + expect(find.text('Above editor'), findsNothing); + expect( + find.byKey(const ValueKey('profile-avatar-editor-page')), + findsOneWidget, + ); + expect(opened, hasLength(beforeVeto)); + expect(pendingHomeScreenShortcut.value, isNull); + await nested.maybePop(); + await tester.pumpAndSettle(); + expect(find.byType(ProfileEditPage), findsNothing); + await tap('message-bestie'); + expect(find.byType(ChannelDetailPage), findsNothing); + expect(find.byType(SearchPage), findsNothing); + expect(opened, hasLength(beforeVeto + 1)); + final completedOpens = List.of(opened); + // Shortcut state rebuilds only its own leaf, never Home. final builds = homeBuilds; tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); @@ -532,7 +937,7 @@ void main() { tester.element(find.byType(HomePage, skipOffstage: false)), ).pop(); await tester.pumpAndSettle(); - expect(opened, [bestie]); + expect(opened, completedOpens); expect(pendingHomeScreenShortcut.value, isNull); await tester.pumpWidget(const SizedBox()); diff --git a/mobile/test/features/invites/invite_create_page_test.dart b/mobile/test/features/invites/invite_create_page_test.dart index c1f16d5690..b0c528a216 100644 --- a/mobile/test/features/invites/invite_create_page_test.dart +++ b/mobile/test/features/invites/invite_create_page_test.dart @@ -7,6 +7,10 @@ import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/utils/string_utils.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:buzz/shared/widgets/duo_toolbar.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -19,6 +23,118 @@ void main() { const alice = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + testWidgets('unfolded invite splits title and controls clear of either rail', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + addTearDown(tester.view.reset); + try { + for (final left in [false, true]) { + await tester.pumpWidget(const SizedBox.shrink()); + final actions = _FakeInviteActions(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + communityInviteActionsProvider.overrideWithValue(actions), + myPubkeyProvider.overrideWithValue(owner), + communityMembershipProvider.overrideWith( + (ref) async => const CommunityMembershipSnapshot( + snapshotFound: true, + members: [ + CommunityMember( + pubkey: owner, + role: CommunityMemberRole.owner, + ), + ], + ), + ), + currentCommunityRoleProvider.overrideWithValue( + const AsyncData( + CommunityMemberRole.owner, + ), + ), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: DuoToolbarScope( + active: true, + strip: FoldStrip( + side: left ? FoldStripSide.left : FoldStripSide.right, + rect: Rect.fromLTWH(left ? 0 : 875, 0, 76, 669), + topClearance: 110, + bottomClearance: 0, + isClearanceEstimated: true, + ), + child: const CommunityInvitePage(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final title = tester.getRect( + find.byKey(const ValueKey('invite-title-pane')), + ); + final controls = tester.getRect( + find.byKey(const ValueKey('invite-controls-pane')), + ); + expect(title.left, left ? 76 : 0); + expect(controls.right, left ? 951 : 875); + expect(title.width, 375); + expect(controls.width, 499); + expect(controls.left, closeTo(title.right + 1, 0.01)); + expect( + tester + .widget(find.byType(IosNavigationBar).first) + .standaloneLargeTitle, + isTrue, + ); + for (final setting in ['expiry', 'max-uses']) { + await tester.tap( + find.byKey(Key('community-invite-$setting-setting')), + ); + await tester.pumpAndSettle(); + final sheet = tester.getRect(find.byType(BottomSheet)); + expect(sheet.left, greaterThanOrEqualTo(controls.left)); + expect(sheet.right, lessThanOrEqualTo(controls.right)); + expect( + find.byKey(const ValueKey('invite-title-pane')), + findsOneWidget, + ); + final barrier = tester.getRect(find.byType(ModalBarrier).last); + expect(barrier.left, greaterThanOrEqualTo(controls.left)); + expect(barrier.right, lessThanOrEqualTo(controls.right)); + await tester.tap( + find.byKey( + Key( + 'community-invite-option-${setting == 'expiry' ? '1-day' : '3-uses'}', + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsNothing); + } + expect(actions.mintRequests.last, (86400, 3)); + tester.view.physicalSize = const Size(800, 1100); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('invite-title-pane')), findsNothing); + expect( + find.byKey(const ValueKey('invite-controls-pane')), + findsNothing, + ); + expect(find.text('Share'), findsOneWidget); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + } finally { + debugDefaultTargetPlatformOverride = null; + } + }); + testWidgets('owner can invite a pasted npub and share generated link', ( tester, ) async { diff --git a/mobile/test/features/onboarding/fullscreen_onboarding_test.dart b/mobile/test/features/onboarding/fullscreen_onboarding_test.dart index 43a98f67eb..cdd0de0ec2 100644 --- a/mobile/test/features/onboarding/fullscreen_onboarding_test.dart +++ b/mobile/test/features/onboarding/fullscreen_onboarding_test.dart @@ -1,3 +1,4 @@ +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import '../../helpers/two_finger_double_tap.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -27,6 +28,51 @@ import '../../helpers/hosted_communities_fixture.dart'; import '../../helpers/widget_helpers.dart'; void main() { + for (final size in [const Size(951, 669), const Size(466, 678)]) { + testWidgets('Duo onboarding content and side Back at $size', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + addTearDown(tester.view.reset); + var backed = false; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: OnboardingStepPage( + title: 'Add a community', + onBack: () => backed = true, + content: const SizedBox( + key: Key('centered-onboarding-content'), + height: 40, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect( + tester + .getCenter(find.byKey(const Key('centered-onboarding-content'))) + .dx, + (size.width - (size.width < 600 ? 76 : 0)) / 2, + ); + final back = find.byKey(const ValueKey('duo-toolbar-Back')); + expect(back, findsOneWidget); + expect(tester.getRect(back).top, greaterThanOrEqualTo(110)); + final bar = tester.widget( + find.descendant(of: back, matching: find.byType(IosNavigationBar)), + ); + bar.leading!.onPressed!(); + expect(backed, isTrue); + debugDefaultTargetPlatformOverride = null; + }); + } + testWidgets('Add uses landing input and leaves room above the keyboard', ( tester, ) async { diff --git a/mobile/test/features/onboarding/internal_build_entry_test.dart b/mobile/test/features/onboarding/internal_build_entry_test.dart index a64e30280e..f9ed070d46 100644 --- a/mobile/test/features/onboarding/internal_build_entry_test.dart +++ b/mobile/test/features/onboarding/internal_build_entry_test.dart @@ -107,6 +107,12 @@ void main() { await tester.scrollUntilVisible( find.byKey(const Key('settings-sign-out')), 200, + scrollable: find + .descendant( + of: find.byType(SettingsPage), + matching: find.byType(Scrollable), + ) + .first, ); await tester.tap(find.byKey(const Key('settings-sign-out'))); await tester.pumpAndSettle(); diff --git a/mobile/test/features/pairing/pairing_page_test.dart b/mobile/test/features/pairing/pairing_page_test.dart index aae574de21..ac2c8ef64c 100644 --- a/mobile/test/features/pairing/pairing_page_test.dart +++ b/mobile/test/features/pairing/pairing_page_test.dart @@ -278,6 +278,44 @@ void main() { 'docks welcome actions and keeps pairing reachable with keyboard', (tester) async { tester.view.devicePixelRatio = 1; + // Folded and unfolded welcome screens keep all actions visible, + // centred on the display even with Duo's asymmetric system rail. + for (final size in [const Size(951, 669), const Size(390, 844)]) { + tester.view.physicalSize = size; + tester.view.padding = size.width > 600 + ? const FakeViewPadding(right: 84) + : const FakeViewPadding(top: 59, bottom: 34); + await tester.pumpWidget( + WidgetHelpers.testable( + child: const PairingPage( + connectionLanding: true, + showConnectionOptions: false, + ), + disableAnimations: true, + ), + ); + await tester.pump(); + final logo = find.byKey(const Key('pairing-buzz-wordmark')); + final scan = find.widgetWithText(FilledButton, 'Scan a QR code'); + expect(tester.getCenter(logo).dx, closeTo(size.width / 2, 1)); + expect(tester.getCenter(scan).dx, closeTo(size.width / 2, 1)); + expect(scan.hitTestable(), findsOneWidget); + final email = find.text('or sign in with email'); + if (email.evaluate().isNotEmpty) { + expect(email.hitTestable(), findsOneWidget); + expect(tester.getBottomLeft(email).dy, lessThan(size.height)); + } + final scroll = tester.state( + find + .descendant( + of: find.byType(CustomScrollView), + matching: find.byType(Scrollable), + ) + .first, + ); + expect(scroll.position.maxScrollExtent, 0); + expect(tester.takeException(), isNull); + } tester.view.physicalSize = const Size(390, 844); tester.view.padding = const FakeViewPadding(top: 59, bottom: 34); addTearDown(tester.view.reset); diff --git a/mobile/test/features/pairing/pairing_qr_scanner_test.dart b/mobile/test/features/pairing/pairing_qr_scanner_test.dart index ae222f7b7e..eba8b3ed61 100644 --- a/mobile/test/features/pairing/pairing_qr_scanner_test.dart +++ b/mobile/test/features/pairing/pairing_qr_scanner_test.dart @@ -7,6 +7,7 @@ import '../../helpers/controllable_pairing_socket.dart'; import 'dart:async'; import 'package:buzz/features/pairing/pairing_qr_scanner.dart'; +import 'package:duo_kit/testing.dart'; import 'package:buzz/features/pairing/pairing_page.dart'; import '../../helpers/widget_helpers.dart'; @@ -176,6 +177,161 @@ void main() { }); }); + for (final pose in [ + FoldTestPose.duoCover, + FoldTestPose.duoCoverWithOcclusions, + FoldTestPose.duoCoverLandscapeLeft, + FoldTestPose.duoCoverLandscapeRight, + FoldTestPose.duoInnerLandscape, + FoldTestPose.duoHalfOpenedLandscape, + ]) { + for (final reducedMotion in [false, true]) { + testWidgets( + 'Duo camera portal ${pose.name}, reduced motion $reducedMotion', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_qrScannerPlatformChannel, ( + call, + ) async { + if (call.method == 'cameraCutoutFrame') { + final media = FoldTestPose.duoCoverWithOcclusions.data; + final rect = media.displayFeatures.first.bounds; + return [ + rect.left, + rect.top, + rect.width, + rect.height, + media.size.width, + media.size.height, + ]; + } + return call.method == 'previewRotationQuarterTurns' ? -1 : null; + }); + final media = pose.data; + await tester.binding.setSurfaceSize(media.size); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final camera = + (media.displayFeatures.isEmpty + ? FoldTestPose.duoCoverWithOcclusions.data + : media) + .displayFeatures + .first + .bounds; + Rect? detectedCamera; + await tester.pumpWidget( + MaterialApp( + builder: (_, child) => MediaQuery( + data: media.copyWith(disableAnimations: reducedMotion), + child: child!, + ), + home: Builder( + builder: (context) => TextButton( + onPressed: () async { + detectedCamera = await resolveDuoQrScannerCameraFrame( + context, + ); + if (!context.mounted || detectedCamera == null) return; + showDynamicIslandPairingQrScanner( + context, + cameraFrame: detectedCamera, + ); + }, + child: const Text('Open scanner'), + ), + ), + ), + ); + await tester.tap(find.text('Open scanner')); + await tester.pump(); + if (pose == FoldTestPose.duoInnerLandscape || + pose == FoldTestPose.duoHalfOpenedLandscape) { + expect(detectedCamera, isNull); + expect( + find.byKey(const ValueKey('dynamic-island-qr-scanner-portal')), + findsNothing, + ); + debugDefaultTargetPlatformOverride = null; + return; + } + expect(detectedCamera, camera); + final portal = find.byKey( + const ValueKey('dynamic-island-qr-scanner-portal'), + ); + if (!reducedMotion) { + final onBottom = camera.center.dy > media.size.height / 2; + final pill = Rect.fromLTRB( + camera.left, + camera.top - (onBottom ? 22 : 4), + camera.right, + camera.bottom + (onBottom ? 4 : 22), + ); + expect(tester.getRect(portal), pill); + expect( + tester.widget(portal).borderRadius, + BorderRadius.circular(camera.shortestSide / 2), + ); + } + await tester.pumpAndSettle(); + expect( + tester + .widget( + find.byKey(const ValueKey('qr-camera-orientation')), + ) + .quarterTurns, + -1, + ); + final expanded = tester.getRect(portal); + if (camera.top == 0 && camera.right == media.size.width) { + expect(expanded.right, lessThan(camera.left)); + } else { + expect(expanded.contains(camera.center), isTrue); + final right = camera.center.dx > media.size.width / 2; + final bottom = camera.center.dy > media.size.height / 2; + expect( + right ? expanded.right : expanded.left, + right ? camera.right : camera.left, + ); + expect( + bottom ? expanded.bottom : expanded.top, + bottom ? camera.bottom + 4 : camera.top - 4, + ); + final radii = tester + .widget(portal) + .borderRadius + .resolve(TextDirection.ltr); + final corner = bottom + ? (right ? radii.bottomRight : radii.bottomLeft) + : (right ? radii.topRight : radii.topLeft); + expect(corner, Radius.circular(camera.shortestSide / 2)); + } + expect((Offset.zero & media.size).contains(expanded.topLeft), isTrue); + expect( + (Offset.zero & media.size).contains(expanded.bottomRight), + isTrue, + ); + expect(expanded.width, expanded.height); + await tester.tapAt(expanded.center); + await tester.pump(); + if (!reducedMotion) { + await tester.pump(const Duration(milliseconds: 300)); + final closing = tester.getRect(portal); + expect( + (closing.center - camera.center).distance, + lessThan((expanded.center - camera.center).distance), + ); + expect(closing.width, lessThan(expanded.width)); + } + await tester.pumpAndSettle(); + expect(portal, findsNothing); + expect(fakeScannerPlatform._isDisposed, isTrue); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); + } + } + group('usesDynamicIslandQrScannerPortal', () { test('asks the native bridge on iOS', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; @@ -230,6 +386,18 @@ void main() { await tester.pump(const Duration(milliseconds: 420)); expect(tester.getRect(sheet).top, closeTo(555, 0.1)); + await tester.binding.setSurfaceSize(const Size(951, 669)); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.text('Scan a QR code')).bottom, + lessThan(tester.getRect(sheet).top), + ); + + expect( + tester.getRect(find.byKey(const ValueKey('fallback-qr-scanner-mask'))), + const Rect.fromLTWH(0, 0, 951, 669), + ); + await tester.tapAt(const Offset(187.5, 100)); await tester.pump(); expect(scannerClosed, isFalse); @@ -365,9 +533,9 @@ void main() { final earlyClosingHeight = tester.getRect(portal).height; expect(earlyClosingHeight, lessThan(280)); expect(find.byType(MobileScanner), findsOneWidget); - await tester.pump(const Duration(milliseconds: 200)); + await tester.pump(const Duration(milliseconds: 100)); final lateClosingHeight = tester.getRect(portal).height; - // The camera is transparent here, but must not shut down mid-collapse. + // Keep native camera teardown outside the closing animation. expect(find.byType(MobileScanner), findsOneWidget); expect( tester diff --git a/mobile/test/features/profile/profile_avatar_crop_cancel_test.dart b/mobile/test/features/profile/profile_avatar_crop_cancel_test.dart new file mode 100644 index 0000000000..a73e648a9c --- /dev/null +++ b/mobile/test/features/profile/profile_avatar_crop_cancel_test.dart @@ -0,0 +1,105 @@ +import 'dart:async'; + +import 'package:buzz/features/profile/profile_avatar_crop_page.dart'; +import 'package:buzz/shared/widgets/frosted_app_bar.dart'; +import 'package:buzz/shared/widgets/duo_toolbar.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +void main() { + for (final side in [null, FoldStripSide.left, FoldStripSide.right]) { + for (final failed in [false, true]) { + testWidgets('crop has one cancel owner: $side, failed=$failed', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final semantics = tester.ensureSemantics(); + final bytes = Completer(); + final strip = side == null + ? null + : FoldStrip( + side: side, + rect: Rect.fromLTWH( + side == FoldStripSide.left ? 0 : 724, + 0, + 76, + 600, + ), + topClearance: 110, + bottomClearance: 0, + isClearanceEstimated: false, + ); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => DuoToolbarScope( + strip: strip, + active: true, + child: ProfileAvatarCropPage(imageBytes: bytes.future), + ), + ), + ), + child: const Text('Open crop'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open crop')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + if (failed) { + bytes.completeError(StateError('Cannot load image')); + await tester.pump(); + await tester.pump(); + expect(find.text("We couldn't prepare that photo."), findsOneWidget); + } + final header = tester.widget(find.byType(FrostedAppBar)); + expect(header.useNativeNavigation, isTrue); + expect(header.automaticallyImplyLeading, isFalse); + expect(find.bySemanticsLabel(RegExp('Cancel|Back')), findsNothing); + final bars = tester.widgetList( + find.byType(IosNavigationBar), + ); + final titleBar = bars.singleWhere((bar) => !bar.standaloneControl); + expect(titleBar.title, 'Position Photo'); + final cancelBar = side == null + ? titleBar + : bars.singleWhere( + (bar) => + bar.standaloneControl && + bar.leading?.label == 'Cancel photo positioning', + ); + final done = side == null + ? titleBar.actions.single + : bars + .singleWhere( + (bar) => + bar.standaloneControl && bar.leading?.label == 'Done', + ) + .leading!; + expect(done.onPressed, isNull); + expect( + cancelBar.leading!.label, + side == null ? 'Back' : 'Cancel photo positioning', + ); + cancelBar.leading!.onPressed!(); + await tester.pumpAndSettle(); + expect(find.byType(ProfileAvatarCropPage), findsNothing); + expect(find.text('Open crop'), findsOneWidget); + expect(tester.takeException(), isNull); + semantics.dispose(); + debugDefaultTargetPlatformOverride = null; + }); + } + } +} diff --git a/mobile/test/features/profile/profile_avatar_crop_resize_test.dart b/mobile/test/features/profile/profile_avatar_crop_resize_test.dart new file mode 100644 index 0000000000..53fdc06dce --- /dev/null +++ b/mobile/test/features/profile/profile_avatar_crop_resize_test.dart @@ -0,0 +1,126 @@ +import 'dart:math' as math; + +import 'package:buzz/features/profile/profile_avatar_crop_page.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:image/image.dart' as image; + +void main() { + for (final sourceSize in [const Size(160, 100), const Size(100, 160)]) { + testWidgets('crop selection survives resizing for $sourceSize', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(400, 800); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final semantics = tester.ensureSemantics(); + final bytes = image.encodePng( + image.Image( + width: sourceSize.width.toInt(), + height: sourceSize.height.toInt(), + ), + ); + final viewerFinder = find.byKey(const ValueKey('avatar-crop-viewer')); + await tester.runAsync(() async { + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: ProfileAvatarCropPage( + imageBytes: Future.value(bytes), + ), + ), + ), + ); + // Observe image preparation completing across its compute boundary. + final deadline = DateTime.now().add(const Duration(seconds: 10)); + while (viewerFinder.evaluate().isEmpty && + DateTime.now().isBefore(deadline)) { + await Future(() {}); + await tester.pump(); + } + }); + expect(viewerFinder, findsOneWidget); + await tester.pumpAndSettle(); + + Semantics cropSemantics() => tester.widget( + find.byWidgetPredicate( + (widget) => + widget is Semantics && widget.properties.label == 'Photo crop', + ), + ); + // Exercise the editor's accessible zoom controls, then a real pan. + for (var i = 0; i < 8; i++) { + final actions = cropSemantics().properties.customSemanticsActions!; + actions.entries + .singleWhere((entry) => entry.key.label == 'Zoom in') + .value(); + await tester.pump(); + } + await tester.drag(viewerFinder, const Offset(48, -36)); + await tester.pumpAndSettle(); + + Rect selectedSourceRect() { + final viewer = tester.widget(viewerFinder); + final canvas = tester.getSize(viewerFinder); + final photo = viewer.child as Image; + final matrix = viewer.transformationController!.value; + final scale = matrix.getMaxScaleOnAxis(); + final diameter = math.min(canvas.width, canvas.height); + // Express the visible crop in original source-image coordinates. + final pixelsPerPoint = sourceSize.width / photo.width!; + return Rect.fromLTWH( + ((canvas.width - diameter) / 2 - matrix.storage[12]) / + scale * + pixelsPerPoint, + ((canvas.height - diameter) / 2 - matrix.storage[13]) / + scale * + pixelsPerPoint, + diameter / scale * pixelsPerPoint, + diameter / scale * pixelsPerPoint, + ); + } + + final selected = selectedSourceRect(); + final zoom = cropSemantics().properties.value; + expect(selected.width, lessThan(sourceSize.shortestSide)); + expect(selected.center.dx, isNot(closeTo(sourceSize.width / 2, 0.01))); + expect(selected.center.dy, isNot(closeTo(sourceSize.height / 2, 0.01))); + final scale = tester + .widget(viewerFinder) + .transformationController! + .value + .getMaxScaleOnAxis(); + for (final size in [ + const Size(800, 600), // Expanded posture: different crop diameter. + const Size(800, 400), // Rotation: short canvas height. + const Size(400, 800), // Fold back without accumulating drift. + ]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + final actual = selectedSourceRect(); + expect(actual.left, closeTo(selected.left, 0.001)); + expect(actual.top, closeTo(selected.top, 0.001)); + expect(actual.width, closeTo(selected.width, 0.001)); + expect(actual.height, closeTo(selected.height, 0.001)); + expect(actual.left, greaterThanOrEqualTo(0)); + expect(actual.top, greaterThanOrEqualTo(0)); + expect(actual.right, lessThanOrEqualTo(sourceSize.width)); + expect(actual.bottom, lessThanOrEqualTo(sourceSize.height)); + expect( + tester + .widget(viewerFinder) + .transformationController! + .value + .getMaxScaleOnAxis(), + closeTo(scale, 0.001), + ); + expect(cropSemantics().properties.value, zoom); + expect(tester.takeException(), isNull); + } + semantics.dispose(); + }); + } +} diff --git a/mobile/test/features/profile/profile_edit_page_test.dart b/mobile/test/features/profile/profile_edit_page_test.dart index b4ec082e3c..bf179f9775 100644 --- a/mobile/test/features/profile/profile_edit_page_test.dart +++ b/mobile/test/features/profile/profile_edit_page_test.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:math' as math; import 'package:buzz/features/profile/profile_edit_page.dart'; +import 'package:buzz/features/settings/settings_page.dart'; import 'package:buzz/features/profile/profile_avatar_draft.dart'; import 'package:buzz/features/profile/profile_avatar_crop_page.dart'; import 'package:buzz/features/profile/avatar_background_grid.dart'; @@ -21,6 +22,7 @@ import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/avatar_image.dart'; import 'package:buzz/shared/widgets/frosted_app_bar.dart'; import 'package:buzz/shared/widgets/ios_native_segmented_control.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; import 'package:buzz/shared/widgets/playing_avatar_image.dart'; import 'package:buzz/shared/widgets/progressive_animated_avatar.dart'; @@ -234,10 +236,27 @@ void main() { tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + const emoji = EmojiEntry( + id: 'smile', + name: 'Smile', + keywords: [], + native: '😊', + categoryId: 'people', + ); + const dataset = EmojiDataset( + categories: [ + EmojiCategory(id: 'people', emoji: [emoji]), + ], + all: [emoji], + nativeToShortcode: {'😊': ':smile:'}, + ); await tester.pumpWidget( WidgetHelpers.testable( - overrides: [profileProvider.overrideWith(_FakeProfileNotifier.new)], + overrides: [ + profileProvider.overrideWith(_FakeProfileNotifier.new), + emojiDatasetOrEmptyProvider.overrideWithValue(dataset), + ], child: const ProfileEditPage(), ), ); @@ -246,6 +265,167 @@ void main() { await tester.pump(); expect(find.byType(IosNativeSegmentedControl), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(678, 466); + tester.view.padding = const FakeViewPadding(right: 84); + tester.view.viewPadding = const FakeViewPadding(right: 84); + addTearDown(tester.view.reset); + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [ + profileProvider.overrideWith(_FakeProfileNotifier.new), + emojiDatasetOrEmptyProvider.overrideWithValue(dataset), + ], + child: SettingsPage( + profileHeader: const SizedBox(), + identityRecoveryPageBuilder: (_) => const SizedBox(), + profileEditPageBuilder: (_) => + const ProfileEditPage(startInPhotoEditor: true), + ), + ), + ); + await tester.pumpAndSettle(); + final photoRow = find.byKey(const ValueKey('edit-profile-photo')); + await tester.ensureVisible(photoRow); + await tester.tap(photoRow); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + final entrance = find.byKey( + const ValueKey('avatar-editor-entrance-transform'), + ); + final enteringOffset = tester + .widget(entrance) + .transform + .getTranslation() + .y; + expect(enteringOffset, lessThan(0)); + await tester.pump(const Duration(milliseconds: 50)); + expect( + tester.widget(entrance).transform.getTranslation().y, + greaterThan(enteringOffset), + ); + expect( + tester.getRect(find.byType(IosNativeSegmentedControl)).right, + lessThan(594), + ); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byType(IosNativeSegmentedControl)).right, + lessThan(594), + ); + final sideOptions = find.byKey( + const ValueKey('avatar-editor-side-options'), + ); + expect(sideOptions, findsOneWidget); + expect( + tester + .getRect( + find + .descendant( + of: sideOptions, + matching: find.byType(IosGlassNavigationButton), + ) + .first, + ) + .left, + greaterThanOrEqualTo(594), + ); + expect(find.text('Camera'), findsOneWidget); + expect(find.text('Photo Library'), findsOneWidget); + tester.view.physicalSize = const Size(466, 678); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = const FakeViewPadding(right: 76); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byType(IosNativeSegmentedControl)).right, + lessThan(390), + ); + final modeControl = tester.widget( + find.byType(IosNativeSegmentedControl), + ); + modeControl.onChanged!(1); + await tester.pumpAndSettle(); + tester.view.physicalSize = const Size(932, 656); + tester.view.padding = const FakeViewPadding(right: 84); + tester.view.viewPadding = const FakeViewPadding(right: 84); + await tester.pumpAndSettle(); + final unfoldedControl = tester.getRect( + find.byType(IosNativeSegmentedControl), + ); + expect(unfoldedControl.left, greaterThan(280)); + expect(unfoldedControl.right, lessThan(848)); + expect( + tester + .widget( + find.byType(IosNativeSegmentedControl), + ) + .selectedIndex, + 1, + ); + expect( + tester + .getRect( + find + .descendant( + of: sideOptions, + matching: find.byType(IosGlassNavigationButton), + ) + .first, + ) + .left, + greaterThanOrEqualTo(848), + ); + final background = find.byKey(const ValueKey('emoji-editor-background')); + expect( + find.descendant(of: sideOptions, matching: background), + findsOneWidget, + ); + final backgroundButton = tester.widget( + background, + ); + backgroundButton.onTap!(); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('emoji-background-editor')), + findsOneWidget, + ); + expect(find.text('Profile'), findsOneWidget); + tester.view.physicalSize = const Size(466, 678); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = const FakeViewPadding(right: 76); + await tester.pumpAndSettle(); + expect( + tester + .widget( + find.byType(IosNativeSegmentedControl), + ) + .selectedIndex, + 1, + ); + final back = find.byKey(const ValueKey('duo-toolbar-Back to profile')); + final bar = tester.widget( + find.descendant(of: back, matching: find.byType(IosNavigationBar)), + ); + bar.leading!.onPressed!(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + expect( + tester.widget(entrance).transform.getTranslation().y, + lessThan(0), + ); + expect(find.byType(IosNativeSegmentedControl), findsOneWidget); + await tester.pumpAndSettle(); + expect(photoRow, findsOneWidget); + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(disableAnimations: true); + addTearDown(tester.platformDispatcher.clearAccessibilityFeaturesTestValue); + await tester.pump(); + await tester.ensureVisible(photoRow); + await tester.tap(photoRow); + await tester.pumpAndSettle(); + expect(tester.widget(entrance).transform.getTranslation().y, 0); + await tester.pumpWidget(const SizedBox()); debugDefaultTargetPlatformOverride = null; }); diff --git a/mobile/test/features/profile/set_status_sheet_test.dart b/mobile/test/features/profile/set_status_sheet_test.dart index aa87e73df9..621bf21430 100644 --- a/mobile/test/features/profile/set_status_sheet_test.dart +++ b/mobile/test/features/profile/set_status_sheet_test.dart @@ -3,6 +3,7 @@ import 'package:buzz/features/profile/user_status.dart'; import 'package:buzz/features/profile/user_status_provider.dart'; import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart'; import 'package:flutter/cupertino.dart'; +import 'package:flutter/services.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -11,6 +12,157 @@ import 'package:buzz/shared/theme/buzz_icons.dart'; import '../../helpers/widget_helpers.dart'; void main() { + testWidgets( + 'iOS status uses native form, retains failed draft, saves and clears', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const channel = MethodChannel('buzz/profile_text_editor'); + final calls = >[]; + final notifier = _RecordingUserStatusNotifier()..failNext = true; + final expiration = DateTime.now().add(const Duration(days: 3)); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'presentStatus'); + calls.add(call.arguments as Map); + if (calls.length == 3) return {'clear': true}; + if (calls.length == 4) return null; + return { + 'text': 'Focused', + 'emoji': ':buzz:', + 'duration': 0, + 'expiresAt': expiration.millisecondsSinceEpoch / 1000, + 'clear': false, + }; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null), + ); + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [ + customEmojiListProvider.overrideWithValue(const []), + userStatusProvider.overrideWith(() => notifier), + ], + child: Builder( + builder: (context) => FilledButton( + onPressed: () => showSetStatusSheet( + context, + currentStatus: const UserStatus( + text: 'Old', + emoji: '🎯', + updatedAt: 1, + ), + ), + child: const Text('Open'), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(calls, hasLength(2)); + expect(calls.first['text'], 'Old'); + expect(calls[1]['text'], 'Focused'); + expect(calls[1]['emoji'], ':buzz:'); + expect(calls[1]['saveError'], true); + expect(notifier.savedText, 'Focused'); + expect( + notifier.savedExpiresAt?.millisecondsSinceEpoch, + expiration.millisecondsSinceEpoch, + ); + expect(find.byType(BottomSheet), findsNothing); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(notifier.savedText, ''); + expect(notifier.savedEmoji, ''); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(calls, hasLength(4)); + expect(notifier.savedText, ''); + debugDefaultTargetPlatformOverride = null; + }, + ); + + for (final invalidExpiration in [ + 9_000_000_000_000, + -9_000_000_000_000, + double.nan, + double.infinity, + 'tomorrow', + null, + ]) { + testWidgets('iOS recovers from invalid expiration $invalidExpiration', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const channel = MethodChannel('buzz/profile_text_editor'); + final calls = >[]; + final notifier = _RecordingUserStatusNotifier(); + final expiration = DateTime.now().add(const Duration(days: 1)); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'presentStatus'); + final draft = call.arguments as Map; + calls.add(draft); + // Bound the mock so a regression reports a failure, not a hang. + if (calls.length > 2) return null; + expect(draft['duration'], 86400); + expect(draft['expiresAt'], isNull); + if (calls.length == 2) { + expect(draft['text'], 'Edited'); + expect(draft['emoji'], '🎯'); + expect(draft['saveError'], true); + expect(notifier.savedText, isNull); + } + return { + 'text': 'Edited', + 'emoji': '🎯', + 'duration': calls.length == 1 ? 0 : draft['duration'], + 'expiresAt': calls.length == 1 + ? invalidExpiration + : expiration.millisecondsSinceEpoch / 1000, + }; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null), + ); + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [userStatusProvider.overrideWith(() => notifier)], + child: Builder( + builder: (context) => FilledButton( + onPressed: () => showSetStatusSheet( + context, + currentStatus: const UserStatus( + text: 'Old', + emoji: '', + updatedAt: 1, + expiresAt: 9_000_000_000_000, + ), + ), + child: const Text('Open'), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(calls, hasLength(2)); + expect(notifier.savedText, 'Edited'); + expect(notifier.savedEmoji, '🎯'); + expect( + notifier.savedExpiresAt?.millisecondsSinceEpoch, + expiration.millisecondsSinceEpoch, + ); + debugDefaultTargetPlatformOverride = null; + }); + } + testWidgets('keeps its resting top edge when the keyboard appears', ( tester, ) async { @@ -198,6 +350,17 @@ void main() { ) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); + const channel = MethodChannel('buzz/profile_text_editor'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + channel, + (_) async => throw MissingPluginException(), + ); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null), + ); + final statusNotifier = _RecordingUserStatusNotifier(); await tester.pumpWidget( WidgetHelpers.testable( @@ -234,6 +397,7 @@ void main() { } class _RecordingUserStatusNotifier extends UserStatusNotifier { + bool failNext = false; String? savedText; String? savedEmoji; DateTime? savedExpiresAt; @@ -247,6 +411,10 @@ class _RecordingUserStatusNotifier extends UserStatusNotifier { String emoji, { DateTime? expiresAt, }) async { + if (failNext) { + failNext = false; + throw StateError('publish failed'); + } savedText = text; savedEmoji = emoji; savedExpiresAt = expiresAt; diff --git a/mobile/test/features/search/search_page_test.dart b/mobile/test/features/search/search_page_test.dart index 291142ceec..7d4ebbdc90 100644 --- a/mobile/test/features/search/search_page_test.dart +++ b/mobile/test/features/search/search_page_test.dart @@ -1,3 +1,7 @@ +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:buzz/shared/widgets/frosted_scaffold.dart'; +import 'package:buzz/shared/widgets/frosted_app_bar.dart'; import 'package:buzz/shared/identity_archives/identity_archives.dart'; import 'package:buzz/shared/widgets/buzz_agent_icon.dart'; import 'package:buzz/features/channels/channel.dart'; @@ -28,6 +32,86 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../../helpers/widget_helpers.dart'; void main() { + testWidgets( + 'Search Close survives result selection without overlapping detail actions', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = tester.view.padding; + addTearDown(tester.view.reset); + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [ + searchProvider.overrideWith( + () => _FakeSearchNotifier(const SearchState.initial()), + ), + recentSearchesProvider.overrideWith( + () => _FakeRecentSearchesNotifier(const []), + ), + profileProvider.overrideWith(() => _FakeProfileNotifier()), + ], + child: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => AdaptiveConversationDestination( + controller: controller, + listToolbarSlots: 1, + child: const SearchPage(), + ), + ), + ), + child: const Text('Open Search'), + ), + ), + ), + ); + await tester.tap(find.text('Open Search')); + await tester.pumpAndSettle(); + controller.open( + 'result', + (_) => FrostedScaffold( + appBar: FrostedAppBar( + nativeTitle: 'Result', + automaticallyImplyLeading: false, + nativeActions: [ + IosNavigationAction( + label: 'Result options', + symbol: 'ellipsis', + onPressed: () {}, + ), + ], + ), + body: const Text('Selected result'), + ), + ); + await tester.pumpAndSettle(); + final close = find.byKey(const ValueKey('duo-toolbar-Close search')); + final options = find.byKey(const ValueKey('duo-toolbar-Result options')); + expect(close, findsOneWidget); + expect( + tester.getRect(close).bottom, + lessThanOrEqualTo(tester.getRect(options).top), + ); + tester + .widget( + find.descendant(of: close, matching: find.byType(IosNavigationBar)), + ) + .leading! + .onPressed!(); + await tester.pumpAndSettle(); + expect(find.text('Open Search'), findsOneWidget); + expect(find.text('Selected result'), findsNothing); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { for (final scale in [1.0, 2.0]) { testWidgets('search controls stay fixed on $platform at scale $scale', ( diff --git a/mobile/test/features/settings/builderlab_account_row_test.dart b/mobile/test/features/settings/builderlab_account_row_test.dart index e4101d8346..d80ce7fe2b 100644 --- a/mobile/test/features/settings/builderlab_account_row_test.dart +++ b/mobile/test/features/settings/builderlab_account_row_test.dart @@ -12,9 +12,15 @@ import 'package:shared_preferences/shared_preferences.dart'; void main() { Future> pumpSettings( WidgetTester tester, { + bool wide = false, bool opens = true, bool throws = false, }) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = wide + ? const Size(1000, 800) + : const Size(390, 844); + addTearDown(tester.view.reset); PackageInfo.setMockInitialValues( appName: 'Buzz', packageName: 'xyz.block.buzz', @@ -53,29 +59,33 @@ void main() { final row = find.byKey(const Key('settings-builderlab-account')); - testWidgets('opens the public Builderlab dashboard in the browser', ( - tester, - ) async { - final opened = await pumpSettings(tester); - await tester.scrollUntilVisible(row, 200); - await tester.tap(row); - await tester.pumpAndSettle(); - expect(opened, [HostedEnvironment.origin]); - expect(find.text('Couldn’t open Builderlab.'), findsNothing); - }, skip: !HostedEnvironment.enabled); - - for (final throws in [false, true]) { - testWidgets( - 'says so when the browser ${throws ? 'throws' : 'does not open'}', - (tester) async { - await pumpSettings(tester, opens: false, throws: throws); - await tester.scrollUntilVisible(row, 200); - await tester.tap(row); + for (final wide in [false, true]) { + Future openAccount(WidgetTester tester) async { + if (wide) { + await tester.tap(find.text('Account')); await tester.pumpAndSettle(); + } + await tester.ensureVisible(row); + await tester.tap(row); + await tester.pumpAndSettle(); + } + + testWidgets('opens the public dashboard (wide=$wide)', (tester) async { + final opened = await pumpSettings(tester, wide: wide); + await openAccount(tester); + expect(opened, [HostedEnvironment.origin]); + expect(find.text('Couldn’t open Builderlab.'), findsNothing); + }, skip: !HostedEnvironment.enabled); + + for (final throws in [false, true]) { + testWidgets('reports browser failure (throws=$throws, wide=$wide)', ( + tester, + ) async { + await pumpSettings(tester, wide: wide, opens: false, throws: throws); + await openAccount(tester); expect(find.text('Couldn’t open Builderlab.'), findsOneWidget); - }, - skip: !HostedEnvironment.enabled, - ); + }, skip: !HostedEnvironment.enabled); + } } testWidgets('is absent outside a public build', (tester) async { diff --git a/mobile/test/features/settings/connection_section_test.dart b/mobile/test/features/settings/connection_section_test.dart index b9fc77624d..937f5d223b 100644 --- a/mobile/test/features/settings/connection_section_test.dart +++ b/mobile/test/features/settings/connection_section_test.dart @@ -59,6 +59,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -144,6 +145,7 @@ void main() { }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('an out-of-range identity shows as unavailable', (tester) async { + _usePhoneViewport(tester); SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); @@ -189,6 +191,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -226,6 +229,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -262,6 +266,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -304,6 +309,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -347,6 +353,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( WidgetHelpers.testable( overrides: [ @@ -427,3 +434,11 @@ class _PairingNotifier extends PairingNotifier { resetCalls++; } } + +void _usePhoneViewport(WidgetTester tester) { + if (tester.view.physicalSize.width / tester.view.devicePixelRatio >= 640) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 1200); + addTearDown(tester.view.reset); + } +} diff --git a/mobile/test/features/settings/settings_page_test.dart b/mobile/test/features/settings/settings_page_test.dart index fa542092af..1af92267a6 100644 --- a/mobile/test/features/settings/settings_page_test.dart +++ b/mobile/test/features/settings/settings_page_test.dart @@ -1,3 +1,6 @@ +import 'package:buzz/shared/widgets/frosted_app_bar.dart'; +import 'package:buzz/shared/widgets/frosted_scaffold.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui; @@ -5,10 +8,12 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; import 'package:buzz/shared/community/community_membership_provider.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/theme/theme.dart'; +import 'package:buzz/shared/theme/buzz_icons.dart'; import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/push/push_relay_capability_provider.dart'; import 'package:buzz/shared/relay/app_lifecycle_provider.dart'; @@ -32,6 +37,184 @@ void main() { ); }); + testWidgets('wide Settings opens categories and editors in the detail pane', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(1000, 800); + addTearDown(tester.view.reset); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + ProviderScope( + overrides: [savedPrefsProvider.overrideWithValue(prefs)], + child: MaterialApp( + theme: AppTheme.light(), + home: SettingsPage( + profileHeader: const SizedBox.shrink(), + identityRecoveryPageBuilder: (_) => const SizedBox.shrink(), + profileEditPageBuilder: (context) => FrostedScaffold( + body: const Text('Photo editor'), + appBar: FrostedAppBar( + nativeTitle: 'Photo editor', + leading: IconButton( + tooltip: 'Back to profile', + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(Icons.arrow_back), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Select a setting'), findsNothing); + expect(find.text('Set status'), findsOneWidget); + expect( + Navigator.of(tester.element(find.text('Set status'))).canPop(), + isFalse, + ); + final workspaceTheme = Theme.of( + tester.element(find.byType(AdaptiveConversationDestination)), + ); + expect( + workspaceTheme.colorScheme.surface, + utilitySurfaceThemeData(AppTheme.light()).colorScheme.surface, + ); + expect( + workspaceTheme.scaffoldBackgroundColor, + workspaceTheme.colorScheme.surface, + ); + + final categoryRows = find.byWidgetPredicate( + (w) => + w is AppListRow && + [ + 'Status', + 'Profile', + 'Notifications', + 'Connection', + ].contains(w.title), + ); + final categoryBounds = { + for (final element in categoryRows.evaluate()) + (element.widget as AppListRow).title: tester.getRect( + find.byWidget(element.widget), + ), + }; + expect(categoryBounds.length, greaterThanOrEqualTo(3)); + for (final element in categoryRows.evaluate()) { + expect( + find.descendant( + of: find.byWidget(element.widget), + matching: find.byIcon(BuzzIcons.chevronRight), + ), + findsOneWidget, + ); + } + expect(find.byIcon(Icons.check), findsNothing); + + await tester.tap(find.text('Profile')); + await tester.pumpAndSettle(); + for (final entry in categoryBounds.entries) { + final row = find.byWidgetPredicate( + (w) => w is AppListRow && w.title == entry.key, + ); + expect(tester.getRect(row), entry.value); + } + expect(find.byIcon(Icons.check), findsNothing); + await tester.tap(find.text('Status')); + await tester.pumpAndSettle(); + expect(find.text('Set status'), findsOneWidget); + expect( + Navigator.of(tester.element(find.text('Set status'))).canPop(), + isFalse, + ); + await tester.tap(find.text('Profile')); + await tester.pumpAndSettle(); + expect( + tester.getCenter(find.text('Edit photo')).dx, + greaterThan(tester.getCenter(find.text('Status')).dx), + ); + expect( + Navigator.of(tester.element(find.text('Edit photo'))).canPop(), + isFalse, + ); + await tester.tap(find.text('Edit photo')); + await tester.pumpAndSettle(); + expect(find.text('Photo editor'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Edit photo'), findsOneWidget); + await tester.tap(find.text('Edit photo')); + await tester.pumpAndSettle(); + expect(find.text('Status'), findsOneWidget); + tester.view.physicalSize = const Size(390, 800); + await tester.pumpAndSettle(); + expect(find.text('Photo editor'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Edit photo'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.physicalSize = const Size(678, 466); + tester.view.viewPadding = const FakeViewPadding(right: 84); + tester.view.padding = const FakeViewPadding(right: 84); + await tester.pumpAndSettle(); + expect(find.text('Profile'), findsNothing); + expect(find.text('Display name'), findsOneWidget); + expect( + find.byWidgetPredicate( + (widget) => widget is FrostedAppBar && widget.railOnly, + ), + findsOneWidget, + ); + expect(find.text('Settings'), findsNothing); + // Book-mode Duo keeps Profile underneath the pushed photo editor. + tester.view.physicalSize = const Size(874, 402); + tester.view.viewPadding = const FakeViewPadding(right: 76); + tester.view.padding = tester.view.viewPadding; + await tester.pumpAndSettle(); + await tester.tap(find.text('Profile')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Edit photo')); + await tester.pumpAndSettle(); + expect(find.text('Photo editor'), findsOneWidget); + expect( + find.byKey(const ValueKey('duo-toolbar-Close settings')), + findsOneWidget, + ); + final closeSettings = find.byKey( + const ValueKey('duo-toolbar-Close settings'), + ); + final backToProfile = find.byKey( + const ValueKey('duo-toolbar-Back to profile'), + ); + expect(backToProfile, findsOneWidget); + expect( + tester.getRect(closeSettings).overlaps(tester.getRect(backToProfile)), + isFalse, + ); + tester + .widget( + find.descendant( + of: backToProfile, + matching: find.byType(IosNavigationBar), + ), + ) + .leading! + .onPressed!(); + await tester.pumpAndSettle(); + expect(find.text('Edit photo'), findsOneWidget); + expect(find.text('Set status'), findsNothing); + + await tester.pumpWidget(const SizedBox.shrink()); + debugDefaultTargetPlatformOverride = null; + }); + for (final buildNumber in ['432', '', '2147483647']) { testWidgets('shows version with build number "$buildNumber"', ( tester, @@ -49,6 +232,7 @@ void main() { ); SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -76,7 +260,11 @@ void main() { await tester.pumpAndSettle(); final label = buildNumber.isEmpty ? 'v0.16.0' : 'v0.16.0 ($buildNumber)'; final version = find.text(label); - await tester.scrollUntilVisible(version, 200); + await tester.scrollUntilVisible( + version, + 200, + scrollable: find.byType(Scrollable).first, + ); await tester.pumpAndSettle(); expect(version.hitTestable(), findsOneWidget); expect( @@ -131,7 +319,11 @@ void main() { ); await tester.pumpAndSettle(); final version = find.text('v0.16.0 (432)'); - await tester.scrollUntilVisible(version, 200); + await tester.scrollUntilVisible( + version, + 200, + scrollable: find.byType(Scrollable).first, + ); await tester.pumpAndSettle(); final target = find.ancestor( of: version, @@ -177,6 +369,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); final capability = Completer(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -231,6 +424,7 @@ void main() { final capability = Future.value(_pushDescriptor); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -280,6 +474,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [savedPrefsProvider.overrideWithValue(prefs)], @@ -359,6 +554,7 @@ void main() { final prefs = await SharedPreferences.getInstance(); final opened = []; + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [savedPrefsProvider.overrideWithValue(prefs)], @@ -400,6 +596,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [savedPrefsProvider.overrideWithValue(prefs)], @@ -432,6 +629,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -464,6 +662,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -495,6 +694,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -526,6 +726,7 @@ void main() { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); + _usePhoneViewport(tester); await tester.pumpWidget( ProviderScope( overrides: [ @@ -570,3 +771,11 @@ const _pushDescriptor = BuzzPushLeaseDescriptor( maxEndpointLength: 2048, maxStringLength: 512, ); + +void _usePhoneViewport(WidgetTester tester) { + if (tester.view.physicalSize.width / tester.view.devicePixelRatio >= 640) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 1200); + addTearDown(tester.view.reset); + } +} diff --git a/mobile/test/features/settings/theme_picker_page_test.dart b/mobile/test/features/settings/theme_picker_page_test.dart index 4e90b17b1f..a8d836d764 100644 --- a/mobile/test/features/settings/theme_picker_page_test.dart +++ b/mobile/test/features/settings/theme_picker_page_test.dart @@ -1,6 +1,9 @@ import 'package:buzz/features/settings/theme_picker_page.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -36,6 +39,173 @@ Future _pumpPicker( } void main() { + testWidgets( + 'Appearance preserves its draft inside Duo content bounds across folds', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final instance = await _prefs({}); + final notifier = _RecordingCommunityThemeNotifier(); + try { + tester.view.physicalSize = const Size(466, 678); + tester.view.viewPadding = const FakeViewPadding(right: 76, bottom: 21); + tester.view.padding = const FakeViewPadding(right: 76, bottom: 21); + await tester.pumpWidget( + WidgetHelpers.testable( + child: const ThemePickerPage(), + overrides: [ + savedPrefsProvider.overrideWithValue(instance), + communityThemeProvider.overrideWith(() => notifier), + ], + ), + ); + await tester.pumpAndSettle(); + // The OS button is the only mocked boundary. + IosNavigationAction railAction(String label) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey('duo-toolbar-$label')), + matching: find.byType(IosNavigationBar), + ), + ) + .leading!; + IosGlassNavigationButton modeButton() => + tester.widget( + find.byKey( + const ValueKey('theme-preview-appearance-action-button'), + ), + ); + modeButton().onPressed!(); + await tester.pumpAndSettle(); + tester + .widget( + find.descendant( + of: find.byKey( + const ValueKey('theme-preview-accent-action-button'), + ), + matching: find.byType(IosGlassNavigationButton), + ), + ) + .onPressed!(); + await tester.pumpAndSettle(); + final jade = chatColorChoices.indexWhere( + (color) => color.name == 'Jade', + ); + final option = find.byKey(ValueKey('accent-option-$jade')); + await tester.ensureVisible(option); + await tester.tap(option); + await tester.pumpAndSettle(); + Navigator.of(tester.element(option)).pop(); + await tester.pumpAndSettle(); + for (final (size, left) in [ + (const Size(466, 678), false), + (const Size(951, 669), false), + (const Size(669, 951), false), + (const Size(678, 466), true), + ]) { + tester.view.physicalSize = size; + final padding = FakeViewPadding( + left: left ? 76 : 0, + right: left ? 0 : 76, + bottom: 21, + ); + tester.view.viewPadding = padding; + tester.view.padding = padding; + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(modeButton().icon, IosGlassNavigationIcon.sun); + expect(notifier.preferenceWrites, 0); + final preview = tester.getRect( + find.byKey(const ValueKey('theme-preview-page-$buzzThemeName')), + ); + expect(preview.left, greaterThanOrEqualTo(left ? 76 : 0)); + expect( + preview.right, + lessThanOrEqualTo(size.width - (left ? 0 : 76)), + ); + final images = tester.getCenter( + find.byKey( + const ValueKey('theme-device-pair-preview-$buzzThemeName'), + ), + ); + expect(images.dy, closeTo(size.height / 2, 1)); + expect(images.dx, closeTo((size.width + (left ? 76 : -76)) / 2, 1)); + final wide = size.width - 76 >= 640 && size.width > size.height; + final controls = tester.getRect( + find.byKey( + ValueKey( + wide ? 'theme-preview-bottom-row' : 'theme-preview-rail-bottom', + ), + ), + ); + final top = tester.getRect( + find.byKey(const ValueKey('duo-toolbar-Set')), + ); + expect(controls.top, greaterThan(top.bottom)); + expect(controls.bottom, lessThanOrEqualTo(size.height)); + if (wide) { + expect(controls.bottom, size.height - 21); + final colorButton = tester.getCenter( + find.byKey(const ValueKey('theme-preview-accent-action-button')), + ); + final appearanceButton = tester.getCenter( + find.byKey( + const ValueKey('theme-preview-appearance-action-button'), + ), + ); + expect(colorButton.dy, appearanceButton.dy); + expect(controls.height, 56); + tester + .widget( + find.descendant( + of: find.byKey( + const ValueKey('theme-preview-accent-action-button'), + ), + matching: find.byType(IosGlassNavigationButton), + ), + ) + .onPressed!(); + await tester.pumpAndSettle(); + final grid = find.byKey(const ValueKey('accent-selection-grid')); + expect(tester.getSize(grid).width, lessThanOrEqualTo(320)); + Navigator.of(tester.element(grid)).pop(); + await tester.pumpAndSettle(); + } else { + expect(controls.center.dx, closeTo(top.center.dx, 1)); + } + final swatch = tester.widget( + find.descendant( + of: find.byKey( + const ValueKey('theme-preview-accent-action-button'), + ), + matching: find.byType(IosGlassNavigationButton), + ), + ); + expect(swatch.icon, IosGlassNavigationIcon.colorSwatch); + expect( + swatch.swatchColor, + chatColorForScheme(lightColorScheme, jade), + ); + expect( + find.byKey(const ValueKey('theme-preview-name-$buzzThemeName')), + findsNothing, + ); + } + railAction('Set').onPressed!(); + await tester.pumpAndSettle(); + expect(notifier.preferenceWrites, 1); + expect(notifier.lastPreference?.mode, ThemeMode.light); + expect( + notifier.lastPreference?.accent, + chatColorChoices[jade].wireValue, + ); + } finally { + debugDefaultTargetPlatformOverride = null; + } + }, + ); + testWidgets('one Home and Chat pair replaces the theme carousel', ( tester, ) async { diff --git a/mobile/test/shared/push/push_root_isolation_test.dart b/mobile/test/shared/push/push_root_isolation_test.dart index 21b2cc3173..cb2e393358 100644 --- a/mobile/test/shared/push/push_root_isolation_test.dart +++ b/mobile/test/shared/push/push_root_isolation_test.dart @@ -103,7 +103,6 @@ void main() { await tester.pump(); await tester.pump(); expect(find.byType(HomePage), findsOneWidget); - expect(find.byType(Navigator), findsOneWidget); expect(tester.takeException(), isNull); final container = ProviderScope.containerOf( tester.element(find.byType(App)), @@ -112,7 +111,10 @@ void main() { container.read(buzzPushSetupStatusProvider).error, isA(), ); - final navigator = tester.state(find.byType(Navigator)); + // The root navigator owns this route; Duo also keeps a detail navigator. + final navigator = tester.state( + find.byType(Navigator).first, + ); unawaited( navigator.push( MaterialPageRoute( @@ -137,7 +139,7 @@ void main() { ); expect(find.text('Open conversation'), findsOneWidget); expect( - tester.state(find.byType(Navigator)), + tester.state(find.byType(Navigator).first), same(navigator), ); @@ -159,8 +161,10 @@ void main() { (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; final semantics = tester.ensureSemantics(); - await tester.binding.setSurfaceSize(const Size(390, 844)); - addTearDown(() => tester.binding.setSurfaceSize(null)); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 844); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); await tester.runAsync(() async { await (FontLoader( 'Inter', @@ -251,7 +255,9 @@ void main() { ); await tester.pump(); expect(find.text('Core app'), findsOneWidget); - final navigator = tester.state(find.byType(Navigator)); + final navigator = tester.state( + find.byType(Navigator).first, + ); unawaited( navigator.push( MaterialPageRoute( @@ -308,7 +314,7 @@ void main() { expect(find.text('Notification setup failed'), findsNothing); await _capture(tester, 'notification-setup-recovered'); expect( - tester.state(find.byType(Navigator)), + tester.state(find.byType(Navigator).first), same(navigator), ); await communities.removeCommunity(removals.first.id); diff --git a/mobile/test/shared/push/push_unconfigured_build_test.dart b/mobile/test/shared/push/push_unconfigured_build_test.dart index 5cf3f414be..e621f41395 100644 --- a/mobile/test/shared/push/push_unconfigured_build_test.dart +++ b/mobile/test/shared/push/push_unconfigured_build_test.dart @@ -108,6 +108,8 @@ void main() { ); expect(find.text('Push notifications'), findsNothing); if (enabled) { + await tester.tap(find.text('Notifications')); + await tester.pumpAndSettle(); final toggle = tester.widget(find.byType(Switch)); expect(toggle.value, isTrue); expect(toggle.onChanged, isNotNull); diff --git a/mobile/test/shared/widgets/adaptive_conversation_pane_test.dart b/mobile/test/shared/widgets/adaptive_conversation_pane_test.dart new file mode 100644 index 0000000000..428e9658fb --- /dev/null +++ b/mobile/test/shared/widgets/adaptive_conversation_pane_test.dart @@ -0,0 +1,716 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:buzz/shared/widgets/text_editor.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:buzz/shared/widgets/frosted_scaffold.dart'; +import 'package:buzz/shared/widgets/frosted_app_bar.dart'; +import 'package:buzz/shared/widgets/modal_presentation.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('reopening a deep link resets its route after thread Back', ( + tester, + ) async { + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(1000, 800); + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: AdaptiveConversationPane( + controller: controller, + list: Builder( + builder: (context) => TextButton( + onPressed: () => openConversationPane( + context, + 'activity-item', + (_) => const _DeepLink(), + reopen: true, + ), + child: const Text('Open activity'), + ), + ), + ), + ), + ), + ); + for (var attempt = 0; attempt < 2; attempt++) { + await tester.tap(find.text('Open activity')); + await tester.pumpAndSettle(); + expect(find.text('Deep-linked thread'), findsOneWidget); + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + expect(find.text('Selected channel'), findsOneWidget); + expect(controller.selectedId, 'activity-item'); + expect( + ConversationPaneScope.isBaseRouteOf( + tester.element(find.text('Selected channel')), + ), + isTrue, + ); + } + }); + + testWidgets('phones stay compact while tablets and Duo retain panes', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + for (final platform in [TargetPlatform.iOS, TargetPlatform.android]) { + debugDefaultTargetPlatformOverride = platform; + for (final scenario in [ + (size: const Size(402, 874), duo: false, top: 24.0, wide: false), + (size: const Size(874, 402), duo: false, top: 24.0, wide: false), + (size: const Size(1024, 768), duo: false, top: 24.0, wide: true), + (size: const Size(768, 1024), duo: false, top: 24.0, wide: true), + (size: const Size(874, 402), duo: true, top: 0.0, wide: true), + ( + size: const Size(669, 951), + duo: false, + top: 82.0, + wide: platform != TargetPlatform.iOS, + ), + ]) { + tester.view.physicalSize = scenario.size; + tester.view.viewPadding = FakeViewPadding(top: scenario.top); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) { + final wide = usesConversationPanes( + context, + strip: scenario.duo + ? const FoldStrip( + side: FoldStripSide.right, + rect: Rect.fromLTWH(798, 0, 76, 402), + topClearance: 0, + bottomClearance: 0, + isClearanceEstimated: true, + ) + : null, + ); + return Text(wide ? 'Split panes' : 'Single pane'); + }, + ), + ), + ); + expect( + find.text(scenario.wide ? 'Split panes' : 'Single pane'), + findsOneWidget, + ); + } + } + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets( + 'detail surface reaches rail and sheet covers the whole workspace', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(951, 669); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = const FakeViewPadding(right: 76); + addTearDown(tester.view.reset); + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + controller.open( + 'settings', + (context) => FrostedScaffold( + key: const ValueKey('detail-surface'), + appBar: const FrostedAppBar(title: Text('Channel settings')), + body: Center( + child: TextButton( + onPressed: () => showBuzzModalBottomSheet( + context: context, + title: 'Channel actions', + builder: (_) => const SizedBox( + height: 200, + child: Center(child: Text('Sheet content')), + ), + ), + child: const Text('Open sheet'), + ), + ), + ), + ); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: IosNavigationMetricsHost( + child: AdaptiveConversationPane( + controller: controller, + strip: const FoldStrip( + side: FoldStripSide.right, + rect: Rect.fromLTWH(875, 0, 76, 669), + topClearance: 110, + bottomClearance: 0, + isClearanceEstimated: true, + ), + list: const ColoredBox( + color: Colors.white, + child: Text('Sidebar'), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey('detail-surface'))).right, + 951, + ); + expect( + tester.getCenter(find.text('Open sheet')).dx, + closeTo((875 / 3 + 1 + 875) / 2, 1), + ); + final flatLeft = tester + .getRect(find.byKey(const ValueKey('detail-surface'))) + .left; + for (final division in [ + [470, 0, 12, 669], + null, + ]) { + IosNavigationMetrics.updateRail(tester.element(find.text('Sidebar')), { + 'centerX': 920, + 'windowWidth': 951, + 'windowHeight': 669, + 'bookDivision': division, + }); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 120)); + final moving = tester.getRect( + find.byKey(const ValueKey('detail-surface')), + ); + expect(moving.left, greaterThan(flatLeft)); + expect(moving.left, lessThan(476)); + expect(moving.right, 951); + await tester.pumpAndSettle(); + final detail = tester.getRect( + find.byKey(const ValueKey('detail-surface')), + ); + expect(detail.left, division == null ? flatLeft : 476); + expect(detail.right, 951); + if (division != null) { + expect(tester.getRect(find.text('Sidebar')).right, detail.left); + expect( + tester.getCenter(find.text('Open sheet')).dx, + closeTo((482 + 875) / 2, 1), + ); + } + expect(controller.selectedId, 'settings'); + expect(find.text('Open sheet'), findsOneWidget); + } + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(disableAnimations: true); + addTearDown( + tester.platformDispatcher.clearAccessibilityFeaturesTestValue, + ); + await tester.pump(); + IosNavigationMetrics.updateRail(tester.element(find.text('Sidebar')), { + 'centerX': 920, + 'windowWidth': 951, + 'windowHeight': 669, + 'bookDivision': [470, 0, 12, 669], + }); + await tester.pump(); + expect( + tester.getRect(find.byKey(const ValueKey('detail-surface'))).left, + 476, + ); + IosNavigationMetrics.updateRail(tester.element(find.text('Sidebar')), { + 'centerX': 920, + 'windowWidth': 951, + 'windowHeight': 669, + }); + await tester.pump(); + expect( + tester.getRect(find.byKey(const ValueKey('detail-surface'))).left, + flatLeft, + ); + await tester.tap(find.text('Open sheet')); + await tester.pumpAndSettle(); + expect(tester.getRect(find.byType(BottomSheet)).left, 0); + expect(tester.getRect(find.byType(BottomSheet)).right, 951); + expect(tester.getRect(find.text('Sheet content')).right, lessThan(875)); + final close = find.byKey( + const ValueKey('duo-toolbar-Close Channel actions'), + ); + expect(close, findsOneWidget); + expect( + find.byKey(const ValueKey('buzz-sheet-ios-glass-close')), + findsNothing, + ); + expect(tester.getRect(close).center.dx, greaterThan(875)); + final railBar = tester.widget( + find.descendant(of: close, matching: find.byType(IosNavigationBar)), + ); + railBar.leading!.onPressed!(); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('detail-surface')), findsOneWidget); + expect(controller.selectedId, 'settings'); + const nativeEditor = MethodChannel('buzz/profile_text_editor'); + final nativeTitles = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + nativeEditor, + (call) async { + nativeTitles.add((call.arguments as Map)['title'] as String); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + nativeEditor, + null, + ), + ); + for (final title in ['Display name', 'Profile description']) { + showTextEditor( + context: tester.element(find.text('Open sheet')), + title: title, + initialValue: 'Original', + hintText: title, + onSave: (_) async {}, + ); + await tester.pumpAndSettle(); + expect(find.byType(TextField), findsNothing); + } + expect(nativeTitles, ['Display name', 'Profile description']); + expect(controller.selectedId, 'settings'); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + testWidgets( + 'result destination keeps its list and closes detail before workspace', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(900, 700); + addTearDown(tester.view.reset); + final navigator = GlobalKey(); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + navigatorKey: navigator, + theme: AppTheme.light(), + home: const Scaffold(body: Text('Home')), + ), + ), + ); + navigator.currentState!.push( + MaterialPageRoute( + builder: (_) => AdaptiveConversationDestination( + child: Builder( + builder: (context) => Scaffold( + body: Column( + children: [ + const TextField(key: ValueKey('result-query')), + TextButton( + onPressed: () => openConversationPane( + context, + 'result', + (_) => const _Conversation(), + ), + child: const Text('Open result'), + ), + ], + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const ValueKey('result-query')), + 'retained query', + ); + await tester.tap(find.text('Open result')); + await tester.pumpAndSettle(); + expect(find.text('retained query'), findsOneWidget); + expect(find.byType(TextField), findsNWidgets(2)); + tester.view.physicalSize = const Size(400, 700); + await tester.pumpAndSettle(); + expect(find.text('Open result'), findsNothing); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Open result'), findsOneWidget); + expect(find.text('retained query'), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Home'), findsOneWidget); + }, + ); + + testWidgets( + 'selection, draft and thread survive compact and regular layouts', + (tester) async { + final controller = ConversationPaneController(); + final active = ValueNotifier(true); + addTearDown(active.dispose); + addTearDown(controller.dispose); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(900, 700); + addTearDown(tester.view.reset); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: Scaffold( + body: ValueListenableBuilder( + valueListenable: active, + builder: (context, isActive, _) => AdaptiveConversationPane( + active: isActive, + controller: controller, + list: Builder( + builder: (context) => Column( + children: [ + TextButton( + onPressed: () => ConversationPaneScope.maybeOf( + context, + )!.open('one', (_) => const _Conversation()), + child: const Text('First chat'), + ), + TextButton( + onPressed: () => + ConversationPaneScope.maybeOf(context)!.open( + 'two', + (_) => const Scaffold( + body: Text('Second conversation'), + ), + ), + child: const Text('Second chat'), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('First chat')); + await tester.pumpAndSettle(); + expect( + tester.getCenter(find.text('First chat')).dx, + lessThan(tester.getCenter(find.byType(TextField)).dx), + ); + await tester.enterText(find.byType(TextField), 'Keep my draft'); + active.value = false; + await tester.pumpAndSettle(); + expect(find.text('Visible: false'), findsOneWidget); + active.value = true; + await tester.pumpAndSettle(); + expect(find.text('Visible: true'), findsOneWidget); + tester.view.physicalSize = const Size(390, 700); + await tester.pumpAndSettle(); + expect(find.text('First chat'), findsNothing); + expect(find.text('Keep my draft'), findsOneWidget); + await tester.tap(find.text('Thread')); + await tester.pumpAndSettle(); + expect(find.text('Thread content'), findsOneWidget); + tester.view.physicalSize = const Size(900, 700); + await tester.pumpAndSettle(); + expect(find.text('First chat'), findsOneWidget); + expect(find.text('Thread content'), findsOneWidget); + await tester.tap(find.byType(BackButton)); + await tester.pumpAndSettle(); + expect(find.text('Keep my draft'), findsOneWidget); + await tester.tap(find.text('Second chat')); + await tester.pumpAndSettle(); + expect(find.text('Second conversation'), findsOneWidget); + expect(controller.selectedId, 'two'); + tester.view.physicalSize = const Size(390, 700); + await tester.pumpAndSettle(); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(controller.selectedId, isNull); + expect(find.text('First chat'), findsOneWidget); + tester.view.physicalSize = const Size(900, 700); + await tester.pumpAndSettle(); + final placeholder = find.text('Select a conversation'); + expect(placeholder, findsOneWidget); + expect( + find.ancestor(of: placeholder, matching: find.byType(Material)), + findsWidgets, + ); + expect( + tester.widget(placeholder).style!.decoration, + TextDecoration.none, + ); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('iPhone back swipe and back button reveal the chat list', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(402, 874); + addTearDown(tester.view.reset); + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + var listTaps = 0; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: AdaptiveConversationPane( + controller: controller, + list: Material( + child: Center( + child: TextButton( + onPressed: () => listTaps++, + child: const Text('Chat list'), + ), + ), + ), + ), + ), + ), + ); + final list = find.text('Chat list'); + final placeholder = find.text('Select a conversation'); + + controller.open('chat', (_) => const _Conversation()); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(list, findsOneWidget, reason: 'the list stays beneath a push'); + await tester.pumpAndSettle(); + expect(list, findsNothing, reason: 'a settled chat covers the list'); + + final swipe = await tester.startGesture(const Offset(5, 400)); + await swipe.moveBy(const Offset(100, 0)); + await tester.pump(); + await swipe.moveBy(const Offset(60, 0)); + await tester.pump(); + expect(list, findsOneWidget); + expect(placeholder, findsNothing); + expect( + tester.getSemantics(list.first), + isNot(matchesSemantics(label: 'Chat list')), + reason: 'the covered list is not a screen-reader stop', + ); + // Cancelling the swipe settles the chat back over the list. + await swipe.moveBy(const Offset(-160, 0)); + await swipe.up(); + await tester.pumpAndSettle(); + expect(controller.selectedId, 'chat'); + expect(list, findsNothing); + + await tester.tap(find.byType(BackButton)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(list, findsOneWidget, reason: 'the list stays beneath a pop'); + expect(placeholder, findsNothing); + await tester.pumpAndSettle(); + expect(controller.selectedId, isNull); + await tester.tap(list); + expect(listTaps, 1); + debugDefaultTargetPlatformOverride = null; + }); + + group('compact keyboard', () { + Future raiseKeyboard(WidgetTester tester) async { + for (var frame = 1; frame <= 20; frame++) { + tester.view.viewInsets = FakeViewPadding(bottom: frame * 15.0); + await tester.pump(const Duration(milliseconds: 16)); + } + } + + testWidgets('does not rebuild the covered list or detail routes', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(402, 874); + addTearDown(tester.view.reset); + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + var listBuilds = 0; + var channelBuilds = 0; + var threadBuilds = 0; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: AdaptiveConversationPane( + controller: controller, + list: _CountedInsets('List', () => listBuilds++), + ), + ), + ), + ); + controller.open( + 'c', + (_) => _CountedSize('Channel', () => channelBuilds++), + ); + await tester.pumpAndSettle(); + listBuilds = 0; + channelBuilds = 0; + + await raiseKeyboard(tester); + + expect(listBuilds, 0, reason: 'covered list'); + expect(channelBuilds, 0, reason: 'channel detail'); + + Navigator.of(tester.element(find.text('Channel'))).push( + MaterialPageRoute( + builder: (_) => _CountedSize('Thread', () => threadBuilds++), + ), + ); + await tester.pumpAndSettle(); + tester.view.viewInsets = FakeViewPadding.zero; + await tester.pump(); + channelBuilds = 0; + threadBuilds = 0; + + await raiseKeyboard(tester); + + expect(threadBuilds, 0, reason: 'thread on top'); + expect(channelBuilds, 0, reason: 'covered channel'); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('list keeps its insets while a popped detail keyboard lowers', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(402, 874); + addTearDown(tester.view.reset); + final controller = ConversationPaneController(); + addTearDown(controller.dispose); + final listInsets = []; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + home: AdaptiveConversationPane( + controller: controller, + list: Builder( + builder: (context) { + listInsets.add(MediaQuery.viewInsetsOf(context).bottom); + return const Text('List'); + }, + ), + ), + ), + ), + ); + controller.open( + 'c', + (_) => const Material( + child: Column( + children: [Text('Channel'), TextField(autofocus: true)], + ), + ), + ); + await tester.pumpAndSettle(); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await tester.pump(); + listInsets.clear(); + + Navigator.of(tester.element(find.text('Channel'))).pop(); + await tester.pumpAndSettle(); + for (var bottom = 280.0; bottom >= 0; bottom -= 40) { + tester.view.viewInsets = FakeViewPadding(bottom: bottom); + await tester.pump(const Duration(milliseconds: 16)); + } + + expect(listInsets.where((bottom) => bottom != 0), isEmpty); + debugDefaultTargetPlatformOverride = null; + }); + }); +} + +class _Conversation extends StatelessWidget { + const _Conversation(); + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Conversation')), + body: Column( + children: [ + Text('Visible: ${ConversationPaneScope.isActiveOf(context)}'), + const TextField(), + TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => Scaffold( + appBar: AppBar(), + body: const Text('Thread content'), + ), + ), + ), + child: const Text('Thread'), + ), + ], + ), + ); +} + +class _DeepLink extends StatefulWidget { + const _DeepLink(); + @override + State<_DeepLink> createState() => _DeepLinkState(); +} + +class _DeepLinkState extends State<_DeepLink> { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => Scaffold( + appBar: AppBar(), + body: const Text('Deep-linked thread'), + ), + ), + ); + }); + } + + @override + Widget build(BuildContext context) => + const Scaffold(body: Text('Selected channel')); +} + +class _CountedInsets extends StatelessWidget { + const _CountedInsets(this.label, this.onBuild); + final String label; + final VoidCallback onBuild; + @override + Widget build(BuildContext context) { + onBuild(); + MediaQuery.viewInsetsOf(context); + return Text(label); + } +} + +class _CountedSize extends StatelessWidget { + const _CountedSize(this.label, this.onBuild); + final String label; + final VoidCallback onBuild; + @override + Widget build(BuildContext context) { + onBuild(); + MediaQuery.sizeOf(context); + return Text(label); + } +} diff --git a/mobile/test/shared/widgets/adaptive_conversation_recording_test.dart b/mobile/test/shared/widgets/adaptive_conversation_recording_test.dart new file mode 100644 index 0000000000..20694141e6 --- /dev/null +++ b/mobile/test/shared/widgets/adaptive_conversation_recording_test.dart @@ -0,0 +1,149 @@ +import 'package:buzz/features/channels/voice_note_composer_recorder.dart'; +import 'package:buzz/features/channels/voice_note_recording.dart'; +import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; +import 'package:buzz/shared/widgets/app_route_observer.dart'; +import 'package:flutter/material.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:buzz/shared/widgets/modal_presentation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +void main() { + for (final rootSheet in [false, true]) { + testWidgets('covering route cancels recording (root sheet: $rootSheet)', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(1000, 700); + addTearDown(tester.view.reset); + final pane = ConversationPaneController(); + final otherPane = ConversationPaneController(); + final recording = ValueNotifier(true); + addTearDown(pane.dispose); + addTearDown(otherPane.dispose); + addTearDown(recording.dispose); + final recorder = _Recorder(); + var cancellations = 0; + var reveals = 0; + void onReveal() => reveals++; + late BuildContext detailContext; + pane.open('channel', (context) { + detailContext = context; + return Scaffold( + body: ValueListenableBuilder( + valueListenable: recording, + builder: (_, active, _) => active + ? VoiceNoteComposerRecorder( + onCancel: () { + cancellations++; + recording.value = false; + }, + onRecorded: (_) => + fail('Covered recording must be discarded'), + ) + : const Text('Composer restored'), + ), + ); + }); + await tester.pumpWidget( + ProviderScope( + overrides: [ + voiceNoteRecorderFactoryProvider.overrideWithValue(() => recorder), + ], + child: MaterialApp( + navigatorObservers: [appRouteObserver], + home: Stack( + children: [ + AdaptiveConversationPane( + controller: pane, + strip: const FoldStrip( + side: FoldStripSide.right, + rect: Rect.fromLTWH(924, 0, 76, 700), + topClearance: 110, + bottomClearance: 0, + isClearanceEstimated: true, + ), + list: const Text('Channels'), + ), + Offstage( + child: AdaptiveConversationPane( + controller: otherPane, + list: const Text('Other tab'), + ), + ), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(recorder.started, isTrue); + expect(recorder.cancelled, isFalse); + final route = ModalRoute.of(detailContext)!; + appRouteObserver.addRevealListener(route, onReveal); + addTearDown(() => appRouteObserver.removeRevealListener(route, onReveal)); + final nested = Navigator.of(detailContext); + expect(nested, isNot(Navigator.of(detailContext, rootNavigator: true))); + + // Folding retains the recorder; only a covering route should cancel it. + tester.view.physicalSize = const Size(400, 700); + await tester.pumpAndSettle(); + tester.view.physicalSize = const Size(1000, 700); + await tester.pumpAndSettle(); + expect(cancellations, 0); + expect(recorder.cancelled, isFalse); + + if (rootSheet) { + showBuzzModalBottomSheet( + context: detailContext, + builder: (_) => const Text('Channel details'), + ); + } else { + nested.push( + MaterialPageRoute( + builder: (_) => const Scaffold(body: Text('Channel details')), + ), + ); + } + await tester.pumpAndSettle(); + expect(find.text('Channel details'), findsOneWidget); + expect(cancellations, 1); + expect(recorder.cancelled, isTrue); + expect(recorder.disposed, isTrue); + expect( + find.byType(VoiceNoteComposerRecorder, skipOffstage: false), + findsNothing, + ); + + Navigator.of(detailContext, rootNavigator: rootSheet).pop(); + await tester.pumpAndSettle(); + expect(find.text('Composer restored'), findsOneWidget); + expect(reveals, rootSheet ? 0 : 1); + expect(cancellations, 1); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + } +} + +class _Recorder implements VoiceNoteRecorder { + bool started = false; + bool cancelled = false; + bool disposed = false; + + @override + Stream get levels => const Stream.empty(); + + @override + Future start() async => started = true; + + @override + Future cancel() async => cancelled = true; + + @override + Future dispose() async => disposed = true; + + @override + Future stop() async => + throw StateError('Unexpected save'); +} diff --git a/mobile/test/shared/widgets/buzz_setting_menu_test.dart b/mobile/test/shared/widgets/buzz_setting_menu_test.dart index 22f907c3a6..a864e9b395 100644 --- a/mobile/test/shared/widgets/buzz_setting_menu_test.dart +++ b/mobile/test/shared/widgets/buzz_setting_menu_test.dart @@ -91,6 +91,16 @@ void main() { SemanticsData option(String key) => tester.getSemantics(find.byKey(Key(key))).getSemanticsData(); expect(option('high').flagsCollection.isChecked, CheckedState.isTrue); + final check = find.descendant( + of: find.byKey(const Key('high')), + matching: find.byIcon(Icons.check), + ); + final label = find.descendant( + of: find.byKey(const Key('high')), + matching: find.text('High'), + ); + expect(tester.getCenter(check).dx, lessThan(tester.getTopLeft(label).dx)); + expect(option('low').flagsCollection.isChecked, CheckedState.isFalse); handle.dispose(); }); diff --git a/mobile/test/shared/widgets/frosted_app_bar_test.dart b/mobile/test/shared/widgets/frosted_app_bar_test.dart index a0c1d463d8..552c9f4003 100644 --- a/mobile/test/shared/widgets/frosted_app_bar_test.dart +++ b/mobile/test/shared/widgets/frosted_app_bar_test.dart @@ -1,5 +1,9 @@ +import 'package:flutter/services.dart'; +import 'package:duo_kit/duo_kit.dart'; +import 'package:buzz/shared/widgets/duo_toolbar.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/frosted_app_bar.dart'; +import 'package:buzz/shared/widgets/frosted_scaffold.dart'; import 'package:buzz/shared/widgets/frosted_scroll_under_scope.dart'; import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; @@ -10,6 +14,298 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; void main() { + testWidgets('Duo uses native pane treatment while title stays in content', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + try { + for (final left in [false, true]) { + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: DuoToolbarScope( + active: true, + strip: FoldStrip( + side: left ? FoldStripSide.left : FoldStripSide.right, + rect: Rect.fromLTWH(left ? 0 : 700, 0, 100, 600), + topClearance: 170, + bottomClearance: 0, + isClearanceEstimated: true, + ), + contentInsets: EdgeInsets.only( + left: left ? 100 : 0, + right: left ? 0 : 100, + ), + child: const FrostedScaffold( + appBar: FrostedAppBar( + nativeTitle: 'Solo', + nativeLargeTitle: true, + ), + body: SizedBox.expand(key: ValueKey('pane-body')), + ), + ), + ), + ), + ); + await tester.pump(); + expect(find.byType(BackdropFilter), findsNothing); + final header = tester.getRect(find.byType(IosNavigationBar)); + expect(header.left, 0); + expect(header.right, 800); + expect( + tester + .widget(find.byType(IosNavigationBar)) + .titleInsets, + EdgeInsets.only(left: left ? 100 : 0, right: left ? 0 : 100), + ); + final body = tester.getRect(find.byKey(const ValueKey('pane-body'))); + expect(body.left, left ? 100 : 0); + expect(body.right, left ? 800 : 700); + } + } finally { + debugDefaultTargetPlatformOverride = null; + } + }); + + testWidgets('Duo keeps list actions in header and profile on aligned rail', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final active = ValueNotifier(true); + final hasStrip = ValueNotifier(true); + final listHeader = ValueNotifier(false); + addTearDown(listHeader.dispose); + addTearDown(active.dispose); + addTearDown(hasStrip.dispose); + var presses = 0; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + builder: (context, child) => IosNavigationMetricsHost( + child: MediaQuery( + // The detail pane can be narrower than its window. + data: MediaQuery.of(context).copyWith(size: const Size(400, 600)), + child: child!, + ), + ), + theme: AppTheme.light(), + home: ListenableBuilder( + listenable: Listenable.merge([active, hasStrip, listHeader]), + builder: (context, _) => DuoToolbarScope( + active: active.value, + strip: hasStrip.value + ? const FoldStrip( + side: FoldStripSide.right, + rect: Rect.fromLTWH(700, 0, 100, 600), + topClearance: 170, + bottomClearance: 0, + isClearanceEstimated: true, + ) + : null, + child: Stack( + children: [ + FrostedAppBar( + nativeLargeTitle: listHeader.value, + nativeLeading: IosNavigationAction( + label: 'Community', + keepInHeaderOnDuo: !listHeader.value, + onPressed: () => presses++, + ), + nativeActions: [ + IosNavigationAction( + label: 'Search', + keepInHeaderOnDuo: true, + onPressed: () => presses++, + ), + IosNavigationAction( + label: 'Inbox', + keepInHeaderOnDuo: true, + onPressed: () => presses++, + ), + IosNavigationAction( + label: 'Profile', + onPressed: () => presses++, + ), + ], + ), + ], + ), + ), + ), + ), + ), + ); + await tester.pump(); + for (final (index, label) in ['Profile'].indexed) { + final control = find.byKey(ValueKey('duo-toolbar-$label')); + expect(tester.getTopLeft(control), Offset(694, 110 + index * 60)); + expect(tester.getSize(control).height, 60); + final view = tester.widget( + find.descendant(of: control, matching: find.byType(UiKitView)), + ); + expect(view.creationParams, containsPair('standaloneControl', true)); + await _nativeAction(tester, control, 910 + index, 'leading'); + } + expect(presses, 1); + final header = tester + .widgetList(find.byType(IosNavigationBar)) + .singleWhere((bar) => !bar.standaloneControl); + expect(header.horizontalControls, isTrue); + + expect(header.alwaysFrosted, isTrue); + expect(find.byType(BackdropFilter), findsNothing); + expect(tester.getSize(find.byWidget(header)).height, 68); + expect(frostedAppBarHeight(tester.element(find.byWidget(header))), 68); + expect(header.centerTitleInPane, isTrue); + expect(header.leading!.label, 'Community'); + expect(header.actions.map((action) => action.label), ['Search', 'Inbox']); + listHeader.value = true; + await tester.pump(); + final listNavigation = tester.widget( + find.byType(IosNavigationBar).first, + ); + expect(listNavigation.horizontalControls, isTrue); + expect(listNavigation.largeTitle, isTrue); + expect(listNavigation.leading, isNull); + listHeader.value = false; + await tester.pump(); + + final toolbarContext = tester.element(find.byType(FrostedAppBar)); + final view = View.of(toolbarContext); + final windowSize = view.physicalSize / view.devicePixelRatio; + IosNavigationMetrics.updateRail(toolbarContext, { + 'centerX': 740, + 'topClearance': 205, + 'windowWidth': windowSize.width, + 'windowHeight': windowSize.height, + }); + await tester.pump(); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Profile'))).dx, + 684, + ); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Profile'))).dy, + 217, + ); + // A measurement from another pose must not move the current controls. + IosNavigationMetrics.updateRail(toolbarContext, { + 'centerX': 500, + 'topClearance': 300, + 'windowWidth': windowSize.height, + 'windowHeight': windowSize.width, + }); + await tester.pump(); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Profile'))).dx, + 694, + ); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Profile'))).dy, + 110, + ); + active.value = false; + await tester.pump(); + expect(find.byKey(const ValueKey('duo-toolbar-Profile')), findsNothing); + active.value = true; + hasStrip.value = false; + await tester.pump(); + expect(find.byType(IosNavigationBar), findsOneWidget); + final restored = tester.widget( + find.byType(IosNavigationBar), + ); + expect(restored.centerTitleInPane, isFalse); + expect(find.byKey(const ValueKey('duo-navigation-backdrop')), findsNothing); + expect(restored.leading!.label, 'Community'); + expect(restored.actions.map((action) => action.label), [ + 'Search', + 'Inbox', + 'Profile', + ]); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('Duo Back follows pushed routes and action menus remain usable', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final navigator = GlobalKey(); + var chosen = false; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + navigatorKey: navigator, + theme: AppTheme.light(), + builder: (context, child) => DuoToolbarScope( + strip: const FoldStrip( + side: FoldStripSide.right, + rect: Rect.fromLTWH(700, 0, 100, 600), + topClearance: 170, + bottomClearance: 0, + isClearanceEstimated: true, + ), + active: true, + child: child!, + ), + home: const Stack(children: [FrostedAppBar(nativeTitle: 'Home')]), + ), + ), + ); + navigator.currentState!.push( + MaterialPageRoute( + builder: (_) => Stack( + children: [ + FrostedAppBar( + nativeTitle: 'Conversation', + nativeActions: [ + IosNavigationAction( + label: 'Options', + children: [ + IosNavigationAction( + label: 'Choose assistant', + onPressed: () => chosen = true, + ), + ], + ), + ], + ), + ], + ), + ), + ); + await tester.pumpAndSettle(); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Back'))).dy, + 110, + ); + expect( + tester.getTopLeft(find.byKey(const ValueKey('duo-toolbar-Options'))).dy, + 170, + ); + await _nativeAction( + tester, + find.byKey(const ValueKey('duo-toolbar-Options')), + 920, + 'leading.0', + ); + expect(chosen, isTrue); + await _nativeAction( + tester, + find.byKey(const ValueKey('duo-toolbar-Back')), + 921, + 'leading', + ); + await tester.pumpAndSettle(); + expect(navigator.currentState!.canPop(), isFalse); + expect(find.byKey(const ValueKey('duo-toolbar-Back')), findsNothing); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }); + testWidgets('iOS conversations request a backdrop before scrolling', ( tester, ) async { @@ -357,3 +653,28 @@ void main() { debugDefaultTargetPlatformOverride = null; }); } + +Future _nativeAction( + WidgetTester tester, + Finder control, + int id, + String action, +) async { + final channel = MethodChannel('buzz/ios_navigation_bar/$id'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (_) async => null, + ); + tester + .widget( + find.descendant(of: control, matching: find.byType(UiKitView)), + ) + .onPlatformViewCreated!(id); + await tester.pump(); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall(MethodCall('action', action)), + (_) {}, + ); + await tester.pump(); +} diff --git a/mobile/test/shared/widgets/ios_navigation_bar_test.dart b/mobile/test/shared/widgets/ios_navigation_bar_test.dart index 814cd6e5ab..2f487e1fd6 100644 --- a/mobile/test/shared/widgets/ios_navigation_bar_test.dart +++ b/mobile/test/shared/widgets/ios_navigation_bar_test.dart @@ -64,6 +64,31 @@ void main() { find.byKey(const ValueKey('navigation-header-avatar-settings')), ); expect(settingsOpened, 1); + await tester.pumpWidget( + _testApp( + home: const MediaQuery( + data: MediaQueryData(), + child: SizedBox( + width: 951, + height: 128, + child: IosNavigationBar( + title: 'Alice', + centerTitleInPane: true, + titleAvatars: [IosNavigationAction(label: 'Alice')], + ), + ), + ), + ), + ); + final paneParams = + tester.widget(find.byType(UiKitView)).creationParams! + as Map; + expect(paneParams['portraitTopPadding'], 12); + expect( + tester.getTopLeft(find.byType(DmHeaderPortrait)).dy - + tester.getTopLeft(find.byType(UiKitView)).dy, + 12, + ); await tester.pumpWidget(const SizedBox()); debugDefaultTargetPlatformOverride = null; }, diff --git a/mobile/test/shared/widgets/modal_presentation_test.dart b/mobile/test/shared/widgets/modal_presentation_test.dart index bc9560f8b3..db7944eef3 100644 --- a/mobile/test/shared/widgets/modal_presentation_test.dart +++ b/mobile/test/shared/widgets/modal_presentation_test.dart @@ -1,3 +1,6 @@ +import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:buzz/shared/widgets/ios_navigation_bar.dart'; import 'package:buzz/shared/widgets/concentric_sheet_surface.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/modal_presentation.dart'; @@ -8,6 +11,105 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { + testWidgets('open sheet follows folding without losing its draft or Close', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + addTearDown(() => debugDefaultTargetPlatformOverride = null); + for (final startWide in [true, false]) { + void posture(bool wide) { + tester.view.physicalSize = wide + ? const Size(951, 669) + : const Size(390, 844); + tester.view.padding = wide + ? const FakeViewPadding(right: 76) + : const FakeViewPadding(bottom: 34); + tester.view.viewPadding = tester.view.padding; + } + + posture(startWide); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: AppTheme.light(), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showBuzzModalBottomSheet( + context: context, + title: 'Draft', + useSafeArea: true, + isDismissible: false, + enableDrag: false, + builder: (_) => const SizedBox( + height: 200, + child: TextField(key: ValueKey('fold-draft')), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const ValueKey('fold-draft')), + 'Keep this edit', + ); + for (final wide in [!startWide, startWide]) { + posture(wide); + await tester.pumpAndSettle(); + expect(find.text('Keep this edit'), findsOneWidget); + expect( + find.byKey(const ValueKey('duo-toolbar-Close Draft')), + wide ? findsOneWidget : findsNothing, + ); + expect( + find.byKey(const ValueKey('buzz-sheet-ios-glass-close')), + wide ? findsNothing : findsOneWidget, + ); + if (wide) { + expect( + tester.getSize(find.byKey(const ValueKey('fold-draft'))).width, + greaterThan(800), + ); + } + } + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pumpAndSettle(); + if (startWide) { + tester + .widget( + find.descendant( + of: find.byKey(const ValueKey('duo-toolbar-Close Draft')), + matching: find.byType(IosNavigationBar), + ), + ) + .leading! + .onPressed!(); + } else { + tester + .widget( + find.byKey(const ValueKey('buzz-sheet-ios-glass-close')), + ) + .onPressed!(); + } + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('fold-draft')), + findsNothing, + reason: 'startWide=$startWide', + ); + await tester.pumpWidget(const SizedBox()); + } + debugDefaultTargetPlatformOverride = null; + }); + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { for (final titled in [false, true]) { for (final ownSafeArea in [false, true]) { @@ -90,6 +192,63 @@ void main() { } } + for (final left in [false, true]) { + for (final width in [480.0, 900.0]) { + testWidgets( + 'bounded sheet localizes rail inset left=$left width=$width', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.physicalSize = const Size(951, 669); + tester.view.devicePixelRatio = 1; + final padding = FakeViewPadding( + left: left ? 76 : 0, + right: left ? 0 : 76, + bottom: 21, + ); + tester.view.padding = padding; + tester.view.viewPadding = padding; + addTearDown(() { + tester.view.reset(); + debugDefaultTargetPlatformOverride = null; + }); + EdgeInsets? local; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.light(), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => showBuzzModalBottomSheet( + context: context, + useDuoFullWidth: false, + constraints: BoxConstraints(maxWidth: width), + showCloseButton: false, + builder: (context) { + local = MediaQuery.paddingOf(context); + return const SizedBox( + height: 100, + width: double.infinity, + ); + }, + ), + child: const Text('Open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + final overlap = (76 - (951 - width) / 2).clamp(0.0, double.infinity); + expect(local!.left, left ? overlap : 0); + expect(local!.right, left ? 0 : overlap); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); + } + } + Border sheetHeaderBorder(WidgetTester tester) { final decoration = tester @@ -157,6 +316,56 @@ void main() { await tester.pump(); expect(find.byType(UiKitView), findsOneWidget); + final nativeView = tester.widget(find.byType(UiKitView)); + expect( + nativeView.creationParams, + containsPair('independentCorners', true), + ); + const viewChannel = MethodChannel('buzz/concentric_sheet_surface/73'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + viewChannel, + (call) async => call.method == 'getCornerRadii' + ? { + 'topLeft': 24.0, + 'topRight': 24.0, + 'bottomLeft': 62.0, + 'bottomRight': 48.0, + } + : null, + ); + nativeView.onPlatformViewCreated!(73); + await tester.pumpAndSettle(); + BorderRadius clipRadius() => + tester + .widget( + find.byKey( + const ValueKey('concentric-sheet-content-clip'), + ), + ) + .borderRadius + as BorderRadius; + expect(clipRadius().bottomLeft, const Radius.circular(62)); + expect(clipRadius().bottomRight, const Radius.circular(48)); + // Rotation/folding can change each corner independently. + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + viewChannel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('cornerRadiiChanged', { + 'topLeft': 48.0, + 'topRight': 62.0, + 'bottomLeft': 24.0, + 'bottomRight': 24.0, + }), + ), + (_) {}, + ); + await tester.pump(); + expect(clipRadius().topRight, const Radius.circular(62)); + expect(clipRadius().bottomLeft, const Radius.circular(24)); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + viewChannel, + null, + ); expect( tester.widget(find.byType(UiKitView)).hitTestBehavior, PlatformViewHitTestBehavior.translucent,