diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index 401b65d7f0..de37344b11 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -20,6 +20,7 @@ C0AF00000000000000000001 /* NativeConfirmationDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AF00000000000000000002 /* NativeConfirmationDialog.swift */; }; C0AF00000000000000000021 /* NativePresenceMenu.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AF00000000000000000022 /* NativePresenceMenu.swift */; }; C0AF00000000000000000011 /* NativeAddMembersSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AF00000000000000000012 /* NativeAddMembersSheet.swift */; }; + D0AF00000000000000000011 /* NativeChannelActionsSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0AF00000000000000000012 /* NativeChannelActionsSheet.swift */; }; C0AF00000000000000000071 /* NativeCreateChannelSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AF00000000000000000072 /* NativeCreateChannelSheet.swift */; }; BZZ00000000000000000001 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = BZZ00000000000000000006 /* NotificationService.swift */; }; BZZ00000000000000000002 /* NotificationService.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = BZZ00000000000000000009 /* NotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; @@ -122,6 +123,7 @@ C0AF00000000000000000002 /* NativeConfirmationDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeConfirmationDialog.swift; sourceTree = ""; }; C0AF00000000000000000022 /* NativePresenceMenu.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativePresenceMenu.swift; sourceTree = ""; }; C0AF00000000000000000012 /* NativeAddMembersSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAddMembersSheet.swift; sourceTree = ""; }; + D0AF00000000000000000012 /* NativeChannelActionsSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeChannelActionsSheet.swift; sourceTree = ""; }; C0AF00000000000000000072 /* NativeCreateChannelSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeCreateChannelSheet.swift; sourceTree = ""; }; BZZ00000000000000000006 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = ""; }; BZZ00000000000000000007 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -334,6 +336,7 @@ C0AF00000000000000000002 /* NativeConfirmationDialog.swift */, C0AF00000000000000000022 /* NativePresenceMenu.swift */, C0AF00000000000000000012 /* NativeAddMembersSheet.swift */, + D0AF00000000000000000012 /* NativeChannelActionsSheet.swift */, C0AF00000000000000000072 /* NativeCreateChannelSheet.swift */, 4A71C01A2F40D00100A17E01 /* NativeProfileTextEditor.swift */, F84390190000000000000002 /* NativeStatusEditor.swift */, @@ -687,6 +690,7 @@ C0AF00000000000000000001 /* NativeConfirmationDialog.swift in Sources */, C0AF00000000000000000021 /* NativePresenceMenu.swift in Sources */, C0AF00000000000000000011 /* NativeAddMembersSheet.swift in Sources */, + D0AF00000000000000000011 /* NativeChannelActionsSheet.swift in Sources */, C0AF00000000000000000071 /* NativeCreateChannelSheet.swift in Sources */, 4A71C0192F40D00100A17E01 /* NativeProfileTextEditor.swift in Sources */, F84390190000000000000001 /* NativeStatusEditor.swift in Sources */, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index e75695ccf7..332d65a482 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -48,6 +48,7 @@ import os.log private var nativeAttachmentPopoverCoordinator: NativeAttachmentPopoverCoordinator? private var nativeEmojiPickerCoordinator: NativeEmojiPickerCoordinator? private var nativeCreateChannelSheetCoordinator: NativeCreateChannelSheetCoordinator? + private var nativeChannelActionsSheetCoordinator: NativeChannelActionsSheetCoordinator? private var nativeAddMembersSheetCoordinator: NativeAddMembersSheetCoordinator? private var nativeConfirmationDialogCoordinator: NativeConfirmationDialogCoordinator? private var nativeProfileSetupCoordinator: NativeProfileSetupCoordinator? @@ -346,6 +347,11 @@ import os.log )?.viewController ) + nativeChannelActionsSheetCoordinator = NativeChannelActionsSheetCoordinator( + messenger: messenger, + parentViewController: engineBridge.pluginRegistry.registrar(forPlugin: "BuzzNativeChannelActionsSheet")?.viewController + ) + nativeAddMembersSheetCoordinator = NativeAddMembersSheetCoordinator( messenger: messenger, parentViewController: engineBridge.pluginRegistry.registrar( diff --git a/mobile/ios/Runner/NativeChannelActionsSheet.swift b/mobile/ios/Runner/NativeChannelActionsSheet.swift new file mode 100644 index 0000000000..02b3976a79 --- /dev/null +++ b/mobile/ios/Runner/NativeChannelActionsSheet.swift @@ -0,0 +1,233 @@ +import Flutter +import UIKit + +/// Presents channel actions above the complete Flutter/native view hierarchy. +final class NativeChannelActionsSheetCoordinator: NSObject, UIAdaptivePresentationControllerDelegate { + private let channel: FlutterMethodChannel + private weak var parent: UIViewController? + private var navigation: UINavigationController? + private var pending: FlutterResult? + private var session: String? + private var finishing = false + private var contentEngine: FlutterEngine? + private var contentChannel: FlutterMethodChannel? + private var payload: [String: Any] = [:] + private var readinessTimeout: DispatchWorkItem? + private var contentReady = false + private var needsContentUpdate = false + + init(messenger: FlutterBinaryMessenger, parentViewController: UIViewController?) { + channel = FlutterMethodChannel(name: "buzz/channel_actions_sheet", binaryMessenger: messenger) + parent = parentViewController + super.init() + channel.setMethodCallHandler { [weak self] call, result in + guard let self else { result(nil); return } + guard let data = call.arguments as? [String: Any], let request = data["session"] as? String else { + result(FlutterError(code: "invalid_arguments", message: "Missing channel actions session", details: nil)); return + } + switch call.method { + case "update": + if request == self.session { + self.payload = data + if self.contentReady { + self.contentChannel?.invokeMethod("update", arguments: data) + } else { + self.needsContentUpdate = true + } + } + result(nil) + case "dismiss": + if request == self.session { self.finish(nil) } + result(nil) + case "present": + guard self.pending == nil else { result(FlutterError(code: "busy", message: "Channel actions are already open", details: nil)); return } + var presenter = self.parent ?? UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + .filter { $0.activationState == .foregroundActive }.flatMap(\.windows).first(where: \.isKeyWindow)?.rootViewController + while let next = presenter?.presentedViewController { presenter = next } + guard let presenter, presenter.view.window != nil, !presenter.isBeingDismissed else { + result(FlutterError(code: "unavailable", message: "Cannot present channel actions", details: nil)); return + } + self.payload = data + self.session = request + self.pending = result + self.finishing = false + guard self.prepareContent(), let engine = self.contentEngine else { + self.resolve(FlutterError(code: "engine_failed", message: "Could not start channel settings", details: nil)) + return + } + // Supply the model without loading a second account. + let flutter = FlutterViewController(engine: engine, nibName: nil, bundle: nil) + let content = NativeChannelContentController(flutter: flutter, data: data) + content.close = { [weak self] in self?.finish(nil) } + let navigation = UINavigationController(rootViewController: content) + navigation.modalPresentationStyle = .formSheet + navigation.overrideUserInterfaceStyle = data["dark"] as? Bool == true ? .dark : .light + navigation.preferredContentSize = CGSize(width: 540, height: max(320, presenter.view.bounds.height - 48)) + navigation.sheetPresentationController?.detents = [.large()] + #if canImport(UIKit, _version: 9127.0.85) + if #available(iOS 27.0, *) { navigation.sheetPresentationController?.preferredPlacement = .center } + #endif + self.navigation = navigation + let timeout = DispatchWorkItem { [weak self] in + guard let self, self.session == request else { return } + self.finish(FlutterError(code: "content_timeout", message: "Channel settings did not load", details: nil)) + } + self.readinessTimeout = timeout + DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: timeout) + presenter.present(navigation, animated: !UIAccessibility.isReduceMotionEnabled) { + navigation.presentationController?.delegate = self + } + default: result(FlutterMethodNotImplemented) + } + } + } + + /// Start only for an eligible presentation, never at app launch or dismissal. + /// The app's camera, audio, storage and account plugins are not used here. + @discardableResult + private func prepareContent() -> Bool { + if contentEngine != nil { return true } + let engine = FlutterEngine(name: "channel-sheet", project: nil, allowHeadlessExecution: true) + guard engine.run(withEntrypoint: "channelSheetMain", libraryURI: "package:buzz/features/channels/channel_actions_sheet.dart") else { + engine.destroyContext() + return false + } + contentEngine = engine + // Flutter requires run() before installing message handlers. + let bridge = FlutterMethodChannel(name: "buzz/channel_sheet_content", binaryMessenger: engine.binaryMessenger) + contentChannel = bridge + bridge.setMethodCallHandler { [weak self, weak engine] call, reply in + guard let self, let engine, self.contentEngine === engine else { reply(nil); return } + switch call.method { + case "initial": + self.needsContentUpdate = false + reply(self.session == nil ? nil : self.payload) + case "ready": + guard self.session != nil else { reply(nil); return } + self.contentReady = true + self.readinessTimeout?.cancel() + if self.needsContentUpdate { + self.contentChannel?.invokeMethod("update", arguments: self.payload) + self.needsContentUpdate = false + } + (self.navigation?.viewControllers.first as? NativeChannelContentController)?.reveal() + reply(nil) + case "select": + reply(nil) + self.finish(call.arguments as? String) + default: reply(FlutterMethodNotImplemented) + } + } + return true + } + + private func finish(_ action: Any?) { + guard !finishing, let navigation else { return } + finishing = true + navigation.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [weak self] in self?.resolve(action) } + } + + func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { + guard presentationController.presentedViewController === navigation else { return } + resolve(nil) + } + + private func resolve(_ action: Any?) { + let callback = pending + pending = nil + navigation = nil + readinessTimeout?.cancel() + readinessTimeout = nil + contentChannel?.setMethodCallHandler(nil) + contentChannel = nil + contentEngine?.destroyContext() + contentEngine = nil + contentReady = false + needsContentUpdate = false + payload = [:] + session = nil + finishing = false + callback?(action) + } + + deinit { + readinessTimeout?.cancel() + contentChannel?.setMethodCallHandler(nil) + contentEngine?.destroyContext() + } +} + +/// UIKit owns only presentation and Close. Buzz's Flutter widgets render content. +private final class NativeChannelContentController: UIViewController { + var close: (() -> Void)? + private let flutter: FlutterViewController + private let background: UIColor + private let loading = UIActivityIndicatorView(style: .medium) + // Flutter scrollables receive raw touches, not UIScrollView pan recognizers. + // Claim drags in the content without cancelling those touches, so UIKit's + // sheet pan waits instead of moving the sheet or cancelling Flutter's drag. + private let contentPan = UIPanGestureRecognizer() + private var coordinatedPans = Set() + + init(flutter: FlutterViewController, data: [String: Any]) { + self.flutter = flutter + let colors = data["colors"] as? [String: Any] + let argb = (colors?["container"] as? NSNumber)?.uint32Value ?? 0xfff2f2f7 + background = UIColor(red: CGFloat((argb >> 16) & 255) / 255, + green: CGFloat((argb >> 8) & 255) / 255, + blue: CGFloat(argb & 255) / 255, + alpha: CGFloat((argb >> 24) & 255) / 255) + super.init(nibName: nil, bundle: nil) + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = background + navigationItem.leftBarButtonItem = UIBarButtonItem(systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close?() }) + let appearance = UINavigationBarAppearance() + appearance.configureWithOpaqueBackground() + appearance.backgroundColor = background + appearance.shadowColor = .clear + navigationItem.standardAppearance = appearance + navigationItem.scrollEdgeAppearance = appearance + addChild(flutter) + flutter.view.translatesAutoresizingMaskIntoConstraints = false + flutter.view.backgroundColor = background + view.addSubview(flutter.view) + contentPan.cancelsTouchesInView = false + contentPan.delaysTouchesBegan = false + contentPan.delaysTouchesEnded = false + flutter.view.addGestureRecognizer(contentPan) + NSLayoutConstraint.activate([ + flutter.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + flutter.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + flutter.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + flutter.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + flutter.didMove(toParent: self) + loading.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(loading) + NSLayoutConstraint.activate([ + loading.centerXAnchor.constraint(equalTo: view.centerXAnchor), + loading.centerYAnchor.constraint(equalTo: view.centerYAnchor), + ]) + loading.startAnimating() + } + override func viewDidLayoutSubviews() { + super.viewDidLayoutSubviews() + // These are ancestors only: the navigation bar remains available for + // UIKit's own swipe dismissal, and Flutter keeps all of its touch events. + var ancestor = flutter.view.superview + while let current = ancestor { + for case let pan as UIPanGestureRecognizer in current.gestureRecognizers ?? [] { + if coordinatedPans.insert(ObjectIdentifier(pan)).inserted { + pan.require(toFail: contentPan) + } + } + if current === navigationController?.presentationController?.containerView { break } + ancestor = current.superview + } + } + + func reveal() { loading.stopAnimating() } +} diff --git a/mobile/lib/features/channels/channel_actions_sheet.dart b/mobile/lib/features/channels/channel_actions_sheet.dart index b429a1861e..5102b14309 100644 --- a/mobile/lib/features/channels/channel_actions_sheet.dart +++ b/mobile/lib/features/channels/channel_actions_sheet.dart @@ -1,13 +1,18 @@ import 'package:buzz/shared/widgets/feedback_snackbar.dart'; + import 'dart:async'; +import 'dart:convert'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:duo_kit/duo_kit.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:flutter/services.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:buzz/shared/theme/buzz_icons.dart'; import '../../shared/clipboard_utils.dart'; +import '../../shared/relay/relay.dart'; import '../../shared/identity_archives/identity_archives.dart'; import '../../shared/identity_names/identity_names_provider.dart'; import 'dm_channel_labels.dart'; @@ -24,6 +29,7 @@ import '../../shared/widgets/frosted_scaffold.dart'; import '../../shared/widgets/ios_glass_navigation_button.dart'; import '../../shared/widgets/tabler_star_icon.dart'; import '../../shared/widgets/modal_presentation.dart'; +import '../../shared/widgets/duo_toolbar.dart'; import 'channel.dart'; import 'add_members_sheet.dart'; import 'channel_identity_names_provider.dart'; @@ -40,6 +46,8 @@ import '../../shared/read_state/read_state_time.dart'; import '../../shared/widgets/covered_route_keyboard_insets.dart'; part 'channel_details_page.dart'; +part 'native_channel_actions.dart'; +part 'native_channel_sheet_app.dart'; /// Opens the mobile channel actions sheet and returns whether its parent page /// should close after a successful lifecycle action. @@ -49,21 +57,69 @@ Future showChannelActionsSheet({ required bool isUnread, VoidCallback? onMarkRead, String? sectionId, -}) => showBuzzModalBottomSheet( - context: context, - isScrollControlled: true, - showDragHandle: true, - constraints: BoxConstraints( - maxWidth: 640, - maxHeight: MediaQuery.sizeOf(context).height * 0.7, - ), - builder: (_) => ChannelActionsSheet( +}) { + final native = _usesNativeChannelSheet(context); + Widget content(BuildContext context) => ChannelActionsSheet( channel: channel, isUnread: isUnread, onMarkRead: onMarkRead, sectionId: sectionId, - ), -); + nativePresentation: native, + ); + if (native) return _showNativeChannelSheet(context, content); + return _showChannelLongPressSheet(context: context, builder: content); +} + +bool _usesNativeChannelSheet(BuildContext context) { + final view = View.of(context); + final size = view.physicalSize / view.devicePixelRatio; + return defaultTargetPlatform == TargetPlatform.iOS && + (DuoToolbarScope.maybeOf(context)?.strip ?? + FoldGeometry.of(context).strip) != + null && + size.width > size.height && + !isCompactDuoWindow(context); +} + +// Keep the result alive after retiring the invisible route for relay work. +class _NativeChannelSheetRoute extends PageRouteBuilder { + _NativeChannelSheetRoute(WidgetBuilder builder) + : super( + opaque: false, + barrierColor: null, + transitionDuration: Duration.zero, + reverseTransitionDuration: Duration.zero, + pageBuilder: (context, _, _) => builder(context), + ); + + Future? lifecycleResult; +} + +Future _showNativeChannelSheet( + BuildContext context, + WidgetBuilder builder, +) async { + final route = _NativeChannelSheetRoute(builder); + final result = await Navigator.of(context, rootNavigator: true).push(route); + return route.lifecycleResult == null ? result : await route.lifecycleResult; +} + +// Other postures retain the existing bottom-sheet presentation. +Future _showChannelLongPressSheet({ + required BuildContext context, + required WidgetBuilder builder, +}) { + return showBuzzModalBottomSheet( + context: context, + isScrollControlled: true, + showDragHandle: true, + constraints: BoxConstraints( + maxWidth: 640, + maxHeight: MediaQuery.sizeOf(context).height * 0.7, + ), + builder: builder, + ); +} /// Mobile action sheet for channel-level read, organization, and lifecycle /// operations. @@ -74,10 +130,12 @@ class ChannelActionsSheet extends HookConsumerWidget { required this.isUnread, this.onMarkRead, this.sectionId, + this.nativePresentation = false, }); final Channel channel; final bool isUnread; + final bool nativePresentation; final VoidCallback? onMarkRead; final String? sectionId; @@ -127,6 +185,209 @@ class ChannelActionsSheet extends HookConsumerWidget { void close() => Navigator.of(context).pop(); + final groups = [ + if (!channel.isDm) ...[ + _ChannelQuickActionsRow( + isStarred: isStarred, + isUnread: isUnread, + onToggleStar: () { + close(); + final notifier = ref.read(channelStarsProvider.notifier); + isStarred + ? notifier.unstarChannel(channel.id) + : notifier.starChannel(channel.id); + }, + onToggleRead: () { + close(); + final timestamp = dateTimeToUnixSeconds(channel.lastMessageAt); + if (isUnread) { + onMarkRead?.call(); + if (timestamp != null) { + ref + .read(readStateProvider.notifier) + .markContextRead( + channel.id, + timestamp, + clearForcedMessages: true, + ); + ref + .read(channelsProvider.notifier) + .clearObservedUnreadCoveredByRead(channel.id, timestamp); + } + } else { + ref + .read(readStateProvider.notifier) + .markContextUnread(channel.id, channelId: channel.id); + } + }, + ), + const SizedBox(height: Grid.xs), + ], + SheetActionSection( + children: [ + if (!channel.isDm) + _ChannelSheetRow( + leading: const Icon(BuzzIcons.folderInput), + title: const Text('Move to section…'), + onTap: () async { + final pageContext = Navigator.of( + context, + rootNavigator: true, + ).context; + close(); + await _showMoveSectionSheet( + pageContext, + ref, + channel: channel, + sectionId: sectionId, + ); + }, + ), + _ChannelSheetRow( + leading: Icon(isMuted ? BuzzIcons.bell : BuzzIcons.bellOff), + title: Text(isMuted ? 'Unmute channel' : 'Mute channel'), + onTap: () { + close(); + final notifier = ref.read(channelMutesProvider.notifier); + isMuted + ? notifier.unmuteChannel(channel.id) + : notifier.muteChannel(channel.id); + }, + ), + if (!channel.isDm) + _ChannelSheetRow( + leading: const Icon(BuzzIcons.settings), + title: const Text('Manage channel'), + onTap: () async { + final shouldClose = await showManageChannelSheet( + context: context, + channel: currentChannel, + canEditDetails: + canManageLifecycle && !currentChannel.isArchived, + onChannelUpdated: (updated) => + displayedChannel.value = updated, + ); + if (shouldClose == true && context.mounted) { + Navigator.of(context).pop(true); + } + }, + ), + ], + ), + SheetActionSection( + children: [ + _ChannelSheetRow( + leading: const Icon(BuzzIcons.copy), + title: const Text('Copy channel name'), + onTap: () { + close(); + copyToClipboard( + context, + currentChannel.name, + message: 'Channel name copied', + ); + }, + ), + _ChannelSheetRow( + leading: const Icon(BuzzIcons.hash), + title: const Text('Copy channel ID'), + onTap: () { + close(); + copyToClipboard( + context, + channel.id, + message: 'Channel ID copied', + ); + }, + ), + ], + ), + if (!channel.isDm) + SheetActionSection( + children: [ + if (channel.isMember && !channel.isArchived) + _ActionTile( + icon: BuzzIcons.logOut, + label: 'Leave channel', + destructive: true, + onTap: () => _confirmAndRun( + context, + ref, + title: 'Leave #${currentChannel.name}?', + body: 'You’ll stop receiving messages from this channel.', + confirmLabel: 'Leave', + action: () => + ref.read(channelActionsProvider).leaveChannel(channel.id), + ), + ), + if (lifecycleCapabilitiesLoading) + const _ChannelSheetRow( + enabled: false, + leading: BuzzLoadingIndicator( + size: 20, + semanticLabel: 'Loading channel actions', + ), + title: Text('Loading channel actions…'), + ) + else if (lifecycleCapabilitiesUnavailable) + const _ChannelSheetRow( + enabled: false, + leading: Icon(BuzzIcons.triangleAlert), + title: Text('Channel actions unavailable'), + ) + else ...[ + if (canArchive) + _ActionTile( + icon: BuzzIcons.archive, + label: 'Archive channel', + onTap: () => _confirmAndRun( + context, + ref, + title: 'Archive #${currentChannel.name}?', + body: 'The channel will become read-only.', + confirmLabel: 'Archive', + action: () => ref + .read(channelActionsProvider) + .archiveChannel(channel.id), + ), + ), + if (canUnarchive) + _ActionTile( + icon: BuzzIcons.archiveRestore, + label: 'Unarchive channel', + onTap: () => _confirmAndRun( + context, + ref, + title: 'Unarchive #${currentChannel.name}?', + body: 'The channel will become active again.', + confirmLabel: 'Unarchive', + action: () => ref + .read(channelActionsProvider) + .unarchiveChannel(channel.id), + ), + ), + if (canDelete) + _ActionTile( + icon: BuzzIcons.trash2, + label: 'Delete channel', + destructive: true, + onTap: () => _confirmAndRun( + context, + ref, + title: 'Delete #${currentChannel.name}?', + body: + 'This permanently deletes the channel and cannot be undone.', + confirmLabel: 'Delete', + action: () => ref + .read(channelActionsProvider) + .deleteChannel(channel.id), + ), + ), + ], + ], + ), + ]; + if (nativePresentation) return _NativeChannelActions(groups: groups); return SafeArea( top: false, child: IconTheme.merge( @@ -138,218 +399,7 @@ class ChannelActionsSheet extends HookConsumerWidget { Grid.gutter, Grid.xs, ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (!channel.isDm) ...[ - _ChannelQuickActionsRow( - isStarred: isStarred, - isUnread: isUnread, - onToggleStar: () { - close(); - final notifier = ref.read(channelStarsProvider.notifier); - isStarred - ? notifier.unstarChannel(channel.id) - : notifier.starChannel(channel.id); - }, - onToggleRead: () { - close(); - final timestamp = dateTimeToUnixSeconds( - channel.lastMessageAt, - ); - if (isUnread) { - onMarkRead?.call(); - if (timestamp != null) { - ref - .read(readStateProvider.notifier) - .markContextRead( - channel.id, - timestamp, - clearForcedMessages: true, - ); - ref - .read(channelsProvider.notifier) - .clearObservedUnreadCoveredByRead( - channel.id, - timestamp, - ); - } - } else { - ref - .read(readStateProvider.notifier) - .markContextUnread(channel.id, channelId: channel.id); - } - }, - ), - const SizedBox(height: Grid.xs), - ], - SheetActionSection( - children: [ - if (!channel.isDm) - ListTile( - leading: const Icon(BuzzIcons.folderInput), - title: const Text('Move to section…'), - onTap: () async { - final pageContext = Navigator.of( - context, - rootNavigator: true, - ).context; - close(); - await _showMoveSectionSheet( - pageContext, - ref, - channel: channel, - sectionId: sectionId, - ); - }, - ), - ListTile( - leading: Icon(isMuted ? BuzzIcons.bell : BuzzIcons.bellOff), - title: Text(isMuted ? 'Unmute channel' : 'Mute channel'), - onTap: () { - close(); - final notifier = ref.read(channelMutesProvider.notifier); - isMuted - ? notifier.unmuteChannel(channel.id) - : notifier.muteChannel(channel.id); - }, - ), - if (!channel.isDm) - ListTile( - leading: const Icon(BuzzIcons.settings), - title: const Text('Manage channel'), - onTap: () async { - final shouldClose = await showManageChannelSheet( - context: context, - channel: currentChannel, - canEditDetails: - canManageLifecycle && !currentChannel.isArchived, - onChannelUpdated: (updated) => - displayedChannel.value = updated, - ); - if (shouldClose == true && context.mounted) { - Navigator.of(context).pop(true); - } - }, - ), - ], - ), - SheetActionSection( - children: [ - ListTile( - leading: const Icon(BuzzIcons.copy), - title: const Text('Copy channel name'), - onTap: () { - close(); - copyToClipboard( - context, - currentChannel.name, - message: 'Channel name copied', - ); - }, - ), - ListTile( - leading: const Icon(BuzzIcons.hash), - title: const Text('Copy channel ID'), - onTap: () { - close(); - copyToClipboard( - context, - channel.id, - message: 'Channel ID copied', - ); - }, - ), - ], - ), - if (!channel.isDm) - SheetActionSection( - children: [ - if (channel.isMember && !channel.isArchived) - _ActionTile( - icon: BuzzIcons.logOut, - label: 'Leave channel', - destructive: true, - onTap: () => _confirmAndRun( - context, - ref, - title: 'Leave #${currentChannel.name}?', - body: - 'You’ll stop receiving messages from this channel.', - confirmLabel: 'Leave', - action: () => ref - .read(channelActionsProvider) - .leaveChannel(channel.id), - ), - ), - if (lifecycleCapabilitiesLoading) - const ListTile( - enabled: false, - leading: BuzzLoadingIndicator( - size: 20, - semanticLabel: 'Loading channel actions', - ), - title: Text('Loading channel actions…'), - ) - else if (lifecycleCapabilitiesUnavailable) - const ListTile( - enabled: false, - leading: Icon(BuzzIcons.triangleAlert), - title: Text('Channel actions unavailable'), - ) - else ...[ - if (canArchive) - _ActionTile( - icon: BuzzIcons.archive, - label: 'Archive channel', - onTap: () => _confirmAndRun( - context, - ref, - title: 'Archive #${currentChannel.name}?', - body: 'The channel will become read-only.', - confirmLabel: 'Archive', - action: () => ref - .read(channelActionsProvider) - .archiveChannel(channel.id), - ), - ), - if (canUnarchive) - _ActionTile( - icon: BuzzIcons.archiveRestore, - label: 'Unarchive channel', - onTap: () => _confirmAndRun( - context, - ref, - title: 'Unarchive #${currentChannel.name}?', - body: 'The channel will become active again.', - confirmLabel: 'Unarchive', - action: () => ref - .read(channelActionsProvider) - .unarchiveChannel(channel.id), - ), - ), - if (canDelete) - _ActionTile( - icon: BuzzIcons.trash2, - label: 'Delete channel', - destructive: true, - onTap: () => _confirmAndRun( - context, - ref, - title: 'Delete #${currentChannel.name}?', - body: - 'This permanently deletes the channel and cannot be undone.', - confirmLabel: 'Delete', - action: () => ref - .read(channelActionsProvider) - .deleteChannel(channel.id), - ), - ), - ], - ], - ), - ], - ), + child: Column(mainAxisSize: MainAxisSize.min, children: groups), ), ), ); @@ -457,7 +507,7 @@ class _ActionTile extends StatelessWidget { final IconData icon; final String label; - final VoidCallback onTap; + final FutureOr Function()? onTap; final bool destructive; @override @@ -467,10 +517,13 @@ class _ActionTile extends StatelessWidget { label, style: destructive ? TextStyle(color: context.colors.error) : null, ), - onTap: () { - unawaited(HapticFeedback.lightImpact()); - onTap(); - }, + enabled: onTap != null, + onTap: onTap == null + ? null + : () { + unawaited(HapticFeedback.lightImpact()); + onTap!(); + }, ); } @@ -489,6 +542,7 @@ Future _confirmAndRun( final ownerNavigator = Navigator.of(sheetContext); final ownerRoute = ModalRoute.of(sheetContext); final pageContext = Navigator.of(sheetContext, rootNavigator: true).context; + final messenger = ScaffoldMessenger.maybeOf(sheetContext); final confirmed = await showBuzzDialog( context: pageContext, builder: (dialogContext) => AlertDialog( @@ -506,15 +560,25 @@ Future _confirmAndRun( ], ), ); - if (confirmed != true) return; + if (confirmed != true || !sheetContext.mounted) return; + Completer? detachedResult; try { - await action(); + // Resolve provider-backed dependencies before disposing their owner. + final pending = action(); + if (ownerRoute is _NativeChannelSheetRoute && ownerNavigator.mounted) { + detachedResult = Completer(); + ownerRoute.lifecycleResult = detachedResult.future; + ownerNavigator.removeRoute(ownerRoute); + } + await pending; + detachedResult?.complete(true); if (ownerNavigator.mounted && ownerRoute?.isCurrent == true) { ownerNavigator.pop(true); } } catch (error) { - if (!pageContext.mounted) return; - ScaffoldMessenger.of(pageContext).showFeedbackSnackBar( + detachedResult?.complete(null); + if (messenger == null || !messenger.mounted) return; + messenger.showFeedbackSnackBar( SnackBar( content: Text( 'Couldn’t ${confirmLabel.toLowerCase()} channel. Try again.', diff --git a/mobile/lib/features/channels/channel_details_page.dart b/mobile/lib/features/channels/channel_details_page.dart index b9e3e6c3af..d1d1acfdb1 100644 --- a/mobile/lib/features/channels/channel_details_page.dart +++ b/mobile/lib/features/channels/channel_details_page.dart @@ -9,7 +9,8 @@ Future showChannelDetailsPage({ required BuildContext context, required Channel channel, required String? currentPubkey, - required void Function(BuildContext context, String pubkey) onMemberTap, + required FutureOr Function(BuildContext context, String pubkey) + onMemberTap, String? sectionId, bool personalChat = false, }) => Navigator.of(context).push( @@ -32,26 +33,24 @@ Future showChannelDetailsSheet({ required BuildContext context, required Channel channel, required String? currentPubkey, - required void Function(BuildContext context, String pubkey) onMemberTap, + required FutureOr Function(BuildContext context, String pubkey) + onMemberTap, String? sectionId, bool personalChat = false, -}) => showBuzzModalBottomSheet( - context: context, - isScrollControlled: true, - showDragHandle: true, - constraints: BoxConstraints( - maxWidth: 640, - maxHeight: MediaQuery.sizeOf(context).height * 0.7, - ), - builder: (_) => ChannelDetailsPage( +}) { + final native = _usesNativeChannelSheet(context); + Widget content(BuildContext context) => ChannelDetailsPage( channel: channel, currentPubkey: currentPubkey, onMemberTap: onMemberTap, sectionId: sectionId, personalChat: personalChat, inSheet: true, - ), -); + nativePresentation: native, + ); + if (native) return _showNativeChannelSheet(context, content); + return _showChannelLongPressSheet(context: context, builder: content); +} /// Combined channel identity, membership, organization, and lifecycle page. class ChannelDetailsPage extends HookConsumerWidget { @@ -63,11 +62,13 @@ class ChannelDetailsPage extends HookConsumerWidget { this.sectionId, this.personalChat = false, this.inSheet = false, + this.nativePresentation = false, }); final Channel channel; final String? currentPubkey; - final void Function(BuildContext context, String pubkey) onMemberTap; + final FutureOr Function(BuildContext context, String pubkey) + onMemberTap; final String? sectionId; /// Solo chats are organized into Solo workspaces, not channel sections, so @@ -77,6 +78,7 @@ class ChannelDetailsPage extends HookConsumerWidget { /// Renders only the scrolling content, without the page's app bar, for a /// bottom sheet that supplies its own drag handle. final bool inSheet; + final bool nativePresentation; @override Widget build(BuildContext context, WidgetRef ref) { @@ -329,6 +331,189 @@ class ChannelDetailsPage extends HookConsumerWidget { } } + if (nativePresentation) { + Widget action( + String label, + IconData icon, + FutureOr Function()? callback, { + bool destructive = false, + }) => _ActionTile( + icon: icon, + label: label, + onTap: callback, + destructive: destructive, + ); + return _NativeChannelActions( + title: displayName, + detailsChannel: resolvedChannel, + heroAvatarUrl: counterpartProfile?.avatarUrl, + heroIsAgent: counterpartProfile?.isAgent ?? false, + memberLabel: isDirectDm ? null : memberLabel, + groups: [ + SheetActionSection( + children: [ + action(isStarred ? 'Unstar' : 'Star', BuzzIcons.star, toggleStar), + action( + isMuted ? 'Unmute' : 'Mute', + isMuted ? BuzzIcons.bell : BuzzIcons.bellOff, + toggleMute, + ), + if (!resolvedChannel.isDm) + action( + 'Edit', + BuzzIcons.pencil, + canEdit ? openManageChannel : null, + ), + ], + ), + if (!isDirectDm) + SheetActionSection( + children: [ + if (canAddMembers) + action('Add members', BuzzIcons.plus, openAddMembers), + if (membersAsync.isLoading && members.isEmpty) + action('Loading members…', BuzzIcons.loaderCircle, null) + else if (membersAsync.hasError && members.isEmpty) + action('Members unavailable', BuzzIcons.triangleAlert, null) + else ...[ + for (final member in previewMembers) + _ChannelMemberPreviewRow( + member: member, + currentPubkey: resolvedCurrentPubkey, + onMemberTap: onMemberTap, + displayName: + userCache[member.pubkey.toLowerCase()]?.displayName, + contextualLabel: + memberLabels[member.pubkey.toLowerCase()], + avatarUrl: + userCache[member.pubkey.toLowerCase()]?.avatarUrl, + isArchived: isArchived(member), + ), + if (memberCount > _channelMemberPreviewLimit) + action('See all', BuzzIcons.users, openMembers), + ], + ], + ), + SheetActionSection( + children: [ + if (!personalChat) + action( + 'Move to section…', + BuzzIcons.folderInput, + () => _showMoveSectionSheet( + context, + ref, + channel: resolvedChannel, + sectionId: currentSectionId, + ), + ), + action( + 'Copy channel name', + BuzzIcons.copy, + () => copyToClipboard( + context, + resolvedChannel.name, + message: 'Channel name copied', + ), + ), + action( + 'Copy channel ID', + BuzzIcons.hash, + () => copyToClipboard( + context, + resolvedChannel.id, + message: 'Channel ID copied', + ), + ), + ], + ), + SheetActionSection( + children: [ + if (canJoin) + action( + isJoining.value ? 'Joining channel…' : 'Join channel', + BuzzIcons.logIn, + isJoining.value ? null : joinChannel, + ), + if (resolvedChannel.isMember && !resolvedChannel.isArchived) + action( + 'Leave channel', + BuzzIcons.logOut, + () => _confirmAndRun( + context, + ref, + title: 'Leave #${resolvedChannel.name}?', + body: 'You’ll stop receiving messages from this channel.', + confirmLabel: 'Leave', + action: () => ref + .read(channelActionsProvider) + .leaveChannel(resolvedChannel.id), + ), + destructive: true, + ), + if (lifecycleCapabilitiesLoading) + action('Loading channel actions…', BuzzIcons.loaderCircle, null) + else if (lifecycleCapabilitiesUnavailable) + action( + 'Channel actions unavailable', + BuzzIcons.triangleAlert, + null, + ) + else ...[ + if (canArchive) + action( + 'Archive channel', + BuzzIcons.archive, + () => _confirmAndRun( + context, + ref, + title: 'Archive #${resolvedChannel.name}?', + body: 'The channel will become read-only.', + confirmLabel: 'Archive', + action: () => ref + .read(channelActionsProvider) + .archiveChannel(resolvedChannel.id), + ), + ), + if (canUnarchive) + action( + 'Unarchive channel', + BuzzIcons.archiveRestore, + () => _confirmAndRun( + context, + ref, + title: 'Unarchive #${resolvedChannel.name}?', + body: 'The channel will become active again.', + confirmLabel: 'Unarchive', + action: () => ref + .read(channelActionsProvider) + .unarchiveChannel(resolvedChannel.id), + ), + ), + if (canDelete) + action( + 'Delete channel', + BuzzIcons.trash2, + () => _confirmAndRun( + context, + ref, + title: 'Delete #${resolvedChannel.name}?', + body: + 'This permanently deletes the channel and cannot be undone.', + confirmLabel: 'Delete', + action: () => ref + .read(channelActionsProvider) + .deleteChannel(resolvedChannel.id), + ), + destructive: true, + ), + ], + ], + ), + ], + ); + } + final reducedMotion = MediaQuery.disableAnimationsOf(context); final usesNativeIosGlassBackButton = Navigator.canPop(context) && @@ -768,7 +953,8 @@ class _ChannelMemberPreviewRow extends StatelessWidget { final ChannelMember member; final String? currentPubkey; - final void Function(BuildContext context, String pubkey) onMemberTap; + final FutureOr Function(BuildContext context, String pubkey) + onMemberTap; final String? displayName; /// The channel's contextual label for this member, when resolved. diff --git a/mobile/lib/features/channels/native_channel_actions.dart b/mobile/lib/features/channels/native_channel_actions.dart new file mode 100644 index 0000000000..92f988b69d --- /dev/null +++ b/mobile/lib/features/channels/native_channel_actions.dart @@ -0,0 +1,296 @@ +part of 'channel_actions_sheet.dart'; + +// A shared declaration for Flutter rows and the UIKit sheet's action model. +class _ChannelSheetRow extends StatelessWidget { + const _ChannelSheetRow({ + required this.title, + this.leading, + this.onTap, + this.enabled = true, + }); + final Text title; + final Widget? leading; + final FutureOr Function()? onTap; + final bool enabled; + @override + Widget build(BuildContext context) => ListTile( + title: title, + leading: leading, + enabled: enabled, + onTap: onTap == null ? null : () => onTap!(), + ); +} + +const _channelActionsBridge = MethodChannel('buzz/channel_actions_sheet'); +int _channelActionsSession = 0; + +class _NativeChannelActions extends HookConsumerWidget { + const _NativeChannelActions({ + required this.groups, + this.title, + this.detailsChannel, + this.heroAvatarUrl, + this.heroIsAgent = false, + this.memberLabel, + }); + final Channel? detailsChannel; + final String? heroAvatarUrl; + final bool heroIsAgent; + final String? memberLabel; + final String? title; + final List groups; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final session = useMemoized(() => '${_channelActionsSession++}'); + final presentationEnded = useRef(false); + final avatarCancellation = useRef?>(null); + final resolvedImages = useState({}); + final imageSources = { + if (heroAvatarUrl?.isNotEmpty == true) heroAvatarUrl!: heroIsAgent, + for (final group in groups.whereType()) + for (final row in group.children.whereType<_ChannelMemberPreviewRow>()) + if (row.avatarUrl?.isNotEmpty == true) + row.avatarUrl!: row.member.isBot, + }..removeWhere((url, _) => url.startsWith('data:')); + final colors = context.colors; + useEffect( + () { + if (presentationEnded.value) return null; + var active = true; + final cancelled = ValueNotifier(false); + avatarCancellation.value = cancelled; + if (imageSources.isNotEmpty) { + final auth = ref.read(mediaGetAuthServiceProvider); + final client = ref.read(mediaHttpClientProvider); + final diskCache = ref.read(mediaDiskCacheProvider); + Future resolveImages() async { + final images = {}; + for (final entry in imageSources.entries) { + final bytes = await nativeAvatarImage( + cancelled: cancelled, + dimension: entry.key == heroAvatarUrl ? 240 : 120, + url: entry.key, + initial: '?', + isAgent: entry.value, + background: colors.surfaceContainer, + foreground: colors.onPrimaryContainer, + networkImages: (url) => smallMediaImageProviders( + url: url, + auth: auth, + client: client, + diskCache: diskCache, + ), + ); + if (!active || cancelled.value) return; + if (bytes != null) { + images[entry.key] = + 'data:image/png;base64,${base64Encode(bytes)}'; + } + } + if (active) resolvedImages.value = images; + } + + unawaited(resolveImages()); + } + return () { + active = false; + cancelled.value = true; + cancelled.dispose(); + }; + }, + [ + imageSources.toString(), + colors.surfaceContainer, + colors.onPrimaryContainer, + ], + ); + String imageSource(String? url) => url?.startsWith('data:') == true + ? url! + : resolvedImages.value[url] ?? ''; + final callbacks = Function()>{}; + final sections = >>[]; + Map entry( + String label, + FutureOr Function()? action, { + bool destructive = false, + IconData? icon, + String? id, + }) { + if (action != null) callbacks[id ?? label] = action; + return { + 'id': id ?? label, + 'label': label, + 'enabled': action != null, + 'destructive': destructive, + 'symbol': _channelActionSymbol(icon), + }; + } + + for (final group in groups) { + if (group is _ChannelQuickActionsRow) { + sections.add([ + entry( + group.isStarred ? 'Unstar' : 'Star', + group.onToggleStar, + icon: BuzzIcons.star, + ), + entry( + group.isUnread ? 'Mark Read' : 'Mark Unread', + group.onToggleRead, + icon: BuzzIcons.checkCheck, + ), + ]); + } else if (group is SheetActionSection) { + final rows = >[]; + for (final row in group.children) { + if (row is _ChannelMemberPreviewRow) { + rows.add({ + ...entry( + row.member.pubkey, + () => row.onMemberTap(context, row.member.pubkey), + id: 'member:${row.member.pubkey}', + ), + 'member': { + 'pubkey': row.member.pubkey, + 'role': row.member.role, + 'currentPubkey': row.currentPubkey ?? '', + 'displayName': row.displayName ?? '', + 'contextualLabel': row.contextualLabel ?? '', + 'avatarUrl': imageSource(row.avatarUrl), + 'archived': row.isArchived, + }, + }); + } else if (row is _ChannelSheetRow) { + rows.add( + entry( + row.title.data!, + row.enabled ? row.onTap : null, + icon: row.leading is Icon ? (row.leading as Icon).icon : null, + ), + ); + } else if (row is _ActionTile) { + rows.add( + entry( + row.label, + row.onTap, + destructive: row.destructive, + icon: row.icon, + ), + ); + } + } + if (rows.isNotEmpty || detailsChannel != null) sections.add(rows); + } + } + final latest = useRef(callbacks)..value = callbacks; + final payload = { + 'session': session, + 'title': title ?? '', + if (detailsChannel != null) 'details': detailsChannel!.toJson(), + 'heroAvatarUrl': imageSource(heroAvatarUrl), + 'heroIsAgent': heroIsAgent, + 'memberLabel': memberLabel ?? '', + 'tiles': + detailsChannel != null || + groups.firstOrNull is _ChannelQuickActionsRow, + 'colors': { + for (final item in { + 'surface': context.colors.surface, + 'container': context.colors.surfaceContainerHighest, + 'control': context.colors.surfaceContainer, + 'onSurface': context.colors.onSurface, + 'onSurfaceVariant': context.colors.onSurfaceVariant, + 'primary': context.colors.primary, + 'onPrimaryContainer': context.colors.onPrimaryContainer, + 'error': context.colors.error, + }.entries) + item.key: item.value.toARGB32(), + }, + 'dark': Theme.of(context).brightness == Brightness.dark, + 'sections': sections, + }; + final latestPayload = useRef(payload)..value = payload; + useEffect(() { + var disposed = false; + WidgetsBinding.instance.addPostFrameCallback((_) async { + if (disposed) return; + final route = ModalRoute.of(context); + try { + final selected = await _channelActionsBridge.invokeMethod( + 'present', + latestPayload.value, + ); + if (disposed || !context.mounted) return; + presentationEnded.value = true; + avatarCancellation.value?.value = true; + final action = latest.value[selected]; + if (action != null) await action(); + } on PlatformException catch (error) { + if (context.mounted) { + ScaffoldMessenger.of(context).showFeedbackSnackBar( + SnackBar( + content: Text( + 'Could not open channel actions: ${error.message ?? error.code}', + ), + ), + kind: ToastKind.error, + ); + } + } on MissingPluginException { + if (context.mounted) { + ScaffoldMessenger.of(context).showFeedbackSnackBar( + const SnackBar( + content: Text('Channel actions are unavailable in this build.'), + ), + kind: ToastKind.error, + ); + } + } finally { + if (!disposed && context.mounted && (route?.isCurrent ?? false)) { + Navigator.of(context).pop(); + } + } + }); + return () { + disposed = true; + unawaited( + _channelActionsBridge + .invokeMethod('dismiss', {'session': session}) + .catchError((Object _) {}), + ); + }; + }, [session]); + useEffect(() { + unawaited( + _channelActionsBridge + .invokeMethod('update', payload) + .catchError((Object _) {}), + ); + return null; + }, [payload.toString()]); + return const SizedBox.shrink(); + } +} + +String _channelActionSymbol(IconData? icon) => switch (icon) { + BuzzIcons.loaderCircle => 'loading', + BuzzIcons.triangleAlert => 'warning', + BuzzIcons.logIn => 'join', + BuzzIcons.pencil => 'pencil', + BuzzIcons.plus => 'plus', + BuzzIcons.users => 'person.2', + BuzzIcons.star => 'star', + BuzzIcons.checkCheck => 'checkmark', + BuzzIcons.folderInput => 'folder', + BuzzIcons.bell => 'bell', + BuzzIcons.bellOff => 'bell.slash', + BuzzIcons.settings => 'gearshape', + BuzzIcons.copy => 'doc.on.doc', + BuzzIcons.hash => 'number', + BuzzIcons.logOut => 'rectangle.portrait.and.arrow.right', + BuzzIcons.archive => 'archivebox', + BuzzIcons.archiveRestore => 'archiveRestore', + BuzzIcons.trash2 => 'trash', + _ => 'ellipsis', +}; diff --git a/mobile/lib/features/channels/native_channel_sheet_app.dart b/mobile/lib/features/channels/native_channel_sheet_app.dart new file mode 100644 index 0000000000..4fd10b307d --- /dev/null +++ b/mobile/lib/features/channels/native_channel_sheet_app.dart @@ -0,0 +1,275 @@ +part of 'channel_actions_sheet.dart'; + +/// Presentation-only Flutter content inside UIKit. Account state and actions +/// remain in the main isolate; this engine receives a live display model only. +@pragma('vm:entry-point') +Future channelSheetMain() async { + WidgetsFlutterBinding.ensureInitialized(); + const bridge = MethodChannel('buzz/channel_sheet_content'); + final initial = + await bridge.invokeMapMethod('initial') ?? {}; + runApp(ProviderScope(child: _ChannelSheetApp(initial: initial))); +} + +class _ChannelSheetApp extends HookWidget { + const _ChannelSheetApp({required this.initial}); + final Map initial; + + @override + Widget build(BuildContext context) { + const bridge = MethodChannel('buzz/channel_sheet_content'); + final data = useState(initial); + useEffect(() { + bridge.setMethodCallHandler((call) async { + if (call.method == 'update') { + data.value = Map.from(call.arguments as Map); + } + }); + WidgetsBinding.instance.addPostFrameCallback((_) { + unawaited(bridge.invokeMethod('ready')); + }); + return () => bridge.setMethodCallHandler(null); + }, const []); + final dark = data.value['dark'] == true; + final base = dark ? AppTheme.dark() : AppTheme.light(); + final colors = data.value['colors'] as Map? ?? {}; + Color color(String key, Color fallback) => + colors[key] is int ? Color(colors[key] as int) : fallback; + final scheme = base.colorScheme; + final theme = utilitySurfaceThemeData( + base.copyWith( + colorScheme: scheme.copyWith( + surface: color('surface', scheme.surface), + surfaceContainerHighest: color( + 'container', + scheme.surfaceContainerHighest, + ), + surfaceContainer: color('control', scheme.surfaceContainer), + onSurface: color('onSurface', scheme.onSurface), + onSurfaceVariant: color('onSurfaceVariant', scheme.onSurfaceVariant), + primary: color('primary', scheme.primary), + onPrimaryContainer: color( + 'onPrimaryContainer', + scheme.onPrimaryContainer, + ), + error: color('error', scheme.error), + ), + ), + ); + return MaterialApp( + debugShowCheckedModeBanner: false, + theme: theme, + home: ChannelSheetContent( + data: data.value, + onSelect: (id) => bridge.invokeMethod('select', id), + ), + ); + } +} + +/// Uses the same hero, tiles, member rows and cards as the regular details page. +class ChannelSheetContent extends HookWidget { + const ChannelSheetContent({ + super.key, + required this.data, + required this.onSelect, + }); + final Map data; + final FutureOr Function(String id) onSelect; + + @override + Widget build(BuildContext context) { + final nameKey = useMemoized(GlobalKey.new); + final details = data['details'] is Map + ? Channel.fromJson(Map.from(data['details'] as Map)) + : null; + final sections = (data['sections'] as List? ?? const []) + .map( + (section) => (section as List) + .map((row) => Map.from(row as Map)) + .toList(), + ) + .toList(); + final title = data['title'] as String? ?? ''; + final avatarUrl = data['heroAvatarUrl'] as String? ?? ''; + VoidCallback? select(Map row) => + row['enabled'] == true ? () => onSelect(row['id'] as String) : null; + return Scaffold( + backgroundColor: context.colors.surface, + body: SafeArea( + top: false, + left: false, + right: false, + child: ListView( + padding: const EdgeInsets.only(bottom: Grid.xs), + children: [ + if (details != null) + _ChannelDetailsHero( + channel: details, + nameKey: nameKey, + displayName: title, + avatar: avatarUrl.isEmpty + ? null + : AvatarImage( + imageUrl: avatarUrl, + radius: 40, + isAgent: data['heroIsAgent'] == true, + backgroundColor: context.controlSurface, + fallback: Text(title.isEmpty ? '?' : title[0]), + ), + ), + for (var index = 0; index < sections.length; index++) + if (index == 0 && data['tiles'] == true) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.gutter, + vertical: _channelDetailsSectionPadding, + ), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var i = 0; i < sections[index].length; i++) ...[ + if (i > 0) const SizedBox(width: Grid.xxs), + Expanded( + child: BuzzActionTile( + icon: _sheetIcon(sections[index][i]['symbol']), + label: sections[index][i]['label'] as String, + iconColor: sections[index][i]['label'] == 'Unmute' + ? context.colors.primary + : null, + isEnabled: select(sections[index][i]) != null, + onTap: select(sections[index][i]) ?? () {}, + iconWidget: sections[index][i]['symbol'] == 'star' + ? TablerStarIcon( + filled: + sections[index][i]['label'] == + 'Unstar', + color: + sections[index][i]['label'] == + 'Unstar' + ? context.colors.primary + : context.colors.onSurface, + ) + : null, + ), + ), + ], + ], + ), + ), + ) + else + AppListCard( + dividerIndent: details != null && index == 1 + ? Grid.xs + 40 + Grid.xs + : null, + label: + details != null && + index == 1 && + (data['memberLabel'] as String? ?? '').isNotEmpty + ? data['memberLabel'] as String + : null, + verticalPadding: _channelDetailsSectionPadding, + children: [ + for (final row in sections[index]) + if (row['member'] is Map) + _ChannelMemberPreviewRow( + member: ChannelMember( + pubkey: (row['member'] as Map)['pubkey'] as String, + role: (row['member'] as Map)['role'] as String, + joinedAt: DateTime(1970), + ), + currentPubkey: + (row['member'] as Map)['currentPubkey'] + as String?, + displayName: + (row['member'] as Map)['displayName'] as String?, + contextualLabel: + ((row['member'] as Map)['contextualLabel'] + as String?) + ?.isEmpty == + true + ? null + : (row['member'] as Map)['contextualLabel'] + as String?, + avatarUrl: + (row['member'] as Map)['avatarUrl'] as String?, + isArchived: + (row['member'] as Map)['archived'] == true, + onMemberTap: (_, _) => onSelect(row['id'] as String), + ) + else if (details != null && + index == 1 && + (row['label'] == 'Add members' || + row['label'] == 'See all')) + AppListRowRaw( + leading: row['label'] == 'See all' + ? const SizedBox.square(dimension: 40) + : Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: context.colors.surfaceContainer, + shape: BoxShape.circle, + ), + child: Icon( + BuzzIcons.plus, + color: context.colors.onSurfaceVariant, + ), + ), + title: Text( + row['label'] as String, + style: context.textTheme.bodyLarge, + ), + trailing: const _ChannelDetailsChevron(), + verticalPadding: Grid.xxs, + onTap: select(row), + ) + else + AppListRow( + icon: _sheetIcon(row['symbol']), + title: row['label'] as String, + trailing: row['symbol'] == 'folder' + ? const _ChannelDetailsChevron() + : row['symbol'] == 'loading' + ? BuzzLoadingIndicator( + size: 20, + semanticLabel: row['label'] as String, + ) + : null, + titleColor: row['destructive'] == true + ? context.colors.error + : null, + onTap: select(row), + ), + ], + ), + ], + ), + ), + ); + } +} + +IconData _sheetIcon(Object? symbol) => switch (symbol) { + 'star' => BuzzIcons.star, + 'checkmark' => BuzzIcons.checkCheck, + 'folder' => BuzzIcons.folderInput, + 'bell' => BuzzIcons.bell, + 'bell.slash' => BuzzIcons.bellOff, + 'gearshape' => BuzzIcons.settings, + 'doc.on.doc' => BuzzIcons.copy, + 'number' => BuzzIcons.hash, + 'rectangle.portrait.and.arrow.right' => BuzzIcons.logOut, + 'archivebox' => BuzzIcons.archive, + 'archiveRestore' => BuzzIcons.archiveRestore, + 'trash' => BuzzIcons.trash2, + 'pencil' => BuzzIcons.pencil, + 'plus' => BuzzIcons.plus, + 'person.2' => BuzzIcons.users, + 'loading' => BuzzIcons.loaderCircle, + 'warning' => BuzzIcons.triangleAlert, + 'join' => BuzzIcons.logIn, + _ => BuzzIcons.ellipsis, +}; diff --git a/mobile/lib/features/profile/user_profile_sheet.dart b/mobile/lib/features/profile/user_profile_sheet.dart index eb92cedefc..30a1191c41 100644 --- a/mobile/lib/features/profile/user_profile_sheet.dart +++ b/mobile/lib/features/profile/user_profile_sheet.dart @@ -36,16 +36,18 @@ import 'user_status_cache_provider.dart'; /// Show a user profile bottom sheet for the given [pubkey]. /// +/// Completes after the profile and any conversation opened from it close. +/// /// The sheet names [pubkey] as the opening surface did: within the live /// comparison context [names] (for example a channel's members). Without it, /// the identity is compared only with itself. -void showUserProfileSheet( +Future showUserProfileSheet( BuildContext context, String pubkey, { ProviderListenable? names, WidgetBuilder? contextualActions, -}) { - showBuzzModalBottomSheet( +}) async { + final channel = await showBuzzModalBottomSheet( context: context, isScrollControlled: true, showDragHandle: false, @@ -54,17 +56,16 @@ void showUserProfileSheet( names: names, contextualActions: contextualActions, ), - ).then((channel) { - if (channel == null || !context.mounted) return; - Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => ChannelDetailPage( - channel: channel, - placement: ChannelRoutePlacement.ordinary, - ), + ); + if (channel == null || !context.mounted) return; + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => ChannelDetailPage( + channel: channel, + placement: ChannelRoutePlacement.ordinary, ), - ); - }); + ), + ); } class UserProfileSheet extends HookConsumerWidget { diff --git a/mobile/lib/shared/widgets/avatar_image.dart b/mobile/lib/shared/widgets/avatar_image.dart index cb3000e056..99ce17f768 100644 --- a/mobile/lib/shared/widgets/avatar_image.dart +++ b/mobile/lib/shared/widgets/avatar_image.dart @@ -4,6 +4,7 @@ import 'dart:ui' as ui; import 'dart:typed_data'; import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart' show ValueListenable; import 'package:flutter_svg/flutter_svg.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; diff --git a/mobile/lib/shared/widgets/avatar_image_native.dart b/mobile/lib/shared/widgets/avatar_image_native.dart index f7feaed3c5..9010bcdc9b 100644 --- a/mobile/lib/shared/widgets/avatar_image_native.dart +++ b/mobile/lib/shared/widgets/avatar_image_native.dart @@ -3,20 +3,21 @@ part of 'avatar_image.dart'; /// Renders the same avatar sources used by Flutter as a PNG for native bars. Future nativeAvatarImage({ required String? url, + ValueListenable? cancelled, required String initial, bool isAgent = false, bool circular = false, + double dimension = 72, required Color background, required Color foreground, required List Function(String url) networkImages, }) async { - const dimension = 72.0; final animatedAvatar = parseAnimatedAvatarUrl(url); final poster = animatedAvatar?.posterUrl ?? url; final source = _AvatarSource.parse(poster); final recorder = ui.PictureRecorder(); final canvas = Canvas(recorder); - final bounds = const Rect.fromLTWH(0, 0, dimension, dimension); + final bounds = Rect.fromLTWH(0, 0, dimension, dimension); canvas.clipPath(avatarPath(bounds, isAgent: isAgent && !circular)); canvas.drawColor(background, BlendMode.src); final imageBounds = isAgent && usesInsetAgentArtwork(url) @@ -73,7 +74,11 @@ Future nativeAvatarImage({ for (var i = 0; i < providers.length; i++) { final ImageInfo image; try { - image = await _loadNativeAvatar(providers[i], dimension.toInt()); + image = await _loadNativeAvatar( + providers[i], + dimension.toInt(), + cancelled, + ); } on NetworkImageLoadException catch (error) { // A missing relay thumbnail moves on to the next one. if (error.statusCode == 404 && i < providers.length - 1) continue; @@ -95,6 +100,10 @@ Future nativeAvatarImage({ } catch (_) { // Match the normal avatar's initial fallback when media is unavailable. } + if (cancelled?.value == true) { + recorder.endRecording().dispose(); + return null; + } if (!rendered) _paintNativeAvatarText(canvas, initial, 32, foreground); final picture = recorder.endRecording(); final image = await picture.toImage(dimension.toInt(), dimension.toInt()); @@ -111,28 +120,59 @@ Future nativeAvatarImage({ Future _loadNativeAvatar( ImageProvider provider, int dimension, + ValueListenable? cancelled, ) async { - final stream = ResizeImage( + if (cancelled?.value == true) throw StateError('Avatar load cancelled'); + final resized = ResizeImage( provider, width: dimension, height: dimension, policy: ResizeImagePolicy.fit, - ).resolve(ImageConfiguration.empty); - final completer = Completer(); - final listener = ImageStreamListener( + ); + final stream = resized.resolve(ImageConfiguration.empty); + final completer = Completer(); + var displayExpired = false; + var settled = false; + late final ImageStreamListener listener; + late final VoidCallback onCancelled; + void finish({bool abandon = false}) { + if (settled) return; + settled = true; + cancelled?.removeListener(onCancelled); + stream.removeListener(listener); + if (abandon) abandonPendingImage(stream, resized, ImageConfiguration.empty); + } + + onCancelled = () { + if (cancelled?.value != true || settled) return; + completer.completeError(StateError('Avatar load cancelled')); + finish(abandon: true); + }; + listener = ImageStreamListener( (image, _) { - if (!completer.isCompleted) completer.complete(image.clone()); + if (settled) return; + completer.complete(displayExpired ? null : image.clone()); + finish(); }, onError: (Object error, StackTrace? stack) { - if (!completer.isCompleted) completer.completeError(error, stack); + if (settled) return; + completer.completeError(error, stack); + finish(); }, ); + cancelled?.addListener(onCancelled); stream.addListener(listener); - try { - return await completer.future.timeout(const Duration(seconds: 10)); - } finally { - stream.removeListener(listener); - } + // This bounds how long the UI waits, not the network request. Keep listening + // until the load settles so a later sheet dismissal can still cancel it. + final image = await completer.future.timeout( + const Duration(seconds: 10), + onTimeout: () { + displayExpired = true; + return null; + }, + ); + if (image == null) throw TimeoutException('Avatar display wait expired'); + return image; } void _paintNativeAvatarText( diff --git a/mobile/test/features/channels/channel_actions_lifecycle_test.dart b/mobile/test/features/channels/channel_actions_lifecycle_test.dart new file mode 100644 index 0000000000..89dac9c0f7 --- /dev/null +++ b/mobile/test/features/channels/channel_actions_lifecycle_test.dart @@ -0,0 +1,195 @@ +import 'dart:async'; + +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_actions_sheet.dart'; +import 'package:buzz/features/channels/channel_management_provider.dart'; +import 'package:buzz/features/channels/channel_sections/channel_sections_provider.dart'; +import 'package:buzz/features/channels/channel_sections/channel_sections_storage.dart'; +import 'package:buzz/shared/mentions/agent_identity_provider.dart'; +import 'package:buzz/shared/relay/relay.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +const _currentPubkey = 'me'; + +Channel _channel({ + String type = 'stream', + bool isArchived = false, + bool isMember = true, +}) => Channel( + id: 'channel-id', + name: type == 'dm' ? 'Alice' : 'general', + channelType: type, + visibility: 'open', + description: '', + createdBy: 'owner', + createdAt: DateTime(2025), + memberCount: 2, + isMember: isMember, + archivedAt: isArchived ? DateTime(2025, 1, 2) : null, +); + +void main() { + for (final native in [false, true]) { + testWidgets('archive returns to an interactive list (native: $native)', ( + tester, + ) async { + var archive = Completer(); + Completer? selection; + var opened = 0; + bool? result; + const bridge = MethodChannel('buzz/channel_actions_sheet'); + if (native) { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + 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); + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(bridge, ( + call, + ) async { + if (call.method != 'present') return null; + opened++; + selection = Completer(); + return selection!.future; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + bridge, + null, + ), + ); + } + await tester.pumpWidget( + ProviderScope( + overrides: [ + currentPubkeyProvider.overrideWith((ref) => _currentPubkey), + channelMembersProvider('channel-id').overrideWith( + (ref) async => [ + ChannelMember( + pubkey: _currentPubkey, + role: 'owner', + joinedAt: DateTime(2025), + ), + ], + ), + channelSectionsProvider.overrideWith( + () => _FakeChannelSectionsNotifier(const ChannelSectionStore()), + ), + agentOwnersProvider.overrideWithValue( + const AsyncValue.data({}), + ), + channelActionsProvider.overrideWith( + (ref) => _FakeChannelActions( + ref, + onArchiveChannel: () => archive.future, + ), + ), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () async { + result = await showChannelDetailsSheet( + context: context, + channel: _channel(), + currentPubkey: _currentPubkey, + onMemberTap: (_, _) {}, + personalChat: true, + ); + }, + child: const Text('Open settings'), + ), + ), + ), + ), + ), + ); + + Future confirmArchive() async { + await tester.tap(find.text('Open settings')); + await tester.pumpAndSettle(); + if (native) { + selection!.complete('Archive channel'); + await tester.pumpAndSettle(); + } else { + await tester.scrollUntilVisible( + find.text('Archive channel'), + 200, + scrollable: find.byType(Scrollable).last, + ); + await tester.tap(find.text('Archive channel')); + } + await tester.pumpAndSettle(); + await tester.tap(find.text('Archive')); + await tester.pumpAndSettle(); + } + + // Closing the sheet while the archive is still in flight leaves Home in + // place once the archive completes. + await confirmArchive(); + if (native) { + expect(result, isNull); + await tester.tap(find.text('Open settings')); + await tester.pumpAndSettle(); + expect(opened, 2); + selection!.complete(null); + } else { + expect(find.text('Archive channel'), findsOneWidget); + await tester.tap(find.byTooltip('Close sheet')); + } + await tester.pumpAndSettle(); + archive.complete(); + await tester.pumpAndSettle(); + expect(find.text('Open settings'), findsOneWidget); + + // Left open, the sheet closes itself once the archive succeeds. + archive = Completer(); + await confirmArchive(); + archive.complete(); + await tester.pumpAndSettle(); + expect(find.text('Archive channel'), findsNothing); + expect(find.text('Open settings'), findsOneWidget); + expect(result, isTrue); + debugDefaultTargetPlatformOverride = null; + }); + } +} + +class _FakeChannelSectionsNotifier extends ChannelSectionsNotifier { + _FakeChannelSectionsNotifier(this._store); + + final ChannelSectionStore _store; + + @override + ChannelSectionsState build() => + ChannelSectionsState(isReady: true, store: _store, version: 1); +} + +class _FakeChannelActions extends ChannelActions { + final Future Function()? onArchiveChannel; + + _FakeChannelActions(Ref ref, {this.onArchiveChannel}) + : super( + ref: ref, + session: ref.read(relaySessionProvider.notifier), + signedEventRelay: SignedEventRelay( + session: ref.read(relaySessionProvider.notifier), + nsec: null, + ), + currentPubkey: _currentPubkey, + ); + + @override + Future archiveChannel(String channelId) async { + await onArchiveChannel?.call(); + } +} diff --git a/mobile/test/features/channels/channel_actions_sheet_test.dart b/mobile/test/features/channels/channel_actions_sheet_test.dart index b8c94bc91e..40bcf688f4 100644 --- a/mobile/test/features/channels/channel_actions_sheet_test.dart +++ b/mobile/test/features/channels/channel_actions_sheet_test.dart @@ -9,6 +9,8 @@ import 'package:buzz/features/channels/manage_channel_sheet.dart'; import 'package:buzz/shared/mentions/agent_identity_provider.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/theme.dart'; +import 'package:buzz/shared/widgets/buzz_action_tile.dart'; +import 'package:buzz/shared/widgets/app_list_card.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -63,6 +65,7 @@ Widget _modalApp({ required Channel channel, required Future> Function() loadMembers, required ChannelActions Function(Ref ref) createChannelActions, + bool soloDetails = false, String? canvasContent, Future? pendingCanvas, }) => ProviderScope( @@ -91,11 +94,19 @@ Widget _modalApp({ home: Builder( builder: (context) => Scaffold( body: TextButton( - onPressed: () => showChannelActionsSheet( - context: context, - channel: channel, - isUnread: false, - ), + onPressed: () => soloDetails + ? showChannelDetailsSheet( + context: context, + channel: channel, + currentPubkey: _currentPubkey, + onMemberTap: (_, _) {}, + personalChat: true, + ) + : showChannelActionsSheet( + context: context, + channel: channel, + isUnread: false, + ), child: const Text('Open actions'), ), ), @@ -104,6 +115,175 @@ Widget _modalApp({ ); void main() { + for (final size in [const Size(800, 390), const Size(669, 951)]) { + testWidgets('Duo cover or portrait $size retains the Flutter sheet', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = tester.view.padding; + addTearDown(tester.view.reset); + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await tester.pumpWidget( + _modalApp( + channel: _channel(), + loadMembers: () async => [], + createChannelActions: (ref) => _FakeChannelActions(ref), + ), + ); + await tester.tap(find.text('Open actions')); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsOneWidget); + expect(find.byType(ChannelActionsSheet), findsOneWidget); + debugDefaultTargetPlatformOverride = null; + }); + } + + for (final soloDetails in [false, true]) { + testWidgets( + 'Duo ${soloDetails ? 'Solo details' : 'channel actions'} uses native presentation and live permissions', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + 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); + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const bridge = MethodChannel('buzz/channel_actions_sheet'); + final clipboard = []; + // Copy feedback creates the app's native toast composition layer. + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + (call) async { + if (call.method == 'create') { + expect((call.arguments as Map)['viewType'], 'buzz/toast_layer'); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + null, + ), + ); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + clipboard.add((call.arguments as Map)['text'] as String); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final result = Completer(); + final members = Completer>(); + final calls = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(bridge, ( + call, + ) async { + calls.add(call); + return call.method == 'present' ? result.future : null; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + bridge, + null, + ), + ); + await tester.pumpWidget( + _modalApp( + channel: _channel(), + soloDetails: soloDetails, + loadMembers: () => members.future, + createChannelActions: (ref) => _FakeChannelActions(ref), + ), + ); + await tester.tap(find.text('Open actions')); + await tester.pumpAndSettle(); + if (soloDetails) { + expect(calls.last.arguments.toString(), contains('general')); + expect( + calls.last.arguments.toString(), + isNot(contains('Move to section')), + ); + } + expect(calls.where((call) => call.method == 'present'), hasLength(1)); + expect(find.byType(Dialog), findsNothing); + expect(find.byType(BottomSheet), findsNothing); + expect( + calls.last.arguments.toString(), + isNot(contains('Delete channel')), + ); + members.complete([ + ChannelMember( + pubkey: _currentPubkey, + role: 'owner', + joinedAt: DateTime(2025), + ), + ]); + await tester.pumpAndSettle(); + expect(calls.last.arguments.toString(), contains('Delete channel')); + final displayModel = Map.from( + calls + .lastWhere( + (call) => + call.method == 'update' || call.method == 'present', + ) + .arguments + as Map, + ); + result.complete('Copy channel ID'); + await tester.pumpAndSettle(); + expect(clipboard, ['channel-id']); + expect(find.byType(ChannelActionsSheet), findsNothing); + expect(find.byType(ChannelDetailsPage), findsNothing); + expect(find.text('Open actions'), findsOneWidget); + expect(tester.takeException(), isNull); + // Render exactly the model handed to the embedded Flutter engine. + tester.view.physicalSize = const Size(540, 580); + final selected = []; + await tester.pumpWidget( + ProviderScope( + key: const ValueKey('embedded-sheet-engine'), + child: MaterialApp( + theme: utilitySurfaceThemeData(AppTheme.light()), + home: ChannelSheetContent( + data: displayModel, + onSelect: selected.add, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(BuzzActionTile), findsNWidgets(soloDetails ? 3 : 2)); + expect(find.byType(AppListCard), findsWidgets); + if (soloDetails) { + expect( + find.byKey(const ValueKey('channel-details-avatar')), + findsOneWidget, + ); + expect(find.text('general'), findsOneWidget); + } + await tester.tap(find.text('Star')); + expect(selected, ['Star']); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); + } + testWidgets('owner sees the complete regular-channel action set', ( tester, ) async { @@ -823,89 +1003,6 @@ void main() { ); }); - testWidgets('archive closes only its own settings sheet, never Home', ( - tester, - ) async { - var archive = Completer(); - await tester.pumpWidget( - ProviderScope( - overrides: [ - currentPubkeyProvider.overrideWith((ref) => _currentPubkey), - channelMembersProvider('channel-id').overrideWith( - (ref) async => [ - ChannelMember( - pubkey: _currentPubkey, - role: 'owner', - joinedAt: DateTime(2025), - ), - ], - ), - channelSectionsProvider.overrideWith( - () => _FakeChannelSectionsNotifier(const ChannelSectionStore()), - ), - agentOwnersProvider.overrideWithValue( - const AsyncValue.data({}), - ), - channelActionsProvider.overrideWith( - (ref) => _FakeChannelActions( - ref, - onArchiveChannel: () => archive.future, - ), - ), - ], - child: MaterialApp( - theme: AppTheme.light(), - home: Builder( - builder: (context) => Scaffold( - body: TextButton( - onPressed: () => showChannelDetailsSheet( - context: context, - channel: _channel(), - currentPubkey: _currentPubkey, - onMemberTap: (_, _) {}, - personalChat: true, - ), - child: const Text('Open settings'), - ), - ), - ), - ), - ), - ); - - Future confirmArchive() async { - await tester.tap(find.text('Open settings')); - await tester.pumpAndSettle(); - await tester.scrollUntilVisible( - find.text('Archive channel'), - 200, - scrollable: find.byType(Scrollable).last, - ); - await tester.tap(find.text('Archive channel')); - await tester.pumpAndSettle(); - await tester.tap(find.text('Archive')); - await tester.pumpAndSettle(); - } - - // Closing the sheet while the archive is still in flight leaves Home in - // place once the archive completes. - await confirmArchive(); - expect(find.text('Archive channel'), findsOneWidget); - await tester.tap(find.byTooltip('Close sheet')); - await tester.pumpAndSettle(); - archive.complete(); - await tester.pumpAndSettle(); - expect(find.text('Open settings'), findsOneWidget); - - // Left open, the sheet closes itself once the archive succeeds. - archive = Completer(); - await confirmArchive(); - archive.complete(); - await tester.pumpAndSettle(); - expect(find.text('Archive channel'), findsNothing); - expect(find.text('Open settings'), findsOneWidget); - }); - testWidgets('DM omits quick actions, then shows mute and copy rows', ( tester, ) async { @@ -966,22 +1063,16 @@ class _FakeChannelActions extends ChannelActions { final Future Function(String)? onSetCanvas; - final Future Function()? onArchiveChannel; - - _FakeChannelActions( - Ref ref, { - this.onUpdateChannel, - this.onSetCanvas, - this.onArchiveChannel, - }) : super( - ref: ref, - session: ref.read(relaySessionProvider.notifier), - signedEventRelay: SignedEventRelay( - session: ref.read(relaySessionProvider.notifier), - nsec: null, - ), - currentPubkey: _currentPubkey, - ); + _FakeChannelActions(Ref ref, {this.onUpdateChannel, this.onSetCanvas}) + : super( + ref: ref, + session: ref.read(relaySessionProvider.notifier), + signedEventRelay: SignedEventRelay( + session: ref.read(relaySessionProvider.notifier), + nsec: null, + ), + currentPubkey: _currentPubkey, + ); @override Future updateChannel({ @@ -1006,9 +1097,7 @@ class _FakeChannelActions extends ChannelActions { Future leaveChannel(String channelId) async {} @override - Future archiveChannel(String channelId) async { - await onArchiveChannel?.call(); - } + Future archiveChannel(String channelId) async {} @override Future unarchiveChannel(String channelId) async { diff --git a/mobile/test/features/profile/user_profile_sheet_message_test.dart b/mobile/test/features/profile/user_profile_sheet_message_test.dart index ebdae37a70..d81665dc15 100644 --- a/mobile/test/features/profile/user_profile_sheet_message_test.dart +++ b/mobile/test/features/profile/user_profile_sheet_message_test.dart @@ -1,13 +1,19 @@ +import 'dart:async'; + import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_actions_sheet.dart'; import 'package:buzz/features/channels/channel_detail_page.dart'; import 'package:buzz/features/channels/channel_management_provider.dart'; import 'package:buzz/features/channels/compose_bar.dart'; import 'package:buzz/features/profile/user_profile_sheet.dart'; import 'package:buzz/shared/me/me_sync.dart'; +import 'package:buzz/shared/mentions/agent_identity_provider.dart'; import 'package:buzz/shared/profile/user_cache_provider.dart'; import 'package:buzz/shared/profile/user_profile.dart'; import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -15,71 +21,170 @@ import 'package:shared_preferences/shared_preferences.dart'; void main() { final peer = 'a' * 64; - testWidgets('Message opens the DM without waiting on Solo', (tester) async { - final dm = Channel( - id: 'dm-peer', - name: 'Peer', - channelType: 'dm', - visibility: 'private', - description: '', - memberCount: 2, - createdBy: 'self', - createdAt: DateTime(2025), - isMember: true, - ); - tester.view.physicalSize = const Size(390, 844); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.reset); - final opened = >[]; - final waits = []; - SharedPreferences.setMockInitialValues({}); - final prefs = await SharedPreferences.getInstance(); - await tester.pumpWidget( - ProviderScope( - overrides: [ - userCacheProvider.overrideWith( - () => _UserCache({ - peer: UserProfile(pubkey: peer, displayName: 'Peer'), - }), + for (final nativeSheet in [false, true]) { + testWidgets( + 'Message opens the DM without waiting on Solo (native sheet: $nativeSheet)', + (tester) async { + final dm = Channel( + id: 'dm-peer', + name: 'Peer', + channelType: 'dm', + visibility: 'private', + description: '', + memberCount: 2, + createdBy: 'self', + createdAt: DateTime(2025), + isMember: true, + ); + final solo = Channel( + id: 'solo-project', + name: 'Project', + channelType: 'group', + visibility: 'private', + description: '', + memberCount: 2, + createdBy: 'self', + createdAt: DateTime(2025), + isMember: true, + ); + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const bridge = MethodChannel('buzz/channel_actions_sheet'); + Completer? nativeResult; + var presentations = 0; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(bridge, ( + call, + ) async { + if (call.method == 'present') { + presentations++; + nativeResult = Completer(); + return nativeResult!.future; + } + return null; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + bridge, + null, ), - channelActionsProvider.overrideWith( - (ref) => _FakeDmActions(dm, opened, waits), - ), - savedPrefsProvider.overrideWithValue(prefs), - // Solo organization is still loading. - meGroupsProvider.overrideWith((ref) => const Stream.empty()), - ], - child: MaterialApp( - theme: AppTheme.light(), - home: Builder( - builder: (context) => Scaffold( - body: TextButton( - onPressed: () => showUserProfileSheet(context, peer), - child: const Text('Open profile'), + ); + final opened = >[]; + final waits = []; + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + currentPubkeyProvider.overrideWith((ref) => 'self'), + agentOwnersProvider.overrideWithValue( + const AsyncValue.data({}), + ), + channelMembersProvider(solo.id).overrideWith( + (ref) async => [ + ChannelMember( + pubkey: peer, + role: 'member', + joinedAt: DateTime(2025), + ), + ], + ), + userCacheProvider.overrideWith( + () => _UserCache({ + peer: UserProfile(pubkey: peer, displayName: 'Peer'), + }), + ), + channelActionsProvider.overrideWith( + (ref) => _FakeDmActions(dm, opened, waits), + ), + savedPrefsProvider.overrideWithValue(prefs), + // Solo organization is still loading. + meGroupsProvider.overrideWith((ref) => const Stream.empty()), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => nativeSheet + ? showChannelDetailsSheet( + context: context, + channel: solo, + currentPubkey: 'self', + personalChat: true, + onMemberTap: (context, pubkey) => + showUserProfileSheet(context, pubkey), + ) + : showUserProfileSheet(context, peer), + child: const Text('Open profile'), + ), + ), ), ), ), - ), - ), - ); - await tester.tap(find.text('Open profile')); - await tester.pumpAndSettle(); - await tester.tap(find.text('Message')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); + ); + Future openProfile() async { + if (nativeSheet) { + tester.view.physicalSize = const Size(1200, 800); + tester.view.padding = const FakeViewPadding(right: 76); + tester.view.viewPadding = tester.view.padding; + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + await tester.pumpAndSettle(); + } + await tester.tap(find.text('Open profile')); + await tester.pumpAndSettle(); + if (nativeSheet) { + // UIKit selection is the OS boundary; follow-up profile/DM routes are real. + debugDefaultTargetPlatformOverride = null; + expect(nativeResult, isNotNull); + expect( + nativeResult!.isCompleted, + isFalse, + reason: 'The underlying list must accept another tap', + ); + nativeResult!.complete('member:$peer'); + await tester.pumpAndSettle(); + } + expect(find.byType(UserProfileSheet), findsOneWidget); + } - expect(opened, [ - [peer], - ]); - // The page opens at once instead of waiting on the full channel list. - expect(waits, [false]); - expect( - tester.widget(find.byType(ChannelDetailPage)).channel, - dm, + await openProfile(); + if (nativeSheet) { + Navigator.of(tester.element(find.byType(UserProfileSheet))).pop(); + await tester.pumpAndSettle(); + // A stranded transparent owner route prevents this real tap from opening again. + await openProfile(); + expect(presentations, 2); + } + await tester.tap(find.text('Message')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(opened, [ + [peer], + ]); + // The page opens at once instead of waiting on the full channel list. + expect(waits, [false]); + expect( + tester + .widget(find.byType(ChannelDetailPage)) + .channel, + dm, + ); + // The DM is usable at once, not a placement spinner. + expect(find.byType(ComposeBar), findsOneWidget); + if (nativeSheet) { + Navigator.of(tester.element(find.byType(ChannelDetailPage))).pop(); + await tester.pumpAndSettle(); + await openProfile(); + expect(presentations, 3); + Navigator.of(tester.element(find.byType(UserProfileSheet))).pop(); + await tester.pumpAndSettle(); + } + }, ); - // The DM is usable at once, not a placement spinner. - expect(find.byType(ComposeBar), findsOneWidget); - }); + } } class _UserCache extends UserCacheNotifier { diff --git a/mobile/test/shared/widgets/native_avatar_image_test.dart b/mobile/test/shared/widgets/native_avatar_image_test.dart index 84d4ab2e8f..b9bf043a2e 100644 --- a/mobile/test/shared/widgets/native_avatar_image_test.dart +++ b/mobile/test/shared/widgets/native_avatar_image_test.dart @@ -1,5 +1,7 @@ import 'dart:ui' as ui; import 'dart:convert'; +import 'dart:async'; +import 'dart:typed_data'; import 'package:buzz/shared/emoji/emoji_avatar.dart'; import 'package:buzz/shared/relay/media_auth.dart'; @@ -106,6 +108,98 @@ void main() { }); }); + for (final scenario in [ + 'cancel', + 'timeout then cancel', + 'timeout then finish', + 'timeout without owner', + ]) { + testWidgets('native avatar $scenario', (tester) async { + final started = Completer(); + final aborted = Completer(); + final response = Completer(); + final cancelled = ValueNotifier(false); + var requests = 0; + final client = _StreamingClient((request) async { + requests++; + (request as http.AbortableRequest).abortTrigger!.then((_) { + if (!response.isCompleted) { + if (!aborted.isCompleted) aborted.complete(); + response.completeError(http.RequestAbortedException(request.url)); + } + }); + if (!started.isCompleted) started.complete(); + return response.future; + }); + final provider = MediaImageProvider( + url: 'https://relay.example/media/held-$scenario.png', + auth: MediaGetAuthService(baseUrl: 'https://relay.example', nsec: null), + client: client, + ); + Future render() => nativeAvatarImage( + url: provider.url, + cancelled: scenario == 'timeout without owner' ? null : cancelled, + initial: 'A', + background: Colors.black, + foreground: Colors.white, + networkImages: (_) => [provider], + ); + final pending = render(); + await tester.pump(); + expect(started.isCompleted, isTrue); + if (scenario != 'cancel') { + await tester.pump(const Duration(seconds: 11)); + expect(aborted.isCompleted, isFalse); + } + if (scenario.contains('cancel')) { + cancelled.value = true; + await tester.pump(); + expect(aborted.isCompleted, isTrue); + await tester.runAsync(() async { + await pending; + }); + } else { + await tester.runAsync(() async { + await pending; + }); + var loaded = false; + final stream = ResizeImage( + provider, + width: 72, + height: 72, + policy: ResizeImagePolicy.fit, + ).resolve(ImageConfiguration.empty); + final listener = ImageStreamListener((_, _) { + loaded = true; + }); + stream.addListener(listener); + final bytes = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAA' + 'AAYAAjCB0C8AAAAASUVORK5CYII=', + ); + response.complete(http.StreamedResponse(Stream.value(bytes), 200)); + // Drain engine decode events and the test zone's microtasks until the + // real image stream settles, without advancing the request's timeout. + while (!loaded) { + await tester.runAsync(() => Future(() {})); + await tester.pump(); + } + stream.removeListener(listener); + await tester.runAsync(() async { + expect(await render(), isNotNull); + expect(await render(), isNotNull); + }); + expect(requests, 1); + expect(aborted.isCompleted, isFalse); + cancelled.value = true; + await tester.pump(); + expect(aborted.isCompleted, isFalse); + } + cancelled.dispose(); + client.close(); + }); + } + for (final size in [const Size(1440, 720), const Size(720, 1440)]) { testWidgets('bounds inline raster decode at $size before native painting', ( tester, @@ -221,3 +315,11 @@ class _RecordingImage extends MemoryImage { return codec; } } + +class _StreamingClient extends http.BaseClient { + _StreamingClient(this.onSend); + final Future Function(http.BaseRequest) onSend; + @override + Future send(http.BaseRequest request) => + onSend(request); +}