From 287b7caf55837b39e1e14c669942d5b1d45deb0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 23:22:41 +0100 Subject: [PATCH] refactor(search): search only inside a conversation Search had grown filters it did not need: a global scope, a type picker, a date range and a sender dropdown. The useful case is "find this message in this chat", so the page is now scoped to one conversation and matches the message text and attachment file names only. It lives where the conversation's things live: a "Search in this chat" tile on the chat info page. A picked hit is handed back to the chat page, which jumps to it with the machinery the reply quote already uses. The Home search entry, the type/date/sender pickers and their strings are gone; the chat menu collapsed into the single "jump to date" action it still had. --- assets/translations/cs.json | 7 +- assets/translations/en.json | 7 +- lib/pages/chat_info_page.dart | 21 +++ lib/pages/chat_page.dart | 59 ++------ lib/pages/home_page.dart | 10 -- lib/pages/search_page.dart | 254 +++------------------------------- lib/utils/message_search.dart | 61 +------- test/message_search_test.dart | 61 +------- 8 files changed, 57 insertions(+), 423 deletions(-) diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 77987c6..0ed9858 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -144,15 +144,10 @@ "selectedCount": "Vybráno: %d", "moreActions": "Další akce", "jumpToLatest": "Skočit na nejnovější", - "searchMessages": "Hledat zprávy", "searchInChat": "Hledat v tomto chatu", "searchHint": "Hledat v lokální historii", - "searchEmptyHint": "Napiš text nebo zvol filtr. Zprávy se hledají jen v tomto zařízení.", + "searchEmptyHint": "Napiš text. Hledá se jen v této konverzaci a jen v tomto zařízení.", "noSearchResults": "Nic nenalezeno", - "anyType": "Jakýkoli typ", - "textOnly": "Text", - "anyDate": "Kdykoli", - "anySender": "Kdokoli", "jumpToDate": "Skočit na datum", "noMessagesOnDate": "Žádné zprávy od toho dne", "allChats": "Vše", diff --git a/assets/translations/en.json b/assets/translations/en.json index 5f61ad8..aae946a 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -144,15 +144,10 @@ "selectedCount": "%d selected", "moreActions": "More actions", "jumpToLatest": "Jump to latest", - "searchMessages": "Search messages", "searchInChat": "Search in this chat", "searchHint": "Search the local history", - "searchEmptyHint": "Type something, or pick a filter. Messages are searched on this device only.", + "searchEmptyHint": "Type to search this conversation. Messages are searched on this device only.", "noSearchResults": "Nothing found", - "anyType": "Any type", - "textOnly": "Text", - "anyDate": "Any date", - "anySender": "Anyone", "jumpToDate": "Jump to date", "noMessagesOnDate": "No messages from that day or later", "allChats": "All", diff --git a/lib/pages/chat_info_page.dart b/lib/pages/chat_info_page.dart index 4ce7d01..13a8f48 100644 --- a/lib/pages/chat_info_page.dart +++ b/lib/pages/chat_info_page.dart @@ -14,6 +14,7 @@ import '../widgets/media_bubble.dart'; import '../widgets/settings_tile.dart'; import 'home_page.dart'; import 'media_viewer_page.dart'; +import 'search_page.dart'; class ChatInfoPage extends StatefulWidget { const ChatInfoPage(this.userId, {super.key}); @@ -98,6 +99,20 @@ class _ChatInfoPageState extends State { ); } + /// Search this conversation. A picked hit is handed back to the chat page, + /// which jumps to it. + Future _openSearch() async { + final user = await CacheUtils.getUserById(widget.userId); + if (user == null || !mounted) { + return; + } + final picked = await Navigator.of(context) + .push(stepRoute(MessageSearchPage(user))); + if (picked != null && mounted) { + Navigator.pop(context, picked); + } + } + @override Widget build(BuildContext context) { return Theme( @@ -112,6 +127,12 @@ class _ChatInfoPageState extends State { SliverToBoxAdapter( child: Column( children: [ + // Search in this conversation + SettingsTile( + icon: Icons.search, + label: 'searchInChat'.tr(), + onPressed: _openSearch, + ), // Chat theme SettingsTile( icon: Icons.palette, diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index a8cf050..8e96389 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -24,15 +24,11 @@ import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; import 'forward_page.dart'; -import 'search_page.dart'; class ChatPage extends StatefulWidget { - const ChatPage(this.user, {this.jumpTo, super.key}); + const ChatPage(this.user, {super.key}); final User user; - /// Opens the conversation at this message instead of the newest one. - final DateTime? jumpTo; - @override State createState() => _ChatPageState(); } @@ -127,10 +123,6 @@ class _ChatPageState extends State { await _loadMessages(); // Then top the conversation up from the server archive _loadHistory(); - final jumpTo = widget.jumpTo; - if (jumpTo != null) { - await _jumpToMessage(jumpTo); - } } /// Keeps the newest message on screen when the keyboard opens. @@ -385,18 +377,14 @@ class _ChatPageState extends State { } Future _openChatInfo() async { - await Navigator.of(context).push(stepRoute(ChatInfoPage(widget.user.id))); + // The info page hands back a timestamp when a search hit was picked there. + final jumpTo = await Navigator.of(context) + .push(stepRoute(ChatInfoPage(widget.user.id))); // The theme (and possibly the user) may have changed while it was open. await _loadChatTheme(); await _loadMessages(); - } - - /// Search this conversation; the picked result is jumped to. - Future _openSearch() async { - final picked = await Navigator.of(context) - .push(stepRoute(MessageSearchPage(peer: widget.user))); - if (picked != null && mounted) { - await _jumpToMessage(picked); + if (jumpTo != null && mounted) { + await _jumpToMessage(jumpTo); } } @@ -1380,37 +1368,10 @@ class _ChatPageState extends State { ), // Action buttons actions: [ - PopupMenuButton( - tooltip: 'moreActions'.tr(), - onSelected: (value) { - if (value == 'search') { - _openSearch(); - } else { - _jumpToDate(); - } - }, - itemBuilder: (context) => [ - PopupMenuItem( - value: 'search', - child: Row( - children: [ - const Icon(Icons.search), - const SizedBox(width: 12), - Text('searchInChat'.tr()), - ], - ), - ), - PopupMenuItem( - value: 'jumpDate', - child: Row( - children: [ - const Icon(Icons.event), - const SizedBox(width: 12), - Text('jumpToDate'.tr()), - ], - ), - ), - ], + IconButton( + icon: const Icon(Icons.event), + tooltip: 'jumpToDate'.tr(), + onPressed: _jumpToDate, ), IconButton( icon: const Icon(Icons.info), diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 4408e59..c99393e 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -17,7 +17,6 @@ import '../utils/message_notifier.dart'; import '../utils/notification_service.dart'; import 'search_user_page.dart'; import 'settings_page.dart'; -import 'search_page.dart'; import '../utils/dialog_utils.dart'; import '../widgets/invite_list_item.dart'; import 'package:whisper_openapi_client_dart/api.dart'; @@ -484,15 +483,6 @@ class _HomePageState extends State title: Text('msgPage'.tr()), // Action buttons actions: [ - // Search across every locally stored conversation - IconButton( - icon: const Icon(Icons.search), - tooltip: 'searchMessages'.tr(), - onPressed: () { - Navigator.of(context) - .push(stepRoute(const MessageSearchPage())); - }, - ), // Settings IconButton( icon: const Icon(Icons.settings), diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart index c3a1629..03b2240 100644 --- a/lib/pages/search_page.dart +++ b/lib/pages/search_page.dart @@ -2,25 +2,20 @@ import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/user.dart'; import '../utils/cache_utils.dart'; -import '../utils/message_notifier.dart'; import '../utils/message_search.dart'; -import '../utils/nav_transitions.dart'; -import 'chat_page.dart'; -/// Searches the local message store. Messages are stored decrypted, so this is -/// a local scan: nothing is sent anywhere. +/// Searches one conversation's local history. Messages are stored decrypted, +/// so this is a local scan: nothing is sent anywhere. /// -/// With [peer] the search is scoped to that conversation and the picked -/// message is returned as a timestamp (the caller jumps to it). Without [peer] -/// the results span every conversation and open the chat at the hit. +/// The page returns the timestamp of the picked message; the chat it belongs to +/// jumps there. class MessageSearchPage extends StatefulWidget { - const MessageSearchPage({this.peer, super.key}); + const MessageSearchPage(this.peer, {super.key}); - final User? peer; + final User peer; @override State createState() => _MessageSearchPageState(); @@ -33,25 +28,6 @@ class _MessageSearchPageState extends State { bool _loading = false; bool _searched = false; - /// Media type name, or [MessageSearchQuery.textType]; null matches any. - String? _type; - DateTimeRange? _range; - - /// Sender (conversation) filter, only offered in the global search. - String? _conversationId; - List _conversations = []; - final Map _users = {}; - - bool get _global => widget.peer == null; - - @override - void initState() { - super.initState(); - if (_global) { - _loadConversations(); - } - } - @override void dispose() { _debounce?.cancel(); @@ -59,31 +35,16 @@ class _MessageSearchPageState extends State { super.dispose(); } - Future _loadConversations() async { - final chats = await MessageNotifier().getLatestPrivateMessages(); - if (!mounted) { - return; - } - setState(() { - _conversations = chats.keys.toList(); - }); - } - - MessageSearchQuery get _query => MessageSearchQuery( - text: _controller.text, - conversationId: widget.peer?.id ?? _conversationId, - from: _range?.start, - to: _range?.end, - type: _type, - ); - void _onTextChanged(String _) { _debounce?.cancel(); _debounce = Timer(const Duration(milliseconds: 250), _run); } Future _run() async { - final query = _query; + final query = MessageSearchQuery( + text: _controller.text, + conversationId: widget.peer.id, + ); if (query.isEmpty) { setState(() { _hits = []; @@ -98,16 +59,6 @@ class _MessageSearchPageState extends State { if (!mounted) { return; } - for (final hit in hits) { - if (_users.containsKey(hit.conversationId)) { - continue; - } - _users[hit.conversationId] = - await CacheUtils.getUserById(hit.conversationId); - } - if (!mounted) { - return; - } setState(() { _hits = hits; _loading = false; @@ -115,161 +66,14 @@ class _MessageSearchPageState extends State { }); } - Future _pickRange() async { - // Tapping the active chip clears it, which is the only way back to "any - // date" without reopening the picker. - if (_range != null) { - setState(() { - _range = null; - }); - await _run(); - return; - } - final now = DateTime.now(); - final picked = await showDateRangePicker( - context: context, - firstDate: DateTime(now.year - 10), - lastDate: now, - ); - if (picked == null || !mounted) { - return; - } - setState(() { - _range = picked; - }); - await _run(); - } - - Future _open(MessageHit hit) async { - final peer = widget.peer; - if (peer != null) { - // The chat page jumps to the picked message. - Navigator.pop(context, hit.message.sentAt); - return; - } - final user = _users[hit.conversationId]; - if (user == null) { - return; - } - await Navigator.of(context) - .push(stepRoute(ChatPage(user, jumpTo: hit.message.sentAt))); - } - - String _displayName(String conversationId) { - final user = _users[conversationId]; - if (user == null || user.username.isEmpty) { - return '?'; - } - return user.username; - } - - Widget _typeSelector() { - return DropdownButton( - value: _type, - underline: const SizedBox.shrink(), - borderRadius: BorderRadius.circular(12), - hint: Text('anyType'.tr()), - items: [ - DropdownMenuItem(value: null, child: Text('anyType'.tr())), - DropdownMenuItem( - value: MessageSearchQuery.textType, child: Text('textOnly'.tr())), - for (final type in [ - MediaType.image, - MediaType.video, - MediaType.voice, - MediaType.file, - MediaType.gif, - ]) - DropdownMenuItem( - value: type.name, child: Text('media${_typeLabel(type)}'.tr())), - ], - onChanged: (value) async { - setState(() { - _type = value; - }); - await _run(); - }, - ); - } - - /// Suffix of the existing media label keys (mediaPhoto, mediaVideo, ...). - String _typeLabel(MediaType type) { - switch (type) { - case MediaType.image: - return 'Photo'; - case MediaType.video: - return 'Video'; - case MediaType.voice: - return 'Voice'; - case MediaType.file: - return 'File'; - case MediaType.gif: - return 'Gif'; - } - } - - Widget _senderSelector() { - return DropdownButton( - value: _conversationId, - underline: const SizedBox.shrink(), - borderRadius: BorderRadius.circular(12), - hint: Text('anySender'.tr()), - items: [ - DropdownMenuItem(value: null, child: Text('anySender'.tr())), - for (final user in _conversations) - DropdownMenuItem( - value: user.id, - child: SizedBox( - width: 140, - child: Text( - user.username.isEmpty ? '?' : user.username, - overflow: TextOverflow.ellipsis, - ), - ), - ), - ], - onChanged: (value) async { - setState(() { - _conversationId = value; - }); - await _run(); - }, - ); - } - - Widget _filters() { - final label = _range == null - ? 'anyDate'.tr() - : '${DateFormat.MMMd().format(_range!.start)}' - ' – ${DateFormat.MMMd().format(_range!.end)}'; - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Wrap( - spacing: 8, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - _typeSelector(), - FilterChip( - label: Text(label), - selected: _range != null, - avatar: const Icon(Icons.date_range, size: 18), - onSelected: (_) => _pickRange(), - ), - if (_global && _conversations.isNotEmpty) _senderSelector(), - ], - ), - ); - } - /// A result line with the found text highlighted. - Widget _snippetText(String text, {int? maxLines}) { + Widget _snippetText(String text) { final scheme = Theme.of(context).colorScheme; + final needle = _controller.text; return Text.rich( TextSpan( children: [ - for (final part in highlightParts( - snippet(text, _controller.text), _controller.text)) + for (final part in highlightParts(snippet(text, needle), needle)) TextSpan( text: part.text, style: part.match @@ -283,51 +87,30 @@ class _MessageSearchPageState extends State { ), ], ), - maxLines: maxLines, - overflow: maxLines == null ? null : TextOverflow.ellipsis, + maxLines: 2, + overflow: TextOverflow.ellipsis, ); } Widget _resultTile(MessageHit hit) { final message = hit.message; - final user = _users[hit.conversationId]; final time = DateFormat.MMMd().add_Hm().format(message.sentAt.toLocal()); - final text = message.preview; return ListTile( - leading: _global - ? CircleAvatar( - radius: 20, - backgroundColor: - user?.avatarColor ?? Theme.of(context).colorScheme.primary, - child: Text( - _displayName(hit.conversationId)[0].toUpperCase(), - style: TextStyle( - fontSize: 16, - color: user?.avatarTextColor ?? Colors.white, - ), - ), - ) - : null, - title: _global - ? Text(_displayName(hit.conversationId)) - : _snippetText(text, maxLines: 2), - subtitle: _global ? _snippetText(text, maxLines: 2) : null, + title: _snippetText(message.preview), trailing: Text( time, style: TextStyle( fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant), ), - onTap: () => _open(hit), + onTap: () => Navigator.pop(context, message.sentAt), ); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(_global ? 'searchMessages'.tr() : widget.peer!.username), - ), + appBar: AppBar(title: Text('searchInChat'.tr())), body: SafeArea( child: Column( children: [ @@ -360,7 +143,6 @@ class _MessageSearchPageState extends State { ), ), ), - _filters(), if (_loading) const LinearProgressIndicator(), Expanded(child: _body()), ], diff --git a/lib/utils/message_search.dart b/lib/utils/message_search.dart index 20c6d3b..3420843 100644 --- a/lib/utils/message_search.dart +++ b/lib/utils/message_search.dart @@ -10,86 +10,35 @@ class MessageHit { final PrivateMessage message; } -/// What to look for in the local message store. +/// What to look for in one conversation's local history. /// /// The store holds decrypted text, so a search is a local scan: nothing leaves /// the device and no server round-trip happens. class MessageSearchQuery { - const MessageSearchQuery({ - this.text = '', - this.conversationId, - this.from, - this.to, - this.type, - }); + const MessageSearchQuery({this.text = '', this.conversationId}); - /// Case-insensitive substring of the message text (or of an attachment name). + /// Case-insensitive substring of the message text (or of a file name). final String text; /// Restricts the search to one conversation. final String? conversationId; - /// Inclusive start of the date range. - final DateTime? from; - - /// Inclusive end of the date range: the whole [to] day counts. - final DateTime? to; - - /// `text`, or a [MediaType.name]; null matches everything. - final String? type; - - /// Value of [type] for messages without an attachment. - static const String textType = 'text'; - /// Whether this query filters anything out at all. - bool get isEmpty => - text.trim().isEmpty && - type == null && - from == null && - to == null && - conversationId == null; + bool get isEmpty => text.trim().isEmpty; bool matches(MessageHit hit) { - final message = hit.message; if (conversationId != null && hit.conversationId != conversationId) { return false; } - if (!_matchesType(message)) { - return false; - } - final time = message.sentAt; - if (from != null && time.isBefore(from!)) { - return false; - } - if (to != null) { - final endOfDay = DateTime(to!.year, to!.month, to!.day, 23, 59, 59, 999); - if (time.isAfter(endOfDay)) { - return false; - } - } final needle = text.trim().toLowerCase(); if (needle.isEmpty) { return true; } + final message = hit.message; // An attachment without a caption is still findable by its file name. return message.message.toLowerCase().contains(needle) || (message.fileName ?? '').toLowerCase().contains(needle); } - - bool _matchesType(PrivateMessage message) { - final wanted = type; - if (wanted == null) { - return true; - } - if (wanted == textType) { - return !message.isMedia; - } - if (message.mediaTypeStr == wanted) { - return true; - } - // An album matches when any of its attachments has the type. - return message.album.any((item) => item.type == wanted); - } } /// How many hits a search returns. A single letter must not walk the whole diff --git a/test/message_search_test.dart b/test/message_search_test.dart index fc3807f..3909b60 100644 --- a/test/message_search_test.dart +++ b/test/message_search_test.dart @@ -1,25 +1,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:whisper/models/private_message.dart'; import 'package:whisper/utils/message_search.dart'; -import 'package:whisper_websocket_client_dart/models/media_type.dart'; PrivateMessage text(String body, DateTime sentAt, {String? fileName}) { return PrivateMessage('peer', body, sentAt, sentAt, true, fileName: fileName); } -PrivateMessage media(String type, DateTime sentAt) { - return PrivateMessage('peer', '', sentAt, sentAt, true, mediaTypeStr: type); -} - -PrivateMessage album(List types, DateTime sentAt) { - final message = PrivateMessage('peer', '', sentAt, sentAt, true); - message.setAlbum([ - for (var i = 0; i < types.length; i++) - AlbumItem(mediaId: '$i', type: types[i], size: 1), - ]); - return message; -} - MessageHit hit(String conversation, PrivateMessage message) => MessageHit(conversation, message); @@ -47,8 +33,7 @@ void main() { test('an attachment is findable by its file name', () { final query = MessageSearchQuery(text: 'smlouva'); - final message = media(MediaType.file.name, base) - ..fileName = 'Smlouva-2026.pdf'; + final message = text('', base, fileName: 'Smlouva-2026.pdf'); expect(query.matches(hit('a', message)), isTrue); }); @@ -59,50 +44,6 @@ void main() { }); }); - group('date range', () { - test('both ends are inclusive', () { - final query = MessageSearchQuery( - from: DateTime(2026, 6, 1), - to: DateTime(2026, 6, 1), - ); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1)))), isTrue); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 1, 23, 59)))), - isTrue); - expect(query.matches(hit('a', text('x', DateTime(2026, 6, 2)))), isFalse); - expect( - query.matches(hit('a', text('x', DateTime(2026, 5, 31)))), isFalse); - }); - }); - - group('type filter', () { - test('text means no attachment', () { - final query = MessageSearchQuery(type: MessageSearchQuery.textType); - expect(query.matches(hit('a', text('ahoj', base))), isTrue); - expect( - query.matches(hit('a', media(MediaType.image.name, base))), isFalse); - }); - - test('a media type matches its messages', () { - final query = MessageSearchQuery(type: MediaType.image.name); - expect( - query.matches(hit('a', media(MediaType.image.name, base))), isTrue); - expect( - query.matches(hit('a', media(MediaType.video.name, base))), isFalse); - }); - - test('an album matches when any attachment has the type', () { - final query = MessageSearchQuery(type: MediaType.video.name); - expect( - query.matches(hit( - 'a', album([MediaType.image.name, MediaType.video.name], base))), - isTrue); - expect( - query.matches(hit( - 'a', album([MediaType.image.name, MediaType.gif.name], base))), - isFalse); - }); - }); - group('result ordering', () { test('newest first and capped', () { final hits = [