From 834bec7ea02069ef7fafbd12ee376dd063f1912f Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:46:50 -0700 Subject: [PATCH 1/2] Make chat selection instant and add bulk selection to direct chats --- documentation/chat-and-messaging.md | 7 + lib/l10n/app_en.arb | 9 + lib/l10n/app_localizations.dart | 12 + lib/l10n/app_localizations_bg.dart | 14 + lib/l10n/app_localizations_cs.dart | 14 + lib/l10n/app_localizations_de.dart | 14 + lib/l10n/app_localizations_en.dart | 14 + lib/l10n/app_localizations_es.dart | 14 + lib/l10n/app_localizations_fr.dart | 14 + lib/l10n/app_localizations_hu.dart | 14 + lib/l10n/app_localizations_it.dart | 14 + lib/l10n/app_localizations_ja.dart | 14 + lib/l10n/app_localizations_ko.dart | 14 + lib/l10n/app_localizations_nl.dart | 14 + lib/l10n/app_localizations_pl.dart | 14 + lib/l10n/app_localizations_pt.dart | 14 + lib/l10n/app_localizations_ru.dart | 14 + lib/l10n/app_localizations_sk.dart | 14 + lib/l10n/app_localizations_sl.dart | 14 + lib/l10n/app_localizations_sv.dart | 14 + lib/l10n/app_localizations_uk.dart | 14 + lib/l10n/app_localizations_zh.dart | 14 + lib/screens/channel_chat_screen.dart | 10 +- lib/screens/chat_screen.dart | 615 ++++++++++++------ lib/widgets/chat_zoom_wrapper.dart | 36 +- test/screens/bulk_message_selection_test.dart | 569 ++++++++++++++++ 26 files changed, 1311 insertions(+), 213 deletions(-) create mode 100644 test/screens/bulk_message_selection_test.dart diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 40826682..ac4c85ae 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -170,6 +170,7 @@ Add emoji reactions to incoming messages (not your own): | Translate | Incoming messages only (when translation is enabled and not yet translated) | Translates the message on-demand using the on-device model | | Mark as Unread | Incoming messages only | Marks this message and all subsequent incoming messages as unread | | Delete | All messages | Removes locally (not from mesh) | +| Select messages | All messages | Starts multi-select with this message picked; see below | | Retry | Failed outgoing messages | Re-sends the message | | Open chat with sender | Room server chats | Opens 1:1 chat with the message sender | @@ -177,6 +178,12 @@ In channel chats the menu also offers **Mark as spam**, **Filter this sender** a Long-pressing directly on a detected GPS coordinate opens the coordinate action sheet (**Copy location** and **Open in maps**) instead of this message menu; long-press non-coordinate text in the message (or right-click on desktop) for message actions. +## Selecting Several Messages + +Channel, direct and room chats share the same multi-select. Choose **Select messages** in the message menu; while selecting, tapping or long-pressing any message toggles it (it shows as selected immediately, with no double-tap delay) and the back button clears the selection. Chat-text double-tap-to-reset-zoom is turned off while selecting. + +The selection bar offers **Copy** (oldest first) and **Delete** (after a confirmation) in all chats. Direct and room chats also offer **Bookmark** and **Resend**, which asks for confirmation and re-sends the selected outgoing messages oldest first. Delete and Resend are unavailable while the radio is offline. + ## Image and translation setup Enable URL images in the contact’s chat settings to preview supported image links; see [URL images](additional-features.md#url-image-previews). Images and files can also be uploaded to a configured IPFS provider from the **+** menu in direct or channel chat; the resulting URL is sent as ordinary text. See [sharing via IPFS](additional-features.md#share-an-image-via-ipfs) and [IPFS provider configuration](settings.md#ipfs-provider-configuration). Mesh image packets are currently sent through channel chat, not the direct-message composer. Set up translation and download a model in [App Settings](settings.md#translation) before using incoming or pre-send translation. diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 642d7f16..99b0964c 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1329,6 +1329,15 @@ "chat_receivedGif": "Received a GIF", "chat_reply": "Reply", "chat_resend": "Resend", + "chat_resendSelectedTitle": "Resend messages?", + "chat_resendSelectedConfirm": "{count, plural, =1{Resend 1 selected outgoing message to this contact?} other{Resend {count} selected outgoing messages to this contact?}}", + "@chat_resendSelectedConfirm": { + "placeholders": { + "count": { + "type": "int" + } + } + }, "chat_addReaction": "Add Reaction", "chat_me": "Me", "reaction_report": "Emoji Reactions", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index b5c8ad8e..10e3b90a 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -4537,6 +4537,18 @@ abstract class AppLocalizations { /// **'Resend'** String get chat_resend; + /// No description provided for @chat_resendSelectedTitle. + /// + /// In en, this message translates to: + /// **'Resend messages?'** + String get chat_resendSelectedTitle; + + /// No description provided for @chat_resendSelectedConfirm. + /// + /// In en, this message translates to: + /// **'{count, plural, =1{Resend 1 selected outgoing message to this contact?} other{Resend {count} selected outgoing messages to this contact?}}'** + String chat_resendSelectedConfirm(int count); + /// No description provided for @chat_addReaction. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 3871cf1b..bd38aaf8 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2616,6 +2616,20 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_resend => 'Изпрати отново'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Добави Реакция'; diff --git a/lib/l10n/app_localizations_cs.dart b/lib/l10n/app_localizations_cs.dart index 14acd0b7..7acb0d24 100644 --- a/lib/l10n/app_localizations_cs.dart +++ b/lib/l10n/app_localizations_cs.dart @@ -2610,6 +2610,20 @@ class AppLocalizationsCs extends AppLocalizations { @override String get chat_resend => 'Odeslat znovu'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Přidat reakci'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 7769c0e0..dc236509 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2619,6 +2619,20 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_resend => 'Erneut senden'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Reaktion hinzufügen'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 3b50a918..e0cd04a1 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2571,6 +2571,20 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_resend => 'Resend'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Add Reaction'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 901e76e5..b47dba53 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2610,6 +2610,20 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_resend => 'Reenviar'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Añadir Reacción'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 2bfc5046..ef527024 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2614,6 +2614,20 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_resend => 'Renvoyer'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Ajouter une réaction'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 97888e91..33aeab50 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2606,6 +2606,20 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_resend => 'Újraküldés'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Reakció hozzáadása'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index e757cc1d..041e65c7 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2613,6 +2613,20 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_resend => 'Reinvia'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Aggiungi Reazione'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index eec2a32e..0332dacb 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2492,6 +2492,20 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_resend => '再送信'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'リアクションを追加'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index ebf3c99f..79f9b5a6 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2492,6 +2492,20 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_resend => '다시 보내기'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => '댓글 추가'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 84d423dc..2228b6c1 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2597,6 +2597,20 @@ class AppLocalizationsNl extends AppLocalizations { @override String get chat_resend => 'Opnieuw verzenden'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Reactie toevoegen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 0c24139c..f9f727d6 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2638,6 +2638,20 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_resend => 'Wyślij ponownie'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Dodaj Reakcję'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index e0e1b7b0..cf56aab0 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2607,6 +2607,20 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_resend => 'Reenviar'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Adicionar Reação'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 0fe4cebb..ae756176 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2618,6 +2618,20 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_resend => 'Отправить снова'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Добавить реакцию'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 94b88ee8..7a2f5ffe 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2610,6 +2610,20 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_resend => 'Odoslať znova'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Pridať Reakciu'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 4a656e3e..27bdc68d 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2611,6 +2611,20 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_resend => 'Pošlji znova'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Dodaj reakcijo'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index b5982c31..5b756a5f 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -2585,6 +2585,20 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_resend => 'Skicka igen'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Lägg till reaktion'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 624c5c27..9c7179a6 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2615,6 +2615,20 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_resend => 'Надіслати знову'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => 'Додати реакцію'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index da104381..9f192abc 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2457,6 +2457,20 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_resend => '重新发送'; + @override + String get chat_resendSelectedTitle => 'Resend messages?'; + + @override + String chat_resendSelectedConfirm(int count) { + String _temp0 = intl.Intl.pluralLogic( + count, + locale: localeName, + other: 'Resend $count selected outgoing messages to this contact?', + one: 'Resend 1 selected outgoing message to this contact?', + ); + return '$_temp0'; + } + @override String get chat_addReaction => '添加表情'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 8b5d26de..cbc1ec57 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -985,6 +985,7 @@ class _ChannelChatScreenState extends State return Stack( children: [ ChatZoomWrapper( + enabled: !_selecting, child: ListView.builder( reverse: true, // List grows from bottom up controller: _scrollController, @@ -1010,14 +1011,19 @@ class _ChannelChatScreenState extends State ); } final row = layout.rowAt(index, messages); - final GlobalKey messageKey; + // Duplicate-id rows use a stable value key + // (not a fresh GlobalKey) so toggling one + // row does not remount every visible row. + final Key messageKey; if (layout.keyedIndices.contains(index)) { messageKey = _messageKeys.putIfAbsent( row.id, GlobalKey.new, ); } else { - messageKey = GlobalKey(); + messageKey = ValueKey( + '${row.id}#dup$index', + ); } final dividerId = _unreadDividerMessageId; final isUnreadAnchor = diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e8d3eba2..f80e1716 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -104,6 +104,8 @@ class _ChatScreenState extends State with WidgetsBindingObserver { final GlobalKey _unreadScrollKey = GlobalKey(); bool _isLoadingOlder = false; bool _showBookmarkedOnly = false; + final Set _selectedIds = {}; + bool get _selecting => _selectedIds.isNotEmpty; MeshCoreConnector? _connector; Message? _pendingUnreadScrollTarget; String? _unreadDividerMessageId; @@ -415,9 +417,14 @@ class _ChatScreenState extends State with WidgetsBindingObserver { @override Widget build(BuildContext context) { return PopScope( - canPop: !_searching, + canPop: !_searching && !_selecting, onPopInvokedWithResult: (didPop, _) { - if (!didPop && _searching) _closeSearch(); + if (didPop) return; + if (_selecting) { + _clearSelection(); + } else if (_searching) { + _closeSearch(); + } }, child: _buildScaffold(context), ); @@ -425,211 +432,224 @@ class _ChatScreenState extends State with WidgetsBindingObserver { Widget _buildScaffold(BuildContext context) { return Scaffold( - appBar: AppBar( - leading: _searching - ? IconButton( - tooltip: context.l10n.chatSearch_close, - icon: const Icon(Icons.arrow_back), - onPressed: _closeSearch, - ) - : null, - title: _searching - ? _buildSearchField() - : Consumer2( - builder: (context, pathService, connector, _) { - final contact = _resolveContact(connector); - final pathLabel = _currentPathLabel(contact); + appBar: _selecting + ? _buildSelectionAppBar(context) + : AppBar( + leading: _searching + ? IconButton( + tooltip: context.l10n.chatSearch_close, + icon: const Icon(Icons.arrow_back), + onPressed: _closeSearch, + ) + : null, + title: _searching + ? _buildSearchField() + : Consumer2( + builder: (context, pathService, connector, _) { + final contact = _resolveContact(connector); + final pathLabel = _currentPathLabel(contact); - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - contact.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () => - ContactRoutingSheet.show(context, contact: contact), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 6), - child: Builder( - builder: (context) { - // Follows the chat text size, capped so the two-line - // title still fits the app bar. - final textScale = context - .select( - (service) => service.scale, - ) - .clamp(1.0, 1.3); - return Text( - pathLabel, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 12 * textScale, - fontWeight: FontWeight.normal, - decoration: TextDecoration.underline, - decorationStyle: TextDecorationStyle.dotted, + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + contact.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => ContactRoutingSheet.show( + context, + contact: contact, + ), + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 6, ), - ); + child: Builder( + builder: (context) { + // Follows the chat text size, capped so the two-line + // title still fits the app bar. + final textScale = context + .select( + (service) => service.scale, + ) + .clamp(1.0, 1.3); + return Text( + pathLabel, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12 * textScale, + fontWeight: FontWeight.normal, + decoration: TextDecoration.underline, + decorationStyle: + TextDecorationStyle.dotted, + ), + ); + }, + ), + ), + ), + ], + ); + }, + ), + centerTitle: false, + bottom: const SyncProgressAppBarBottom(), + actionsPadding: const EdgeInsetsDirectional.only(end: 4), + // While searching the field gets the whole bar; the leading arrow + // closes the search. + actions: _searching + ? null + : [ + const RadioStatsIconButton(), + IconButton( + tooltip: context.l10n.chatSearch_tooltip, + icon: const Icon(Icons.search), + onPressed: _openSearch, + ), + Consumer( + builder: (context, connector, _) { + final contact = _resolveContact(connector); + final isRoom = contact.type == advTypeRoom; + final readOnly = isRadioReadOnly(connector); + + return PopupMenuButton( + icon: const Icon(Icons.more_vert), + onSelected: (value) { + switch (value) { + case 'routing': + ContactRoutingSheet.show( + context, + contact: contact, + ); + case 'info': + _showContactInfo(context); + case 'settings': + _showContactSettings(context); + case 'showBookmarks': + setState( + () => _showBookmarkedOnly = + !_showBookmarkedOnly, + ); + case 'background': + showChatBackgroundSheet( + context, + ChatBackgroundService.contactKey(contact), + ); + case 'telemetry': + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => TelemetryScreen( + contact: widget.contact, + ), + ), + ); + case 'roomManagement': + _showRoomManagementLogin(contact); + case 'clearChat': + _confirmClearChat(context, connector); + case 'removeContact': + confirmRemoveContact( + context, + connector, + contact, + onRemoved: () { + if (mounted) Navigator.of(context).pop(); + }, + ); + } }, - ), - ), + itemBuilder: (context) => [ + PopupMenuItem( + value: 'routing', + child: MeshMenuItemRow( + icon: Icons.route, + label: context.l10n.routing_title, + ), + ), + PopupMenuItem( + value: 'info', + child: MeshMenuItemRow( + icon: Icons.info_outline, + label: context.l10n.contact_info, + ), + ), + PopupMenuItem( + value: 'telemetry', + enabled: !readOnly, + child: MeshMenuItemRow( + icon: Icons.bar_chart, + label: context.l10n.contact_telemetry, + ), + ), + if (isRoom) + PopupMenuItem( + value: 'roomManagement', + enabled: !readOnly, + child: MeshMenuItemRow( + icon: Icons.room_preferences, + label: context.l10n.room_management, + ), + ), + PopupMenuItem( + value: 'settings', + child: MeshMenuItemRow( + icon: Icons.settings, + label: context.l10n.contact_settings, + ), + ), + PopupMenuItem( + value: 'showBookmarks', + child: MeshMenuItemRow( + icon: _showBookmarkedOnly + ? Icons.bookmark + : Icons.bookmark_border, + label: context.l10n.chat_showBookmarks, + color: _showBookmarkedOnly + ? const Color(0xFFFFE54A) + : null, + ), + ), + PopupMenuItem( + value: 'background', + child: MeshMenuItemRow( + icon: Icons.wallpaper, + label: context.l10n.chatBackground_title, + ), + ), + PopupMenuItem( + value: 'clearChat', + enabled: !readOnly, + child: MeshMenuItemRow( + icon: Icons.delete, + label: context.l10n.contact_clearChat, + color: readOnly + ? null + : Theme.of(context).colorScheme.error, + ), + ), + PopupMenuItem( + value: 'removeContact', + enabled: !readOnly, + child: MeshMenuItemRow( + icon: Icons.person_remove, + label: + context.l10n.contacts_removeFromContacts, + color: readOnly + ? null + : Theme.of(context).colorScheme.error, + ), + ), + ], + ); + }, ), ], - ); - }, - ), - centerTitle: false, - bottom: const SyncProgressAppBarBottom(), - actionsPadding: const EdgeInsetsDirectional.only(end: 4), - // While searching the field gets the whole bar; the leading arrow - // closes the search. - actions: _searching - ? null - : [ - const RadioStatsIconButton(), - IconButton( - tooltip: context.l10n.chatSearch_tooltip, - icon: const Icon(Icons.search), - onPressed: _openSearch, - ), - Consumer( - builder: (context, connector, _) { - final contact = _resolveContact(connector); - final isRoom = contact.type == advTypeRoom; - final readOnly = isRadioReadOnly(connector); - - return PopupMenuButton( - icon: const Icon(Icons.more_vert), - onSelected: (value) { - switch (value) { - case 'routing': - ContactRoutingSheet.show(context, contact: contact); - case 'info': - _showContactInfo(context); - case 'settings': - _showContactSettings(context); - case 'showBookmarks': - setState( - () => _showBookmarkedOnly = !_showBookmarkedOnly, - ); - case 'background': - showChatBackgroundSheet( - context, - ChatBackgroundService.contactKey(contact), - ); - case 'telemetry': - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - TelemetryScreen(contact: widget.contact), - ), - ); - case 'roomManagement': - _showRoomManagementLogin(contact); - case 'clearChat': - _confirmClearChat(context, connector); - case 'removeContact': - confirmRemoveContact( - context, - connector, - contact, - onRemoved: () { - if (mounted) Navigator.of(context).pop(); - }, - ); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'routing', - child: MeshMenuItemRow( - icon: Icons.route, - label: context.l10n.routing_title, - ), - ), - PopupMenuItem( - value: 'info', - child: MeshMenuItemRow( - icon: Icons.info_outline, - label: context.l10n.contact_info, - ), - ), - PopupMenuItem( - value: 'telemetry', - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.bar_chart, - label: context.l10n.contact_telemetry, - ), - ), - if (isRoom) - PopupMenuItem( - value: 'roomManagement', - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.room_preferences, - label: context.l10n.room_management, - ), - ), - PopupMenuItem( - value: 'settings', - child: MeshMenuItemRow( - icon: Icons.settings, - label: context.l10n.contact_settings, - ), - ), - PopupMenuItem( - value: 'showBookmarks', - child: MeshMenuItemRow( - icon: _showBookmarkedOnly - ? Icons.bookmark - : Icons.bookmark_border, - label: context.l10n.chat_showBookmarks, - color: _showBookmarkedOnly - ? const Color(0xFFFFE54A) - : null, - ), - ), - PopupMenuItem( - value: 'background', - child: MeshMenuItemRow( - icon: Icons.wallpaper, - label: context.l10n.chatBackground_title, - ), - ), - PopupMenuItem( - value: 'clearChat', - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.delete, - label: context.l10n.contact_clearChat, - color: readOnly - ? null - : Theme.of(context).colorScheme.error, - ), - ), - PopupMenuItem( - value: 'removeContact', - enabled: !readOnly, - child: MeshMenuItemRow( - icon: Icons.person_remove, - label: context.l10n.contacts_removeFromContacts, - color: readOnly - ? null - : Theme.of(context).colorScheme.error, - ), - ), - ], - ); - }, - ), - ], - ), + ), body: _showSearchResults ? _buildSearchResults(_loadSearchEntries) : Consumer( @@ -759,6 +779,7 @@ class _ChatScreenState extends State with WidgetsBindingObserver { }); return ChatZoomWrapper( + enabled: !_selecting, child: AnchoredChatListView.builder( scrollAnchor: _scrollAnchor, reverse: true, // List grows from bottom up @@ -840,7 +861,7 @@ class _ChatScreenState extends State with WidgetsBindingObserver { message.receivedAt, ); final highlighted = message.messageId == _highlightedMessageId; - final shown = highlighted + final styled = highlighted ? AnimatedContainer( duration: const Duration(milliseconds: 300), decoration: BoxDecoration( @@ -852,6 +873,9 @@ class _ChatScreenState extends State with WidgetsBindingObserver { child: bubble, ) : bubble; + final shown = _selecting + ? _buildSelectableRow(message, styled) + : styled; final child = isUnreadAnchor || startsDay ? Column( mainAxisSize: MainAxisSize.min, @@ -1428,6 +1452,14 @@ class _ChatScreenState extends State with WidgetsBindingObserver { _showEmojiPicker(message, contact); }, ), + ListTile( + leading: const Icon(Icons.checklist), + title: Text(context.l10n.chat_selectMessages), + onTap: () { + Navigator.pop(sheetContext); + _toggleSelected(message); + }, + ), ListTile( leading: const Icon(Icons.route), title: Text(context.l10n.chat_path), @@ -1555,6 +1587,183 @@ class _ChatScreenState extends State with WidgetsBindingObserver { ); } + // ---- bulk selection ------------------------------------------------------- + + void _toggleSelected(Message message) { + HapticFeedback.selectionClick(); + setState(() { + if (!_selectedIds.remove(message.messageId)) { + _selectedIds.add(message.messageId); + } + }); + } + + void _clearSelection() => setState(_selectedIds.clear); + + /// Selected messages still in the transcript, oldest first. + List _selectedMessages() { + final messages = context.read().getMessages( + widget.contact, + ); + return [ + for (final m in messages) + if (_selectedIds.contains(m.messageId)) m, + ]; + } + + Widget _buildSelectableRow(Message message, Widget messageBody) { + final scheme = Theme.of(context).colorScheme; + final selected = _selectedIds.contains(message.messageId); + return Semantics( + selected: selected, + button: true, + child: Material( + color: selected + ? scheme.primary.withValues(alpha: 0.16) + : Colors.transparent, + child: InkWell( + onTap: () => _toggleSelected(message), + onLongPress: () => _toggleSelected(message), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 8), + child: Row( + children: [ + Icon( + selected ? Icons.check_circle : Icons.radio_button_unchecked, + size: 28, + color: selected ? scheme.primary : scheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + // Links, images and reactions inside the bubble must not + // react while picking messages. + Expanded(child: AbsorbPointer(child: messageBody)), + ], + ), + ), + ), + ), + ); + } + + PreferredSizeWidget _buildSelectionAppBar(BuildContext context) { + final l10n = context.l10n; + final selected = _selectedMessages(); + final readOnly = context.radioReadOnly; + final canResend = + !readOnly && selected.any((m) => m.isOutgoing && !m.isCli); + return AppBar( + leading: IconButton( + tooltip: l10n.chat_clearSelection, + icon: const Icon(Icons.close), + onPressed: _clearSelection, + ), + title: Text(l10n.chat_selectedCount(selected.length)), + actions: [ + if (canResend) + IconButton( + tooltip: l10n.chat_resend, + icon: const Icon(Icons.replay), + onPressed: () => _bulkResend(selected), + ), + IconButton( + tooltip: l10n.chat_bookmark, + icon: const Icon(Icons.bookmark_border), + onPressed: selected.isEmpty ? null : () => _bulkBookmark(selected), + ), + IconButton( + tooltip: l10n.common_copy, + icon: const Icon(Icons.copy), + onPressed: selected.isEmpty ? null : () => _bulkCopy(selected), + ), + IconButton( + tooltip: l10n.common_delete, + icon: const Icon(Icons.delete_outline), + onPressed: selected.isEmpty || readOnly + ? null + : () => _bulkDelete(selected), + ), + ], + ); + } + + void _bulkCopy(List messages) { + final text = messages.map((m) => m.text).join('\n'); + setState(_selectedIds.clear); + copyChatMessageText(context, text); + } + + void _bulkBookmark(List messages) { + final connector = context.read(); + final contact = _resolveContact(connector); + final me = connector.selfName ?? context.l10n.chat_me; + setState(_selectedIds.clear); + for (final m in messages) { + unawaited( + connector.setBookmarkedMessage( + BookmarkedMessage.fromContact( + message: m, + contactKey: widget.contact.publicKeyHex, + contactName: widget.contact.name, + senderName: m.isOutgoing ? me : contact.name, + ), + isBookmarked: true, + ), + ); + } + } + + Future _bulkDelete(List messages) async { + if (!ensureRadioConnected(context)) return; + final connector = context.read(); + final confirmed = await confirmBulkDelete(context, messages.length); + if (!confirmed || !mounted) return; + setState(_selectedIds.clear); + for (final m in messages) { + await connector.deleteMessage(m); + } + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_messagesDeleted(messages.length)), + ); + } + + Future _bulkResend(List messages) async { + if (!ensureRadioConnected(context)) return; + final connector = context.read(); + final outgoing = [ + for (final m in messages) + if (m.isOutgoing && !m.isCli) m, + ]; + final confirmed = await showDialog( + context: context, + builder: (dialogContext) { + final l10n = dialogContext.l10n; + return AlertDialog( + title: Text(l10n.chat_resendSelectedTitle), + content: Text(l10n.chat_resendSelectedConfirm(outgoing.length)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(l10n.chat_resend), + ), + ], + ); + }, + ); + if (confirmed != true || !mounted) return; + final contact = _resolveContact(connector); + setState(_selectedIds.clear); + // Oldest first so the resent messages keep their order. + for (final m in outgoing) { + await connector.resendMessage(contact, m); + } + } + Future _deleteMessage(Message message) async { if (!ensureRadioConnected(context)) return; await context.read().deleteMessage(message); diff --git a/lib/widgets/chat_zoom_wrapper.dart b/lib/widgets/chat_zoom_wrapper.dart index f0c6815e..30ebb27e 100644 --- a/lib/widgets/chat_zoom_wrapper.dart +++ b/lib/widgets/chat_zoom_wrapper.dart @@ -4,14 +4,27 @@ import 'package:provider/provider.dart'; import '../services/chat_text_scale_service.dart'; /// Gesture wrapper that exposes two-finger pinch-to-zoom for chat scrollables. -/// Double-tap resets the scale. Only the wrapper itself listens to gestures; -/// child scrollables keep their normal touch handling. +/// Double-tap resets the scale, but only while the text is zoomed (or the +/// caller supplies [onDoubleTap]) and [enabled] is true: a double-tap +/// recognizer in the gesture arena makes every single tap on the child wait +/// 300 ms, so it is left out wherever taps must be instant. Only the wrapper +/// itself listens to gestures; child scrollables keep their normal touch +/// handling. class ChatZoomWrapper extends StatefulWidget { - const ChatZoomWrapper({super.key, required this.child, this.onDoubleTap}); + const ChatZoomWrapper({ + super.key, + required this.child, + this.onDoubleTap, + this.enabled = true, + }); final Widget child; final VoidCallback? onDoubleTap; + /// When false (e.g. while selecting messages) no double-tap is recognized, + /// so taps on the child are never delayed or swallowed. + final bool enabled; + @override State createState() => _ChatZoomWrapperState(); } @@ -22,14 +35,21 @@ class _ChatZoomWrapperState extends State { @override Widget build(BuildContext context) { final service = context.read(); + final zoomed = context.select( + (s) => s.scale != 1.0, + ); + final allowDoubleTap = + widget.enabled && (zoomed || widget.onDoubleTap != null); return GestureDetector( behavior: HitTestBehavior.translucent, - onDoubleTap: () { - service.reset(); - service.persist(); - widget.onDoubleTap?.call(); - }, + onDoubleTap: allowDoubleTap + ? () { + service.reset(); + service.persist(); + widget.onDoubleTap?.call(); + } + : null, onScaleStart: (details) { if (details.pointerCount != 2) return; _startScale = service.scale; diff --git a/test/screens/bulk_message_selection_test.dart b/test/screens/bulk_message_selection_test.dart new file mode 100644 index 00000000..40671d7e --- /dev/null +++ b/test/screens/bulk_message_selection_test.dart @@ -0,0 +1,569 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; + +/// Multi-select in channels, direct chats and rooms: taps must register +/// within 250 ms (no double-tap recognizer may hold them back), and direct +/// and room chats offer the same bulk actions as channels. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('bulk_selection_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + setUp(() { + clipboard = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + clipboard = (call.arguments as Map)['text'] as String?; + } + return null; + }); + }); + + testWidgets('direct and room chats: bulk bookmark saves every selected ' + 'message', (tester) async { + // One test for both: a bookmark write started in fake time only finishes + // inside that test, and the next write queues behind it. + for (final room in [false, true]) { + final p = room ? 'room' : 'dm'; + _view(tester, const Size(400, 800)); + await _pumpChat(tester, room: room); + await _enterChatSelection(tester, '$p 8'); + await tester.tap( + find.textContaining('$p 9', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.byTooltip('Bookmark')); + await _settle(tester); + // Bookmarks are stored per radio in the preferences; the writes + // started in fake time need real time to finish. + final prefs = PrefsManager.instance; + String stored() => [ + for (final key in prefs.getKeys()) + if (key.startsWith('message_bookmarks_')) prefs.getString(key) ?? '', + ].join(); + for (var i = 0; i < 200 && !stored().contains('$p 9'); i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + final saved = stored(); + expect(saved, contains('"text":"$p 8"')); + expect(saved, contains('"text":"$p 9"')); + expect(saved, isNot(contains('"text":"$p 7"'))); + expect(find.textContaining('selected'), findsNothing); + await tester.pumpWidget(const SizedBox()); + } + await _tearDown(tester); + }); + + group('instant selection taps', () { + testWidgets('channel: a tap selects within 250 ms and two taps 100 ms ' + 'apart both select', (tester) async { + _view(tester, const Size(400, 800)); + await _pumpChannel(tester); + await _enterChannelSelection(tester); + expect(find.text('1 selected'), findsOneWidget); + + await tester.tap( + find.textContaining('History 38', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap( + find.textContaining('History 37', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('3 selected'), findsOneWidget); + expect(find.byIcon(Icons.check_circle), findsNWidgets(3)); + + // A lone tap needs no extra time either. + await tester.tap( + find.textContaining('History 36', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.byIcon(Icons.check_circle), findsNWidgets(4)); + await _tearDown(tester); + }); + + testWidgets('channel: a single frame after the tap already shows it', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + await _pumpChannel(tester); + await _enterChannelSelection(tester); + await tester.tap( + find.textContaining('History 38', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(); + expect(find.byIcon(Icons.check_circle), findsNWidgets(2)); + await _tearDown(tester); + }); + + testWidgets('direct chat: taps select within 250 ms', (tester) async { + _view(tester, const Size(400, 800)); + final dm = await _pumpChat(tester, room: false); + await _enterChatSelection(tester, 'dm 9'); + await tester.tap( + find.textContaining('dm 8', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap( + find.textContaining('dm 7', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('3 selected'), findsOneWidget); + expect(find.byIcon(Icons.check_circle), findsNWidgets(3)); + expect(dm.$1.getMessages(dm.$2), isNotEmpty); + await _tearDown(tester); + }); + + testWidgets('room chat: taps select within 250 ms', (tester) async { + _view(tester, const Size(400, 800)); + await _pumpChat(tester, room: true); + await _enterChatSelection(tester, 'room 9'); + await tester.tap( + find.textContaining('room 8', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 100)); + await tester.tap( + find.textContaining('room 7', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('3 selected'), findsOneWidget); + await _tearDown(tester); + }); + + testWidgets('long press on a row toggles it while selecting', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + await _pumpChat(tester, room: false); + await _enterChatSelection(tester, 'dm 9'); + await tester.longPress( + find.textContaining('dm 8', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('2 selected'), findsOneWidget); + await tester.longPress( + find.textContaining('dm 8', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('1 selected'), findsOneWidget); + await _tearDown(tester); + }); + }); + + for (final room in [false, true]) { + final name = room ? 'room chat' : 'direct chat'; + final p = room ? 'room' : 'dm'; + + group('$name bulk actions', () { + testWidgets('back clears the selection instead of leaving', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + await _pumpChat(tester, room: room); + await _enterChatSelection(tester, '$p 9'); + await tester.tap( + find.textContaining('$p 8', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.text('2 selected'), findsOneWidget); + + await tester.binding.handlePopRoute(); + await tester.pump(const Duration(milliseconds: 250)); + expect(find.textContaining('selected'), findsNothing); + expect(find.byType(ChatScreen), findsOneWidget); + await _tearDown(tester); + }); + + testWidgets('copy puts the selected messages oldest first', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + await _pumpChat(tester, room: room); + await _enterChatSelection(tester, '$p 8'); + await tester.tap( + find.textContaining('$p 5', findRichText: true), + warnIfMissed: false, + ); + await tester.tap( + find.textContaining('$p 9', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.byTooltip('Copy')); + await tester.pump(const Duration(milliseconds: 250)); + expect(clipboard, '$p 5\n$p 8\n$p 9'); + expect(find.textContaining('selected'), findsNothing); + await _tearDown(tester); + }); + + testWidgets('delete asks first, then removes the selected messages', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + final (connector, contact) = await _pumpChat(tester, room: room); + await _enterChatSelection(tester, '$p 8'); + await tester.tap( + find.textContaining('$p 9', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.byTooltip('Delete')); + await tester.pump(const Duration(milliseconds: 250)); + expect( + find.text('Delete 2 messages from this device?'), + findsOneWidget, + ); + await tester.tap(find.text('Delete')); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 100)), + ); + await tester.pump(const Duration(milliseconds: 250)); + final texts = connector.getMessages(contact).map((m) => m.text); + expect(texts, isNot(contains('$p 8'))); + expect(texts, isNot(contains('$p 9'))); + expect(texts, contains('$p 7')); + await _tearDown(tester); + }); + + testWidgets('resend confirms, cancel does nothing, confirm resends', ( + tester, + ) async { + _view(tester, const Size(400, 800)); + final (connector, contact) = await _pumpChat( + tester, + room: room, + outgoing: true, + ); + List ids() => [ + for (final m in connector.getMessages(contact)) + if (m.isOutgoing) m.messageId, + ]; + final before = ids(); + expect(before, hasLength(2)); + + await _enterChatSelection(tester, '$p out 1'); + await tester.tap( + find.textContaining('$p out 2', findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.byTooltip('Resend')); + await tester.pump(const Duration(milliseconds: 250)); + expect( + find.text('Resend 2 selected outgoing messages to this contact?'), + findsOneWidget, + ); + + await tester.tap(find.text('Cancel')); + await tester.pump(const Duration(milliseconds: 250)); + expect(ids(), before); + expect(find.text('2 selected'), findsOneWidget); + + await tester.tap(find.byTooltip('Resend')); + await tester.pump(const Duration(milliseconds: 250)); + await tester.tap(find.widgetWithText(FilledButton, 'Resend')); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 300)), + ); + await tester.pump(const Duration(milliseconds: 250)); + final after = ids(); + expect(after, hasLength(2)); + expect(after, isNot(before)); + expect(find.textContaining('selected'), findsNothing); + await _tearDown(tester); + }); + }); + } + + group('no overflow at 320 dp', () { + for (final scale in [1.3, 2.0]) { + testWidgets('channel selection bar at ${scale}x text', (tester) async { + _view(tester, const Size(320, 700)); + await _pumpChannel(tester, textScale: scale); + await _enterChannelSelection(tester); + await tester.tap(find.byIcon(Icons.radio_button_unchecked).first); + await tester.pump(const Duration(milliseconds: 250)); + expect(tester.takeException(), isNull); + await _tearDown(tester); + }); + + testWidgets('direct chat selection bar at ${scale}x text', ( + tester, + ) async { + _view(tester, const Size(320, 700)); + await _pumpChat(tester, room: false, outgoing: true, textScale: scale); + await _enterChatSelection(tester, 'dm out 2'); + expect(find.byTooltip('Resend'), findsOneWidget); + expect(find.byTooltip('Delete'), findsOneWidget); + expect(tester.takeException(), isNull); + await _tearDown(tester); + }); + } + }); +} + +String? clipboard; + +void _view(WidgetTester tester, Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + // Let writes started during the test finish, so they cannot stall the + // next test's preferences writes. + for (var i = 0; i < 20; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 25)), + ); + await tester.pump(const Duration(milliseconds: 25)); + } + await tester.pump(const Duration(minutes: 1)); +} + +/// Opens the message action sheet for the message showing [text] (by calling +/// its long-press handler: a real long press on bubble text starts text +/// selection in tests) and picks "Select messages". +Future _enterSelectionFrom(WidgetTester tester, Finder message) async { + final target = tester.getCenter(message); + final detector = find + .byWidgetPredicate((w) => w is GestureDetector && w.onLongPress != null) + .evaluate() + .firstWhere((e) { + final box = e.renderObject! as RenderBox; + // Full-width detectors: match on the message's row, not its text. + return (box.localToGlobal(box.size.center(Offset.zero)).dy - target.dy) + .abs() < + 20; + }); + (detector.widget as GestureDetector).onLongPress!(); + await _settle(tester); + await tester.ensureVisible(find.text('Select messages')); + await tester.pump(); + await tester.tap(find.text('Select messages')); + await _settle(tester); +} + +Future _enterChannelSelection(WidgetTester tester) => _enterSelectionFrom( + tester, + find.textContaining('History 39', findRichText: true), +); + +Future _enterChatSelection(WidgetTester tester, String text) => + _enterSelectionFrom(tester, find.textContaining(text, findRichText: true)); + +(MeshCoreConnector, List)? _shared; + +Widget _app(List providers, Widget home, double textScale) => + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: home, + ), + ); + +var _stamp = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 100000; + +Future _pumpChannel( + WidgetTester tester, { + double textScale = 1.0, +}) async { + final (connector, providers) = _shared ??= await _connect(tester); + final channel = connector.channels[0]; + if (connector.getChannelMessages(channel).length < 40) { + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channel.index, + sender: 'Alice', + message: 'History $i', + timestampSecs: _stamp + i * 60, + ), + ); + } + } + await tester.pumpWidget( + _app(providers, ChannelChatScreen(channel: channel), textScale), + ); + await _settle(tester); + return connector; +} + +/// Shows a direct chat (or the review radio's room) holding ten incoming +/// messages "dm 0".."dm 9" / "room 0".."room 9", plus two outgoing ones when +/// [outgoing]. +Future<(MeshCoreConnector, Contact)> _pumpChat( + WidgetTester tester, { + required bool room, + bool outgoing = false, + double textScale = 1.0, + bool fresh = false, +}) async { + final (connector, providers) = fresh + ? await _connect(tester) + : (_shared ??= await _connect(tester)); + final contact = connector.contacts.firstWhere( + (c) => room ? c.type == advTypeRoom : c.type == advTypeChat, + ); + final p = room ? 'room' : 'dm'; + connector.clearMessagesForContact(contact); + await tester.runAsync(() => connector.flushPendingWrites()); + for (var i = 0; i < 10; i++) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: '$p $i', + timestampSecs: _stamp++, + ), + ); + } + if (outgoing) { + await tester.runAsync(() async { + await connector.sendMessage(contact, '$p out 1'); + await connector.sendMessage(contact, '$p out 2'); + }); + } + connector.markContactRead(contact.publicKeyHex); + await tester.pumpWidget( + _app(providers, ChatScreen(contact: contact), textScale), + ); + await _settle(tester); + return (connector, contact); +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((!connector.contacts.any((c) => c.type == advTypeRoom) || + !connector.contacts.any((c) => c.type == advTypeChat) || + connector.channels.length < 2) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + await Future.delayed(const Duration(milliseconds: 500)); + }); + expect(connector.channels.length, greaterThanOrEqualTo(2)); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} From a8b57d54e9cbffe02b173ed0014b66c1795221ad Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:27:03 -0700 Subject: [PATCH 2/2] Use each room message's author when bulk-bookmarking --- lib/screens/chat_screen.dart | 27 +++++--- test/screens/bulk_message_selection_test.dart | 61 ++++++++++++++++++- 2 files changed, 77 insertions(+), 11 deletions(-) diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 928c978b..7a4fc444 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -837,12 +837,7 @@ class _ChatScreenState extends State with WidgetsBindingObserver { if (isRoom) { // Room-server messages carry the original author's 4-byte prefix // separately from message.text; use it only for resolving the name. - roomAuthor = _resolveContactFrom4Bytes( - connector, - message.fourByteRoomContactKey.isEmpty - ? Uint8List.fromList([0, 0, 0, 0]) - : message.fourByteRoomContactKey, - ); + roomAuthor = _roomAuthorOf(connector, message); fourByteHex = message.fourByteRoomContactKey .map((b) => b.toRadixString(16).padLeft(2, '0')) .join() @@ -886,8 +881,9 @@ class _ChatScreenState extends State with WidgetsBindingObserver { ? AnimatedContainer( duration: const Duration(milliseconds: 300), decoration: BoxDecoration( - color: Theme.of(context).colorScheme.primary - .withValues(alpha: 0.18), + color: Theme.of( + context, + ).colorScheme.primary.withValues(alpha: 0.18), borderRadius: BorderRadius.circular(MeshRadii.md), ), child: bubble, @@ -1117,6 +1113,15 @@ class _ChatScreenState extends State with WidgetsBindingObserver { return connector.contacts[_resolveContactIndex]; } + /// The known author of a room-server post, or null when unknown. + Contact? _roomAuthorOf(MeshCoreConnector connector, Message message) => + _resolveContactFrom4Bytes( + connector, + message.fourByteRoomContactKey.isEmpty + ? Uint8List.fromList([0, 0, 0, 0]) + : message.fourByteRoomContactKey, + ); + Contact? _resolveContactFrom4Bytes( MeshCoreConnector connector, Uint8List key4Bytes, @@ -1715,6 +1720,7 @@ class _ChatScreenState extends State with WidgetsBindingObserver { void _bulkBookmark(List messages) { final connector = context.read(); final contact = _resolveContact(connector); + final isRoom = contact.type == advTypeRoom; final me = connector.selfName ?? context.l10n.chat_me; setState(_selectedIds.clear); for (final m in messages) { @@ -1724,7 +1730,10 @@ class _ChatScreenState extends State with WidgetsBindingObserver { message: m, contactKey: widget.contact.publicKeyHex, contactName: widget.contact.name, - senderName: m.isOutgoing ? me : contact.name, + senderName: m.isOutgoing + ? me + : (isRoom ? _roomAuthorOf(connector, m) : null)?.name ?? + contact.name, ), isBookmarked: true, ), diff --git a/test/screens/bulk_message_selection_test.dart b/test/screens/bulk_message_selection_test.dart index 40671d7e..9cd919bf 100644 --- a/test/screens/bulk_message_selection_test.dart +++ b/test/screens/bulk_message_selection_test.dart @@ -69,13 +69,38 @@ void main() { for (final room in [false, true]) { final p = room ? 'room' : 'dm'; _view(tester, const Size(400, 800)); - await _pumpChat(tester, room: room); + final (connector, chat) = await _pumpChat(tester, room: room); + // Room posts name their author by key prefix; the bookmark must carry + // that author's name, not the room server's. + final authors = connector.contacts + .where((c) => c.type == advTypeChat) + .take(2) + .toList(); + final posts = ['by author one', 'by author two']; + if (room) { + expect(authors, hasLength(2)); + for (var i = 0; i < 2; i++) { + connector.handleFrameForTest( + _roomPost(chat, authors[i], posts[i], _stamp++), + ); + } + await _settle(tester); + } await _enterChatSelection(tester, '$p 8'); await tester.tap( find.textContaining('$p 9', findRichText: true), warnIfMissed: false, ); await tester.pump(const Duration(milliseconds: 250)); + if (room) { + for (final post in posts) { + await tester.tap( + find.textContaining(post, findRichText: true), + warnIfMissed: false, + ); + await tester.pump(const Duration(milliseconds: 250)); + } + } await tester.tap(find.byTooltip('Bookmark')); await _settle(tester); // Bookmarks are stored per radio in the preferences; the writes @@ -85,7 +110,11 @@ void main() { for (final key in prefs.getKeys()) if (key.startsWith('message_bookmarks_')) prefs.getString(key) ?? '', ].join(); - for (var i = 0; i < 200 && !stored().contains('$p 9'); i++) { + for ( + var i = 0; + i < 200 && !stored().contains(room ? posts[1] : '$p 9'); + i++ + ) { await tester.runAsync( () => Future.delayed(const Duration(milliseconds: 50)), ); @@ -95,6 +124,16 @@ void main() { expect(saved, contains('"text":"$p 8"')); expect(saved, contains('"text":"$p 9"')); expect(saved, isNot(contains('"text":"$p 7"'))); + if (room) { + for (var i = 0; i < 2; i++) { + final entry = RegExp( + '\\{[^{}]*"text":"${posts[i]}"[^{}]*\\}', + ).firstMatch(saved)?.group(0); + expect(entry, isNotNull, reason: 'missing ${posts[i]}'); + expect(entry, contains('"senderName":"${authors[i].name}"')); + expect(entry, isNot(contains('"senderName":"${chat.name}"'))); + } + } expect(find.textContaining('selected'), findsNothing); await tester.pumpWidget(const SizedBox()); } @@ -360,6 +399,24 @@ void main() { }); } +/// A room-server post: a signed contact message whose 4-byte "signature" is +/// the author's public key prefix. +Uint8List _roomPost(Contact room, Contact author, String text, int stamp) { + final writer = BufferWriter(); + writer.writeByte(respCodeContactMsgRecvV3); + writer.writeByte(24); + writer.writeByte(0); + writer.writeByte(0); + writer.writeBytes(Uint8List.fromList(room.publicKey.sublist(0, 6))); + writer.writeByte(0xFF); + writer.writeByte(txtTypeSigned); + writer.writeUInt32LE(stamp); + writer.writeBytes(Uint8List.fromList(author.publicKey.sublist(0, 4))); + writer.writeString(text); + writer.writeByte(0); + return writer.toBytes(); +} + String? clipboard; void _view(WidgetTester tester, Size size) {