From d0351b9823155217877ece26de842b2d54c2db54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 23:14:36 +0100 Subject: [PATCH 1/3] feat(search): search the local message history Messages are stored decrypted, so the search is a local scan of the message box: the query never reaches the server and there is no second index that could drift from what is on disk. A 250 ms debounce and a hard cap of 300 hits keep a one-letter query from walking the whole history into the list. Filters: conversation (the sender, which is the peer in a 1:1 chat), media type (an album matches when any attachment does), and a date range whose ends are inclusive. Results are newest first with a window of text around the match; the found term is highlighted, so a hit is obvious even when the match sits inside formatting markers. The page is reachable globally from Home and scoped from a chat; the scoped version returns the picked timestamp instead of opening a page. --- assets/translations/cs.json | 15 ++ assets/translations/en.json | 15 ++ lib/pages/search_page.dart | 394 ++++++++++++++++++++++++++++++++++ lib/utils/cache_utils.dart | 22 ++ lib/utils/message_search.dart | 164 ++++++++++++++ test/message_search_test.dart | 160 ++++++++++++++ 6 files changed, 770 insertions(+) create mode 100644 lib/pages/search_page.dart create mode 100644 lib/utils/message_search.dart create mode 100644 test/message_search_test.dart diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 8083260..77987c6 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -144,6 +144,21 @@ "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í.", + "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", + "unreadChats": "Nepřečtené", + "pinnedChats": "Připnuté", + "noChatsInFilter": "Tady nic není", "chatPinned": "Chat připnut", "chatUnpinned": "Chat odebrán z připnutých", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", diff --git a/assets/translations/en.json b/assets/translations/en.json index eb0da38..5f61ad8 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -144,6 +144,21 @@ "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.", + "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", + "unreadChats": "Unread", + "pinnedChats": "Pinned", + "noChatsInFilter": "Nothing here", "chatPinned": "Chat pinned", "chatUnpinned": "Chat unpinned", "noChatsToForward": "No chats yet, search for a user", diff --git a/lib/pages/search_page.dart b/lib/pages/search_page.dart new file mode 100644 index 0000000..c3a1629 --- /dev/null +++ b/lib/pages/search_page.dart @@ -0,0 +1,394 @@ +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. +/// +/// 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. +class MessageSearchPage extends StatefulWidget { + const MessageSearchPage({this.peer, super.key}); + + final User? peer; + + @override + State createState() => _MessageSearchPageState(); +} + +class _MessageSearchPageState extends State { + final TextEditingController _controller = TextEditingController(); + Timer? _debounce; + List _hits = []; + 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(); + _controller.dispose(); + 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; + if (query.isEmpty) { + setState(() { + _hits = []; + _searched = false; + }); + return; + } + setState(() { + _loading = true; + }); + final hits = await CacheUtils.searchMessages(query); + 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; + _searched = true; + }); + } + + 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}) { + final scheme = Theme.of(context).colorScheme; + return Text.rich( + TextSpan( + children: [ + for (final part in highlightParts( + snippet(text, _controller.text), _controller.text)) + TextSpan( + text: part.text, + style: part.match + ? TextStyle( + fontWeight: FontWeight.bold, + color: scheme.onPrimaryContainer, + backgroundColor: + scheme.primaryContainer.withValues(alpha: 0.8), + ) + : null, + ), + ], + ), + maxLines: maxLines, + overflow: maxLines == null ? null : 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, + trailing: Text( + time, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + onTap: () => _open(hit), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: Text(_global ? 'searchMessages'.tr() : widget.peer!.username), + ), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: TextField( + controller: _controller, + autofocus: true, + textInputAction: TextInputAction.search, + onChanged: _onTextChanged, + onSubmitted: (_) => _run(), + decoration: InputDecoration( + hintText: 'searchHint'.tr(), + prefixIcon: const Icon(Icons.search), + suffixIcon: _controller.text.isEmpty + ? null + : IconButton( + icon: const Icon(Icons.clear), + tooltip: 'cancel'.tr(), + onPressed: () { + _controller.clear(); + _run(); + }, + ), + filled: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(24), + borderSide: BorderSide.none, + ), + ), + ), + ), + _filters(), + if (_loading) const LinearProgressIndicator(), + Expanded(child: _body()), + ], + ), + ), + ); + } + + Widget _body() { + if (!_searched) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'searchEmptyHint'.tr(), + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ), + ); + } + if (_hits.isEmpty) { + return Center(child: Text('noSearchResults'.tr())); + } + return ListView.builder( + itemCount: _hits.length, + itemBuilder: (context, index) => _resultTile(_hits[index]), + ); + } +} diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index 123a175..9f3024d 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -14,6 +14,7 @@ import '../models/user.dart'; import 'color_utils.dart'; import 'crypto_utils.dart'; import 'media_utils.dart'; +import 'message_search.dart'; import 'singleton.dart'; import 'utils.dart'; @@ -779,6 +780,27 @@ class CacheUtils { return counts; } + /// Searches the stored conversations, newest hit first. + /// + /// The message box holds decrypted text, so this is a local scan: the query + /// never reaches the server. + static Future> searchMessages( + MessageSearchQuery query) async { + final box = await _openPrivateMessagesBox(); + final hits = []; + for (final key in box.keys.whereType()) { + final conversationId = conversationOfKey(key); + if (conversationId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage) { + hits.add(MessageHit(conversationId, value)); + } + } + return filterMessages(hits, query); + } + /// Oldest unread message of a conversation: the anchor of the "new messages" /// divider, taken before the chat marks everything read. static Future firstUnreadSentAt(String userId) async { diff --git a/lib/utils/message_search.dart b/lib/utils/message_search.dart new file mode 100644 index 0000000..20c6d3b --- /dev/null +++ b/lib/utils/message_search.dart @@ -0,0 +1,164 @@ +import '../models/private_message.dart'; + +/// One stored message that matched a search, with the conversation it belongs +/// to (the other side's user id, not the sender: an archived message we sent +/// lives in the peer's conversation). +class MessageHit { + const MessageHit(this.conversationId, this.message); + + final String conversationId; + final PrivateMessage message; +} + +/// What to look for in the local message store. +/// +/// 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, + }); + + /// Case-insensitive substring of the message text (or of an attachment 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 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; + } + // 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 +/// history into a list. +const int searchResultLimit = 300; + +/// Applies [query] to [hits] and returns the newest first. +List filterMessages( + Iterable hits, MessageSearchQuery query) { + final matched = hits.where(query.matches).toList() + ..sort((a, b) => b.message.sentAt.compareTo(a.message.sentAt)); + return matched.length > searchResultLimit + ? matched.sublist(0, searchResultLimit) + : matched; +} + +/// A window of [text] around the first occurrence of [needle], for the result +/// list. Returns [text] when the needle is not in it. +String snippet(String text, String needle, {int radius = 40}) { + final trimmed = needle.trim(); + if (trimmed.isEmpty) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + final at = text.toLowerCase().indexOf(trimmed.toLowerCase()); + if (at < 0) { + return text.length <= radius * 2 + ? text + : '${text.substring(0, radius * 2)}…'; + } + var start = at - radius; + var end = at + trimmed.length + radius; + if (start < 0) { + start = 0; + } + if (end > text.length) { + end = text.length; + } + final prefix = start > 0 ? '…' : ''; + final suffix = end < text.length ? '…' : ''; + return '$prefix${text.substring(start, end)}$suffix'; +} + +/// Splits [text] into alternating plain and matched runs, so a result can show +/// what it found. Case-insensitive; every occurrence is marked. +List<({String text, bool match})> highlightParts(String text, String needle) { + final plain = [(text: text, match: false)]; + final trimmed = needle.trim(); + if (trimmed.isEmpty || text.isEmpty) { + return plain; + } + final lowered = text.toLowerCase(); + final target = trimmed.toLowerCase(); + final parts = <({String text, bool match})>[]; + var index = 0; + while (true) { + final at = lowered.indexOf(target, index); + if (at < 0) { + if (index < text.length) { + parts.add((text: text.substring(index), match: false)); + } + break; + } + if (at > index) { + parts.add((text: text.substring(index, at), match: false)); + } + parts.add((text: text.substring(at, at + target.length), match: true)); + index = at + target.length; + } + return parts.isEmpty ? plain : parts; +} diff --git a/test/message_search_test.dart b/test/message_search_test.dart new file mode 100644 index 0000000..fc3807f --- /dev/null +++ b/test/message_search_test.dart @@ -0,0 +1,160 @@ +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); + +/// Renders a highlighted line back to text, marking matches in brackets, so a +/// test can assert on the split without inspecting styles. +String marked(String text, String needle) => highlightParts(text, needle) + .map((part) => part.match ? '[${part.text}]' : part.text) + .join(); + +void main() { + final base = DateTime(2026, 6, 1, 12); + + group('text matching', () { + test('is case-insensitive and matches inside a word', () { + final query = MessageSearchQuery(text: 'AHOJ'); + expect(query.matches(hit('a', text('tak ahoj tam', base))), isTrue); + expect(query.matches(hit('a', text('nic', base))), isFalse); + }); + + test('an empty query matches everything', () { + const query = MessageSearchQuery(); + expect(query.isEmpty, isTrue); + expect(query.matches(hit('a', text('cokoli', base))), isTrue); + }); + + 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'; + expect(query.matches(hit('a', message)), isTrue); + }); + + test('the conversation filter scopes the search', () { + final query = MessageSearchQuery(text: 'ahoj', conversationId: 'b'); + expect(query.matches(hit('a', text('ahoj', base))), isFalse); + expect(query.matches(hit('b', text('ahoj', base))), isTrue); + }); + }); + + 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 = [ + for (var i = 0; i < searchResultLimit + 5; i++) + hit('a', text('ahoj', base.add(Duration(minutes: i)))), + ]; + final result = + filterMessages(hits, const MessageSearchQuery(text: 'ahoj')); + expect(result.length, searchResultLimit); + expect(result.first.message.sentAt.isAfter(result.last.message.sentAt), + isTrue); + }); + }); + + group('snippet', () { + test('short text is returned as it is', () { + expect(snippet('ahoj', 'ahoj'), 'ahoj'); + }); + + test('long text is cut around the match', () { + final long = '${'a' * 100} hledané ${'b' * 100}'; + final value = snippet(long, 'hledané', radius: 10); + expect(value.startsWith('…'), isTrue); + expect(value.endsWith('…'), isTrue); + expect(value, contains('hledané')); + expect(value.length, lessThan(long.length)); + }); + + test('a missing needle still returns a short window', () { + final value = snippet('a' * 200, 'nic'); + expect(value.endsWith('…'), isTrue); + expect(value.length, 81); + }); + }); + + group('highlighting', () { + test('no needle is a single plain run', () { + expect(highlightParts('ahoj', '').single.match, isFalse); + }); + + test('every occurrence is marked, case-insensitively', () { + expect(marked('Ahoj ahoj AHoj', 'ahoj'), '[Ahoj] [ahoj] [AHoj]'); + }); + + test('the text around the matches is preserved', () { + expect(marked('tak ahoj tam', 'ahoj'), 'tak [ahoj] tam'); + }); + + test('a needle that is not there changes nothing', () { + final parts = highlightParts('tak ahoj tam', 'nic'); + expect(parts.single.text, 'tak ahoj tam'); + expect(parts.single.match, isFalse); + }); + }); +} From f471d9e10b68a13adf3f6dafc69c9e3b93f40def Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 23:14:41 +0100 Subject: [PATCH 2/3] feat(chat): jump to date and to a search hit The chat app bar gets a menu with "search in this chat" and "jump to date". Both end in the same jump: the window is widened until the target is rendered and `Scrollable.ensureVisible` moves to it, which already backs the reply quote. A picked day lands on the first message of that day (or the first one after it), with a toast when the conversation has nothing that recent. A search hit returns its timestamp from the scoped search page, and a global hit opens the chat with `jumpTo`, so the result is where the search said it is. `stepRoute` is generic now, so it can return a value from the page it opens. --- lib/pages/chat_page.dart | 83 +++++++++++++++++++++++++++++++++- lib/utils/nav_transitions.dart | 4 +- 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index 46654e6..a8cf050 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -24,11 +24,15 @@ 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, {super.key}); + const ChatPage(this.user, {this.jumpTo, super.key}); final User user; + /// Opens the conversation at this message instead of the newest one. + final DateTime? jumpTo; + @override State createState() => _ChatPageState(); } @@ -123,6 +127,10 @@ 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. @@ -383,6 +391,47 @@ class _ChatPageState extends State { 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); + } + } + + /// Jump to the first message of a picked day (or the first one after it). + Future _jumpToDate() async { + if (_messages.isEmpty) { + return; + } + final oldest = _messages.first.sentAt.toLocal(); + final firstDay = DateTime(oldest.year, oldest.month, oldest.day); + final now = DateTime.now(); + final picked = await showDatePicker( + context: context, + initialDate: now, + firstDate: firstDay.isBefore(DateTime(2000)) ? DateTime(2000) : firstDay, + lastDate: now, + ); + if (picked == null || !mounted) { + return; + } + DateTime? target; + for (final message in _messages) { + if (!message.sentAt.isBefore(picked)) { + target = message.sentAt; + break; + } + } + if (target == null) { + await Fluttertoast.showToast( + msg: 'noMessagesOnDate'.tr(), backgroundColor: Colors.orange); + return; + } + await _jumpToMessage(target); + } + // --------------------------------------------------------------------------- // Reply and multi-select // --------------------------------------------------------------------------- @@ -1331,6 +1380,38 @@ 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.info), tooltip: 'infoButton'.tr(), diff --git a/lib/utils/nav_transitions.dart b/lib/utils/nav_transitions.dart index e0c7e59..cf1ecbc 100644 --- a/lib/utils/nav_transitions.dart +++ b/lib/utils/nav_transitions.dart @@ -33,8 +33,8 @@ Route fadeRoute(Widget child) { /// Opens the next step of a flow (forwarding, onboarding): it comes in from /// the side, the way a form usually does. -Route stepRoute(Widget child) { - return PageTransition( +Route stepRoute(Widget child) { + return PageTransition( type: PageTransitionType.rightToLeft, child: child, duration: navDuration, From 4e28dda3a05844f1256e8b9440eb02999cc70153 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20R=C3=A1=C5=BE?= Date: Tue, 17 Nov 2026 23:14:41 +0100 Subject: [PATCH 3/3] feat(chats): filter the list by unread and pinned Folder chips above the chat list: everything, unread, pinned. The filter lives in memory only, so it cannot go stale against the messages. The roadmap asks for unread and favourites; favourites arrive with contacts in F7, so pinned conversations stand in for them and the chips grow a fourth entry then. No new storage: the counts and the pin set the list already loads drive the filter. --- lib/pages/home_page.dart | 74 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 95345b9..4408e59 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -17,6 +17,7 @@ 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'; @@ -33,6 +34,12 @@ class HomePage extends StatefulWidget { State createState() => _HomePageState(); } +/// Which rows the chat list shows. +/// +/// The roadmap lists folders for unread and favourites; favourites arrive in F7 +/// with contacts, so the pinned chats stand in for them. +enum _ChatFilter { all, unread, pinned } + class _HomePageState extends State with SingleTickerProviderStateMixin { final WebSocketManager _webSocketManager = WebSocketManager(); @@ -46,6 +53,9 @@ class _HomePageState extends State /// Conversation ids pinned to the top of the list. Set _pinnedChats = {}; + + /// Which rows the list shows; folders without extra storage. + _ChatFilter _filter = _ChatFilter.all; bool _firstLoad = true; String? _pendingFid; // Store pending FID @@ -333,6 +343,56 @@ class _HomePageState extends State await _getServerInvites(); } + /// Chats that pass the current folder filter. + List> get _visibleChats { + switch (_filter) { + case _ChatFilter.unread: + return _chatEntries + .where((chat) => (_unreadCounts[chat.key.id] ?? 0) > 0) + .toList(); + case _ChatFilter.pinned: + return _chatEntries + .where((chat) => _pinnedChats.contains(chat.key.id)) + .toList(); + case _ChatFilter.all: + return _chatEntries; + } + } + + String _filterLabel(_ChatFilter filter) { + switch (filter) { + case _ChatFilter.all: + return 'allChats'.tr(); + case _ChatFilter.unread: + return 'unreadChats'.tr(); + case _ChatFilter.pinned: + return 'pinnedChats'.tr(); + } + } + + /// Folder chips above the list: everything, unread, pinned. + Widget _filterChips() { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + child: Row( + children: [ + for (final filter in _ChatFilter.values) + Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(_filterLabel(filter)), + selected: _filter == filter, + onSelected: (_) => setState(() { + _filter = filter; + }), + ), + ), + ], + ), + ); + } + /// Get ListView with content ListView _getContent(List> chats) { _firstLoad = false; @@ -424,6 +484,15 @@ 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), @@ -485,6 +554,7 @@ class _HomePageState extends State Column( children: [ SizedBox(height: 10), + _filterChips(), // Messages and avatar list Expanded( child: _firstLoad @@ -494,7 +564,9 @@ class _HomePageState extends State child: CircularProgressIndicator(), ), ) - : _getContent(_chatEntries), + : _visibleChats.isEmpty + ? Center(child: Text('noChatsInFilter'.tr())) + : _getContent(_visibleChats), ), ], ),