diff --git a/mobile/README.md b/mobile/README.md index 6496e36f08..671d200238 100644 --- a/mobile/README.md +++ b/mobile/README.md @@ -307,7 +307,7 @@ from the native section menu, which also retains its quick-sort actions. Show of Active; Active reveals inline 1-, 7-, 30-, and 90-day choices. Apply commits the draft; Cancel discards it. A failed filter save keeps the draft for Retry. -Filtered sections offer **Show hidden channels** in the main list, expanding +Filtered sections offer **Show more** in the main list, expanding the original sorted roster without changing the saved filter. Filtered-empty sections retain their header, options and recovery control. Section membership and sorting ownership are unchanged. Filter mode and duration are confirmed diff --git a/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift b/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift index 6450bd1b95..87ae5390e2 100644 --- a/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift +++ b/mobile/ios/NativeControlTests/SettingMenuSelectionTests.swift @@ -81,12 +81,13 @@ struct SettingMenuSelectionTests { // Invoke the actual menu UIAction through UIKit, without synthesizing a // Flutter method-channel message or depending on dismissal callback order. let selection = UIButton(primaryAction: choices[0]) + let interaction = UIContextMenuInteraction(delegate: button) + let configuration = UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: nil) + button.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: nil) selection.sendActions(for: .touchUpInside) precondition(messenger.selections == (deferred ? [] : [0])) if deferred { - precondition(button.pendingMenuAction != nil) - button.pendingMenuAction?() - button.pendingMenuAction = nil + button.contextMenuInteraction(interaction, willEndFor: configuration, animator: nil) precondition(messenger.selections == [0]) } } diff --git a/mobile/ios/Runner/JumpToLatestGlassButton.swift b/mobile/ios/Runner/JumpToLatestGlassButton.swift index f9717b7999..3a92dfb825 100644 --- a/mobile/ios/Runner/JumpToLatestGlassButton.swift +++ b/mobile/ios/Runner/JumpToLatestGlassButton.swift @@ -43,6 +43,7 @@ private final class JumpToLatestGlassButton: UIButton { final class NavigationGlassButton: UIButton { var opensMenuAbove = false var hitTargetInsets = UIEdgeInsets.zero + private static weak var visibleMenuButton: NavigationGlassButton? private var pendingMenuAction: (() -> Void)? private var menuVisible = false private var menuDismissing = false @@ -56,6 +57,7 @@ final class NavigationGlassButton: UIButton { } private func finishMenuDismissal() { + if !menuVisible && Self.visibleMenuButton === self { Self.visibleMenuButton = nil } menuDismissing = false let action = pendingMenuAction pendingMenuAction = nil @@ -87,6 +89,10 @@ final class NavigationGlassButton: UIButton { menuVisible = true pendingMenuAction = nil super.contextMenuInteraction(interaction, willDisplayMenuFor: configuration, animator: animator) + if let previous = Self.visibleMenuButton, previous !== self, previous.window === window { + previous.contextMenuInteraction?.dismissMenu() + } + Self.visibleMenuButton = self animateMenu?(true, animator) menuVisibilityChanged?(true) UIImpactFeedbackGenerator(style: .light).impactOccurred() @@ -555,7 +561,8 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { } if let menu = arguments?["menu"] as? [[String: Any]] { // Keep titled sections in reading order even above a bottom-bar trigger. - button.preferredMenuElementOrder = menu.contains { $0["sectionTitle"] is String } ? .fixed : .automatic + let hasImages = menu.contains { !(($0["symbol"] as? String) ?? "").isEmpty } + button.preferredMenuElementOrder = !hasImages || menu.contains { $0["sectionTitle"] is String } ? .fixed : .automatic var groups: [[UIMenuElement]] = [[]] var groupTitles = [""] for item in menu { @@ -567,7 +574,7 @@ final class NavigationGlassButtonPlatformView: NSObject, FlutterPlatformView { if let title = item["sectionTitle"] as? String { groupTitles[groupTitles.count - 1] = title } - let symbol = (item["symbol"] as? String).flatMap { + let symbol = (hasImages ? item["symbol"] as? String : nil).flatMap { // A transparent image keeps the native menu's icon column aligned. $0.isEmpty ? UIGraphicsImageRenderer(size: CGSize(width: 24, height: 24)).image { _ in } diff --git a/mobile/ios/Runner/NativeProfileTextEditor.swift b/mobile/ios/Runner/NativeProfileTextEditor.swift index 9e03473ba3..2f1555c79f 100644 --- a/mobile/ios/Runner/NativeProfileTextEditor.swift +++ b/mobile/ios/Runner/NativeProfileTextEditor.swift @@ -7,6 +7,7 @@ import UIKit final class NativeProfileTextEditorCoordinator: NSObject, UIAdaptivePresentationControllerDelegate { + private let sectionEmojiChannel: FlutterMethodChannel private let channel: FlutterMethodChannel private weak var parentViewController: UIViewController? private weak var presentedController: UIViewController? @@ -20,6 +21,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, name: "buzz/profile_text_editor", binaryMessenger: messenger ) + sectionEmojiChannel = FlutterMethodChannel(name: "buzz/section_emoji", binaryMessenger: messenger) self.parentViewController = parentViewController super.init() channel.setMethodCallHandler { [weak self] call, result in @@ -37,7 +39,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, } return } - guard call.method == "present" || call.method == "presentChannel" || call.method == "presentProject" else { + guard call.method == "present" || call.method == "presentChannel" || call.method == "presentProject" || call.method == "presentSection" else { result(FlutterMethodNotImplemented) return } @@ -74,6 +76,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, pageBackgroundColor: UIColor(argb: pageBackgroundArgb.uint32Value), containerBackgroundColor: UIColor(argb: containerBackgroundArgb.uint32Value), containerCornerRadius: CGFloat(containerCornerRadius.doubleValue), + requireNonEmpty: arguments["requireNonEmpty"] as? Bool ?? false, allowUnchangedSubmission: allowUnchangedSubmission, channelDescription: call.method == "presentChannel" ? arguments["description"] as? String : nil, originalName: arguments["originalName"] as? String, @@ -83,6 +86,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, canvasContent: arguments["canvasContent"] as? String ?? "", canvasLoaded: arguments["canvasLoaded"] as? Bool ?? false, isProjectEditor: call.method == "presentProject", + sectionEmoji: call.method == "presentSection" ? arguments : nil, result: result ) } @@ -131,6 +135,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, pageBackgroundColor: UIColor, containerBackgroundColor: UIColor, containerCornerRadius: CGFloat, + requireNonEmpty: Bool = false, allowUnchangedSubmission: Bool, channelDescription: String?, originalName: String?, @@ -140,6 +145,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, canvasContent: String, canvasLoaded: Bool, isProjectEditor: Bool, + sectionEmoji: [String: Any]?, result: @escaping FlutterResult ) { guard presentedController == nil else { @@ -175,6 +181,7 @@ final class NativeProfileTextEditorCoordinator: NSObject, pageBackgroundColor: pageBackgroundColor, containerBackgroundColor: containerBackgroundColor, containerCornerRadius: containerCornerRadius, + requireNonEmpty: requireNonEmpty, allowUnchangedSubmission: allowUnchangedSubmission, channelDescription: channelDescription, originalName: originalName, @@ -187,6 +194,13 @@ final class NativeProfileTextEditorCoordinator: NSObject, onCancel: { [weak self] in self?.finish(value: nil) }, onSet: { [weak self] value in self?.finish(value: value) } ) + if let sectionEmoji { + editor.configureSectionEmoji(sectionEmoji) { [weak self] completion in + self?.sectionEmojiChannel.invokeMethod("choose", arguments: nil) { result in + completion(result as? [String: Any]) + } + } + } let navigationController = UINavigationController(rootViewController: editor) navigationController.overrideUserInterfaceStyle = brightness == "dark" ? .dark @@ -281,6 +295,7 @@ final class NativeProfileTextEditorViewController: private let pageBackgroundColor: UIColor private let containerBackgroundColor: UIColor private let containerCornerRadius: CGFloat + private let requireNonEmpty: Bool private let allowUnchangedSubmission: Bool private let onCancel: () -> Void private let onSet: (Any) -> Void @@ -298,6 +313,50 @@ final class NativeProfileTextEditorViewController: private var hasFocusedEditor = false private var isChannelEditor: Bool { channelDescription != nil } + private var originalSectionIcon: String? + private var sectionIcon = "" + private let emojiButton = UIButton(type: .system) + + func configureSectionEmoji(_ initial: [String: Any], + choose: @escaping (@escaping ([String: Any]?) -> Void) -> Void) { + originalSectionIcon = initial["icon"] as? String ?? "" + emojiButton.accessibilityLabel = "Choose section emoji" + emojiButton.backgroundColor = containerBackgroundColor + emojiButton.layer.cornerRadius = 26 + emojiButton.titleLabel?.font = .systemFont(ofSize: 24) + displaySectionSelection(initial) + emojiButton.addAction(UIAction { [weak self] _ in + guard let self else { return } + self.textField.resignFirstResponder() + self.emojiButton.isEnabled = false + choose { [weak self] selection in + guard let self else { return } + self.emojiButton.isEnabled = true + if let selection { + self.displaySectionSelection(selection) + self.updateNavigation() + } + self.textField.becomeFirstResponder() + } + }, for: .touchUpInside) + } + + private func displaySectionSelection(_ selection: [String: Any]) { + sectionIcon = selection["icon"] as? String ?? "" + emojiButton.accessibilityValue = sectionIcon.isEmpty ? nil : sectionIcon + let custom = sectionIcon.hasPrefix(":") && sectionIcon.hasSuffix(":") + var image: UIImage? + if let bytes = selection["iconBytes"] as? FlutterStandardTypedData, + let source = UIImage(data: bytes.data) { + image = source.preparingThumbnail(of: CGSize(width: 26, height: 26))?.withRenderingMode(.alwaysOriginal) + } + if image == nil && (sectionIcon.isEmpty || custom) { + image = UIImage(systemName: custom ? "sparkles" : "face.smiling") + } + emojiButton.setImage(image, for: .normal) + emojiButton.setTitle(image == nil ? sectionIcon : nil, for: .normal) + } + private lazy var textField: UITextField = { let field = UITextField() field.translatesAutoresizingMaskIntoConstraints = false @@ -350,6 +409,7 @@ final class NativeProfileTextEditorViewController: pageBackgroundColor: UIColor, containerBackgroundColor: UIColor, containerCornerRadius: CGFloat, + requireNonEmpty: Bool = false, allowUnchangedSubmission: Bool, channelDescription: String?, originalName: String?, @@ -368,6 +428,7 @@ final class NativeProfileTextEditorViewController: self.pageBackgroundColor = pageBackgroundColor self.containerBackgroundColor = containerBackgroundColor self.containerCornerRadius = containerCornerRadius + self.requireNonEmpty = requireNonEmpty self.allowUnchangedSubmission = allowUnchangedSubmission self.channelDescription = channelDescription self.originalName = originalName @@ -431,6 +492,7 @@ final class NativeProfileTextEditorViewController: } private var hasUnsavedChanges: Bool { + if let originalSectionIcon, sectionIcon != originalSectionIcon { return true } if isProjectEditor { return !currentValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } @@ -460,7 +522,7 @@ final class NativeProfileTextEditorViewController: } private func updateNavigation() { - navigationItem.rightBarButtonItem?.isEnabled = canEditDetails && hasUnsavedChanges + navigationItem.rightBarButtonItem?.isEnabled = canEditDetails && hasUnsavedChanges && validText && (!isChannelEditor || !canonicalChannelName.isEmpty) && (!isProjectEditor || ( !currentValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty @@ -498,8 +560,12 @@ final class NativeProfileTextEditorViewController: .trimmingCharacters(in: .whitespacesAndNewlines) } + private var validText: Bool { + !requireNonEmpty || !currentValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + @objc private func setTapped() { - guard canEditDetails && hasUnsavedChanges else { return } + guard canEditDetails && hasUnsavedChanges && validText else { return } if isProjectEditor { let name = currentValue.trimmingCharacters(in: .whitespacesAndNewlines) guard !name.isEmpty, currentValue.count <= 120 else { return } @@ -507,6 +573,8 @@ final class NativeProfileTextEditorViewController: } else if isChannelEditor { guard !canonicalChannelName.isEmpty else { return } onSet(["action": "save", "name": canonicalChannelName, "description": textView.text ?? ""]) + } else if originalSectionIcon != nil { + onSet(["name": currentValue, "icon": sectionIcon]) } else { onSet(currentValue) } @@ -608,6 +676,29 @@ final class NativeProfileTextEditorViewController: placeholderLabel.topAnchor.constraint(equalTo: textView.topAnchor), ]) placeholderLabel.isHidden = !textView.text.isEmpty + } else if originalSectionIcon != nil { + cell.backgroundColor = .clear + cell.clipsToBounds = false + let fieldContainer = UIView() + fieldContainer.layer.cornerRadius = containerCornerRadius + fieldContainer.layer.cornerCurve = .continuous + fieldContainer.backgroundColor = containerBackgroundColor + fieldContainer.addSubview(textField) + let row = UIStackView(arrangedSubviews: [emojiButton, fieldContainer]) + row.spacing = 8 + row.translatesAutoresizingMaskIntoConstraints = false + cell.contentView.addSubview(row) + NSLayoutConstraint.activate([ + row.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor), + row.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor), + row.topAnchor.constraint(equalTo: cell.contentView.topAnchor), + row.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor), + emojiButton.widthAnchor.constraint(equalTo: row.heightAnchor), + textField.leadingAnchor.constraint(equalTo: fieldContainer.leadingAnchor, constant: 16), + textField.trailingAnchor.constraint(equalTo: fieldContainer.trailingAnchor, constant: -16), + textField.topAnchor.constraint(equalTo: fieldContainer.topAnchor), + textField.bottomAnchor.constraint(equalTo: fieldContainer.bottomAnchor), + ]) } else { cell.contentView.addSubview(textField) NSLayoutConstraint.activate([ diff --git a/mobile/lib/features/channels/channel_filter/channel_filter_manager.dart b/mobile/lib/features/channels/channel_filter/channel_filter_manager.dart index e2920a2469..d9fa46a81a 100644 --- a/mobile/lib/features/channels/channel_filter/channel_filter_manager.dart +++ b/mobile/lib/features/channels/channel_filter/channel_filter_manager.dart @@ -10,6 +10,7 @@ import 'channel_filter_store.dart'; /// Whole-record LWW, with an explicit preflight and confirmed readback. Cached /// data is display-only. No automatic publication or retry of failed edits. class ChannelFilterManager extends ChangeNotifier { + final String coordinate; final String pubkey; final ChannelSortCrypto crypto; final Future> Function() fetch; @@ -25,6 +26,7 @@ class ChannelFilterManager extends ChangeNotifier { int _createdAt = 0; ChannelFilterManager({ + this.coordinate = 'channel-filter', required this.pubkey, required this.crypto, required this.fetch, @@ -46,7 +48,7 @@ class ChannelFilterManager extends ChangeNotifier { (e) => e.kind == EventKind.readState && e.pubkey == pubkey && - e.getTagValue('d') == 'channel-filter' && + e.getTagValue('d') == coordinate && e.createdAt <= DateTime.now().millisecondsSinceEpoch ~/ 1000 + 300, ) diff --git a/mobile/lib/features/channels/channel_filter/channel_filter_provider.dart b/mobile/lib/features/channels/channel_filter/channel_filter_provider.dart index 6aef06753d..6ba6b968e3 100644 --- a/mobile/lib/features/channels/channel_filter/channel_filter_provider.dart +++ b/mobile/lib/features/channels/channel_filter/channel_filter_provider.dart @@ -11,9 +11,17 @@ import '../channel_sort/channel_sort_storage.dart'; import 'channel_filter_manager.dart'; import 'channel_filter_store.dart'; -final channelFilterProvider = Provider.autoDispose(( - ref, -) { +final channelFilterProvider = Provider.autoDispose( + (ref) => _createManager(ref, 'channel-filter'), +); + +// Solo projects and Team sections each support 100 entries. Keep their +// preference budgets independent when both inventories are full. +final soloFilterProvider = Provider.autoDispose( + (ref) => _createManager(ref, 'solo-channel-filter'), +); + +ChannelFilterManager? _createManager(Ref ref, String coordinate) { // Identity and community scope only: push bookkeeping rewrites the active // community and the socket reconnects without changing either, and a new // manager would abandon an open section sheet. @@ -33,7 +41,7 @@ final channelFilterProvider = Provider.autoDispose(( } final prefs = ref.read(savedPrefsProvider); final cacheKey = - 'buzz.channel-filter.v1:$pubkey:${Uri.encodeComponent(normalizeChannelSortRelayUrl(relayUrl))}'; + 'buzz.$coordinate.v1:$pubkey:${Uri.encodeComponent(normalizeChannelSortRelayUrl(relayUrl))}'; ChannelFilterStore? cached; try { final raw = prefs.getString(cacheKey); @@ -48,6 +56,7 @@ final channelFilterProvider = Provider.autoDispose(( final session = ref.read(relaySessionProvider.notifier); final signer = SignedEventRelay(session: session, nsec: nsec); final manager = ChannelFilterManager( + coordinate: coordinate, isGroupLive: (group) => !group.startsWith('section:') || ref.read(sidebarLayoutProvider).section(group.substring(8)) != null, @@ -58,8 +67,8 @@ final channelFilterProvider = Provider.autoDispose(( NostrFilter( kinds: const [EventKind.readState], authors: [pubkey], - tags: const { - '#d': ['channel-filter'], + tags: { + '#d': [coordinate], }, limit: 1, ), @@ -68,9 +77,9 @@ final channelFilterProvider = Provider.autoDispose(( await signer.submit( kind: EventKind.readState, content: content, - tags: const [ - ['d', 'channel-filter'], - ['t', 'channel-filter'], + tags: [ + ['d', coordinate], + ['t', coordinate], ], createdAt: createdAt, ); @@ -95,4 +104,4 @@ final channelFilterProvider = Provider.autoDispose(( }); ref.onDispose(manager.dispose); return manager; -}); +} diff --git a/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart b/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart index 061a1376b3..b771117bff 100644 --- a/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart +++ b/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart @@ -264,7 +264,7 @@ class ChannelSectionsManager { markDirty(); } - void renameSection(String sectionId, String newName) { + void renameSection(String sectionId, String? newName, {String? icon}) { if (!_editable) return; _store = ChannelSectionStore( sections: [ @@ -272,8 +272,8 @@ class ChannelSectionsManager { if (s.id == sectionId) ChannelSection( id: s.id, - name: newName.trim(), - icon: s.icon, + name: newName?.trim() ?? s.name, + icon: icon ?? s.icon, order: s.order, ) else diff --git a/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart b/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart index 49eba708e4..281e9cd7d9 100644 --- a/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart +++ b/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart @@ -103,8 +103,8 @@ class ChannelSectionsNotifier extends Notifier { void createSection(String name) => _manager?.createSection(name); - void renameSection(String sectionId, String newName) => - _manager?.renameSection(sectionId, newName); + void renameSection(String sectionId, String? newName, {String? icon}) => + _manager?.renameSection(sectionId, newName, icon: icon); void deleteSection(String sectionId) { final manager = _manager; diff --git a/mobile/lib/features/channels/channel_sections/filtered_channel_section_body.dart b/mobile/lib/features/channels/channel_sections/filtered_channel_section_body.dart new file mode 100644 index 0000000000..ebe672c119 --- /dev/null +++ b/mobile/lib/features/channels/channel_sections/filtered_channel_section_body.dart @@ -0,0 +1,170 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; + +import '../../../shared/theme/buzz_icons.dart'; +import '../../../shared/theme/theme.dart'; +import '../../../shared/widgets/collapsible_section_body.dart'; +import '../../../shared/widgets/collapsible_sliver_body.dart'; +import '../channel.dart'; + +class _FilteredRowKey extends ValueKey { + const _FilteredRowKey(super.value); +} + +/// Lazily reveals chats that fall outside a section's active filter. +class FilteredChannelSectionBody extends HookWidget { + const FilteredChannelSectionBody({ + super.key, + required this.expanded, + required this.channels, + required this.isVisible, + required this.buildRow, + this.emptySliver, + this.disclosureInset = Grid.gutter, + }); + + final bool expanded; + final List channels; + final bool Function(Channel) isVisible; + final Widget Function(Channel) buildRow; + final Widget? emptySliver; + final double disclosureInset; + + @override + Widget build(BuildContext context) { + final visibleChannels = []; + final hiddenIds = {}; + for (final channel in channels) { + if (isVisible(channel)) { + visibleChannels.add(channel); + } else { + hiddenIds.add(channel.id); + } + } + final hiddenCount = hiddenIds.length; + final reveal = useState(false); + final controller = useAnimationController( + duration: sectionExpandDuration, + reverseDuration: sectionCollapseDuration, + ); + final motion = useMemoized( + () => CurvedAnimation( + parent: controller, + curve: sectionExpandCurve, + reverseCurve: sectionCollapseCurve, + ), + [controller], + ); + useEffect(() => motion.dispose, [motion]); + // A sliver keeps laying out children until it fills the viewport. A + // long run of nearly zero-height rows would mount the entire inventory. + // Retain some layout extent on large reveals and fade those rows in. + final largeReveal = hiddenCount > 24; + final boundedMotion = useMemoized( + () => Tween(begin: 0.5, end: 1).animate(motion), + [motion], + ); + final renderingHidden = useState(false); + useEffect(() { + void onStatus(AnimationStatus status) { + if (status == AnimationStatus.dismissed) renderingHidden.value = false; + } + + controller.addStatusListener(onStatus); + return () => controller.removeStatusListener(onStatus); + }, [controller]); + final reduceMotion = MediaQuery.disableAnimationsOf(context); + useEffect(() { + controller.value = 0; + renderingHidden.value = false; + reveal.value = false; + return null; + }, [hiddenIds.join(',')]); + final displayed = renderingHidden.value ? channels : visibleChannels; + final indexById = { + for (final (index, channel) in displayed.indexed) channel.id: index, + }; + + return CollapsibleSliverBody( + expanded: expanded, + sliver: channels.isEmpty && emptySliver != null + ? emptySliver! + : SliverList.builder( + itemCount: displayed.length + (hiddenCount == 0 ? 0 : 1), + findChildIndexCallback: (key) => + key is ValueKey ? indexById[key.value] : null, + itemBuilder: (context, index) { + if (index < displayed.length) { + final channel = displayed[index]; + final row = buildRow(channel); + if (!hiddenIds.contains(channel.id)) return row; + return SizeTransition( + key: _FilteredRowKey(channel.id), + sizeFactor: largeReveal ? boundedMotion : motion, + child: largeReveal + ? FadeTransition(opacity: motion, child: row) + : row, + ); + } + final color = Theme.of(context).brightness == Brightness.dark + ? const Color(0xFF949494) + : const Color(0xFF707070); + return Semantics( + expanded: reveal.value, + button: true, + child: InkWell( + borderRadius: BorderRadius.circular(Radii.md), + onTap: () { + reveal.value = !reveal.value; + if (reveal.value) renderingHidden.value = true; + if (reduceMotion) { + controller.value = reveal.value ? 1 : 0; + renderingHidden.value = reveal.value; + } else if (reveal.value) { + unawaited(controller.forward()); + } else { + unawaited(controller.reverse()); + } + }, + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: disclosureInset, + vertical: Grid.inventoryRowInset, + ), + child: Row( + children: [ + SizedBox( + width: 24, + height: 22, + child: Align( + alignment: Alignment.centerLeft, + child: Icon( + reveal.value + ? BuzzIcons.chevronUp + : BuzzIcons.chevronDown, + size: 20, + color: color, + ), + ), + ), + const SizedBox(width: Grid.inventoryLabelGap), + Expanded( + child: Text( + reveal.value ? 'Show fewer' : 'Show more', + style: navigationChatTitleTextStyle.copyWith( + color: color, + ), + ), + ), + ], + ), + ), + ), + ); + }, + ), + ); + } +} diff --git a/mobile/lib/features/channels/channel_sections/section_options_button.dart b/mobile/lib/features/channels/channel_sections/section_options_button.dart new file mode 100644 index 0000000000..fb820c76cc --- /dev/null +++ b/mobile/lib/features/channels/channel_sections/section_options_button.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart'; + +import '../../../shared/theme/buzz_icons.dart'; +import '../../../shared/theme/theme.dart'; + +class SectionOptionsButton extends StatelessWidget { + const SectionOptionsButton({ + super.key, + required this.tooltip, + required this.onPressed, + }); + + final String tooltip; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) => Semantics( + button: true, + label: tooltip, + onTap: onPressed, + excludeSemantics: true, + child: Tooltip( + message: tooltip, + child: SizedBox( + width: 64, + height: 48, + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(Radii.full), + child: Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 44, + child: Center( + child: Icon( + BuzzIcons.ellipsis, + size: 14, + color: navigationAccessoryForeground(context), + ), + ), + ), + ), + ), + ), + ), + ); +} diff --git a/mobile/lib/features/channels/channel_sections/section_reorder_sheet.dart b/mobile/lib/features/channels/channel_sections/section_reorder_sheet.dart new file mode 100644 index 0000000000..58a65e9053 --- /dev/null +++ b/mobile/lib/features/channels/channel_sections/section_reorder_sheet.dart @@ -0,0 +1,421 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../shared/relay/relay.dart'; +import '../../../shared/theme/theme.dart'; +import '../../../shared/widgets/app_list.dart'; +import '../../../shared/widgets/buzz_sheet_header.dart'; +import '../../../shared/widgets/ios_glass_navigation_button.dart'; +import '../../../shared/widgets/modal_presentation.dart'; + +final mobileSectionOrderKeyProvider = Provider((ref) { + final pubkey = ref.watch(myPubkeyProvider); + if (pubkey == null) return null; + final relay = ref.watch( + relayConfigProvider.select((config) => config.baseUrl), + ); + return 'section-order:$relay:$pubkey'; +}); + +final mobileSectionOrderProvider = + AsyncNotifierProvider.family<_MobileSectionOrder, List, String>( + _MobileSectionOrder.new, + ); + +class _MobileSectionOrder extends AsyncNotifier> { + _MobileSectionOrder(this.key); + + final String key; + bool _saving = false; + + @override + Future> build() async => List.unmodifiable( + (await SharedPreferences.getInstance()).getStringList(key) ?? + const [], + ); + + Future save(List previous, List next) async { + if (_saving || !listEquals(state.asData?.value, previous)) return false; + _saving = true; + try { + final prefs = await SharedPreferences.getInstance(); + if (!await prefs.setStringList(key, next)) { + throw StateError('Unable to save section order'); + } + if (ref.mounted) state = AsyncData(List.unmodifiable(next)); + return true; + } finally { + _saving = false; + } + } +} + +List resolveMobileSectionOrder( + List defaults, + List saved, +) => [ + ...{...saved.where(defaults.contains), ...defaults}, +]; + +/// Captures the visible inventory, including built-ins and mixed workspaces. +class SectionOrderScope extends InheritedWidget { + const SectionOrderScope({ + super.key, + required this.labels, + required this.defaultOrder, + required this.storageKey, + required super.child, + }); + final Map labels; + final List defaultOrder; + final String storageKey; + + static SectionOrderScope? of(BuildContext context) => + context.getInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(SectionOrderScope oldWidget) => + !mapEquals(labels, oldWidget.labels) || + !listEquals(defaultOrder, oldWidget.defaultOrder) || + storageKey != oldWidget.storageKey; + + Future show(BuildContext context) async { + final container = ProviderScope.containerOf(context, listen: false); + final route = ModalRoute.of(context); + try { + await container.read(mobileSectionOrderProvider(storageKey).future); + } catch (_) { + if (context.mounted && route?.isCurrent != false) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + const SnackBar( + content: Text('Could not load section order. Try again.'), + ), + ); + } + return; + } + if (!context.mounted || route?.isCurrent == false) return; + if (container.read(mobileSectionOrderKeyProvider) != storageKey) return; + await showBuzzModalBottomSheet( + context: context, + isScrollControlled: true, + showCloseButton: false, + enableDrag: false, + builder: (_) => _ReorderSheet(scope: this), + ); + } +} + +class _ReorderSheet extends HookConsumerWidget { + const _ReorderSheet({required this.scope}); + final SectionOrderScope scope; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = mobileSectionOrderProvider(scope.storageKey); + final saved = ref.watch(provider).value ?? const []; + final activeScope = ref.watch(mobileSectionOrderKeyProvider); + final initialSaved = useMemoized(() => saved); + final fullOrder = useMemoized( + () => resolveMobileSectionOrder(scope.defaultOrder, initialSaved), + ); + final initialVisible = useMemoized( + () => fullOrder.where(scope.labels.containsKey).toList(), + ); + final draft = useState(initialVisible); + final saving = useState(false); + final failed = useState(false); + final orderChanged = !listEquals(saved, initialSaved); + final scopeChanged = activeScope != scope.storageKey; + final canEdit = !saving.value && !orderChanged && !scopeChanged; + final scroll = useScrollController(); + final rowContexts = useMemoized(() => {}); + final dragIndex = useRef(null); + final lastSlot = useRef(0); + final pointer = useRef(null); + final pointerY = useRef(0.0); + final origin = useRef(0.0); + final heights = useMemoized(() => {}); + + void updateSlot() { + final start = dragIndex.value; + if (start == null || !scroll.hasClients) return; + final travel = pointerY.value + scroll.offset - origin.value; + final direction = travel < 0 ? -1 : 1; + var remaining = travel.abs(); + var slot = start; + for ( + var i = start + direction; + i >= 0 && i < draft.value.length; + i += direction + ) { + final row = rowContexts[i]; + final height = row != null && row.mounted ? row.size?.height : null; + if (height != null) heights[i] = height; + final extent = heights[i]; + if (extent == null || remaining < extent / 2) break; + slot = i; + remaining -= extent; + } + if (slot != lastSlot.value) { + lastSlot.value = slot; + unawaited(HapticFeedback.selectionClick()); + } + } + + useEffect(() { + scroll.addListener(updateSlot); + return () => scroll.removeListener(updateSlot); + }, [scroll]); + + void move(int from, int to) { + if (saving.value || !canEdit || from == to) return; + final next = draft.value.toList(); + if (from < 0 || from >= next.length || to < 0 || to >= next.length) { + return; + } + next.insert(to, next.removeAt(from)); + draft.value = next; + } + + Future save() async { + if (saving.value || !canEdit || dragIndex.value != null) return; + if (ref.read(mobileSectionOrderKeyProvider) != scope.storageKey) return; + if (listEquals(draft.value, initialVisible)) { + Navigator.pop(context); + return; + } + saving.value = true; + failed.value = false; + final route = ModalRoute.of(context)!; + try { + final visible = draft.value.iterator; + // Refill the visible slots in the new order and keep hidden slots + // (such as an empty Starred section) in place. + final next = [ + for (final key in fullOrder) + if (scope.labels.containsKey(key) && visible.moveNext()) + visible.current + else + key, + ]; + final persisted = await ref + .read(provider.notifier) + .save(initialSaved, next); + if (!context.mounted) return; + if (persisted) { + if (route.isCurrent) { + Navigator.pop(context); + } else if (route.isActive) { + Navigator.of(context).removeRoute(route); + } + } else { + failed.value = true; + } + } catch (_) { + if (context.mounted) failed.value = true; + } finally { + if (context.mounted) saving.value = false; + } + } + + void discard() { + if (!saving.value) Navigator.pop(context); + } + + return PopScope( + canPop: !saving.value, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * .85, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BuzzSheetHeader( + title: 'Reorder sections', + leading: defaultTargetPlatform == TargetPlatform.iOS + ? IosGlassNavigationButton( + icon: IosGlassNavigationIcon.close, + semanticLabel: 'Discard order', + onPressed: saving.value ? null : discard, + ) + : IconButton( + tooltip: 'Discard order', + onPressed: saving.value ? null : discard, + icon: const Icon(Icons.close), + ), + trailing: defaultTargetPlatform == TargetPlatform.iOS + ? IosGlassNavigationButton( + icon: IosGlassNavigationIcon.check, + semanticLabel: 'Save order', + onPressed: canEdit ? save : null, + isBusy: saving.value, + ) + : IconButton( + tooltip: 'Save order', + onPressed: canEdit ? save : null, + icon: const Icon(Icons.check), + ), + ), + Flexible( + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Grid.gutter, + vertical: Grid.xxs, + ), + child: Material( + color: context.colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(Radii.container), + clipBehavior: Clip.antiAlias, + child: Listener( + onPointerMove: (event) { + if (event.pointer != pointer.value) return; + pointerY.value = event.position.dy; + updateSlot(); + }, + child: ReorderableListView.builder( + scrollController: scroll, + onReorderStart: (index) { + dragIndex.value = index; + lastSlot.value = index; + unawaited(HapticFeedback.mediumImpact()); + }, + onReorderEnd: (_) => dragIndex.value = null, + shrinkWrap: true, + buildDefaultDragHandles: false, + itemCount: draft.value.length, + onReorderItem: move, + itemBuilder: (_, index) { + final key = draft.value[index]; + return Builder( + key: ValueKey(key), + builder: (rowContext) { + rowContexts[index] = rowContext; + return Column( + children: [ + if (index > 0) + Divider( + height: 1, + indent: Grid.gutter, + endIndent: Grid.gutter, + color: context.colors.onSurface.withValues( + alpha: .07, + ), + ), + AppListRow( + verticalPadding: Grid.xxs, + title: scope.labels[key]!, + trailing: Listener( + onPointerDown: (event) { + if (dragIndex.value != null) return; + pointer.value = event.pointer; + pointerY.value = event.position.dy; + origin.value = + event.position.dy + scroll.offset; + heights.clear(); + }, + child: _SectionDragHandle( + index: index, + label: scope.labels[key]!, + enabled: canEdit, + onMove: (direction) { + if (dragIndex.value != null) return; + final from = draft.value.indexOf(key); + move(from, from + direction); + }, + ), + ), + ), + ], + ); + }, + ); + }, + ), + ), + ), + ), + ), + if (!saving.value && (orderChanged || scopeChanged || failed.value)) + Semantics( + liveRegion: true, + child: Text( + scopeChanged + ? 'Account or community changed. Reopen section order to try again.' + : orderChanged + ? 'Section order changed. Reopen to try again.' + : 'Could not save section order. Try again.', + ), + ), + ], + ), + ), + ); + } +} + +class _SectionDragHandle extends HookWidget { + const _SectionDragHandle({ + required this.index, + required this.label, + required this.enabled, + required this.onMove, + }); + + final int index; + final String label; + final bool enabled; + final ValueChanged onMove; + + @override + Widget build(BuildContext context) { + final highlighted = useState(false); + return FocusableActionDetector( + enabled: enabled, + onShowFocusHighlight: (value) => highlighted.value = value, + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent( + TraversalDirection.up, + ), + SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent( + TraversalDirection.down, + ), + }, + actions: { + DirectionalFocusIntent: CallbackAction( + onInvoke: (intent) { + onMove(intent.direction == TraversalDirection.up ? -1 : 1); + return null; + }, + ), + }, + child: Tooltip( + message: 'Move $label with the up and down arrow keys', + excludeFromSemantics: true, + child: ReorderableDragStartListener( + index: index, + enabled: enabled, + child: SizedBox.square( + dimension: 44, + child: DecoratedBox( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(Radii.sm), + border: highlighted.value + ? Border.all(color: context.colors.primary) + : null, + ), + child: const Icon(Icons.drag_handle, size: 20), + ), + ), + ), + ), + ); + } +} diff --git a/mobile/lib/features/channels/channels_page.dart b/mobile/lib/features/channels/channels_page.dart index d4898b4452..13aa6e4aeb 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -1,4 +1,5 @@ import '../../shared/widgets/native_route_controls.dart'; +import '../../shared/emoji/emoji_picker.dart'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; @@ -7,7 +8,6 @@ import 'channel_filter/channel_filter_activity.dart'; import 'channel_filter/channel_filter_provider.dart'; import 'channel_filter/channel_filter_store.dart'; import '../../shared/widgets/collapsible_section_body.dart'; -import '../../shared/widgets/collapsible_sliver_body.dart'; import '../../shared/http/app_http_client.dart'; import '../../shared/me/me_sync.dart'; import '../../shared/hosted/hosted_relay_auth.dart'; @@ -27,7 +27,7 @@ import '../../shared/hosted/organization_sign_in.dart'; import 'dart:async'; import 'dart:convert'; import 'dart:io'; -import 'dart:math' show max, min; +import 'dart:math' show Random, max, min; import 'dart:ui'; import 'package:flutter/foundation.dart'; @@ -49,7 +49,7 @@ import '../../shared/community/community_grid_add.dart'; import '../../shared/community/paired_community_landing.dart'; import '../../shared/community/community_membership_provider.dart'; import '../../shared/widgets/app_list.dart'; -import '../../shared/widgets/buzz_sheet_header.dart'; +import 'channels_page/filters.dart'; import '../../shared/widgets/app_list_card.dart'; import '../../shared/widgets/app_list_card_item.dart'; import '../../shared/widgets/sheet_action_section.dart'; @@ -58,6 +58,8 @@ import '../../shared/theme/theme.dart'; import '../../shared/widgets/avatar_image.dart'; import '../../shared/widgets/bee_refresh_indicator.dart'; import '../../shared/widgets/buzz_loading_indicator.dart'; +import '../../shared/widgets/buzz_toast.dart'; +import '../../shared/widgets/ios_composition_layer.dart'; import '../../shared/widgets/buzz_setting_menu.dart'; import '../../shared/widgets/buzz_titled_sheet_layout.dart'; import '../../shared/widgets/ios_glass_navigation_action.dart'; @@ -68,6 +70,7 @@ import '../../shared/widgets/frosted_scaffold.dart'; import '../../shared/widgets/modal_presentation.dart'; import '../../shared/widgets/confirmation_dialog.dart'; import '../../shared/widgets/skeleton.dart'; +import '../../shared/widgets/tabler_star_icon.dart'; import '../profile/profile_provider.dart'; import '../profile/presence_cache_provider.dart'; import '../../shared/identity_names/identity_names_provider.dart'; @@ -87,8 +90,11 @@ import 'mentions/stable_mention_rows.dart'; import 'dm_channel_labels.dart'; import 'ephemeral_channel_display.dart'; import 'channel_mutes/channel_mutes_provider.dart'; +import 'channel_sections/section_options_button.dart'; +import 'channel_sections/filtered_channel_section_body.dart'; import 'channel_sections/channel_sections_provider.dart'; import 'channel_sections/workspace_layout.dart'; +import 'channel_sections/section_reorder_sheet.dart'; import '../../shared/custom_emoji/custom_emoji.dart' show normalizeShortcode; import '../../shared/custom_emoji/custom_emoji_provider.dart'; import '../../shared/custom_emoji/custom_emoji_render.dart'; @@ -104,8 +110,10 @@ import '../../shared/read_state/read_state_provider.dart'; import '../../shared/read_state/read_state_time.dart'; part 'channels_page/body.dart'; +part 'channels_page/activity_recovery.dart'; part 'channels_page/sections.dart'; -part 'channels_page/filters.dart'; +part 'channels_page/rename_section.dart'; + part 'channels_page/channel_tile.dart'; part 'channels_page/sheets.dart'; part 'channels_page/badges.dart'; @@ -613,7 +621,7 @@ class ChannelsPage extends HookConsumerWidget { usesPinnedGradient: usesPinnedGradient, scrollController: channelsScrollController, onRefresh: () async { - // Solo has no banner, so pulling must also restart its reader. + // Restart the reader for Solo chat and project placement. if (soloSliver != null) ref.invalidate(meGroupsProvider); ref.invalidate(channelFilterActivityProvider); await Future.wait([ diff --git a/mobile/lib/features/channels/channels_page/activity_recovery.dart b/mobile/lib/features/channels/channels_page/activity_recovery.dart new file mode 100644 index 0000000000..6a9f5ff1a7 --- /dev/null +++ b/mobile/lib/features/channels/channels_page/activity_recovery.dart @@ -0,0 +1,121 @@ +part of '../channels_page.dart'; + +/// Observes route visibility without rebuilding the channel inventory. +class _ActivityRecovery extends HookConsumerWidget { + const _ActivityRecovery({required this.activity, required this.child}); + final Map> activity; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final activityScope = ( + ref.watch(relayConfigProvider.select((config) => config.baseUrl)), + ref.watch(myPubkeyProvider), + ); + final notice = useMemoized(() => ObjectRef(null), [ + activityScope, + ]); + final failures = useMemoized(() => {}, [activityScope]); + final automaticAttempts = useMemoized(() => ObjectRef(0), [activityScope]); + failures.retainAll(activity.keys); + for (final MapEntry(key: id, value: status) in activity.entries) { + if (status.hasError) { + failures.add(id); + } else if (!status.isLoading) { + failures.remove(id); + } + } + final unavailable = failures.isNotEmpty; + if (!unavailable) automaticAttempts.value = 0; + + bool retryFailures() { + var started = false; + for (final id in failures.toList()) { + final provider = channelFilterActivityProvider(id); + if (ref.read(provider).isLoading) continue; + ref.invalidate(provider); + started = true; + } + return started; + } + + // Compact detail routes cover the list within Home's route and mute its + // tickers. On wide layouts the Messages list stays visible beside detail. + final listOnstage = TickerMode.valuesOf(context).enabled; + final routeCurrent = ModalRoute.isCurrentOf(context) ?? true; + final messagesVisible = listOnstage && routeCurrent; + final canRetry = + messagesVisible && + ref.watch(appLifecycleProvider) == AppLifecycleState.resumed && + ref.watch(relaySessionProvider.select((s) => s.status)) == + SessionStatus.connected; + final hasRetryableFailure = failures.any((id) => !activity[id]!.isLoading); + final attempts = automaticAttempts.value; + useEffect(() { + if (!hasRetryableFailure || !canRetry || attempts >= 3) return null; + // Back off over consecutive failed rounds and stagger relay traffic + // across clients. Wait for a failed lookup before scheduling a round. + final delayMs = 10_000 * (1 << attempts); + final spread = delayMs ~/ 5; + final timer = Timer( + Duration(milliseconds: delayMs - spread + Random().nextInt(2 * spread)), + () { + if (retryFailures()) automaticAttempts.value++; + }, + ); + return timer.cancel; + }, [hasRetryableFailure, canRetry, automaticAttempts, attempts]); + + void removeNotice() { + notice.value?.remove(); + notice.value?.dispose(); + notice.value = null; + } + + useEffect(() => removeNotice, [notice]); + useEffect(() { + if (!messagesVisible) { + removeNotice(); + return null; + } + var active = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!active || !context.mounted) return; + if (notice.value != null) { + notice.value!.markNeedsBuild(); + } else if (unavailable) { + late final OverlayEntry entry; + entry = OverlayEntry( + builder: (_) => IosCompositionLayer( + child: Stack( + children: [ + ReconnectCapsule( + visible: failures.isNotEmpty, + message: 'Some activity couldn’t load', + actionLabel: 'Retry', + onHidden: () { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (identical(notice.value, entry) && + failures.isEmpty) { + removeNotice(); + } + }); + }, + onSignIn: () { + if (!context.mounted) return; + retryFailures(); + }, + ), + ], + ), + ), + ); + notice.value = entry; + Overlay.of(context, rootOverlay: true).insert(entry); + } + }); + return () => active = false; + }, [notice, unavailable, messagesVisible]); + return child; + } +} diff --git a/mobile/lib/features/channels/channels_page/body.dart b/mobile/lib/features/channels/channels_page/body.dart index 08fbd41d03..8d449e7d20 100644 --- a/mobile/lib/features/channels/channels_page/body.dart +++ b/mobile/lib/features/channels/channels_page/body.dart @@ -258,11 +258,12 @@ class _SliverChannelsList extends HookConsumerWidget { var nextExpiry = 0; for (final MapEntry(key: id, value: key) in sectionKeyOf.entries) { - if (key == 'solo') continue; final group = sidebarGroupKey(key); if (filters?.store.modeFor(group) != ChannelFilterMode.active) continue; final evidence = ref.watch(channelFilterActivityProvider(id)); activity[id] = evidence; + // Solo uses the same evidence and handles its own row expiry. + if (key == 'solo') continue; final at = evidence.asData?.value; if (at == null) continue; final expiry = at + filters!.store.windowFor(group); @@ -383,8 +384,7 @@ class _SliverChannelsList extends HookConsumerWidget { } // Only the team sections record can be edited, and only until desktop's - // unified workspaces exist. Sorted as displayed, so Move up and Move down - // follow what the user sees, not storage order. + // unified workspaces exist. The mobile display order is stored separately. final teamSections = sectionsState.editable ? (sectionsState.store.sections.toList() ..sort((a, b) => a.order.compareTo(b.order))) @@ -421,19 +421,21 @@ class _SliverChannelsList extends HookConsumerWidget { // section's ID when a Solo project shares that ID. _SectionEdits editsFor(ChannelSection section, String layoutId) => ( onRename: () async { - final name = await showBuzzDialog( - context: context, - builder: (_) => _SectionNameDialog( - title: 'Rename Section', - confirmLabel: 'Rename', - initialValue: section.name, - ), - ); - if (name != null && name.isNotEmpty) { - ref - .read(channelSectionsProvider.notifier) - .renameSection(section.id, name); + final config = ref.read(relayConfigProvider); + final edit = await showSectionRenameEditor(context, section); + if (!context.mounted || edit == null) return; + final current = ref.read(relayConfigProvider); + if (current.storedOrigin != config.storedOrigin || + current.nsec != config.nsec) { + return; } + ref + .read(channelSectionsProvider.notifier) + .renameSection( + section.id, + edit.name == section.name.trim() ? null : edit.name, + icon: edit.icon == section.icon ? null : edit.icon, + ); }, onDelete: () async { final confirmed = await showBuzzDialog( @@ -481,11 +483,6 @@ class _SliverChannelsList extends HookConsumerWidget { } } }, - onMoveUp: () => - ref.read(channelSectionsProvider.notifier).moveSectionUp(section.id), - onMoveDown: () => ref - .read(channelSectionsProvider.notifier) - .moveSectionDown(section.id), ); Widget? sectionFor(String key) { @@ -532,8 +529,6 @@ class _SliverChannelsList extends HookConsumerWidget { isVisible: (c) => visible(group, c), buildRow: (c) => row(c, key), expanded: sectionExpanded(section.id), - isFirst: team == null || teamSections.first.id == team.id, - isLast: team == null || teamSections.last.id == team.id, onToggle: () => toggleSection(section.id), edits: team == null ? null : editsFor(team, section.id), sortMode: mode(), @@ -541,44 +536,47 @@ class _SliverChannelsList extends HookConsumerWidget { ); } - final sections = [for (final key in layout.sectionKeys) ?sectionFor(key)]; + final keys = layout.sectionKeys.where((key) => key != 'forums').toList(); + final orderKey = ref.watch(mobileSectionOrderKeyProvider); + final saved = orderKey == null + ? const [] + : ref.watch(mobileSectionOrderProvider(orderKey)).value ?? + const []; + final labels = {}; + final sections = []; + for (final key in resolveMobileSectionOrder(keys, saved)) { + final section = sectionFor(key); + if (section == null) continue; + sections.add(section); + labels[key] = switch (key) { + 'starred' => 'Starred', + 'solo' => 'Solo', + 'channels' => 'Team', + 'dms' => 'Direct messages', + _ => layout.section(key.substring(6))!.name, + }; + } final empty = sectionKeyOf.isEmpty && layout.sections.isEmpty; - - return SliverPadding( - padding: EdgeInsets.zero, - sliver: SliverMainAxisGroup( - slivers: [ - if (activity.values.any((value) => value.hasError)) - SliverToBoxAdapter( - child: ListTile( - title: const Text( - 'Some channel activity is unavailable. Channels remain visible.', - ), - trailing: TextButton( - onPressed: () { - for (final entry in activity.entries) { - if (entry.value.hasError) { - ref.invalidate( - channelFilterActivityProvider(entry.key), - ); - } - } - }, - child: const Text('Retry'), - ), - ), - ), - if (empty) ...[ - ?soloSliver, - const SliverToBoxAdapter(child: _EmptyState()), - ] else - for (final (index, section) in sections.indexed) ...[ - if (index > 0) - const SliverToBoxAdapter(child: SizedBox(height: Grid.xxs)), - section, - ], - ], - ), + final inventory = SliverMainAxisGroup( + slivers: [ + if (empty) ...[ + ?soloSliver, + const SliverToBoxAdapter(child: _EmptyState()), + ] else + for (final (index, section) in sections.indexed) ...[ + if (index > 0) + const SliverToBoxAdapter(child: SizedBox(height: Grid.xxs)), + section, + ], + ], + ); + final content = _ActivityRecovery(activity: activity, child: inventory); + if (orderKey == null) return content; + return SectionOrderScope( + labels: labels, + defaultOrder: keys, + storageKey: orderKey, + child: content, ); } } diff --git a/mobile/lib/features/channels/channels_page/channel_tile.dart b/mobile/lib/features/channels/channels_page/channel_tile.dart index 9ff4119605..5b5bd03b44 100644 --- a/mobile/lib/features/channels/channels_page/channel_tile.dart +++ b/mobile/lib/features/channels/channels_page/channel_tile.dart @@ -58,7 +58,7 @@ class _ChannelTile extends ConsumerWidget { child: Padding( padding: const EdgeInsets.only( left: _kChannelSectionInset, - right: _kChannelSectionInset, + right: _kChannelSectionInset + Grid.half, top: _kChannelRowVerticalPadding, bottom: _kChannelRowVerticalPadding, ), @@ -124,61 +124,76 @@ class _ChannelTile extends ConsumerWidget { ], ), ), - 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), - ), - ), + ConstrainedBox( + constraints: const BoxConstraints( + minWidth: Grid.inventoryAccessoryWidth, ), - ], - if (showAttention) ...[ - const SizedBox(width: Grid.xxs), - SizedBox( - width: _kChannelIconSize, - child: Center( - child: Container( - key: ValueKey('channel-attention-dot-${channel.id}'), - width: 6, - height: 6, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: context.colors.primary, + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.end, + children: [ + 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 (showAttention) ...[ + const SizedBox(width: Grid.xxs), + SizedBox( + width: _kChannelIconSize, + child: Center( + child: Container( + key: ValueKey( + 'channel-attention-dot-${channel.id}', + ), + width: 6, + height: 6, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: context.colors.primary, + ), + ), + ), ), - ), - ), + ], + 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/filters.dart b/mobile/lib/features/channels/channels_page/filters.dart index 8e10a96fa7..8dde7c14fb 100644 --- a/mobile/lib/features/channels/channels_page/filters.dart +++ b/mobile/lib/features/channels/channels_page/filters.dart @@ -1,54 +1,99 @@ -part of '../channels_page.dart'; +import '../channel_sort/channel_sort_provider.dart'; +import '../channel_sections/section_reorder_sheet.dart'; +import '../../../shared/widgets/app_list.dart'; +import '../channel_sections/channel_sections_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import '../../../shared/theme/theme.dart'; +import '../../../shared/theme/buzz_icons.dart'; +import 'package:flutter/foundation.dart'; +import '../../../shared/widgets/buzz_setting_menu.dart'; +import '../../../shared/widgets/ios_glass_navigation_button.dart'; +import '../../../shared/widgets/app_list_card.dart'; +import '../../../shared/widgets/collapsible_section_body.dart'; +import '../../../shared/widgets/buzz_sheet_header.dart'; -Future _showSectionViewSheet( +import '../../../shared/widgets/modal_presentation.dart'; +import '../../../shared/widgets/bottom_up_page_route.dart'; +import '../channel_filter/channel_filter_provider.dart'; +import '../channel_filter/channel_filter_store.dart'; +import '../channel_sort/channel_sort_storage.dart'; + +Future showSectionViewSheet( BuildContext context, { required String title, required String group, required ChannelSortMode sortMode, required ValueChanged onSort, bool custom = false, - bool isFirst = false, - bool isLast = false, -}) => showBuzzModalBottomSheet( - context: context, - showCloseButton: false, - showDragHandle: false, - isScrollControlled: true, - isDismissible: false, - enableDrag: false, - builder: (_) => _SectionViewSheet( - title: title, - group: group, - initialSort: sortMode, - onSort: onSort, - custom: custom, - isFirst: isFirst, - isLast: isLast, - ), -); +}) async { + final orderScope = context + .getElementForInheritedWidgetOfExactType(); + final presentingRoute = defaultTargetPlatform == TargetPlatform.iOS + ? ModalRoute.of(context) + : null; + final release = presentingRoute == null + ? null + : BottomUpPageRoute.retainControlsForSheet(presentingRoute); + ModalRoute? sheetRoute; + try { + return await showBuzzModalBottomSheet( + context: context, + nativeIosBarrier: presentingRoute != null, + showCloseButton: false, + showDragHandle: false, + isScrollControlled: true, + isDismissible: true, + enableDrag: false, + builder: (sheetContext) { + if (release != null) sheetRoute = ModalRoute.of(sheetContext); + return _SectionViewSheet( + onReorder: orderScope != null + ? () { + if (!orderScope.mounted) return; + (orderScope.widget as SectionOrderScope).show(sheetContext); + } + : null, + title: title, + group: group, + initialSort: sortMode, + onSort: onSort, + custom: custom, + ); + }, + ); + } finally { + // A pop resolves before the scrim finishes fading. + if (release != null) { + await sheetRoute?.completed; + release(); + } + } +} class _SectionViewSheet extends HookConsumerWidget { + final VoidCallback? onReorder; final String title; final String group; final ChannelSortMode initialSort; final ValueChanged onSort; final bool custom; - final bool isFirst; - final bool isLast; const _SectionViewSheet({ + required this.onReorder, required this.title, required this.group, required this.initialSort, required this.onSort, required this.custom, - required this.isFirst, - required this.isLast, }); @override Widget build(BuildContext context, WidgetRef ref) { - final manager = ref.watch(channelFilterProvider); + final manager = ref.watch( + group.startsWith('solo:') ? soloFilterProvider : channelFilterProvider, + ); useListenable(manager); // Watched, not captured: a sheet opened before desktop's unified records // arrive turns read-only when they do. @@ -142,37 +187,24 @@ class _SectionViewSheet extends HookConsumerWidget { Map values, T selected, ValueChanged? change, - ) => AppListCard( + ) => BuzzSettingMenu( + controlKey: ValueKey('section-menu-$label'), + grouped: true, + trailingIcon: Icons.unfold_more, + enabled: change != null, label: label, - dividerIndent: Grid.xs, - children: [ + value: selected, + valueLabel: values[selected]!, + onSelected: (value) => change?.call(value), + options: [ for (final entry in values.entries) - Semantics( - checked: entry.key == selected, - inMutuallyExclusiveGroup: true, - enabled: change != null, - child: AppListRow( - key: ValueKey('section-choice-$label-${entry.value}'), - title: entry.value, - trailing: entry.key == selected - ? Icon( - BuzzIcons.check, - size: 18, - color: context.colors.primary, - ) - : null, - titleColor: change == null - ? context.colors.onSurfaceVariant - : null, - onTap: change == null - ? null - : () { - change(entry.key); - }, - ), - ), + BuzzSettingMenuOption(label: entry.value, value: entry.key), ], ); + final onApply = saving.value || (filterChanged() && manager?.busy == true) + ? null + : apply; + final applyLabel = saving.value ? 'Saving…' : 'Apply changes'; return PopScope( canPop: !saving.value, child: SafeArea( @@ -187,60 +219,98 @@ class _SectionViewSheet extends HookConsumerWidget { children: [ BuzzSheetHeader( title: title, - trailing: saving.value - ? const IconButton( - tooltip: 'Saving…', - onPressed: null, - icon: Icon(BuzzIcons.x), + leading: defaultTargetPlatform == TargetPlatform.iOS + ? IosGlassNavigationButton( + icon: IosGlassNavigationIcon.close, + semanticLabel: 'Discard changes', + onPressed: saving.value ? null : () => close(), ) - : null, + : IconButton( + tooltip: 'Discard changes', + onPressed: saving.value ? null : () => close(), + icon: const Icon(BuzzIcons.x), + ), + trailing: defaultTargetPlatform == TargetPlatform.iOS + ? IosGlassNavigationButton( + icon: IosGlassNavigationIcon.check, + semanticLabel: applyLabel, + onPressed: onApply, + isBusy: saving.value, + ) + : IconButton( + tooltip: applyLabel, + onPressed: onApply, + icon: const Icon(BuzzIcons.check), + ), ), Flexible( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - choices( - 'Sort', - { - ChannelSortMode.alpha: 'A–Z', - ChannelSortMode.recent: 'Recent', - }, - sort.value, - saving.value || !sortEditable - ? null - : (value) => sort.value = value, - ), - choices( - 'Show', - { - ChannelFilterMode.all: 'All', - ChannelFilterMode.unreads: 'Unreads', - ChannelFilterMode.active: 'Active', - }, - mode.value, - writable - ? (value) { - filterDirty.value = true; - mode.value = value; - } - : null, - ), - CollapsibleSectionBody( - expanded: mode.value == ChannelFilterMode.active, - child: choices( - 'Active in the past', - { - for (final day in {1, 7, 30, 90, days.value}) - day: '$day ${day == 1 ? 'day' : 'days'}', - }, - days.value, - writable - ? (value) { - filterDirty.value = true; - days.value = value; - } - : null, + AnimatedSize( + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : sectionExpandDuration, + alignment: Alignment.topCenter, + curve: sectionExpandCurve, + child: AppListCard( + // A rounded clip around UIKit pickers also clips Flutter's + // following overlay, hiding the management actions below. + clipBehavior: + defaultTargetPlatform == TargetPlatform.iOS + ? Clip.none + : Clip.antiAlias, + dividerIndent: Grid.xs, + children: [ + choices( + 'Sort', + { + ChannelSortMode.alpha: 'A–Z', + ChannelSortMode.recent: 'Recent', + }, + sort.value, + saving.value || !sortEditable + ? null + : (value) => sort.value = value, + ), + choices( + 'Show', + { + ChannelFilterMode.all: 'All', + ChannelFilterMode.unreads: 'Unreads', + ChannelFilterMode.active: 'Active', + }, + mode.value, + writable + ? (value) { + filterDirty.value = true; + mode.value = value; + } + : null, + ), + if (mode.value == ChannelFilterMode.active) + choices( + 'Active in the past', + { + for (final day in { + 1, + 7, + 30, + 90, + days.value, + }) + day: '$day ${day == 1 ? 'day' : 'days'}', + }, + days.value, + writable + ? (value) { + filterDirty.value = true; + days.value = value; + } + : null, + ), + ], ), ), if (manager?.ready != true) @@ -257,36 +327,34 @@ class _SectionViewSheet extends HookConsumerWidget { }, child: const Text('Retry loading preferences'), ), - if (custom && layoutEditable) ...[ - const Divider(), - for (final action in { - 'rename': ('Rename section', BuzzIcons.pencil), - 'move_up': ('Move up', BuzzIcons.arrowUp), - 'move_down': ('Move down', BuzzIcons.arrowDown), - 'delete': ('Delete section', BuzzIcons.trash2), - }.entries) - ListTile( - contentPadding: EdgeInsets.zero, - leading: Icon( - action.value.$2, - size: 16, - color: action.key == 'delete' - ? context.colors.error - : null, - ), - title: Text( - action.value.$1, - style: action.key == 'delete' - ? TextStyle(color: context.colors.error) - : null, - ), - enabled: - !saving.value && - !(action.key == 'move_up' && isFirst) && - !(action.key == 'move_down' && isLast), - onTap: () => close(action.key), - ), - ], + if (custom && layoutEditable || onReorder != null) + AppListCard( + children: [ + if (custom && layoutEditable) + AppListRow( + title: 'Rename section', + icon: BuzzIcons.pencil, + onTap: saving.value + ? null + : () => close('rename'), + ), + if (onReorder != null) + AppListRow( + title: 'Reorder sections', + icon: BuzzIcons.arrowUpDown, + onTap: saving.value ? null : onReorder, + ), + if (custom && layoutEditable) + AppListRow( + title: 'Delete section', + icon: BuzzIcons.trash2, + titleColor: context.colors.error, + onTap: saving.value + ? null + : () => close('delete'), + ), + ], + ), ], ), ), @@ -305,44 +373,6 @@ class _SectionViewSheet extends HookConsumerWidget { ), ), ), - const SizedBox(height: Grid.xxs), - Padding( - padding: const EdgeInsets.symmetric(horizontal: Grid.gutter), - child: Align( - alignment: Alignment.centerRight, - child: Wrap( - alignment: WrapAlignment.end, - spacing: Grid.xxs, - runSpacing: Grid.xxs, - children: [ - TextButton( - onPressed: saving.value ? null : () => close(), - child: const Text('Cancel'), - ), - FilledButton( - style: FilledButton.styleFrom( - backgroundColor: context.colors.onSurface, - foregroundColor: context.colors.surface, - ), - // Only a filter write waits on the filter read; - // sort applies locally, as it did before filters. - onPressed: - saving.value || - (filterChanged() && manager?.busy == true) - ? null - : apply, - child: Text( - saving.value - ? 'Saving…' - : failed.value - ? 'Retry' - : 'Apply', - ), - ), - ], - ), - ), - ), ], ), ), diff --git a/mobile/lib/features/channels/channels_page/rename_section.dart b/mobile/lib/features/channels/channels_page/rename_section.dart new file mode 100644 index 0000000000..dead0cc826 --- /dev/null +++ b/mobile/lib/features/channels/channels_page/rename_section.dart @@ -0,0 +1,150 @@ +part of '../channels_page.dart'; + +/// Values submitted by the section rename editor. +typedef SectionRenameResult = ({String name, String? icon}); + +/// Edits a section’s name and icon together, returning null on cancellation. +Future showSectionRenameEditor( + BuildContext context, + ChannelSection section, +) async { + if (defaultTargetPlatform == TargetPlatform.iOS) { + const editor = MethodChannel('buzz/profile_text_editor'); + const picker = MethodChannel('buzz/section_emoji'); + final theme = utilitySurfaceThemeData(Theme.of(context)); + final container = ProviderScope.containerOf(context, listen: false); + Map selection(String icon) { + if (!icon.startsWith(':')) return {'icon': icon}; + final url = container + .read(customEmojiListProvider) + .where((e) => ':${e.shortcode}:' == icon) + .firstOrNull + ?.url; + return { + 'icon': icon, + if (url != null) + 'iconBytes': container + .read(customEmojiBytesCacheProvider) + .lookup(url), + }; + } + + var editorOpen = true; + picker.setMethodCallHandler((call) async { + if (call.method != 'choose' || !context.mounted) return null; + var unicodeOnly = false; + try { + await container.read(customEmojiPaletteProvider.future); + } catch (_) { + unicodeOnly = true; + } + if (!editorOpen || !context.mounted) return null; + final result = Completer?>(); + showEmojiPicker( + context: context, + nativeEmojiOnly: unicodeOnly, + onSelect: (value) { + if (!result.isCompleted) result.complete(selection(value)); + }, + onDismiss: () { + if (!result.isCompleted) result.complete(null); + }, + ); + return result.future; + }); + try { + final value = await editor + .invokeMapMethod('presentSection', { + 'title': 'Rename section', + 'initialValue': section.name, + 'placeholder': 'Section name', + 'multiline': false, + 'requireNonEmpty': true, + 'brightness': theme.brightness.name, + 'pageBackgroundArgb': theme.colorScheme.surface.toARGB32(), + 'containerBackgroundArgb': theme.colorScheme.surfaceContainerHighest + .toARGB32(), + 'containerCornerRadius': Radii.container, + ...selection(section.icon ?? ''), + }); + if (value == null) return null; + final name = (value['name'] as String).trim(); + final icon = value['icon'] as String; + return name.isEmpty + ? null + : (name: name, icon: icon.isEmpty ? null : icon); + } on MissingPluginException { + // Older iOS builds use the same editable fields in Flutter. + } on PlatformException { + // A presentation failure still allows editing in Flutter. + } finally { + editorOpen = false; + picker.setMethodCallHandler(null); + } + } + if (!context.mounted) return null; + return showBuzzDialog( + context: context, + builder: (_) => _SectionNameDialog(section), + ); +} + +class _SectionNameDialog extends HookWidget { + const _SectionNameDialog(this.section); + final ChannelSection section; + + @override + Widget build(BuildContext context) { + final controller = useTextEditingController(text: section.name); + final icon = useState(section.icon); + void confirm() { + final name = controller.text.trim(); + if (name.isNotEmpty) { + Navigator.of(context).pop((name: name, icon: icon.value)); + } + } + + return AlertDialog( + scrollable: true, + title: const Text('Rename Section'), + content: Row( + children: [ + SizedBox.square( + dimension: 52, + child: IconButton.filledTonal( + tooltip: 'Choose section emoji', + icon: icon.value == null + ? const Icon(Icons.emoji_emotions_outlined) + : _WorkspaceIcon(icon.value!), + onPressed: () => showEmojiPicker( + context: context, + onSelect: (value) { + if (context.mounted) icon.value = value; + }, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), + child: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration(labelText: 'Name'), + onSubmitted: (_) => confirm(), + ), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + TextButton(onPressed: confirm, child: const Text('Rename')), + ], + ); + } +} diff --git a/mobile/lib/features/channels/channels_page/sections.dart b/mobile/lib/features/channels/channels_page/sections.dart index 269dacca53..1632b9d759 100644 --- a/mobile/lib/features/channels/channels_page/sections.dart +++ b/mobile/lib/features/channels/channels_page/sections.dart @@ -8,8 +8,6 @@ class _CustomChannelSection extends StatelessWidget { final bool Function(Channel) isVisible; final Widget Function(Channel) buildRow; final bool expanded; - final bool isFirst; - final bool isLast; final VoidCallback onToggle; final _SectionEdits? edits; final ChannelSortMode sortMode; @@ -22,8 +20,6 @@ class _CustomChannelSection extends StatelessWidget { required this.isVisible, required this.buildRow, required this.expanded, - required this.isFirst, - required this.isLast, required this.onToggle, required this.edits, required this.sortMode, @@ -37,15 +33,13 @@ class _CustomChannelSection extends StatelessWidget { child: _CustomSectionHeader( section: section, expanded: expanded, - isFirst: isFirst, - isLast: isLast, onToggle: onToggle, edits: edits, sortMode: sortMode, onSortModeChange: onSortModeChange, ), ), - _SectionChannelsBody( + FilteredChannelSectionBody( expanded: expanded, channels: channels, isVisible: isVisible, @@ -55,27 +49,31 @@ class _CustomChannelSection extends StatelessWidget { ); } -typedef _SectionEdits = ({ - VoidCallback onRename, - VoidCallback onDelete, - VoidCallback onMoveUp, - VoidCallback onMoveDown, -}); +typedef _SectionEdits = ({VoidCallback onRename, VoidCallback onDelete}); /// A workspace's decorative icon: a Unicode emoji, or a community custom /// emoji. As on desktop, a shortcode the catalog lacks draws nothing. class _WorkspaceIcon extends ConsumerWidget { - const _WorkspaceIcon(this.icon); + const _WorkspaceIcon(this.icon, {this.inHeader = false}); + final bool inHeader; final String icon; @override Widget build(BuildContext context, WidgetRef ref) { - Widget spaced(Widget child) => Padding( - padding: const EdgeInsets.only(right: Grid.quarter), - child: ExcludeSemantics(child: child), - ); + Widget display(Widget child) { + if (!inHeader) return ExcludeSemantics(child: child); + return _SectionLeadingIcon(child); + } + if (!(icon.length > 2 && icon.startsWith(':') && icon.endsWith(':'))) { - return spaced(Text(icon, style: navigationSectionTextStyle)); + return display( + FittedBox( + child: Text( + icon, + style: const TextStyle(fontSize: _kWorkspaceIconSize, height: 1), + ), + ), + ); } final shortcode = normalizeShortcode(icon); final url = shortcode == null @@ -89,7 +87,7 @@ class _WorkspaceIcon extends ConsumerWidget { ), ); if (url == null) return const SizedBox.shrink(); - return spaced( + return display( CustomEmojiImage( shortcode: shortcode!, url: url, @@ -102,11 +100,31 @@ class _WorkspaceIcon extends ConsumerWidget { const _kWorkspaceIconSize = 16.0; +class _SectionLeadingIcon extends StatelessWidget { + const _SectionLeadingIcon(this.child); + final Widget child; + + @override + Widget build(BuildContext context) { + const sideInset = (_kChannelIconSize - _kWorkspaceIconSize) / 2; + return Padding( + padding: const EdgeInsets.only(right: Grid.xxs - sideInset), + child: SizedBox.square( + dimension: _kChannelIconSize, + child: Center( + child: SizedBox.square( + dimension: _kWorkspaceIconSize, + child: ExcludeSemantics(child: child), + ), + ), + ), + ); + } +} + class _CustomSectionHeader extends StatelessWidget { final WorkspaceSection section; final bool expanded; - final bool isFirst; - final bool isLast; final VoidCallback onToggle; final _SectionEdits? edits; final ChannelSortMode sortMode; @@ -115,8 +133,6 @@ class _CustomSectionHeader extends StatelessWidget { const _CustomSectionHeader({ required this.section, required this.expanded, - required this.isFirst, - required this.isLast, required this.onToggle, required this.edits, required this.sortMode, @@ -129,43 +145,31 @@ class _CustomSectionHeader extends StatelessWidget { final edits = this.edits; final onSortModeChange = this.onSortModeChange; Future openOptions(BuildContext buttonContext) async { - final action = await _showSectionViewSheet( + final action = await showSectionViewSheet( buttonContext, title: label, group: sectionSortGroupKey(section.id), sortMode: sortMode, onSort: (mode) => onSortModeChange?.call(mode), custom: edits != null, - isFirst: isFirst, - isLast: isLast, ); if (!buttonContext.mounted || edits == null) return; switch (action) { case 'rename': edits.onRename(); - case 'move_up': - edits.onMoveUp(); - case 'move_down': - edits.onMoveDown(); case 'delete': edits.onDelete(); } } final menu = [ - if (edits != null) ...[ + if (edits != null) (label: 'Rename section', symbol: 'pencil', onPressed: edits.onRename), - ( - label: 'Move up', - symbol: 'arrow.up', - onPressed: isFirst ? null : edits.onMoveUp, - ), - ( - label: 'Move down', - symbol: 'arrow.down', - onPressed: isLast ? null : edits.onMoveDown, - ), - ], + ( + label: 'Reorder sections', + symbol: 'arrow.up.arrow.down', + onPressed: () => SectionOrderScope.of(context)?.show(context), + ), ..._sortMenu(sortMode, onSortModeChange), ( label: 'Filter…', @@ -175,17 +179,19 @@ class _CustomSectionHeader extends StatelessWidget { if (edits != null) (label: 'Delete section', symbol: 'trash', onPressed: edits.onDelete), ]; - final sortAt = edits == null ? 0 : 3; + final sortAt = edits == null ? 1 : 2; final sectionColor = navigationHeadingForeground(context); return GestureDetector( onTap: onToggle, behavior: HitTestBehavior.opaque, child: Padding( - padding: const EdgeInsets.fromLTRB( + padding: EdgeInsets.fromLTRB( Grid.gutter, _kSectionHeaderVerticalPadding, - Grid.gutter, + _usesNativeSectionMenu(context) + ? Grid.gutter + Grid.half + : Grid.twelve, _kSectionHeaderVerticalPadding, ), child: Row( @@ -201,7 +207,7 @@ class _CustomSectionHeader extends StatelessWidget { child: _SectionLabel( label: label, icon: switch (section.icon) { - final icon? => _WorkspaceIcon(icon), + final icon? => _WorkspaceIcon(icon, inHeader: true), null => null, }, expanded: expanded, @@ -232,14 +238,9 @@ class _CustomSectionHeader extends StatelessWidget { ) else Builder( - builder: (buttonContext) => _SectionOptionsButton( + builder: (buttonContext) => SectionOptionsButton( key: ValueKey('section-menu-${section.id}'), tooltip: '$label options', - icon: Icon( - BuzzIcons.ellipsis, - size: 14, - color: navigationAccessoryForeground(context), - ), onPressed: () => openOptions(buttonContext), ), ), @@ -250,45 +251,6 @@ class _CustomSectionHeader extends StatelessWidget { } } -class _SectionNameDialog extends HookWidget { - final String title; - final String confirmLabel; - final String initialValue; - - const _SectionNameDialog({ - required this.title, - required this.confirmLabel, - this.initialValue = '', - }); - - @override - Widget build(BuildContext context) { - final controller = useTextEditingController(text: initialValue); - - void confirm() { - final name = controller.text.trim(); - if (name.isNotEmpty) Navigator.of(context).pop(name); - } - - return AlertDialog( - title: Text(title), - content: TextField( - controller: controller, - autofocus: true, - decoration: const InputDecoration(labelText: 'Name'), - onSubmitted: (_) => confirm(), - ), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('Cancel'), - ), - TextButton(onPressed: confirm, child: Text(confirmLabel)), - ], - ); - } -} - class _ChannelSection extends StatelessWidget { final String title; @@ -330,7 +292,7 @@ class _ChannelSection extends StatelessWidget { onSortModeChange: onSortModeChange, ), ), - _SectionChannelsBody( + FilteredChannelSectionBody( expanded: expanded, channels: channels, isVisible: isVisible, @@ -361,71 +323,6 @@ class _ChannelSection extends StatelessWidget { ); } -class _SectionChannelsBody extends HookWidget { - const _SectionChannelsBody({ - required this.expanded, - required this.channels, - required this.isVisible, - required this.buildRow, - this.emptySliver, - }); - - final bool expanded; - final List channels; - final bool Function(Channel) isVisible; - final Widget Function(Channel) buildRow; - final Widget? emptySliver; - - @override - Widget build(BuildContext context) { - final visibleChannels = []; - final hiddenIds = []; - for (final channel in channels) { - if (isVisible(channel)) { - visibleChannels.add(channel); - } else { - hiddenIds.add(channel.id); - } - } - final hiddenCount = hiddenIds.length; - final reveal = useState(false); - useEffect(() { - reveal.value = false; - return null; - }, [hiddenIds.join(',')]); - final displayed = reveal.value ? channels : visibleChannels; - - return CollapsibleSliverBody( - expanded: expanded, - sliver: channels.isEmpty && emptySliver != null - ? emptySliver! - : SliverList.builder( - itemCount: displayed.length + (hiddenCount == 0 ? 0 : 1), - findChildIndexCallback: (key) { - final index = displayed.indexWhere( - (c) => ValueKey(c.id) == key, - ); - return index < 0 ? null : index; - }, - itemBuilder: (context, index) { - if (index < displayed.length) return buildRow(displayed[index]); - return Align( - alignment: Alignment.centerLeft, - child: TextButton( - onPressed: () => reveal.value = !reveal.value, - child: Text( - reveal.value - ? 'Hide filtered channels' - : 'Show hidden channels · $hiddenCount', - ), - ), - ); - }, - ), - ); - } -} - class _EmptyState extends StatelessWidget { const _EmptyState(); @@ -478,7 +375,7 @@ class _SectionHeader extends StatelessWidget { @override Widget build(BuildContext context) { void openOptions(BuildContext buttonContext, ChannelSortMode mode) { - _showSectionViewSheet( + showSectionViewSheet( buttonContext, title: label, group: group, @@ -493,10 +390,12 @@ class _SectionHeader extends StatelessWidget { onTap: onToggle, behavior: HitTestBehavior.opaque, child: Padding( - padding: const EdgeInsets.fromLTRB( + padding: EdgeInsets.fromLTRB( Grid.gutter, _kSectionHeaderVerticalPadding, - Grid.gutter, + _usesNativeSectionMenu(context) + ? Grid.gutter + Grid.half + : Grid.twelve, _kSectionHeaderVerticalPadding, ), child: Row( @@ -504,6 +403,15 @@ class _SectionHeader extends StatelessWidget { Expanded( child: _SectionLabel( label: label, + icon: group == 'starred' + ? _SectionLeadingIcon( + TablerStarIcon( + color: sectionColor, + filled: true, + size: _kWorkspaceIconSize, + ), + ) + : null, expanded: expanded, color: sectionColor, ), @@ -536,14 +444,9 @@ class _SectionHeader extends StatelessWidget { ) else Builder( - builder: (buttonContext) => _SectionOptionsButton( + builder: (buttonContext) => SectionOptionsButton( key: ValueKey('sort-menu-$label'), tooltip: '$label options', - icon: Icon( - BuzzIcons.ellipsis, - size: 14, - color: navigationAccessoryForeground(context), - ), onPressed: () => openOptions(buttonContext, mode), ), ), @@ -572,7 +475,7 @@ class _SectionLabel extends StatelessWidget { @override Widget build(BuildContext context) => Padding( - padding: const EdgeInsets.only(top: Grid.xxs), + padding: EdgeInsets.only(top: icon == null ? Grid.xxs : 0), child: Row( children: [ ?icon, @@ -639,41 +542,3 @@ bool _usesNativeSectionMenu(BuildContext context) => defaultTargetPlatform == TargetPlatform.iOS && (DuoToolbarScope.maybeStripOf(context) ?? FoldGeometry.of(context).strip) != null; - -class _SectionOptionsButton extends StatelessWidget { - const _SectionOptionsButton({ - super.key, - required this.tooltip, - required this.icon, - required this.onPressed, - }); - - final String tooltip; - final Widget icon; - final VoidCallback onPressed; - - @override - Widget build(BuildContext context) => Semantics( - button: true, - label: tooltip, - onTap: onPressed, - excludeSemantics: true, - child: Tooltip( - message: tooltip, - child: SizedBox.square( - dimension: 44, - child: InkWell( - onTap: onPressed, - borderRadius: BorderRadius.circular(Radii.full), - child: Align( - alignment: Alignment.centerRight, - child: SizedBox( - width: _kChannelIconSize, - child: Center(child: icon), - ), - ), - ), - ), - ), - ); -} diff --git a/mobile/lib/features/channels/me/me_page.dart b/mobile/lib/features/channels/me/me_page.dart index fb8dfe348e..8233888598 100644 --- a/mobile/lib/features/channels/me/me_page.dart +++ b/mobile/lib/features/channels/me/me_page.dart @@ -1,4 +1,12 @@ +import 'dart:async'; import 'dart:convert'; +import '../channel_filter/channel_filter_activity.dart'; +import '../channel_sort/channel_sort_provider.dart'; +import '../channel_sort/channel_sort_storage.dart'; +import '../channel_filter/channel_filter_provider.dart'; +import '../channel_filter/channel_filter_store.dart'; +import '../channel_sections/filtered_channel_section_body.dart'; +import '../channels_page/filters.dart'; import 'package:buzz/shared/widgets/feedback_snackbar.dart'; import 'package:buzz/shared/widgets/adaptive_conversation_pane.dart'; @@ -11,6 +19,7 @@ import 'package:uuid/uuid.dart'; import '../../../shared/profile/user_cache_provider.dart'; import '../../../shared/widgets/concentric_sheet_surface.dart'; import '../../../shared/widgets/bee_refresh_indicator.dart'; +import '../../../shared/widgets/collapsible_sliver_body.dart'; import 'me_section.dart'; import 'me_working_provider.dart'; import 'solo_working_dots.dart'; @@ -49,8 +58,6 @@ import '../channel_member_profile_actions.dart'; import '../channel_management_provider.dart'; import '../channels_provider.dart'; import '../channel_sections/channel_sections_provider.dart'; -import '../channel_sort/channel_sort_provider.dart'; -import '../channel_sort/channel_sort_storage.dart'; import '../channel_stars/channel_stars_provider.dart'; part 'me_page_helpers.dart'; @@ -104,7 +111,7 @@ class MePage extends HookConsumerWidget { ref.watch(meOfflineSaveWarningProvider).value ?? false; final channels = ref.watch(channelsProvider); // Rows read unread state themselves; keep it alive while Solo is shown. - ref.watch(meUnreadChannelIdsProvider); + final unreadIds = ref.watch(meUnreadChannelIdsProvider); final busy = useState(false); Future perform(Future Function() action) async { if (busy.value) return; @@ -250,21 +257,35 @@ class MePage extends HookConsumerWidget { ), ), ?offlineNotice, - MeSection( - sliver: true, + _SoloFilterSection( key: const ValueKey('me-ungrouped-chats'), + group: 'solo', label: 'Solo', - children: [ - for (final channel in unfiled) row(channel), - if (unfiled.isEmpty && organization != null) - const _MeSectionEmpty('No chats yet'), - ], + chats: unfiled, + unread: unreadIds, + row: row, + empty: organization == null ? null : 'No chats yet', ), ], ), ); } + Widget section( + String group, + String label, + Iterable chats, + String empty, + ) => _SoloFilterSection( + key: ValueKey(group), + group: group, + label: label, + chats: chats, + unread: unreadIds, + row: row, + empty: empty, + ); + final inventorySlivers = [ SliverPadding( padding: EdgeInsets.fromLTRB( @@ -290,35 +311,21 @@ class MePage extends HookConsumerWidget { for (final group in sections) ...[ if (group != sections.first) const SliverToBoxAdapter(child: SizedBox(height: Grid.xxs)), - MeSection( - sliver: true, - key: ValueKey(group['id']), - label: group['name'] as String, - children: [ - for (final channel in visible.where( - (c) => assignments[c.id] == group['id'], - )) - row(channel), - if (!visible.any((c) => assignments[c.id] == group['id'])) - const _MeSectionEmpty('No chats in this workspace yet'), - ], + section( + 'solo:workspace:${group['id']}', + group['name'] as String, + visible.where((c) => assignments[c.id] == group['id']), + 'No chats in this workspace yet', ), ], if (sections.isNotEmpty) const SliverToBoxAdapter(child: SizedBox(height: Grid.xxs)), if (visible.isNotEmpty || sections.isNotEmpty) - MeSection( - sliver: true, - key: const ValueKey('me-ungrouped-chats'), - label: 'Chats', - children: [ - for (final channel in visible.where( - (c) => !assignments.containsKey(c.id), - )) - row(channel), - if (!visible.any((c) => !assignments.containsKey(c.id))) - const _MeSectionEmpty('No chats yet'), - ], + section( + 'solo:chats', + 'Chats', + visible.where((c) => !assignments.containsKey(c.id)), + 'No chats yet', ), ], ), @@ -363,7 +370,12 @@ class MePage extends HookConsumerWidget { edgeOffset: topSectionHeight, onRefresh: () async { ref.invalidate(meGroupsProvider); - await ref.read(channelsProvider.notifier).refresh(); + ref.invalidate(channelFilterActivityProvider); + await Future.wait([ + ref.read(channelsProvider.notifier).refresh(), + if (ref.read(soloFilterProvider) case final manager?) + manager.refresh(), + ]); await ref.read(meGroupsProvider.future); }, child: CustomScrollView( @@ -433,3 +445,112 @@ class MePage extends HookConsumerWidget { ); } } + +class _SoloFilterSection extends HookConsumerWidget { + const _SoloFilterSection({ + super.key, + required this.group, + required this.label, + required this.chats, + required this.unread, + required this.row, + required this.empty, + }); + final String group; + final String label; + final Iterable chats; + final Set unread; + final Widget Function(Channel) row; + final String? empty; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final manager = ref.watch( + group == 'solo' ? channelFilterProvider : soloFilterProvider, + ); + useListenable(manager); + final mode = manager?.store.modeFor(group) ?? ChannelFilterMode.all; + final window = + manager?.store.windowFor(group) ?? defaultActiveWindowSeconds; + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final selected = ConversationPaneScope.maybeOf(context)?.selectedId; + final tick = useState(0); + int? nextExpiry; + final visibleIds = {}; + final sortMode = ref.watch( + channelSortProvider.select( + (state) => group == 'solo' + ? state.sortModeFor(group) + : state.store.groups[group] ?? ChannelSortMode.recent, + ), + ); + final orderedChats = sortMode == ChannelSortMode.alpha + ? sortChannelsForList(chats.toList(), sortMode) + : chats.toList(); + for (final chat in orderedChats) { + final activity = mode == ChannelFilterMode.active + ? ref.watch(channelFilterActivityProvider(chat.id)).asData + : null; + final at = activity?.value; + if (at != null) { + final expiry = at + window; + if (expiry > now && (nextExpiry == null || expiry < nextExpiry)) { + nextExpiry = expiry; + } + } + if (channelMatchesFilter( + mode: mode, + unread: unread.contains(chat.id), + activitySeconds: at, + activityKnown: activity != null, + nowSeconds: now, + windowSeconds: window, + selected: selected == chat.id, + )) { + visibleIds.add(chat.id); + } + } + useEffect(() { + if (nextExpiry == null) return null; + return Timer( + Duration(seconds: nextExpiry - now), + () => tick.value++, + ).cancel; + }, [nextExpiry, tick.value]); + return MeSection.sliverBody( + label: label, + onFilter: () => showSectionViewSheet( + context, + group: group, + title: label, + sortMode: sortMode, + onSort: (value) => + ref.read(channelSortProvider.notifier).setSortModeFor(group, value), + ), + buildBody: (expanded) => group == 'solo' + ? FilteredChannelSectionBody( + expanded: expanded, + channels: orderedChats, + isVisible: (chat) => visibleIds.contains(chat.id), + buildRow: row, + disclosureInset: Grid.xxs, + emptySliver: empty == null + ? null + : SliverToBoxAdapter(child: _MeSectionEmpty(empty!)), + ) + : CollapsibleSliverBody( + expanded: expanded, + sliver: SliverList.list( + children: [ + for (final chat in orderedChats) + if (visibleIds.contains(chat.id)) row(chat), + if (visibleIds.isEmpty && (chats.isNotEmpty || empty != null)) + _MeSectionEmpty( + chats.isEmpty ? empty! : 'No matching chats', + ), + ], + ), + ), + ); + } +} diff --git a/mobile/lib/features/channels/me/me_page_helpers.dart b/mobile/lib/features/channels/me/me_page_helpers.dart index 79b611958b..599bfe163c 100644 --- a/mobile/lib/features/channels/me/me_page_helpers.dart +++ b/mobile/lib/features/channels/me/me_page_helpers.dart @@ -100,9 +100,11 @@ class _MeChatRow extends ConsumerWidget { onTap: onTap, onLongPress: onLongPress, child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: Grid.xxs, - vertical: Grid.inventoryRowInset, + padding: const EdgeInsets.fromLTRB( + Grid.xxs, + Grid.inventoryRowInset, + Grid.xxs + Grid.half, + Grid.inventoryRowInset, ), child: Row( children: [ @@ -125,10 +127,20 @@ class _MeChatRow extends ConsumerWidget { ), ), ), - if (working.isNotEmpty) ...[ - const SizedBox(width: Grid.xs), - SoloWorkingDots(color: color), - ], + SizedBox( + width: Grid.inventoryAccessoryWidth, + child: Align( + alignment: Alignment.centerRight, + child: SizedBox( + width: 20, + child: Center( + child: working.isEmpty + ? null + : SoloWorkingDots(color: color), + ), + ), + ), + ), ], ), ), diff --git a/mobile/lib/features/channels/me/me_section.dart b/mobile/lib/features/channels/me/me_section.dart index 8fc735ef50..ae42ee2979 100644 --- a/mobile/lib/features/channels/me/me_section.dart +++ b/mobile/lib/features/channels/me/me_section.dart @@ -6,6 +6,8 @@ import '../../../shared/theme/buzz_icons.dart'; import '../../../shared/widgets/collapsible_section_body.dart'; import '../../../shared/widgets/collapsible_sliver_body.dart'; +import '../channel_sections/section_options_button.dart'; + /// A project or unassigned-chat section matching the Channels list headings. class MeSection extends HookWidget { const MeSection({ @@ -13,21 +15,29 @@ class MeSection extends HookWidget { required this.label, required this.children, this.sliver = false, - }); + this.onFilter, + }) : buildBody = null; + + const MeSection.sliverBody({ + super.key, + required this.label, + required this.buildBody, + this.onFilter, + }) : sliver = true, + children = const []; final String label; - - /// Render rows individually in the containing scroll view. + final VoidCallback? onFilter; final bool sliver; - final List children; + final Widget Function(bool expanded)? buildBody; @override Widget build(BuildContext context) { final expanded = useState(true); final color = navigationHeadingForeground(context); final reducedMotion = MediaQuery.disableAnimationsOf(context); - final header = Semantics( + final toggle = Semantics( label: label, excludeSemantics: true, onTap: () => expanded.value = !expanded.value, @@ -74,14 +84,29 @@ class MeSection extends HookWidget { ), ), ); + final header = onFilter == null + ? toggle + : Row( + children: [ + Expanded(child: toggle), + Padding( + padding: EdgeInsets.zero, + child: SectionOptionsButton( + tooltip: '$label options', + onPressed: onFilter!, + ), + ), + ], + ); if (sliver) { return SliverMainAxisGroup( slivers: [ SliverToBoxAdapter(child: header), - CollapsibleSliverBody( - expanded: expanded.value, - sliver: SliverList.list(children: children), - ), + buildBody?.call(expanded.value) ?? + CollapsibleSliverBody( + expanded: expanded.value, + sliver: SliverList.list(children: children), + ), ], ); } diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index 1079a09ad1..700cb1080f 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -328,8 +328,11 @@ class RelaySessionNotifier extends Notifier { NostrFilter filter, { Duration timeout = const Duration(seconds: 8), }) async { + final generation = _contextGeneration; if (_rateLimitGate.isActive) await _rateLimitGate.wait(); - if (_disposed) throw StateError('Relay session is disposed'); + if (_disposed || generation != _contextGeneration) { + throw StateError('Relay history request belongs to a retired session'); + } final subId = _nextSubId('h'); final completer = Completer>(); @@ -511,13 +514,6 @@ class RelaySessionNotifier extends Notifier { void debugHandleSocketMessageForTest(List data) => _handleMessage(data); - @visibleForTesting - void debugAttachSocketForTest(RelaySocket socket) { - _socket?.dispose(); - _socket = socket; - _socketConnected = true; - } - /// Registers a visible channel and returns an owner-scoped release callback. /// The most recently registered owner is prioritized during reconnect replay. void Function() registerVisibleChannel(String channelId) { diff --git a/mobile/lib/shared/relay/relay_session_test_hooks.dart b/mobile/lib/shared/relay/relay_session_test_hooks.dart index 3766fa7597..7fbfc8fd8a 100644 --- a/mobile/lib/shared/relay/relay_session_test_hooks.dart +++ b/mobile/lib/shared/relay/relay_session_test_hooks.dart @@ -2,6 +2,13 @@ part of 'relay_session.dart'; /// Test hooks into the session's private connection state. extension RelaySessionTestHooks on RelaySessionNotifier { + @visibleForTesting + void debugAttachSocketForTest(RelaySocket socket) { + _socket?.dispose(); + _socket = socket; + _socketConnected = true; + } + @visibleForTesting void debugHandleDisconnected([Object? error]) { _socketConnected = false; diff --git a/mobile/lib/shared/theme/grid.dart b/mobile/lib/shared/theme/grid.dart index de1597c1b3..9a1b7bfdeb 100644 --- a/mobile/lib/shared/theme/grid.dart +++ b/mobile/lib/shared/theme/grid.dart @@ -1,4 +1,7 @@ class Grid { + /// Space beneath the header actions reserved for row accessories. + static const double inventoryAccessoryWidth = 92; + /// Gap from inventory icons to labels. static const double inventoryLabelGap = 10.0; diff --git a/mobile/lib/shared/widgets/app_list_card.dart b/mobile/lib/shared/widgets/app_list_card.dart index 44e1aac2c2..a76e7f0542 100644 --- a/mobile/lib/shared/widgets/app_list_card.dart +++ b/mobile/lib/shared/widgets/app_list_card.dart @@ -11,6 +11,7 @@ class AppListCard extends StatelessWidget { super.key, this.label, this.dividerIndent, + this.clipBehavior = Clip.antiAlias, this.verticalPadding = Grid.xxs, this.horizontalPadding = Grid.gutter, required this.children, @@ -18,6 +19,7 @@ class AppListCard extends StatelessWidget { /// Rendered above the card in sentence case, as written — no uppercasing. final String? label; + final Clip clipBehavior; /// Separator inset from the card edge. Defaults to the standard row label /// column, clearing a leading icon. Icon-free cards can pass [_inset] so @@ -94,7 +96,7 @@ class AppListCard extends StatelessWidget { color: context.colors.surfaceContainerHighest, borderRadius: BorderRadius.circular(Radii.container), // Keeps row ripples inside the rounded corners. - clipBehavior: Clip.antiAlias, + clipBehavior: clipBehavior, child: AppListInset( horizontal: _inset, child: Column( diff --git a/mobile/lib/shared/widgets/app_route_observer.dart b/mobile/lib/shared/widgets/app_route_observer.dart index 708fc1175a..a1deb169be 100644 --- a/mobile/lib/shared/widgets/app_route_observer.dart +++ b/mobile/lib/shared/widgets/app_route_observer.dart @@ -1,5 +1,7 @@ import 'package:flutter/widgets.dart'; +import 'bottom_up_page_route.dart'; + /// Shared route lifecycle for native navigation and recording cleanup. final appRouteObserver = AppRouteObserver(); @@ -31,6 +33,12 @@ class AppRouteObserver extends RouteObserver> { previousRoute is! ModalRoute) { return; } + // Capture this while the sheet still owns its retention. Its completion + // also releases that retention, before some reveal callbacks run. + if (route is PopupRoute && + BottomUpPageRoute.hasRetainedControls(previousRoute)) { + return; + } route.completed.then((_) { if (!previousRoute.isCurrent) return; final listeners = List.of( diff --git a/mobile/lib/shared/widgets/bottom_up_page_route.dart b/mobile/lib/shared/widgets/bottom_up_page_route.dart index 95251f7aab..0c73e41bbd 100644 --- a/mobile/lib/shared/widgets/bottom_up_page_route.dart +++ b/mobile/lib/shared/widgets/bottom_up_page_route.dart @@ -53,6 +53,22 @@ class BottomUpPageRoute extends PageRouteBuilder { static ValueListenable sheetsAbove(ModalRoute route) => _coveringSheets[route] ??= ValueNotifier(0); + static final _retained = Expando(); + + static bool hasRetainedControls(ModalRoute? route) => + route != null && (_retained[route] ?? 0) > 0; + + /// Keep the presenting route's controls mounted through a modal's exit. + static VoidCallback retainControlsForSheet(ModalRoute route) { + final count = _coveringSheets[route] ??= ValueNotifier(0); + count.value++; + _retained[route] = (_retained[route] ?? 0) + 1; + return () { + _retained[route] = _retained[route]! - 1; + count.value--; + }; + } + ModalRoute? _coveredRoute; void _setCoveredRoute(ModalRoute? route) { diff --git a/mobile/lib/shared/widgets/buzz_toast.dart b/mobile/lib/shared/widgets/buzz_toast.dart index a62c1d6a97..99bf774431 100644 --- a/mobile/lib/shared/widgets/buzz_toast.dart +++ b/mobile/lib/shared/widgets/buzz_toast.dart @@ -158,10 +158,15 @@ class _ToastBubble extends HookWidget { if (persistent) { if (reduceMotion) { controller.value = visible ? 1 : 0; + if (!visible) onDismiss(); } else if (visible) { controller.forward(); } else { - controller.reverse(); + // An interrupted outro must not remove a notice that became + // relevant again. Reverse also completes if already dismissed. + controller.reverse().whenCompleteOrCancel(() { + if (context.mounted && controller.isDismissed) onDismiss(); + }); } return null; } diff --git a/mobile/lib/shared/widgets/ios_navigation_bar.dart b/mobile/lib/shared/widgets/ios_navigation_bar.dart index 7e0e15607a..ad624ba51c 100644 --- a/mobile/lib/shared/widgets/ios_navigation_bar.dart +++ b/mobile/lib/shared/widgets/ios_navigation_bar.dart @@ -16,6 +16,7 @@ import 'avatar_image.dart'; import 'dm_header_portrait.dart'; import 'dm_header_cluster.dart'; import 'app_route_observer.dart'; +import 'bottom_up_page_route.dart'; import 'ios_navigation_metrics.dart'; export 'ios_navigation_metrics.dart'; @@ -534,6 +535,9 @@ class IosNavigationBar extends HookConsumerWidget { } void scheduleRestore() { + // The section sheet keeps Home visible at the same scroll depth. A + // second UIKit layout pass during its scrim fade disturbs the glass. + if (BottomUpPageRoute.hasRetainedControls(route)) return; // Restore at reveal and again after the covering route exits. Route // transforms can change UIKit's safe-area layout during transitions. // The initial didPopNext alone runs before that transform has settled. diff --git a/mobile/lib/shared/widgets/ios_text_editor.dart b/mobile/lib/shared/widgets/ios_text_editor.dart index e91329ae3b..eb93576eef 100644 --- a/mobile/lib/shared/widgets/ios_text_editor.dart +++ b/mobile/lib/shared/widgets/ios_text_editor.dart @@ -15,6 +15,7 @@ class IosTextEditor { required String initialValue, required String placeholder, required bool multiline, + bool requireNonEmpty = false, required Brightness brightness, required Color pageBackgroundColor, required Color containerBackgroundColor, @@ -24,6 +25,7 @@ class IosTextEditor { 'initialValue': initialValue, 'placeholder': placeholder, 'multiline': multiline, + if (requireNonEmpty) 'requireNonEmpty': true, 'brightness': brightness.name, 'pageBackgroundArgb': pageBackgroundColor.toARGB32(), 'containerBackgroundArgb': containerBackgroundColor.toARGB32(), @@ -38,6 +40,7 @@ class IosTextEditor { required String initialValue, required String placeholder, required bool multiline, + bool requireNonEmpty = false, required Brightness brightness, required Color pageBackgroundColor, required Color containerBackgroundColor, @@ -55,6 +58,7 @@ class IosTextEditor { initialValue: draft, placeholder: placeholder, multiline: multiline, + requireNonEmpty: requireNonEmpty, brightness: brightness, pageBackgroundColor: pageBackgroundColor, containerBackgroundColor: containerBackgroundColor, diff --git a/mobile/lib/shared/widgets/modal_presentation.dart b/mobile/lib/shared/widgets/modal_presentation.dart index 56a3454be2..963a6e5150 100644 --- a/mobile/lib/shared/widgets/modal_presentation.dart +++ b/mobile/lib/shared/widgets/modal_presentation.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../theme/theme.dart'; import 'buzz_sheet_header.dart'; +import 'ios_composition_layer.dart'; import 'duo_toolbar.dart'; import 'ios_navigation_bar.dart'; import 'buzz_titled_sheet_layout.dart'; @@ -42,6 +43,7 @@ Future showBuzzModalBottomSheet({ Clip? clipBehavior, BoxConstraints? constraints, Color? barrierColor, + bool nativeIosBarrier = false, bool isScrollControlled = false, double scrollControlDisabledMaxHeightRatio = 9.0 / 16.0, bool useRootNavigator = false, @@ -80,73 +82,68 @@ Future showBuzzModalBottomSheet({ sheetTheme.colorScheme.surface; final reduceMotion = MediaQuery.disableAnimationsOf(context); - return showModalBottomSheet( - context: context, - 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), + Widget buildSheet(BuildContext 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), ), ), ), @@ -156,46 +153,78 @@ Future showBuzzModalBottomSheet({ ), ), ), - ); - 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, + ), + ); + 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, ), ), - 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, - ), - ), + ), + ); + } + + if (isIos && nativeIosBarrier) { + final navigator = Navigator.of(context, rootNavigator: true); + final localizations = MaterialLocalizations.of(context); + return navigator.push( + _NativeBarrierSheetRoute( + builder: buildSheet, + capturedThemes: InheritedTheme.capture( + from: context, + to: navigator.context, ), - ); - }, + isScrollControlled: isScrollControlled, + isDismissible: isDismissible, + enableDrag: enableDrag, + barrierLabel: barrierLabel ?? localizations.scrimLabel, + barrierOnTapHint: localizations.scrimOnTapHint( + localizations.bottomSheetLabel, + ), + scrimColor: + barrierColor ?? + theme.bottomSheetTheme.modalBarrierColor ?? + Colors.black54, + sheetAnimationStyle: reduceMotion + ? AnimationStyle.noAnimation + : (sheetAnimationStyle ?? buzzModalAnimationStyle), + ), + ); + } + return showModalBottomSheet( + context: context, + builder: buildSheet, backgroundColor: isIos || title != null ? Colors.transparent : surfaceColor, barrierLabel: barrierLabel, elevation: elevation, @@ -226,6 +255,46 @@ Future showBuzzModalBottomSheet({ ); } +/// Paint the section sheet's dimming in the barrier entry, above Home's +/// retained UIKit controls and below the sheet's own controls. +class _NativeBarrierSheetRoute extends ModalBottomSheetRoute { + _NativeBarrierSheetRoute({ + required super.builder, + required super.capturedThemes, + required super.isScrollControlled, + required super.isDismissible, + required super.enableDrag, + required super.barrierLabel, + required super.barrierOnTapHint, + required super.sheetAnimationStyle, + required this.scrimColor, + }) : super( + modalBarrierColor: Colors.transparent, + backgroundColor: Colors.transparent, + showDragHandle: false, + constraints: const BoxConstraints(maxWidth: double.infinity), + ); + + final Color scrimColor; + + @override + Widget buildModalBarrier() => Stack( + fit: StackFit.expand, + children: [ + IgnorePointer( + child: FadeTransition( + opacity: animation!.drive(CurveTween(curve: barrierCurve)), + child: IosCompositionLayer( + color: scrimColor, + child: const SizedBox(), + ), + ), + ), + super.buildModalBarrier(), + ], + ); +} + /// Window insets only apply where they intersect a centered sheet's bounds. class _SheetLocalSafeArea extends StatelessWidget { const _SheetLocalSafeArea({required this.localize, required this.child}); diff --git a/mobile/lib/shared/widgets/reconnect_capsule.dart b/mobile/lib/shared/widgets/reconnect_capsule.dart index c2abd3afa6..6072ac9dcd 100644 --- a/mobile/lib/shared/widgets/reconnect_capsule.dart +++ b/mobile/lib/shared/widgets/reconnect_capsule.dart @@ -6,6 +6,7 @@ class ReconnectCapsule extends HookWidget { super.key, required this.onSignIn, this.visible = true, + this.onHidden, this.message = 'Reconnect to Builderlab', this.actionLabel = 'Sign in', this.destructiveAction = false, @@ -17,6 +18,7 @@ class ReconnectCapsule extends HookWidget { final VoidCallback onSignIn; final bool visible; + final VoidCallback? onHidden; /// Persistent status displayed beside or above the actions. final String message; @@ -47,7 +49,7 @@ class ReconnectCapsule extends HookWidget { destructiveAction: destructiveAction, secondaryAction: secondaryAction, onRetry: onSignIn, - onDismiss: () {}, + onDismiss: onHidden ?? () {}, persistent: true, visible: visible, islandOrigin: islandOrigin, diff --git a/mobile/lib/shared/widgets/text_editor.dart b/mobile/lib/shared/widgets/text_editor.dart index 81b32bea26..d2121d9f23 100644 --- a/mobile/lib/shared/widgets/text_editor.dart +++ b/mobile/lib/shared/widgets/text_editor.dart @@ -18,6 +18,7 @@ Future showTextEditor({ required String hintText, required Future Function(String value) onSave, bool multiline = false, + bool requireNonEmpty = false, String keyPrefix = 'text-editor', bool Function(Object error)? shouldRetryOnError, }) async { @@ -29,6 +30,7 @@ Future showTextEditor({ initialValue: initialValue, placeholder: hintText, multiline: multiline, + requireNonEmpty: requireNonEmpty, brightness: sheetTheme.brightness, pageBackgroundColor: sheetTheme.colorScheme.surface, containerBackgroundColor: @@ -61,6 +63,7 @@ Future showTextEditor({ initialValue: initialValue, hintText: hintText, multiline: multiline, + requireNonEmpty: requireNonEmpty, onSave: onSave, shouldRetryOnError: shouldRetryOnError, keyPrefix: keyPrefix, @@ -80,6 +83,7 @@ class _TextEditSheet extends HookWidget { required this.initialValue, required this.hintText, required this.multiline, + required this.requireNonEmpty, required this.onSave, this.shouldRetryOnError, required this.keyPrefix, @@ -89,6 +93,7 @@ class _TextEditSheet extends HookWidget { final String initialValue; final String hintText; final bool multiline; + final bool requireNonEmpty; final Future Function(String value) onSave; final bool Function(Object error)? shouldRetryOnError; @@ -98,7 +103,10 @@ class _TextEditSheet extends HookWidget { useListenable(controller); final isSaving = useState(false); final error = useState(null); - final hasChanges = controller.text.trim() != initialValue.trim(); + final trimmed = controller.text.trim(); + final hasChanges = + trimmed != initialValue.trim() && + (!requireNonEmpty || trimmed.isNotEmpty); Future save() async { if (!hasChanges || isSaving.value) return; diff --git a/mobile/lib/shared/widgets/toast_capsule_content.dart b/mobile/lib/shared/widgets/toast_capsule_content.dart index e7a758c2fc..2c060a2ca9 100644 --- a/mobile/lib/shared/widgets/toast_capsule_content.dart +++ b/mobile/lib/shared/widgets/toast_capsule_content.dart @@ -1,4 +1,7 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../theme/theme.dart'; @@ -52,7 +55,10 @@ class ToastCapsuleContent extends StatelessWidget { bool destructive = false, bool secondary = false, }) => FilledButton( - onPressed: onPressed, + onPressed: () { + unawaited(HapticFeedback.selectionClick()); + onPressed(); + }, style: FilledButton.styleFrom( backgroundColor: destructive ? lightColorScheme.error diff --git a/mobile/test/features/channels/channel_reader_recovery_test.dart b/mobile/test/features/channels/channel_reader_recovery_test.dart index f7fb50188a..84b79e7cbd 100644 --- a/mobile/test/features/channels/channel_reader_recovery_test.dart +++ b/mobile/test/features/channels/channel_reader_recovery_test.dart @@ -1962,6 +1962,17 @@ void wholeBlobLanes(SharedPreferences Function() prefs) { expect(names(), ['mine']); }); + fakeAsyncTest('an emoji-only edit preserves the current section name', ( + clock, + ) { + start(clock).createSection('Original'); + final id = m.store.sections.single.id; + m.renameSection(id, 'Updated'); + m.renameSection(id, null, icon: '🎨'); + expect(m.store.sections.single.name, 'Updated'); + expect(m.store.sections.single.icon, '🎨'); + }); + fakeAsyncTest('OK before echo keeps a coherent cursor', (clock) { start(clock).createSection('mine'); clock.elapse(const Duration(seconds: 5)); @@ -2018,7 +2029,8 @@ void wholeBlobLanes(SharedPreferences Function() prefs) { start(clock).createSection('mine'); clock.elapse(const Duration(seconds: 5)); final own = relay.published.single; - m.renameSection(m.store.sections.single.id, 'new-local'); + m.renameSection(m.store.sections.single.id, 'new-local', icon: '🎨'); + expect(m.store.sections.single.icon, '🎨'); final loser = relay.event( 'channel-sections', blob('loser'), @@ -2083,7 +2095,8 @@ void wholeBlobLanes(SharedPreferences Function() prefs) { start(clock).createSection('mine'); clock.elapse(const Duration(seconds: 5)); expect(relay.published, hasLength(1)); - m.renameSection(m.store.sections.single.id, 'new-local'); + m.renameSection(m.store.sections.single.id, 'new-local', icon: '🎨'); + expect(m.store.sections.single.icon, '🎨'); relay.holdOk!.complete(); relay.holdOk = null; clock.flushMicrotasks(); diff --git a/mobile/test/features/channels/channel_sections/filtered_channel_section_body_test.dart b/mobile/test/features/channels/channel_sections/filtered_channel_section_body_test.dart new file mode 100644 index 0000000000..28e3b6898f --- /dev/null +++ b/mobile/test/features/channels/channel_sections/filtered_channel_section_body_test.dart @@ -0,0 +1,65 @@ +import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_sections/filtered_channel_section_body.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('disclosure keeps hundreds of filtered rows lazy', ( + tester, + ) async { + final channels = [ + for (var index = 0; index < 300; index++) + Channel( + id: 'chat-$index', + name: 'Chat $index', + channelType: 'stream', + visibility: 'open', + description: '', + memberCount: 1, + createdBy: 'owner', + createdAt: DateTime(2026), + isMember: true, + ), + ]; + final built = {}; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: [ + FilteredChannelSectionBody( + expanded: true, + channels: channels, + isVisible: (_) => false, + buildRow: (channel) { + built.add(channel.id); + return SizedBox( + key: ValueKey(channel.id), + height: 44, + child: Text(channel.name), + ); + }, + ), + ], + ), + ), + ), + ); + expect(built, isEmpty); + + await tester.tap(find.text('Show more')); + await tester.pump(); + expect(built, isNotEmpty); + expect(built.length, lessThan(60)); + await tester.pumpAndSettle(); + expect(find.text('Chat 0'), findsOneWidget); + expect(find.text('Chat 299'), findsNothing); + + await tester.scrollUntilVisible(find.text('Show fewer'), 500); + expect(find.text('Chat 299'), findsOneWidget); + await tester.tap(find.text('Show fewer')); + await tester.pumpAndSettle(); + expect(find.text('Chat 299'), findsNothing); + expect(find.text('Show more'), findsOneWidget); + }); +} diff --git a/mobile/test/features/channels/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index e3ca947f8e..6457ee9abd 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -1,4 +1,6 @@ +import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; import 'package:buzz/shared/widgets/app_list.dart'; +import 'package:buzz/features/channels/channel_filter/channel_filter_activity.dart'; import 'package:buzz/features/channels/channel_filter/channel_filter_provider.dart'; import 'package:buzz/features/channels/channel_filter/channel_filter_manager.dart'; import 'package:buzz/features/channels/channel_filter/channel_filter_store.dart'; @@ -93,6 +95,17 @@ part 'channels_page_test/filter_feedback_tests.dart'; part 'channels_page_test/home_community_flight.dart'; part 'channels_page_test/read_seed_journey.dart'; +Future _chooseSectionOption( + WidgetTester tester, + String row, + String value, +) async { + await tester.tap(find.byKey(ValueKey('section-menu-$row'))); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(MenuItemButton, value)); + await tester.pumpAndSettle(); +} + void main() { setUpAll(() async { if (Platform.environment.containsKey('COMMUNITY_SCREENSHOTS') || @@ -250,13 +263,15 @@ void main() { await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); expect(find.text('general'), findsNothing); - final all = tester.widget( - find.ancestor(of: find.text('All'), matching: find.byType(AppListRow)), + expect( + tester + .widget(find.byKey(const ValueKey('section-menu-Show'))) + .onTap, + isNull, ); - expect(all.onTap, isNull); - await tester.tap(find.text('Cancel')); + await tester.binding.handlePopRoute(); await tester.pumpAndSettle(); - await tester.tap(find.text('Show hidden channels · 1')); + await tester.tap(find.text('Show more')); await tester.pumpAndSettle(); expect(find.text('general'), findsOneWidget); expect(tester.widget(_dmTileFor('general')).onTap, isNotNull); @@ -312,7 +327,7 @@ void main() { await tester.pumpAndSettle(); // Sort is available while preferences load. A late verified load must // update the untouched filter draft and never cause an All publication. - await tester.tap(find.text('Recent')); + await _chooseSectionOption(tester, 'Sort', 'Recent'); await tester.pumpAndSettle(); await manager.refresh(); await tester.pumpAndSettle(); @@ -324,31 +339,17 @@ void main() { ), ); expect(unreads.trailing, isA()); - await tester.tap(find.text('Apply')); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); expect(publications, 0); expect(manager.store.modeFor('channels'), ChannelFilterMode.unreads); await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - final header = find.byType(BuzzSheetHeader); - final apply = find.widgetWithText(FilledButton, 'Apply'); - final collapsedTop = tester.getTopLeft(header).dy; - final footerBottom = tester.getBottomRight(apply).dy; - await tester.tap(find.text('Active')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 80)); - final expandingTop = tester.getTopLeft(header).dy; - expect(expandingTop, lessThan(collapsedTop)); - expect(tester.getBottomRight(apply).dy, closeTo(footerBottom, 0.1)); - await tester.pumpAndSettle(); - final expandedTop = tester.getTopLeft(header).dy; - expect(expandedTop, lessThan(expandingTop)); - expect(tester.getBottomRight(apply).dy, closeTo(footerBottom, 0.1)); - await tester.ensureVisible(find.text('7 days')); - await tester.tap(find.text('7 days')); - await tester.pumpAndSettle(); + expect(find.text('Active in the past'), findsNothing); + await _chooseSectionOption(tester, 'Show', 'Active'); + await _chooseSectionOption(tester, 'Active in the past', '7 days'); expect(manager.store.modeFor('channels'), ChannelFilterMode.unreads); - await tester.tap(find.text('Apply')); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); expect(manager.store.modeFor('channels'), ChannelFilterMode.active); expect(manager.store.windowFor('channels'), 7 * 86400); @@ -361,16 +362,9 @@ void main() { ), ); expect(days.trailing, isA()); - await tester.tap(find.text('All')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 80)); - final collapsingTop = tester.getTopLeft(header).dy; - expect(collapsingTop, greaterThan(expandedTop)); - expect(collapsingTop, lessThan(collapsedTop)); - await tester.pumpAndSettle(); - expect(tester.getTopLeft(header).dy, closeTo(collapsedTop, 0.1)); + await _chooseSectionOption(tester, 'Show', 'All'); expect(find.text('Active in the past'), findsNothing); - await tester.tap(find.text('Cancel')); + await tester.tap(find.byTooltip('Discard changes')); await tester.pumpAndSettle(); expect(manager.store.modeFor('channels'), ChannelFilterMode.active); expect(find.byType(AlertDialog), findsNothing); @@ -380,7 +374,7 @@ void main() { ); testWidgets( - 'failed Active Apply retains duration draft; Cancel discards it at enlarged text', + 'failed save keeps the duration draft until dismissal at enlarged text', (tester) async { tester.view.physicalSize = const Size(390, 844); tester.view.devicePixelRatio = 1; @@ -401,13 +395,13 @@ void main() { await tester.pumpAndSettle(); await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - await tester.tap(find.text('Active')); + await _chooseSectionOption(tester, 'Show', 'Active'); await tester.pumpAndSettle(); - await tester.ensureVisible(find.text('7 days')); - await tester.tap(find.text('7 days')); + + await _chooseSectionOption(tester, 'Active in the past', '7 days'); await tester.pumpAndSettle(); - await tester.ensureVisible(find.text('Apply')); - await tester.tap(find.text('Apply')); + + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); expect( find.text( @@ -421,10 +415,10 @@ void main() { final status = tester.getSemantics(failure); expect(status.getSemanticsData().flagsCollection.isLiveRegion, isTrue); final errorRect = tester.getRect(failure); - final footerRect = tester.getRect(find.text('Retry')); + final headerRect = tester.getRect(find.byTooltip('Apply changes')); expect(errorRect.top, greaterThanOrEqualTo(0)); - expect(errorRect.bottom, lessThanOrEqualTo(footerRect.top)); - expect(footerRect.bottom, lessThanOrEqualTo(844)); + expect(headerRect.bottom, lessThanOrEqualTo(errorRect.top)); + expect(errorRect.bottom, lessThanOrEqualTo(844)); final selected = tester.widget( find.ancestor( of: find.text('7 days'), @@ -432,7 +426,7 @@ void main() { ), ); expect(selected.trailing, isA()); - await tester.tap(find.text('Cancel')); + await tester.binding.handlePopRoute(); await tester.pumpAndSettle(); expect(find.byType(AlertDialog), findsNothing); expect(manager.store.modeFor('channels'), ChannelFilterMode.all); @@ -832,11 +826,11 @@ void main() { ), ) .dx, - closeTo(tester.getTopRight(find.byTooltip('Team options')).dx - 3, 0.01), + closeTo(tester.getTopRight(find.byTooltip('Team options')).dx - 15, 0.01), ); await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - expect(find.text('Recent'), findsOneWidget); + expect(find.text('Recent'), findsNothing); expect(find.text('A–Z'), findsOneWidget); expect(find.text('Show'), findsOneWidget); expect(find.byType(AlertDialog), findsNothing); @@ -844,7 +838,7 @@ void main() { find.ancestor(of: find.text('A–Z'), matching: find.byType(AppListRow)), ); expect(alpha.trailing, isA()); - await tester.tap(find.text('Cancel')); + await tester.binding.handlePopRoute(); await tester.pumpAndSettle(); for (final label in ['general', 'Alice']) { @@ -1379,9 +1373,13 @@ void main() { testWidgets( 'section options preserve management actions and Duo quick sort', (tester) async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); await tester.pumpWidget( buildTestable( overrides: [ + myPubkeyProvider.overrideWithValue('aabb'), + savedPrefsProvider.overrideWithValue(prefs), channelsProvider.overrideWith(() => _FakeNotifier(testChannels)), channelSectionsProvider.overrideWith( () => _FakeChannelSectionsNotifier( @@ -1435,7 +1433,7 @@ void main() { tester .getTopRight(find.byKey(const Key('section-menu-section-1'))) .dx - - 3, + 15, 0.01, ), ); @@ -1444,26 +1442,18 @@ void main() { for (final (label, icon) in [ ('Rename section', BuzzIcons.pencil), - ('Move up', BuzzIcons.arrowUp), - ('Move down', BuzzIcons.arrowDown), + ('Reorder sections', BuzzIcons.arrowUpDown), ('Delete section', BuzzIcons.trash2), ]) { final row = find.ancestor( of: find.text(label), - matching: find.byType(ListTile), + matching: find.byType(AppListRow), ); expect( find.descendant(of: row, matching: find.byIcon(icon)), findsOneWidget, ); } - final moveUp = tester.widget( - find.ancestor( - of: find.text('Move up'), - matching: find.byType(ListTile), - ), - ); - expect(moveUp.enabled, isFalse); final deleteText = tester.widget(find.text('Delete section')); expect( deleteText.style?.color, @@ -1473,13 +1463,13 @@ void main() { find.descendant( of: find.ancestor( of: find.text('Delete section'), - matching: find.byType(ListTile), + matching: find.byType(AppListRow), ), matching: find.byIcon(BuzzIcons.trash2), ), ); expect(deleteIcon.color, deleteText.style?.color); - await tester.tap(find.text('Cancel')); + await tester.binding.handlePopRoute(); await tester.pumpAndSettle(); try { @@ -1492,21 +1482,21 @@ void main() { await tester.pumpWidget(const SizedBox.shrink()); SharedPreferences.setMockInitialValues({}); final duoPrefs = await SharedPreferences.getInstance(); + final sections = _FakeChannelSectionsNotifier( + const ChannelSectionStore( + sections: [ + ChannelSection(id: 'section-1', name: 'Design\u0085', order: 0), + ], + ), + ); await tester.pumpWidget( buildTestable( realHome: true, overrides: [ + myPubkeyProvider.overrideWithValue('aabb'), savedPrefsProvider.overrideWithValue(duoPrefs), channelsProvider.overrideWith(() => _FakeNotifier(testChannels)), - channelSectionsProvider.overrideWith( - () => _FakeChannelSectionsNotifier( - const ChannelSectionStore( - sections: [ - ChannelSection(id: 'section-1', name: 'Design', order: 0), - ], - ), - ), - ), + channelSectionsProvider.overrideWith(() => sections), ], ), ); @@ -1519,21 +1509,35 @@ void main() { expect(nativeMenu().iconSize, 14); expect(nativeMenu().actions.map((action) => action.label), [ 'Rename section', - 'Move up', - 'Move down', + 'Reorder sections', 'Sort: Recent', 'Sort: A–Z', 'Filter…', 'Delete section', ]); - expect(nativeMenu().actions[1].onPressed, isNull); - expect(nativeMenu().actions[2].onPressed, isNull); - expect(nativeMenu().destructiveIndices, {6}); + const editor = MethodChannel('buzz/profile_text_editor'); + final messenger = tester.binding.defaultBinaryMessenger; + MethodCall? rename; + messenger.setMockMethodCallHandler(editor, (call) async { + rename = call; + return {'name': 'Design', 'icon': '🎨'}; + }); + addTearDown(() => messenger.setMockMethodCallHandler(editor, null)); + nativeMenu().actions.first.onPressed!(); + await tester.pumpAndSettle(); + expect(sections.lastRename, (name: null, icon: '🎨')); + expect(rename?.method, 'presentSection'); + expect(rename?.arguments.containsKey('icon'), isTrue); + expect(rename?.arguments['title'], 'Rename section'); + expect(rename?.arguments['initialValue'], 'Design\u0085'); + expect(rename?.arguments['requireNonEmpty'], isTrue); + expect(nativeMenu().actions[1].onPressed, isNotNull); + expect(nativeMenu().destructiveIndices, {5}); final newMenu = find.byKey(const ValueKey('horizontal-create-menu')); expect(newMenu, findsOneWidget); - nativeMenu().actions[4].onPressed!(); + nativeMenu().actions[3].onPressed!(); await tester.pumpAndSettle(); - expect(nativeMenu().selectedIndex, 4); + expect(nativeMenu().selectedIndex, 3); expect(newMenu, findsOneWidget); expect( find.byKey(const Key('section-popover-section-1')), @@ -1544,11 +1548,33 @@ void main() { .singleWhere((action) => action.label == 'Filter…') .onPressed!(); await tester.pumpAndSettle(); - expect(find.text('Sort'), findsOneWidget); - expect(find.text('Show'), findsOneWidget); - await tester.tap(find.text('Cancel')); + final sortPicker = tester.widget( + find.byKey(const ValueKey('section-menu-Sort')), + ); + expect(sortPicker.actions.map((action) => action.label), [ + 'A–Z', + 'Recent', + ]); + expect( + tester + .widget( + find.byKey(const ValueKey('section-menu-Show')), + ) + .actions + .map((action) => action.label), + ['All', 'Unreads', 'Active'], + ); + tester + .widget( + find.byWidgetPredicate( + (widget) => + widget is IosGlassNavigationButton && + widget.semanticLabel == 'Apply changes', + ), + ) + .onPressed!(); await tester.pumpAndSettle(); - expect(nativeMenu().selectedIndex, 4); + expect(nativeMenu().selectedIndex, 3); expect(ModalRoute.of(tester.element(newMenu))!.isCurrent, isTrue); expect(tester.takeException(), isNull); } finally { @@ -4272,6 +4298,7 @@ void main() { addTearDown(filters.dispose); await tester.pumpWidget( buildTestable( + disableAnimations: true, overrides: [ channelsProvider.overrideWith( () => _FakeNotifier( @@ -4325,8 +4352,8 @@ void main() { } expect(find.text('general'), findsNothing); - await tester.tap(find.text('Show hidden channels · 1')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Show more')); + await tester.pump(); expect(find.text('general'), findsOneWidget); expect( find.byKey(const ValueKey('channel-attention-dot-1')), @@ -4336,6 +4363,9 @@ void main() { tester.getSemantics(find.byKey(const ValueKey('1'))).value, isEmpty, ); + await tester.tap(find.text('Show fewer')); + await tester.pump(); + expect(find.text('general'), findsNothing); semantics.dispose(); }); } @@ -4462,7 +4492,7 @@ void main() { final hiddenByUnreads = seenAt != null && !bold && !dot; if (hiddenByUnreads) { expect(find.text('general'), findsNothing); - await tester.tap(find.text('Show hidden channels · 1')); + await tester.tap(find.text('Show more')); await tester.pumpAndSettle(); } @@ -4705,6 +4735,13 @@ class _FakeChannelSectionsNotifier extends ChannelSectionsNotifier { final ChannelSectionStore _store; + ({String? name, String? icon})? lastRename; + + @override + void renameSection(String sectionId, String? newName, {String? icon}) { + lastRename = (name: newName, icon: icon); + } + @override ChannelSectionsState build() => ChannelSectionsState(isReady: true, store: _store, version: 1); diff --git a/mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart b/mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart index a730a63895..978f10a58f 100644 --- a/mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart +++ b/mobile/test/features/channels/channels_page_test/filter_feedback_tests.dart @@ -1,8 +1,144 @@ part of '../channels_page_test.dart'; void _filterFeedbackTests( - Widget Function({required List overrides}) buildTestable, + Widget Function({required List overrides, bool realHome}) + buildTestable, ) { + for (final coverMessages in [true, false]) { + testWidgets( + 'activity retry ${coverMessages ? 'pauses while Messages is covered' : 'backs off and leaves manual recovery available'}', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(390, 844); + addTearDown(tester.view.reset); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final haptics = []; + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(SystemChannels.platform, ( + call, + ) async { + if (call.method == 'HapticFeedback.vibrate' && + call.arguments == 'HapticFeedbackType.heavyImpact') { + haptics.add(call); + } + return null; + }); + addTearDown( + () => + messenger.setMockMethodCallHandler(SystemChannels.platform, null), + ); + final manager = _filterTestManager( + cached: ChannelFilterStore.empty().edit( + 'channels', + ChannelFilterMode.active, + ), + ); + final initialRead = Completer(); + final recovery = Completer(); + var canRecover = false; + final reads = {}; + const ids = ['failed', 'loaded']; + await tester.pumpWidget( + buildTestable( + realHome: coverMessages, + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + channelsProvider.overrideWith( + () => _FakeNotifier([ + for (final id in ids) + Channel( + id: id, + name: id, + channelType: 'stream', + visibility: 'open', + description: '', + memberCount: 1, + createdBy: 'pk', + createdAt: DateTime(2025), + isMember: true, + ), + ]), + ), + relaySessionProvider.overrideWith( + () => _ReconnectingRelaySession( + initialStatus: SessionStatus.connected, + ), + ), + channelFilterProvider.overrideWithValue(manager), + for (final id in ids) + channelFilterActivityProvider(id).overrideWith((_) async { + final count = reads.update( + id, + (value) => value + 1, + ifAbsent: () => 1, + ); + if (id == 'failed') { + if (count == 1) return initialRead.future; + if (canRecover) return recovery.future; + throw StateError('Activity unavailable'); + } + return DateTime.now().millisecondsSinceEpoch ~/ 1000; + }), + ], + ), + ); + await tester.pumpAndSettle(); + final notice = find.text('Some activity couldn’t load'); + if (coverMessages) { + await tester.tap(find.byTooltip('Search')); + await tester.pumpAndSettle(); + } + initialRead.completeError(StateError('Activity unavailable')); + await tester.pumpAndSettle(); + if (coverMessages) { + await tester.pump(const Duration(seconds: 13)); + expect(notice, findsNothing); + expect(reads['failed'], 1); + await tester.tap(find.byKey(const Key('search-close'))); + await tester.pumpAndSettle(); + expect(notice, findsOneWidget); + + await tester.tap(find.text('loaded')); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 13)); + expect(notice, findsNothing); + expect(reads['failed'], 1); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + } else { + for (final (index, minimum, maximum) in [ + (0, 8, 12), + (1, 16, 24), + (2, 32, 48), + ]) { + await tester.pump(Duration(seconds: minimum - 1)); + expect(reads['failed'], index + 1); + await tester.pump(Duration(seconds: maximum - minimum + 1)); + await tester.pumpAndSettle(); + expect(reads['failed'], index + 2); + } + await tester.pump(const Duration(minutes: 2)); + await tester.pumpAndSettle(); + expect(reads['failed'], 4); + } + expect(find.text('failed'), findsOneWidget); + expect(notice, findsOneWidget); + expect(haptics, isEmpty); + canRecover = true; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(notice, findsOneWidget); + recovery.complete(DateTime.now().millisecondsSinceEpoch ~/ 1000); + await tester.pumpAndSettle(); + expect(reads, {'failed': coverMessages ? 2 : 5, 'loaded': 1}); + expect(notice, findsNothing); + await tester.pumpWidget(const SizedBox()); + manager.dispose(); + }, + ); + } + testWidgets( 'deleting an unfiltered section persists offline without filter publication', (tester) async { @@ -137,12 +273,47 @@ void _filterFeedbackTests( ); await tester.pumpAndSettle(); expect(find.text('history'), findsNothing); - await tester.tap(find.text('Show hidden channels · 1')); + await tester.tap(find.text('Show more')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 70)); + expect( + tester + .widget( + find + .ancestor( + of: find.byKey(const ValueKey('history')), + matching: find.byType(SizeTransition), + ) + .first, + ) + .sizeFactor + .value, + allOf(greaterThan(0), lessThan(1)), + ); await tester.pumpAndSettle(); expect( tester.widget(find.text('history')).style?.fontWeight, FontWeight.w400, ); + await tester.tap(find.text('Show fewer')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 70)); + expect( + tester + .widget( + find + .ancestor( + of: find.byKey(const ValueKey('history')), + matching: find.byType(SizeTransition), + ) + .first, + ) + .sizeFactor + .value, + allOf(greaterThan(0), lessThan(1)), + ); + await tester.pumpAndSettle(); + expect(find.text('history'), findsNothing); await tester.pumpWidget(const SizedBox()); manager.dispose(); }); @@ -205,27 +376,29 @@ void _filterFeedbackTests( final manager = container.read(channelFilterProvider)!; expect(manager.ready, isTrue); const reopen = 'Preferences changed. Reopen section options to continue.'; - FilledButton applyButton() => tester.widget( - find.widgetWithText(FilledButton, 'Apply'), + IconButton applyButton() => tester.widget( + find.byWidgetPredicate( + (widget) => widget is IconButton && widget.tooltip == 'Apply changes', + ), ); // A push lease write lands while a filter save awaits confirmation: the // save completes and the co-staged sort still applies. await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - await tester.tap(find.text('Recent')); - await tester.tap(find.text('Unreads')); - await tester.tap(find.text('Apply')); + await _chooseSectionOption(tester, 'Sort', 'Recent'); + await _chooseSectionOption(tester, 'Show', 'Unreads'); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); expect(relay.filterPublishes, 1); - expect(find.text('Saving…'), findsOneWidget); + expect(find.byTooltip('Saving…'), findsOneWidget); await communities.reservePushLeaseGeneration(community.id); await tester.pumpAndSettle(); expect(container.read(channelFilterProvider), same(manager)); expect(find.text(reopen), findsNothing); relay.releaseHeld(); await tester.pumpAndSettle(); - expect(find.text('Cancel'), findsNothing); + expect(find.byTooltip('Apply changes'), findsNothing); expect(manager.store.modeFor('channels'), ChannelFilterMode.unreads); expect( container.read(channelSortProvider).sortModeFor('channels'), @@ -238,9 +411,9 @@ void _filterFeedbackTests( // and the replacement's queued refresh restores write access. await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - await tester.tap(find.text('All')); - await tester.tap(find.text('Unreads')); - await tester.tap(find.text('A–Z')); + await _chooseSectionOption(tester, 'Show', 'All'); + await _chooseSectionOption(tester, 'Show', 'Unreads'); + await _chooseSectionOption(tester, 'Sort', 'A–Z'); relay.holdNextFilterRead = true; unawaited(manager.refresh()); relay.setReconnecting(); @@ -251,9 +424,9 @@ void _filterFeedbackTests( expect(manager.busy, isTrue); expect(find.text(reopen), findsNothing); expect(applyButton().onPressed, isNotNull); - await tester.tap(find.text('Apply')); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); - expect(find.text('Cancel'), findsNothing); + expect(find.byTooltip('Apply changes'), findsNothing); expect( container.read(channelSortProvider).sortModeFor('channels'), ChannelSortMode.alpha, @@ -267,7 +440,7 @@ void _filterFeedbackTests( // A failed load leaves a staged filter edit recoverable from the sheet. await tester.tap(find.byTooltip('Team options')); await tester.pumpAndSettle(); - await tester.tap(find.text('All')); + await _chooseSectionOption(tester, 'Show', 'All'); relay.setReconnecting(); await tester.pumpAndSettle(); relay.holdNextFilterRead = true; @@ -276,17 +449,17 @@ void _filterFeedbackTests( relay.releaseHeld(fail: true); await tester.pumpAndSettle(); expect(manager.ready, isFalse); - await tester.tap(find.text('Apply')); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); await tester.ensureVisible(find.text('Retry loading preferences')); await tester.tap(find.text('Retry loading preferences')); await tester.pumpAndSettle(); expect(manager.ready, isTrue); - await tester.tap(find.widgetWithText(FilledButton, 'Apply')); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); relay.releaseHeld(); await tester.pumpAndSettle(); - expect(find.text('Cancel'), findsNothing); + expect(find.byTooltip('Apply changes'), findsNothing); expect(manager.store.modeFor('channels'), ChannelFilterMode.all); // Switching community still abandons the sheet. diff --git a/mobile/test/features/channels/me/me_page_test.dart b/mobile/test/features/channels/me/me_page_test.dart index 3c7ffcc207..3ce2e269e0 100644 --- a/mobile/test/features/channels/me/me_page_test.dart +++ b/mobile/test/features/channels/me/me_page_test.dart @@ -1,3 +1,7 @@ +import 'package:buzz/features/channels/channel_filter/channel_filter_activity.dart'; +import 'package:buzz/features/channels/channel_filter/channel_filter_manager.dart'; +import 'package:buzz/features/channels/channel_filter/channel_filter_provider.dart'; +import 'package:buzz/features/channels/channel_sort/channel_sort_manager.dart'; import 'dart:convert'; import 'package:image_picker/image_picker.dart'; @@ -128,6 +132,94 @@ class LabeledChannels extends ChannelsNotifier { } void main() { + testWidgets('Solo workspace activity window leaves unfiled chats visible', ( + tester, + ) async { + final keys = nostr.Keys.generate(); + const coordinate = 'solo-channel-filter'; + var history = []; + final manager = ChannelFilterManager( + coordinate: coordinate, + pubkey: keys.public, + crypto: ChannelSortCrypto(keys.nsec, keys.public), + fetch: () async => history, + publish: (content, at) async { + history = [ + NostrEvent.fromJson( + nostr.Event.from( + kind: EventKind.readState, + tags: const [ + ['d', coordinate], + ], + content: content, + createdAt: at, + secretKey: nostr.Nip19.decode(payload: keys.nsec).data, + verify: false, + ).toMap(), + ), + ]; + }, + cache: (_) {}, + ); + addTearDown(manager.dispose); + await manager.refresh(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + defaultAgentProvider.overrideWith((ref) => Stream.value(null)), + myPubkeyProvider.overrideWithValue('owner'), + channelsProvider.overrideWith(LabeledChannels.new), + soloFilterProvider.overrideWithValue(manager), + channelFilterActivityProvider('filed').overrideWith( + (ref) async => + DateTime.now() + .subtract(const Duration(days: 8)) + .millisecondsSinceEpoch ~/ + 1000, + ), + meGroupsProvider.overrideWith( + (ref) => Stream.value( + const MeGroups( + groups: [ + { + 'id': 'project', + 'name': 'App work', + 'defaultTemplateId': '', + }, + ], + assignments: {'filed': 'project'}, + ), + ), + ), + ], + child: MaterialApp(theme: AppTheme.light(), home: const MePage()), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Filed labeled chat'), findsOneWidget); + await tester.tap(find.byTooltip('App work options')); + await tester.pumpAndSettle(); + expect(find.text('Sort'), findsOneWidget); + await tester.tap(find.text('Show')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Active')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Active in the past')); + await tester.pumpAndSettle(); + for (final label in ['1 day', '7 days', '30 days', '90 days']) { + expect(find.widgetWithText(MenuItemButton, label), findsOneWidget); + } + await tester.ensureVisible(find.text('7 days')); + await tester.tap(find.text('7 days')); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Apply changes')); + await tester.pumpAndSettle(); + expect(history, hasLength(1)); + expect(find.text('Filed labeled chat'), findsNothing); + expect(find.text('Unfiled labeled chat'), findsOneWidget); + expect(find.text('No matching chats'), findsOneWidget); + }); + testWidgets('label-only desktop chats appear in projects and unfiled chats', ( tester, ) async { diff --git a/mobile/test/features/channels/section_rename_editor_test.dart b/mobile/test/features/channels/section_rename_editor_test.dart new file mode 100644 index 0000000000..b41bb90c86 --- /dev/null +++ b/mobile/test/features/channels/section_rename_editor_test.dart @@ -0,0 +1,92 @@ +import 'dart:async'; + +import 'package:buzz/features/channels/channel_sections/channel_sections_storage.dart'; +import 'package:buzz/features/channels/channels_page.dart'; +import 'package:buzz/shared/custom_emoji/custom_emoji.dart'; +import 'package:buzz/shared/custom_emoji/custom_emoji_provider.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'; + +class _PendingPalette extends CustomEmojiPaletteNotifier { + _PendingPalette(this.pending); + final Future> pending; + + @override + Future> build() => pending; +} + +const section = ChannelSection(id: 'design', name: 'Design', order: 0); + +void main() { + testWidgets('closing Rename cancels a waiting iOS picker', (tester) async { + final palette = Completer>(); + final editor = Completer?>(); + final messenger = tester.binding.defaultBinaryMessenger; + const editorChannel = MethodChannel('buzz/profile_text_editor'); + const emojiChannel = MethodChannel('buzz/native_emoji_picker'); + messenger.setMockMethodCallHandler(editorChannel, (_) => editor.future); + var presentations = 0; + messenger.setMockMethodCallHandler(emojiChannel, (_) async { + presentations++; + return null; + }); + addTearDown(() { + messenger.setMockMethodCallHandler(editorChannel, null); + messenger.setMockMethodCallHandler(emojiChannel, null); + }); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + customEmojiPaletteProvider.overrideWith( + () => _PendingPalette(palette.future), + ), + ], + child: const MaterialApp(home: Scaffold()), + ), + ); + final edit = showSectionRenameEditor( + tester.element(find.byType(Scaffold)), + section, + ); + final choose = messenger.handlePlatformMessage( + 'buzz/section_emoji', + const StandardMethodCodec().encodeMethodCall(const MethodCall('choose')), + (_) {}, + ); + await tester.pump(); + editor.complete(null); + await tester.pump(); + expect(await edit, isNull); + palette.complete([]); + await tester.pumpAndSettle(); + await choose; + expect(presentations, 0); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + + testWidgets('the Android name field grows with large text', (tester) async { + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(2.5)), + child: child!, + ), + home: const Scaffold(), + ), + ); + final edit = showSectionRenameEditor( + tester.element(find.byType(Scaffold)), + section, + ); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(TextField)).height, greaterThan(52)); + await tester.enterText(find.byType(TextField), 'New name'); + await tester.tap(find.text('Rename')); + await tester.pumpAndSettle(); + expect((await edit)?.name, 'New name'); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); +} diff --git a/mobile/test/features/channels/sidebar_workspaces_journey_test.dart b/mobile/test/features/channels/sidebar_workspaces_journey_test.dart index bd631e6fa3..7a9ec12f74 100644 --- a/mobile/test/features/channels/sidebar_workspaces_journey_test.dart +++ b/mobile/test/features/channels/sidebar_workspaces_journey_test.dart @@ -1,4 +1,8 @@ +import 'dart:async'; + import 'package:buzz/features/channels/channel.dart'; +import 'package:buzz/features/channels/channel_filter/channel_filter_activity.dart'; +import 'package:buzz/features/channels/channel_sections/section_reorder_sheet.dart'; import 'package:buzz/features/channels/channel_stars/channel_stars_provider.dart'; import 'package:buzz/features/channels/channel_stars/channel_stars_storage.dart'; import 'package:buzz/features/channels/channels_provider.dart'; @@ -12,12 +16,16 @@ import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/me/me_sync.dart'; import 'package:buzz/shared/relay/relay.dart'; +import 'package:buzz/shared/theme/buzz_icons.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/app_list.dart'; +import 'package:buzz/shared/widgets/tabler_star_icon.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'; +import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'sidebar_sync_fixture.dart'; @@ -32,12 +40,17 @@ void main() { tester.view.devicePixelRatio = 3; addTearDown(tester.view.reset); SharedPreferences.setMockInitialValues({}); + final orderStore = _OrderStore(); + final previousStore = SharedPreferencesStorePlatform.instance; + SharedPreferencesStorePlatform.instance = orderStore; + addTearDown(() => SharedPreferencesStorePlatform.instance = previousStore); final prefs = await SharedPreferences.getInstance(); final relay = SidebarRelay(); // The relay this Home's config names; its store holds the heads below. relay.session.debugRelayUrl = 'https://relay.example'; _viewer = relay.pubkey; final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + var soloActivityReads = 0; // Before desktop's unified record, the legacy Team sections apply. relay.stored.add( relay.event('channel-sections', { @@ -67,6 +80,12 @@ void main() { ), ), channelsProvider.overrideWith(_Channels.new), + channelFilterActivityProvider('solo-scratch').overrideWith((_) async { + if (soloActivityReads++ == 0) { + throw StateError('Activity unavailable'); + } + return now - 8 * 86400; + }), meGroupsProvider.overrideWith( (ref) => Stream.value( const MeGroups( @@ -112,12 +131,16 @@ void main() { await tester.tap(find.byTooltip('Old options')); await tester.pumpAndSettle(); expect(find.text('Rename section'), findsOneWidget); - ListTile option(String label) => tester.widget( - find.ancestor(of: find.text(label), matching: find.byType(ListTile)), + await tester.tap(find.text('Reorder sections')); + await tester.pumpAndSettle(); + final list = tester.widget( + find.byType(ReorderableListView), ); - expect(option('Move up').enabled, isTrue); - expect(option('Move down').enabled, isFalse); - await tester.tap(find.text('Cancel')); + list.onReorderItem!(0, 1); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Discard order')); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Discard changes')); await tester.pumpAndSettle(); // Team actions follow the Team section, not the Solo project sharing its // ID. @@ -125,7 +148,7 @@ void main() { await tester.tap(find.byTooltip('$header options')); await tester.pumpAndSettle(); expect(find.text('Rename section'), team ? findsOneWidget : findsNothing); - await tester.tap(find.text('Cancel')); + await tester.tap(find.byTooltip('Discard changes')); await tester.pumpAndSettle(); } @@ -189,7 +212,45 @@ void main() { reason: '$label follows ${order[index - 1]}', ); } - expect(inList('🚀'), findsOneWidget); + Finder menuIcon(String label) => find.descendant( + of: find.byTooltip('$label options'), + matching: find.byIcon(BuzzIcons.ellipsis), + ); + final teamIcon = menuIcon('Team'); + for (final label in ['Solo', 'Direct messages', 'Launch']) { + final icon = menuIcon(label); + expect(tester.getCenter(icon).dx, tester.getCenter(teamIcon).dx); + expect(tester.getSize(icon), tester.getSize(teamIcon)); + expect( + tester.widget(icon).color, + tester.widget(teamIcon).color, + ); + } + expect( + tester.getTopLeft(find.byIcon(BuzzIcons.messageCircle).first).dx, + tester.getTopLeft(find.byKey(const ValueKey('channel-icon-general'))).dx, + ); + final emoji = tester.getRect( + find.ancestor(of: inList('🚀'), matching: find.byType(FittedBox)).first, + ); + final channelIcon = tester.getRect( + find.byKey(const ValueKey('channel-icon-general')), + ); + final star = find.byType(TablerStarIcon); + expect(tester.widget(star).filled, isTrue); + expect(tester.getCenter(star).dx, channelIcon.center.dx); + expect(tester.getCenter(star).dy, tester.getCenter(inList('Starred')).dy); + expect( + tester.getTopLeft(inList('Starred')).dx, + tester.getTopLeft(inList('Launch')).dx, + ); + expect(emoji.center.dx, channelIcon.center.dx); + expect(emoji.center.dy, tester.getCenter(inList('Launch')).dy); + expect( + emoji.center.dy, + tester.getCenter(find.byTooltip('Launch options')).dy, + ); + expect(tester.getTopLeft(inList('Launch')).dx - emoji.right, 8); // A workspace holds team and Solo rows alike, in desktop's sort. for (final filed in ['design-crit', 'solo-plan']) { expect(top(filed), greaterThan(top('Launch'))); @@ -199,16 +260,21 @@ void main() { expect(inList('No chats yet'), findsNothing); // Desktop owns these workspaces and their sort: only filters remain. - await tester.tap(find.byTooltip('Launch options')); + final launchOptions = tester.getRect(find.byTooltip('Launch options')); + expect(launchOptions.size, const Size(64, 48)); + await tester.tapAt(launchOptions.bottomRight - const Offset(2, 2)); await tester.pumpAndSettle(); expect(find.text('Show'), findsOneWidget); expect(find.text('Rename section'), findsNothing); expect(find.text('Delete section'), findsNothing); - final sortChoice = find.byKey(const ValueKey('section-choice-Sort-Recent')); + final sortChoice = find.byKey(const ValueKey('section-menu-Sort')); expect(tester.widget(sortChoice).onTap, isNull); // Unreads keeps the unread Solo chat its row shows as unread. + await tester.tap(find.byKey(const ValueKey('section-menu-Show'))); + await tester.pumpAndSettle(); await tester.tap(find.text('Unreads')); - await tester.tap(find.text('Apply')); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Apply changes')); await tester.pumpAndSettle(); expect(inList('solo-plan'), findsOneWidget); expect(inList('design-crit'), findsNothing); @@ -216,6 +282,185 @@ void main() { // Only the filter choice was saved; no layout or sort record desktop // would have to reconcile. expect(relay.published.map((e) => e.getTagValue('d')), ['channel-filter']); + final soloSection = find.byKey(const ValueKey('me-ungrouped-chats')); + Finder soloDisclosure(String label) => + find.descendant(of: soloSection, matching: find.text(label)); + await tester.tap(find.byTooltip('Solo options')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('section-menu-Show'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Unreads').last); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Apply changes')); + await tester.pumpAndSettle(); + expect(inList('solo-scratch'), findsNothing); + relay.session.setStatus(SessionStatus.disconnected); + await tester.pumpAndSettle(); + await tester.tap(soloDisclosure('Show more')); + await tester.pumpAndSettle(); + expect(inList('solo-scratch'), findsOneWidget); + await tester.tap(soloDisclosure('Show fewer')); + await tester.pumpAndSettle(); + expect(inList('solo-scratch'), findsNothing); + expect(relay.published.map((e) => e.getTagValue('d')), [ + 'channel-filter', + 'channel-filter', + ]); + relay.session.setStatus(SessionStatus.connected); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('Solo options')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('section-menu-Show'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Active')); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('section-menu-Active in the past')), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('7 days')); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Apply changes')); + await tester.pumpAndSettle(); + expect(inList('solo-scratch'), findsOneWidget); + expect(find.text('Some activity couldn’t load'), findsOneWidget); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.text('Some activity couldn’t load'), findsNothing); + expect(inList('solo-scratch'), findsNothing); + expect(inList('solo-plan'), findsOneWidget); + await tester.tap(find.byTooltip('Solo options')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reorder sections')); + await tester.pumpAndSettle(); + Finder handle(String id) => find.descendant( + of: find.byKey(ValueKey(id)).last, + matching: find.byIcon(Icons.drag_handle), + ); + final haptics = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'HapticFeedback.vibrate') { + haptics.add(call.arguments); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final start = tester.getCenter(handle('solo')); + final gesture = await tester.startGesture(start); + await tester.pump(); + for (var step = 1; step <= 18; step++) { + await gesture.moveTo(start - Offset(0, step * 10)); + await tester.pump(const Duration(milliseconds: 24)); + } + await tester.pumpAndSettle(); + expect(haptics.first, 'HapticFeedbackType.mediumImpact'); + expect(haptics.skip(1), isNotEmpty); + expect(haptics.skip(1), everyElement('HapticFeedbackType.selectionClick')); + await gesture.up(); + await tester.pumpAndSettle(); + expect( + tester.getCenter(handle('solo')).dy, + lessThan(tester.getCenter(handle('channels')).dy), + ); + + const sectionIds = [ + 'starred', + 'group:launch', + 'group:later', + 'channels', + 'solo', + 'dms', + ]; + List sheetOrder(Iterable ids) => ids.toList() + ..sort( + (a, b) => tester + .getCenter(handle(a)) + .dy + .compareTo(tester.getCenter(handle(b)).dy), + ); + final firstOrder = sheetOrder(sectionIds); + // The signing identity owns the device-local order before a profile loads. + final key = 'section-order:https://relay.example:${relay.pubkey}'; + final container = ProviderScope.containerOf(tester.element(handle('solo'))); + final orders = container.read(mobileSectionOrderProvider(key).notifier); + final gate = Completer(); + orderStore.gate = gate; + await tester.tap(find.byTooltip('Save order')); + await tester.pumpAndSettle(); + // Flutter's screen-reader reorder actions call this even with drag disabled. + tester + .widget(find.byType(ReorderableListView)) + .onReorderItem!(0, 1); + await tester.pump(); + expect(sheetOrder(sectionIds), firstOrder); + expect(await orders.save(const [], firstOrder.reversed.toList()), isFalse); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byType(ReorderableListView), findsOneWidget); + gate.complete(); + await tester.pumpAndSettle(); + expect(prefs.getStringList(key), firstOrder); + expect(await orders.save(const [], firstOrder.reversed.toList()), isFalse); + + // Reopening from the same options sheet uses the order just saved. + await tester.tap(find.text('Reorder sections')); + await tester.pumpAndSettle(); + expect(sheetOrder(sectionIds), firstOrder); + await tester.tap(find.byTooltip('Discard order')); + await tester.pumpAndSettle(); + + final stars = container.read(channelStarsProvider.notifier) as _Stars; + stars.setStarred(false); + await tester.pumpAndSettle(); + await tester.tap(find.text('Reorder sections')); + await tester.pumpAndSettle(); + expect(find.text('Starred'), findsNothing); + + final dmFocus = Focus.of(tester.element(handle('dms'))); + for (var n = 0; n < 10 && !dmFocus.hasPrimaryFocus; n++) { + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + } + expect(dmFocus.hasPrimaryFocus, isTrue); + final visibleOrder = firstOrder.where((id) => id != 'starred').toList(); + final from = visibleOrder.indexOf('dms'); + visibleOrder.insert(from - 1, visibleOrder.removeAt(from)); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + expect(sheetOrder(visibleOrder), visibleOrder); + await tester.tap(find.byTooltip('Save order')); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('Discard changes')); + await tester.pumpAndSettle(); + final starredIndex = firstOrder.indexOf('starred'); + visibleOrder.insert(starredIndex, 'starred'); + expect(prefs.getStringList(key), visibleOrder); + expect( + prefs.getStringList('section-order:https://relay.example:null'), + isNull, + ); + stars.setStarred(true); + await tester.pumpAndSettle(); + final labels = { + 'starred': 'Starred', + 'group:launch': 'Launch', + 'group:later': 'Later', + 'channels': 'Team', + 'solo': 'Solo', + 'dms': 'Direct messages', + }; + final rendered = labels.keys.toList() + ..sort((a, b) => top(labels[a]!).compareTo(top(labels[b]!))); + expect(rendered, visibleOrder); await tester.pumpWidget(const SizedBox()); }); } @@ -256,6 +501,21 @@ class _Stars extends ChannelStarsNotifier { channels: {'pinned': ChannelStarEntry(starred: true, updatedAt: 1)}, ), ); + + void setStarred(bool starred) => + state = starred ? build() : const ChannelStarsState(isReady: true); +} + +class _OrderStore extends InMemorySharedPreferencesStore { + _OrderStore() : super.empty(); + + Completer? gate; + + @override + Future setValue(String type, String key, Object value) async { + if (key.startsWith('flutter.section-order:')) await gate?.future; + return super.setValue(type, key, value); + } } class _Config extends RelayConfigNotifier { diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index cb77642e5e..08062adb23 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -1981,6 +1981,26 @@ void main() { session.debugDispose(); }); + test('gated history cannot register on a replacement relay', () async { + final gate = RelayRateLimitGate(); + final harness = _queryHarness( + gate: gate, + client: http_testing.MockClient((_) async => http.Response('[]', 200)), + ); + addTearDown(harness.container.dispose); + gate.activate(4); + final retired = expectLater( + harness.session.fetchHistory(_channelFilter), + throwsStateError, + ); + harness.container.invalidate(relayConfigProvider); + harness.container.read(relaySessionProvider); + final replacement = _RecordingRelaySocket(); + harness.session.debugAttachSocketForTest(replacement); + await retired; + expect(_reqs(replacement), isEmpty); + }); + test('rate-limited history CLOSED gates the next REQ', () async { final gateTimers = <_ManualTimer>[]; final gate = RelayRateLimitGate( diff --git a/mobile/test/shared/widgets/buzz_toast_test.dart b/mobile/test/shared/widgets/buzz_toast_test.dart index 3a31f31f94..094059d375 100644 --- a/mobile/test/shared/widgets/buzz_toast_test.dart +++ b/mobile/test/shared/widgets/buzz_toast_test.dart @@ -72,8 +72,25 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Next route'), findsOneWidget); expect(find.text('Retry').hitTestable(), findsOneWidget); + final haptics = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'HapticFeedback.vibrate') { + haptics.add(call.arguments); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); await tester.tap(find.text('Retry')); await tester.pumpAndSettle(); + expect(haptics, ['HapticFeedbackType.selectionClick']); expect(retries, 1); expect(find.text('Try again'), findsNothing); expect(tester.takeException(), isNull); diff --git a/mobile/test/shared/widgets/native_route_controls_test.dart b/mobile/test/shared/widgets/native_route_controls_test.dart index ac22ae8c9a..26fb7c2c06 100644 --- a/mobile/test/shared/widgets/native_route_controls_test.dart +++ b/mobile/test/shared/widgets/native_route_controls_test.dart @@ -1,5 +1,8 @@ +import 'package:buzz/features/channels/channels_page/filters.dart'; +import 'package:buzz/features/channels/channel_sort/channel_sort_storage.dart'; import 'dart:async'; +import 'package:buzz/shared/widgets/app_route_observer.dart'; import 'package:buzz/shared/widgets/bottom_up_page_route.dart'; import 'package:buzz/shared/widgets/ios_glass_navigation_action.dart'; import 'package:buzz/shared/widgets/ios_glass_navigation_button.dart'; @@ -365,6 +368,80 @@ void main() { debugDefaultTargetPlatformOverride = null; }); + testWidgets( + 'section options keep Home controls mounted through the scrim transition', + (tester) async { + final nav = GlobalKey(); + late BuildContext home; + final observer = AppRouteObserver(); + var restores = 0; + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + navigatorKey: nav, + navigatorObservers: [observer], + home: Scaffold( + body: HookBuilder( + builder: (context) { + home = context; + return useNativeRouteControlsVisible(context) + ? IosGlassNavigationButton( + icon: IosGlassNavigationIcon.more, + semanticLabel: 'Home actions', + onPressed: () {}, + ) + : const SizedBox(); + }, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final control = find.byTooltip('Home actions'); + final original = tester.element(control); + observer.addRevealListener(ModalRoute.of(home)!, () => restores++); + unawaited( + showSectionViewSheet( + home, + title: 'Team', + group: 'channels', + sortMode: ChannelSortMode.alpha, + onSort: (_) {}, + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 80)); + final scrim = find.byWidgetPredicate( + (w) => w is UiKitView && w.viewType == 'buzz/toast_layer', + ); + double scrimOpacity() => tester + .widget( + find + .ancestor(of: scrim, matching: find.byType(FadeTransition)) + .first, + ) + .opacity + .value; + expect(tester.getRect(scrim).contains(tester.getCenter(control)), isTrue); + expect(scrimOpacity(), allOf(greaterThan(0), lessThan(1))); + expect(tester.element(control), same(original)); + await tester.pumpAndSettle(); + expect(tester.element(control), same(original)); + expect(scrimOpacity(), 1); + nav.currentState!.pop(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 80)); + expect(tester.element(control), same(original)); + await tester.pumpAndSettle(); + expect(tester.element(control), same(original)); + expect(scrim, findsNothing); + expect(restores, 0); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + testWidgets('route visibility rebuilds only when it changes', (tester) async { final navigator = GlobalKey(); final builds = [];