diff --git a/mobile/lib/features/channels/channel_actions_sheet.dart b/mobile/lib/features/channels/channel_actions_sheet.dart index 137e46e920..bcfcf5fd02 100644 --- a/mobile/lib/features/channels/channel_actions_sheet.dart +++ b/mobile/lib/features/channels/channel_actions_sheet.dart @@ -263,7 +263,6 @@ class ChannelActionsSheet extends HookConsumerWidget { close(); await _showMoveSectionSheet( pageContext, - ref, channel: channel, sectionId: sectionId, ); @@ -616,34 +615,55 @@ Future _confirmAndRun( } Future _showMoveSectionSheet( - BuildContext context, - WidgetRef ref, { + BuildContext context, { required Channel channel, required String? sectionId, }) async { - final sections = [...ref.read(channelSectionsProvider).store.sections] + // The actions sheet that opened this picker is already closing, and its + // WidgetRef is disposed with it. Use the page's container throughout. + final container = ProviderScope.containerOf(context, listen: false); + // A notification can switch communities while the picker or name dialog is + // open. Both close then, and only the community that opened them is edited. + final config = container.read(relayConfigProvider); + bool inScope() { + final current = container.read(relayConfigProvider); + return current.storedOrigin == config.storedOrigin && + current.nsec == config.nsec; + } + + void edit(void Function(ChannelSectionsNotifier sections) change) { + if (inScope()) change(container.read(channelSectionsProvider.notifier)); + } + + final sections = [...container.read(channelSectionsProvider).store.sections] ..sort((a, b) => a.order.compareTo(b.order)); BuildContext? sheet; - // Desktop's unified layout can lock legacy filing while this is open. The - // sheet that opened this picker may already be gone, so listen on the - // page's container. - final container = ProviderScope.containerOf(context, listen: false); + void close() { + final open = sheet; + if (open != null) _closeOwnRoute(open); + } + + // Desktop's unified layout can lock legacy filing while this is open. final lock = container.listen( channelSectionsProvider.select((state) => state.editable), (_, editable) { - final open = sheet; - if (!editable && open != null && open.mounted) Navigator.of(open).pop(); + if (!editable) close(); }, ); + final scope = container.listen(relayConfigProvider, (_, _) { + if (!inScope()) close(); + }); await showBuzzModalBottomSheet( context: context, showDragHandle: true, builder: (sheetContext) { - // A lock that landed before this first frame found no sheet to close. - if (sheet == null && !container.read(channelSectionsProvider).editable) { - WidgetsBinding.instance.addPostFrameCallback((_) { - if (sheetContext.mounted) Navigator.of(sheetContext).pop(); - }); + // A lock or switch that landed before this first frame found no sheet + // to close. + if (sheet == null && + (!container.read(channelSectionsProvider).editable || !inScope())) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => _closeOwnRoute(sheetContext), + ); } sheet = sheetContext; return SafeArea( @@ -670,9 +690,7 @@ Future _showMoveSectionSheet( : null, onTap: () { Navigator.of(sheetContext).pop(); - ref - .read(channelSectionsProvider.notifier) - .assignChannel(channel.id, section.id); + edit((s) => s.assignChannel(channel.id, section.id)); }, ), ListTile( @@ -680,19 +698,12 @@ Future _showMoveSectionSheet( title: const Text('New section…'), onTap: () async { Navigator.of(sheetContext).pop(); - final name = await _showSectionNameDialog(context); + final name = await _showSectionNameDialog( + context, + inScope: inScope, + ); if (name == null || name.isEmpty) return; - final notifier = ref.read(channelSectionsProvider.notifier); - notifier.createSection(name); - final created = ref - .read(channelSectionsProvider) - .store - .sections - .where((section) => section.name == name.trim()) - .lastOrNull; - if (created != null) { - notifier.assignChannel(channel.id, created.id); - } + edit((s) => s.createSection(name, channelId: channel.id)); }, ), if (sectionId != null) @@ -701,9 +712,7 @@ Future _showMoveSectionSheet( title: const Text('Remove from section'), onTap: () { Navigator.of(sheetContext).pop(); - ref - .read(channelSectionsProvider.notifier) - .unassignChannel(channel.id); + edit((s) => s.unassignChannel(channel.id)); }, ), ], @@ -712,29 +721,70 @@ Future _showMoveSectionSheet( ), ); }, - ).whenComplete(lock.close); + ).whenComplete(() { + lock.close(); + scope.close(); + }); } -Future _showSectionNameDialog(BuildContext context) async { - final controller = TextEditingController(); - final result = await showBuzzDialog( - context: context, - builder: (dialogContext) => AlertDialog( +/// Closes the route that [context] belongs to, once. Later calls, such as a +/// second community switch, find it already leaving and never pop the page +/// underneath. +void _closeOwnRoute(BuildContext context) { + if (!context.mounted) return; + final route = ModalRoute.of(context); + if (route == null || !route.isActive) return; + final navigator = Navigator.of(context); + if (route.isCurrent) { + navigator.pop(); + } else { + navigator.removeRoute(route); + } +} + +Future _showSectionNameDialog( + BuildContext context, { + required bool Function() inScope, +}) => showBuzzDialog( + context: context, + builder: (_) => _SectionNameDialog(inScope: inScope), +); + +/// Owns its controller so the field outlives the dialog's exit animation. +class _SectionNameDialog extends HookConsumerWidget { + const _SectionNameDialog({required this.inScope}); + + /// False once the community that opened the dialog is no longer active. + final bool Function() inScope; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final controller = useTextEditingController(); + ref.listen(relayConfigProvider, (_, _) { + if (!inScope()) _closeOwnRoute(context); + }); + // A switch that landed before this first frame found no dialog to close. + useEffect(() { + if (!inScope()) { + WidgetsBinding.instance.addPostFrameCallback( + (_) => _closeOwnRoute(context), + ); + } + return null; + }, const []); + return AlertDialog( title: const Text('New Section'), content: TextField(controller: controller, autofocus: true), actions: [ TextButton( - onPressed: () => Navigator.of(dialogContext).pop(), + onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel'), ), FilledButton( - onPressed: () => - Navigator.of(dialogContext).pop(controller.text.trim()), + onPressed: () => Navigator.of(context).pop(controller.text.trim()), child: const Text('Create'), ), ], - ), - ); - controller.dispose(); - return result; + ); + } } diff --git a/mobile/lib/features/channels/channel_details_page.dart b/mobile/lib/features/channels/channel_details_page.dart index c6e3728160..6cc65b68e4 100644 --- a/mobile/lib/features/channels/channel_details_page.dart +++ b/mobile/lib/features/channels/channel_details_page.dart @@ -404,7 +404,6 @@ class ChannelDetailsPage extends HookConsumerWidget { BuzzIcons.folderInput, () => _showMoveSectionSheet( context, - ref, channel: resolvedChannel, sectionId: currentSectionId, ), @@ -687,7 +686,6 @@ class ChannelDetailsPage extends HookConsumerWidget { onTap: () async { await _showMoveSectionSheet( context, - ref, channel: resolvedChannel, sectionId: currentSectionId, ); 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 b771117bff..26657a028e 100644 --- a/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart +++ b/mobile/lib/features/channels/channel_sections/channel_sections_manager.dart @@ -245,7 +245,8 @@ class ChannelSectionsManager { _unsubscribe = null; } - void createSection(String name) { + /// Files [channelId] in the new section in the same write, when given. + void createSection(String name, {String? channelId}) { if (!_editable) return; final maxOrder = _store.sections.fold( -1, @@ -258,7 +259,9 @@ class ChannelSectionsManager { ); _store = ChannelSectionStore( sections: [..._store.sections, section], - assignments: _store.assignments, + assignments: channelId == null + ? _store.assignments + : {..._store.assignments, channelId: section.id}, ); _persist(); markDirty(); 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 281e9cd7d9..bef834eb21 100644 --- a/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart +++ b/mobile/lib/features/channels/channel_sections/channel_sections_provider.dart @@ -101,7 +101,9 @@ class ChannelSectionsNotifier extends Notifier { ); } - void createSection(String name) => _manager?.createSection(name); + /// Files [channelId] in the new section in the same write, when given. + void createSection(String name, {String? channelId}) => + _edit((m) => m.createSection(name, channelId: channelId)); void renameSection(String sectionId, String? newName, {String? icon}) => _manager?.renameSection(sectionId, newName, icon: icon); @@ -119,10 +121,19 @@ class ChannelSectionsNotifier extends Notifier { _manager?.moveSectionDown(sectionId); void assignChannel(String channelId, String sectionId) => - _manager?.assignChannel(channelId, sectionId); + _edit((m) => m.assignChannel(channelId, sectionId)); void unassignChannel(String channelId) => - _manager?.unassignChannel(channelId); + _edit((m) => m.unassignChannel(channelId)); + + /// Applies a local edit and emits it at once, as [deleteSection] does, + /// rather than waiting for the relay to echo it back. + void _edit(void Function(ChannelSectionsManager manager) edit) { + final manager = _manager; + if (manager == null) return; + edit(manager); + _emitManagerState(manager); + } void _emitManagerState(ChannelSectionsManager manager) { if (_manager != manager) return; diff --git a/mobile/test/features/channels/channel_actions_sheet_test.dart b/mobile/test/features/channels/channel_actions_sheet_test.dart index e67f8cc69d..2b8e532675 100644 --- a/mobile/test/features/channels/channel_actions_sheet_test.dart +++ b/mobile/test/features/channels/channel_actions_sheet_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'package:buzz/features/channels/channel.dart'; import 'package:buzz/features/channels/channel_actions_sheet.dart'; @@ -10,6 +11,7 @@ import 'package:buzz/features/channels/channels_provider.dart'; import 'package:buzz/features/channels/manage_channel_sheet.dart'; import 'package:buzz/shared/mentions/agent_identity_provider.dart'; import 'package:buzz/shared/read_state/read_state_provider.dart'; +import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/theme/theme.dart'; import 'package:buzz/shared/widgets/buzz_action_tile.dart'; @@ -19,6 +21,10 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:hooks_riverpod/misc.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; const _currentPubkey = 'me'; @@ -72,13 +78,18 @@ Widget _modalApp({ bool details = false, String? canvasContent, Future? pendingCanvas, + List? sectionOverrides, + String? sectionId, }) => ProviderScope( overrides: [ currentPubkeyProvider.overrideWith((ref) => _currentPubkey), channelMembersProvider(channel.id).overrideWith((ref) => loadMembers()), - channelSectionsProvider.overrideWith( - () => _FakeChannelSectionsNotifier(const ChannelSectionStore()), - ), + ...sectionOverrides ?? + [ + channelSectionsProvider.overrideWith( + () => _FakeChannelSectionsNotifier(const ChannelSectionStore()), + ), + ], agentOwnersProvider.overrideWithValue( const AsyncValue.data({}), ), @@ -110,6 +121,7 @@ Widget _modalApp({ context: context, channel: channel, isUnread: false, + sectionId: sectionId, ), child: const Text('Open actions'), ), @@ -602,6 +614,206 @@ void main() { }); } + for (final (pick, laterExists) in [ + ('Work', false), + ('Remove from section', false), + ('New section…', false), + ('New section…', true), + ]) { + testWidgets('Move to section: $pick files the channel after the actions ' + 'sheet closes (a "Later" section already exists: $laterExists)', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 3000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final keys = nostr.Keys.generate(); + const relayUrl = 'https://relay.example'; + final storeKey = channelSectionsKey(keys.public, relayUrl); + // Records every snapshot saved for this layout, so one pick must be + // exactly one write. + final saves = _LayoutSaves('flutter.$storeKey', { + 'flutter.$storeKey': jsonEncode( + ChannelSectionStore( + sections: [ + const ChannelSection(id: 'work', name: 'Work', order: 0), + if (laterExists) + const ChannelSection(id: 'old-later', name: 'Later', order: 1), + ], + assignments: { + if (pick == 'Remove from section') 'channel-id': 'work', + }, + ).toJson(), + ), + }); + final previousStore = SharedPreferencesStorePlatform.instance; + SharedPreferencesStorePlatform.instance = saves; + SharedPreferences.resetStatic(); + addTearDown(() { + SharedPreferencesStorePlatform.instance = previousStore; + SharedPreferences.resetStatic(); + }); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + _modalApp( + channel: _channel(), + loadMembers: () async => const [], + createChannelActions: (ref) => _FakeChannelActions(ref), + sectionId: pick == 'Remove from section' ? 'work' : null, + sectionOverrides: [ + savedPrefsProvider.overrideWithValue(prefs), + relayConfigProvider.overrideWith( + () => _SignedInConfig(relayUrl, keys.nsec), + ), + activeCommunityProvider.overrideWith((ref) async => null), + ], + ), + ); + final container = ProviderScope.containerOf( + tester.element(find.text('Open actions')), + ); + await tester.tap(find.text('Open actions')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Move to section…')); + await tester.pumpAndSettle(); + expect(find.byType(ChannelActionsSheet), findsNothing); + + await tester.tap(find.text(pick)); + await tester.pumpAndSettle(); + if (pick == 'New section…') { + await tester.enterText(find.byType(TextField), 'Later'); + await tester.tap(find.text('Create')); + await tester.pumpAndSettle(); + } + + expect(tester.takeException(), isNull); + // The provider shows the move at once, and it is saved in one write. + final shown = container.read(channelSectionsProvider).store; + final saved = ChannelSectionStore.fromJson( + jsonDecode(saves.snapshots.single) as Map, + ); + expect(prefs.getString(storeKey), saves.snapshots.single); + for (final store in [shown, saved]) { + final filed = store.assignments['channel-id']; + switch (pick) { + case 'Work': + expect(filed, 'work'); + case 'Remove from section': + expect(store.assignments, isNot(contains('channel-id'))); + default: + final created = store.sections.singleWhere( + (s) => s.name == 'Later' && s.id != 'old-later', + ); + expect(filed, created.id); + } + } + }); + } + + for (final (pick, newKey, beforeDialog) in [ + ('Work', true, false), + ('Work', false, false), + ('New section…', true, false), + ('New section…', false, false), + // The switch lands after the tap but before the name dialog's first frame. + ('New section…', true, true), + ('New section…', false, true), + ]) { + testWidgets('Move to section: $pick closes and files nothing once the ' + 'community changes behind it (new signing key: $newKey, before the ' + 'dialog builds: $beforeDialog)', (tester) async { + tester.view.physicalSize = const Size(1200, 3000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final keys = nostr.Keys.generate(); + final other = nostr.Keys.generate(); + const relayUrl = 'https://relay.example'; + const otherRelayUrl = 'https://other.example'; + final mine = channelSectionsKey(keys.public, relayUrl); + // A portable identity keeps its key in another community's relay. + final theirs = newKey + ? channelSectionsKey(other.public, relayUrl) + : channelSectionsKey(keys.public, otherRelayUrl); + final workOnly = jsonEncode( + const ChannelSectionStore( + sections: [ChannelSection(id: 'work', name: 'Work', order: 0)], + assignments: {}, + ).toJson(), + ); + SharedPreferences.setMockInitialValues({ + mine: workOnly, + theirs: workOnly, + }); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget( + _modalApp( + channel: _channel(), + loadMembers: () async => const [], + createChannelActions: (ref) => _FakeChannelActions(ref), + sectionOverrides: [ + savedPrefsProvider.overrideWithValue(prefs), + relayConfigProvider.overrideWith( + () => _SignedInConfig(relayUrl, keys.nsec), + ), + activeCommunityProvider.overrideWith((ref) async => null), + ], + ), + ); + final container = ProviderScope.containerOf( + tester.element(find.text('Open actions')), + ); + await tester.tap(find.text('Open actions')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Move to section…')); + await tester.pumpAndSettle(); + final config = + container.read(relayConfigProvider.notifier) as _SignedInConfig; + void switchToThird() => config.signInAs( + nostr.Keys.generate().nsec, + baseUrl: 'https://third.example', + ); + // A second switch follows, so a stale route is asked to close more + // than once. Before the dialog builds, it lands just after the first + // frame builds the dialog. + void switchCommunity() { + config.signInAs( + newKey ? other.nsec : keys.nsec, + baseUrl: newKey ? relayUrl : otherRelayUrl, + ); + if (beforeDialog) { + tester.binding.addPostFrameCallback((_) => switchToThird()); + } else { + switchToThird(); + } + } + + if (beforeDialog) { + await tester.tap(find.text(pick)); + } else if (pick == 'New section…') { + await tester.tap(find.text(pick)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'Later'); + } + switchCommunity(); + await tester.pumpAndSettle(); + + // The stale picker or name dialog closes rather than offering a pick + // that would be dropped. + expect(find.text(pick), findsNothing); + expect(find.text('Create'), findsNothing); + // Only the stale route closes; the page under it stays. + expect(find.text('Open actions'), findsOneWidget); + + expect(tester.takeException(), isNull); + expect( + container.read(channelSectionsProvider).store.assignments, + isEmpty, + ); + expect(prefs.getString(mine), workOnly); + expect(prefs.getString(theirs), workOnly); + }); + } + testWidgets('member sees neither owner action', (tester) async { await tester.pumpWidget( _app( @@ -1172,6 +1384,31 @@ void main() { }); } +class _LayoutSaves extends InMemorySharedPreferencesStore { + _LayoutSaves(this.key, Map data) : super.withData(data); + + final String key; + final snapshots = []; + + @override + Future setValue(String valueType, String key, Object value) { + if (key == this.key) snapshots.add(value as String); + return super.setValue(valueType, key, value); + } +} + +class _SignedInConfig extends RelayConfigNotifier { + _SignedInConfig(this.baseUrl, this.nsec); + final String baseUrl; + final String nsec; + + @override + RelayConfig build() => RelayConfig(baseUrl: baseUrl, nsec: nsec); + + void signInAs(String other, {required String baseUrl}) => + state = RelayConfig(baseUrl: baseUrl, nsec: other); +} + class _FakeChannelSectionsNotifier extends ChannelSectionsNotifier { _FakeChannelSectionsNotifier(this._store);