diff --git a/assets/translations/cs.json b/assets/translations/cs.json index 708aa82..8083260 100644 --- a/assets/translations/cs.json +++ b/assets/translations/cs.json @@ -138,6 +138,14 @@ "attachmentSaveFailed": "Uložení přílohy se nepovedlo", "forwardTo": "Přeposlat komu", "forwarded": "Přeposláno", + "showFull": "Zobrazit více", + "showLess": "Zobrazit méně", + "newMessages": "Nové zprávy", + "selectedCount": "Vybráno: %d", + "moreActions": "Další akce", + "jumpToLatest": "Skočit na nejnovější", + "chatPinned": "Chat připnut", + "chatUnpinned": "Chat odebrán z připnutých", "noChatsToForward": "Zatím žádné chaty, vyhledej uživatele", "mediaFile": "Soubor", "fileTooLarge": "Soubor je příliš velký, maximum je", diff --git a/assets/translations/en.json b/assets/translations/en.json index de29ca8..eb0da38 100644 --- a/assets/translations/en.json +++ b/assets/translations/en.json @@ -138,6 +138,14 @@ "attachmentSaveFailed": "Saving the attachment failed", "forwardTo": "Forward to", "forwarded": "Forwarded", + "showFull": "Show full message", + "showLess": "Show less", + "newMessages": "New messages", + "selectedCount": "%d selected", + "moreActions": "More actions", + "jumpToLatest": "Jump to latest", + "chatPinned": "Chat pinned", + "chatUnpinned": "Chat unpinned", "noChatsToForward": "No chats yet, search for a user", "mediaFile": "File", "fileTooLarge": "File is too large, the maximum is", diff --git a/lib/models/private_message.dart b/lib/models/private_message.dart index a4aa1df..8d091bf 100644 --- a/lib/models/private_message.dart +++ b/lib/models/private_message.dart @@ -5,6 +5,7 @@ import 'package:hive/hive.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../utils/singleton.dart'; +import '../utils/text_envelope.dart'; part 'private_message.g.dart'; @@ -162,6 +163,19 @@ class PrivateMessage extends HiveObject { @HiveField(15) String? albumJson; + /// Sender of the message this one quotes, null when it is not a reply. + @HiveField(16) + String? replyToSenderId; + + /// Client timestamp of the quoted message, null when it is not a reply. + @HiveField(17) + DateTime? replyToSentAt; + + /// Preview of the quoted message, kept here so the quote survives its + /// original being deleted on this device. + @HiveField(18) + String? replyToPreview; + /// Cache for [album], keyed by the [albumJson] it was decoded from. String? _albumCacheJson; List? _albumCache; @@ -183,8 +197,35 @@ class PrivateMessage extends HiveObject { this.fileName, this.sendStatus = SendStatus.sent, this.albumJson, + this.replyToSenderId, + this.replyToSentAt, + this.replyToPreview, }); + /// The quoted message, or null when this message is not a reply. + ReplyRef? get replyTo { + final senderId = replyToSenderId; + final sentAt = replyToSentAt; + if (senderId == null || sentAt == null) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: sentAt, + preview: replyToPreview ?? '', + ); + } + + /// Stores (or clears) the message this one quotes. + void setReplyTo(ReplyRef? reply) { + replyToSenderId = reply?.senderId; + replyToSentAt = reply?.sentAt; + replyToPreview = reply?.preview; + } + + /// Whether this message quotes another one. + bool get isReply => replyToSentAt != null; + /// Stored instead of the text when a message cannot be decrypted. It keeps a /// visible gap in the chat, and the receiver only acks what it stored, so the /// server still has the ciphertext. diff --git a/lib/models/private_message.g.dart b/lib/models/private_message.g.dart index 6585502..a8cc2a3 100644 --- a/lib/models/private_message.g.dart +++ b/lib/models/private_message.g.dart @@ -33,13 +33,16 @@ class PrivateMessageAdapter extends TypeAdapter { fileName: fields[13] as String?, sendStatus: fields[14] == null ? 1 : fields[14] as int, albumJson: fields[15] as String?, + replyToSenderId: fields[16] as String?, + replyToSentAt: fields[17] as DateTime?, + replyToPreview: fields[18] as String?, ); } @override void write(BinaryWriter writer, PrivateMessage obj) { writer - ..writeByte(16) + ..writeByte(19) ..writeByte(0) ..write(obj.senderId) ..writeByte(1) @@ -71,7 +74,13 @@ class PrivateMessageAdapter extends TypeAdapter { ..writeByte(14) ..write(obj.sendStatus) ..writeByte(15) - ..write(obj.albumJson); + ..write(obj.albumJson) + ..writeByte(16) + ..write(obj.replyToSenderId) + ..writeByte(17) + ..write(obj.replyToSentAt) + ..writeByte(18) + ..write(obj.replyToPreview); } @override diff --git a/lib/pages/chat_page.dart b/lib/pages/chat_page.dart index a3f981e..46654e6 100644 --- a/lib/pages/chat_page.dart +++ b/lib/pages/chat_page.dart @@ -1,10 +1,12 @@ import 'dart:async'; import 'dart:io'; -import 'dart:typed_data'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; +import 'package:sprintf/sprintf.dart'; +import '../utils/dialog_utils.dart'; import '../utils/nav_transitions.dart'; import 'package:whisper_websocket_client_dart/models/media_type.dart'; import '../models/private_message.dart'; @@ -12,13 +14,16 @@ import '../models/user.dart'; import '../utils/cache_utils.dart'; import '../utils/chat_sender.dart'; import '../utils/media_utils.dart'; +import '../utils/message_actions.dart'; import '../utils/message_notifier.dart'; import '../utils/singleton.dart'; +import '../utils/text_envelope.dart'; import '../utils/utils.dart' as utils; import '../utils/theme_utils.dart'; import '../widgets/attachment_confirm_sheet.dart'; import '../widgets/chat_bubble.dart'; import 'chat_info_page.dart'; +import 'forward_page.dart'; class ChatPage extends StatefulWidget { const ChatPage(this.user, {super.key}); @@ -42,7 +47,7 @@ class _ChatPageState extends State { int _visibleCount = _pageSize; // Buttons bool _isSending = false; - // ScrollController for content (list is reversed: offset 0 is the newest) + // ScrollController for content final ScrollController _scrollController = ScrollController(); // Indicates whether messages are being load for the first time bool _firstLoad = true; @@ -50,6 +55,8 @@ class _ChatPageState extends State { bool _loading = false; // Guards against overlapping history requests bool _historyLoading = false; + // Guards against overlapping "grow the window upwards" passes + bool _growing = false; // Whether the newest archive page was already asked for bool _historyLoaded = false; // Cursor for the next (older) archive page, null when the archive ends @@ -65,32 +72,84 @@ class _ChatPageState extends State { // Per-chat theme override, null means the global theme Color? _chatThemeColor; + /// The message the composer is quoting, null when not replying. + PrivateMessage? _replyTo; + + /// Oldest message that was unread when the chat opened: the "new messages" + /// divider. Captured before this page marks everything read. + DateTime? _unreadAnchor; + final GlobalKey _unreadDividerKey = GlobalKey(); + + /// Client timestamps (microseconds) of the messages picked in multi-select. + final Set _selected = {}; + + /// Bubble keys by client timestamp, for jumping to a quoted message. + final Map _messageKeys = {}; + + /// Newest message the viewport has already shown at the bottom; anything + /// after it while scrolled up counts as unseen. + int _newestSeenSentAt = 0; + int _unseenCount = 0; + + bool get _selectionMode => _selected.isNotEmpty; + @override void initState() { super.initState(); MessageNotifier().addListener(_onMessagesChanged); _scrollController.addListener(_onScroll); - // Load messages from cache - _loadMessages(); - // Then top the conversation up from the server archive - _loadHistory(); + _metricsObserver = _KeyboardObserver(() { + if (_atBottom) { + WidgetsBinding.instance.addPostFrameCallback((_) => _jumpToBottom()); + } + }); + WidgetsBinding.instance.addObserver(_metricsObserver); + _start(); // Load concept message getConceptMessage(); // Load per-chat theme _loadChatTheme(); } + /// The read state must be captured before the chat marks it read, otherwise + /// there is no divider left to draw. + Future _start() async { + final firstUnread = await CacheUtils.firstUnreadSentAt(widget.user.id); + if (mounted && firstUnread != null) { + setState(() { + _unreadAnchor = firstUnread; + }); + } + await _loadMessages(); + // Then top the conversation up from the server archive + _loadHistory(); + } + + /// Keeps the newest message on screen when the keyboard opens. + late final _KeyboardObserver _metricsObserver; + /// Reload the conversation from the cache when messages or media state change. void _onMessagesChanged() { _loadMessages(); } + /// Whether the viewport sits at the newest message. + bool get _atBottom { + if (!_scrollController.hasClients) { + return true; + } + final position = _scrollController.position; + return position.pixels >= position.maxScrollExtent - 40; + } + /// Load the conversation once per change instead of once per build. Future _loadMessages() async { if (_loading || !mounted) { return; } _loading = true; + final first = _firstLoad; + final wasAtBottom = _atBottom; try { final messages = await MessageNotifier().getMessages(widget.user.id); if (!mounted) { @@ -98,16 +157,40 @@ class _ChatPageState extends State { } // The first content frame decrypts every visible attachment, so keep it // out of the push animation and let the spinner ride along instead. - if (_firstLoad) { + if (first) { await _waitForRouteAnimation(); } if (!mounted) { return; } + final newest = + messages.isEmpty ? 0 : messages.last.sentAt.microsecondsSinceEpoch; setState(() { _messages = messages; + if (!first) { + if (wasAtBottom) { + _unseenCount = 0; + } else if (newest > _newestSeenSentAt) { + _unseenCount += messages + .where((message) => + !message.isMe && + message.sentAt.microsecondsSinceEpoch > _newestSeenSentAt) + .length; + } + } + _newestSeenSentAt = newest; _firstLoad = false; }); + if (first || wasAtBottom) { + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + _jumpToBottom(); + if (first) { + await _jumpToFirstUnread(); + } + } } finally { _loading = false; } @@ -133,21 +216,85 @@ class _ChatPageState extends State { await done.future; } + void _jumpToBottom({bool animate = false}) { + if (!_scrollController.hasClients) { + return; + } + final target = _scrollController.position.maxScrollExtent; + if (animate) { + _scrollController.animateTo(target, + duration: const Duration(milliseconds: 250), curve: Curves.easeOut); + } else { + _scrollController.jumpTo(target); + } + if (_unseenCount != 0) { + setState(() { + _unseenCount = 0; + }); + } + } + + /// Opens the chat on the first message the user has not read yet. + Future _jumpToFirstUnread() async { + if (_unreadAnchor == null) { + return; + } + await WidgetsBinding.instance.endOfFrame; + final context = _unreadDividerKey.currentContext; + if (context == null || !context.mounted) { + return; + } + await Scrollable.ensureVisible(context, + alignment: 0.15, duration: const Duration(milliseconds: 250)); + } + /// Extend the rendered window when the user scrolls towards older messages. void _onScroll() { if (!_scrollController.hasClients) { return; } - if (_scrollController.position.extentAfter < 200) { - if (_visibleCount < _messages.length) { - setState(() { - _visibleCount += _pageSize; - }); - } else if (_historyCursor != null) { - // The cache ran out: ask the server for the page below it. - _loadHistory(older: true); + final position = _scrollController.position; + if (position.pixels >= position.maxScrollExtent - 40 && _unseenCount != 0) { + setState(() { + _unseenCount = 0; + }); + } + // Older messages are above: the window grows near the top of the list. + if (position.pixels > 200) { + return; + } + if (_visibleCount < _messages.length) { + _growWindow(_pageSize); + } else if (_historyCursor != null) { + // The cache ran out: ask the server for the page above it. + _loadHistory(older: true); + } + } + + /// Renders more messages above the viewport without moving what is on screen. + Future _growWindow(int by) async { + if (_growing || !mounted) { + return; + } + _growing = true; + final before = _scrollController.hasClients + ? _scrollController.position.maxScrollExtent + : 0.0; + setState(() { + _visibleCount += by; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + _growing = false; + return; + } + if (_scrollController.hasClients) { + final delta = _scrollController.position.maxScrollExtent - before; + if (delta > 0) { + _scrollController.jumpTo(_scrollController.offset + delta); } } + _growing = false; } /// Fetch one page of the conversation from the server archive. @@ -166,6 +313,9 @@ class _ChatPageState extends State { return; } _historyLoading = true; + final before = _scrollController.hasClients + ? _scrollController.position.maxScrollExtent + : 0.0; try { final page = await utils.Utils.callApi( () => Singleton().messagesApi.getHistory(widget.user.id, @@ -184,11 +334,20 @@ class _ChatPageState extends State { return; } await utils.Utils.storeHistoryPage(page.messages); - if (mounted) { - // Show the page that just arrived without making the user scroll again. - setState(() { - _visibleCount += page.messages.length; - }); + if (!mounted) { + return; + } + // Show the page that just arrived without making the user scroll again. + setState(() { + _visibleCount += page.messages.length; + }); + await WidgetsBinding.instance.endOfFrame; + if (!mounted || !_scrollController.hasClients) { + return; + } + final delta = _scrollController.position.maxScrollExtent - before; + if (delta > 0) { + _scrollController.jumpTo(_scrollController.offset + delta); } } finally { _historyLoading = false; @@ -224,17 +383,131 @@ class _ChatPageState extends State { await _loadMessages(); } + // --------------------------------------------------------------------------- + // Reply and multi-select + // --------------------------------------------------------------------------- + + /// Quote [message] in the composer. + void _startReply(PrivateMessage message) { + if (_selectionMode) { + return; + } + setState(() { + _replyTo = message; + }); + } + + /// Adds or removes [message] from the selection; leaving it empty closes the + /// selection mode. + void _toggleSelected(PrivateMessage message) { + final micros = message.sentAt.microsecondsSinceEpoch; + setState(() { + if (!_selected.remove(micros)) { + _selected.add(micros); + } + }); + } + + void _clearSelection() { + setState(_selected.clear); + } + + /// Messages currently picked, oldest first. + List get _selectedMessages => _messages + .where((message) => + _selected.contains(message.sentAt.microsecondsSinceEpoch)) + .toList(); + + Future _copySelected() async { + final text = _selectedMessages + .map((message) => message.message) + .where((text) => text.isNotEmpty) + .join('\n'); + _clearSelection(); + if (text.isEmpty) { + return; + } + await Clipboard.setData(ClipboardData(text: text)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + Future _forwardSelected() async { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + _clearSelection(); + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); + } + + void _deleteSelected() { + final messages = _selectedMessages; + if (messages.isEmpty) { + return; + } + DialogUtils.yesNoDialog( + context, 'deleteMessageConfirm'.tr(), 'deleteMessageConfirmText'.tr(), + () async { + for (final message in messages) { + await CacheUtils.deletePrivateMessage(widget.user.id, message); + } + _clearSelection(); + MessageNotifier().notify(); + }); + } + + /// Scrolls to the message a reply quotes, widening the window when it is + /// older than what is rendered. + Future _jumpToMessage(DateTime sentAt) async { + final micros = sentAt.microsecondsSinceEpoch; + final context = _messageKeys[micros]?.currentContext; + if (context != null) { + await Scrollable.ensureVisible(context, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + return; + } + // Not rendered: open the window up to it, then try once more. + final index = _messages.indexWhere((message) => message.sentAt == sentAt); + if (index < 0) { + return; + } + final needed = _messages.length - index + 5; + if (needed > _visibleCount) { + await _growWindow(needed - _visibleCount); + } + await WidgetsBinding.instance.endOfFrame; + if (!mounted) { + return; + } + final retry = _messageKeys[micros]?.currentContext; + if (retry != null && retry.mounted) { + await Scrollable.ensureVisible(retry, + alignment: 0.3, duration: const Duration(milliseconds: 250)); + } + } + /// Send the typed text. Future _sendMessage() async { final text = _controllerMessage.text; if (text.isEmpty) { return; } + final quoted = _replyTo; + final reply = quoted == null + ? null + : ReplyRef( + senderId: quoted.senderId, + sentAt: quoted.sentAt, + preview: ReplyRef.previewOf(quoted.preview), + ); setState(() { _isSending = true; }); - if (await ChatSender.sendText(widget.user, text)) { + if (await ChatSender.sendText(widget.user, text, reply: reply)) { _controllerMessage.text = ''; + setState(() { + _replyTo = null; + }); await CacheUtils.deleteMessageConcept(widget.user.id); } if (mounted) { @@ -657,6 +930,63 @@ class _ChatPageState extends State { ); } + /// Quoted message above the composer, dismissable. + Widget _buildReplyBar() { + final reply = _replyTo!; + final author = reply.isMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Container( + margin: const EdgeInsets.only(bottom: 6), + padding: const EdgeInsets.only(left: 10), + decoration: BoxDecoration( + color: chatTheme.colorScheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(12), + border: Border( + left: BorderSide(color: chatTheme.colorScheme.primary, width: 3), + ), + ), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: chatTheme.colorScheme.primary, + ), + ), + Text( + reply.preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: chatTheme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + tooltip: 'cancel'.tr(), + icon: const Icon(Icons.close, size: 18), + onPressed: () { + setState(() { + _replyTo = null; + }); + }, + ), + ], + ), + ); + } + /// Bar shown while recording a voice message. Widget _buildRecordingBar() { final color = _cancelRecording ? Colors.red : chatTheme.colorScheme.primary; @@ -736,49 +1066,142 @@ class _ChatPageState extends State { ); } - /// Reversed list: offset 0 is the newest message, so the chat opens at the - /// bottom and growing bubbles or the keyboard never strand it mid-list. + /// The "new messages" divider, drawn above the first unread message. + Widget _buildUnreadDivider() { + final color = Theme.of(context).colorScheme.primary; + return Padding( + key: _unreadDividerKey, + padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16), + child: Row( + children: [ + Expanded(child: Divider(color: color)), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Text( + 'newMessages'.tr(), + style: TextStyle( + fontSize: 12, color: color, fontWeight: FontWeight.bold), + ), + ), + Expanded(child: Divider(color: color)), + ], + ), + ); + } + + /// Calendar day a message belongs to, in the timezone the bubble shows. + DateTime _dayOf(PrivateMessage message) { + final time = (message.isMe ? message.sentAt : message.receivedAt).toLocal(); + return DateTime(time.year, time.month, time.day); + } + + String _dayLabel(DateTime day) { + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final days = today.difference(day).inDays; + if (days <= 0) { + return 'todayText'.tr(); + } + if (days == 1) { + return 'yesterdayText'.tr(); + } + if (days < 7) { + return DateFormat.EEEE().format(day); + } + if (day.year == now.year) { + return DateFormat.MMMMd().format(day); + } + return DateFormat.yMMMMd().format(day); + } + + Widget _buildBubble( + PrivateMessage message, PrivateMessage? older, PrivateMessage? newer) { + final micros = message.sentAt.microsecondsSinceEpoch; + final key = _messageKeys.putIfAbsent(micros, () => GlobalKey()); + final showsDivider = _unreadAnchor?.microsecondsSinceEpoch == micros; + final bubble = ChatBubble( + older, + message, + newer, + widget.user, + key: key, + // The picked chat color itself, not a tonal derivative of it. + accentColor: _chatThemeColor ?? Singleton().appTheme.color, + selectionMode: _selectionMode, + selected: _selected.contains(micros), + onSelect: () => _toggleSelected(message), + onReply: () => _startReply(message), + onTapQuote: message.isReply + ? () => _jumpToMessage(message.replyTo!.sentAt) + : null, + ); + if (!showsDivider) { + return bubble; + } + // The divider sits above its message and goes away once the day header + // does not repeat it. + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [_buildUnreadDivider(), bubble], + ); + } + + /// Messages, grouped by day: each day gets a sticky header. Widget _getContent(List messages) { final start = messages.length > _visibleCount ? messages.length - _visibleCount : 0; final visible = messages.sublist(start); final hasOlder = start > 0; - final itemCount = visible.length + 1; - return ListView.builder( + final days = >{}; + for (var i = 0; i < visible.length; i++) { + days.putIfAbsent(_dayOf(visible[i]), () => []).add(i); + } + final orderedDays = days.keys.toList()..sort(); + + return CustomScrollView( + controller: _scrollController, physics: const BouncingScrollPhysics( parent: AlwaysScrollableScrollPhysics(), ), - controller: _scrollController, - reverse: true, - itemCount: itemCount, - itemBuilder: (context, index) { - // Last item is the conversation header (top of the screen). - if (index == visible.length) { - if (hasOlder) { - return const Padding( - padding: EdgeInsets.symmetric(vertical: 16), - child: Center( - child: SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ), - ), - ); - } - return _buildHeader(); - } - // index 0 is the newest message; older messages have higher indices. - final message = visible[visible.length - 1 - index]; - final position = visible.length - 1 - index; - final older = position > 0 ? visible[position - 1] : null; - final newer = - position < visible.length - 1 ? visible[position + 1] : null; - return ChatBubble(older, message, newer, widget.user, - // The picked chat color itself, not a tonal derivative of it. - accentColor: _chatThemeColor ?? Singleton().appTheme.color); - }, + slivers: [ + SliverToBoxAdapter( + child: hasOlder + ? const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center( + child: SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ) + : _buildHeader(), + ), + for (final day in orderedDays) ...[ + SliverPersistentHeader( + pinned: true, + delegate: _DayHeader( + label: _dayLabel(day), + textColor: Theme.of(context).colorScheme.onSurfaceVariant, + background: chatBackground(tintAlpha: 0.35), + ), + ), + SliverList.builder( + itemCount: days[day]!.length, + itemBuilder: (context, index) { + final position = days[day]![index]; + final message = visible[position]; + return _buildBubble( + message, + position > 0 ? visible[position - 1] : null, + position < visible.length - 1 ? visible[position + 1] : null, + ); + }, + ), + ], + ], ); } @@ -786,6 +1209,7 @@ class _ChatPageState extends State { void dispose() { MessageNotifier().removeListener(_onMessagesChanged); _scrollController.removeListener(_onScroll); + WidgetsBinding.instance.removeObserver(_metricsObserver); _recordTimer?.cancel(); _recorderController?.dispose(); _controllerMessage.dispose(); @@ -830,6 +1254,92 @@ class _ChatPageState extends State { .withValues(alpha: 0.85); } + /// Chat AppBar, or the selection AppBar while messages are picked. + Widget _buildAppBarContent() { + if (_selectionMode) { + final single = + _selectedMessages.length == 1 ? _selectedMessages.first : null; + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: IconButton( + icon: const Icon(Icons.close), + tooltip: 'cancel'.tr(), + onPressed: _clearSelection, + ), + title: Text(sprintf('selectedCount'.tr(), [_selected.length])), + actions: [ + IconButton( + icon: Icon(MessageActions.copyIcon), + tooltip: 'copyMessage'.tr(), + onPressed: _copySelected, + ), + IconButton( + icon: Icon(MessageActions.forwardIcon), + tooltip: 'forwardMessage'.tr(), + onPressed: _forwardSelected, + ), + IconButton( + icon: Icon(MessageActions.deleteIcon), + tooltip: 'deleteMessageForMe'.tr(), + onPressed: _deleteSelected, + ), + // Save, resend and the rest still live in the single-message sheet. + if (single != null) + IconButton( + icon: const Icon(Icons.more_vert), + tooltip: 'moreActions'.tr(), + onPressed: () => + MessageActions.showSheet(context, single, widget.user.id), + ), + ], + ); + } + return AppBar( + automaticallyImplyLeading: false, + backgroundColor: appBarBackground(), + leading: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => Navigator.pop(context), + ), + GestureDetector( + onTap: _openChatInfo, + child: CircleAvatar( + radius: 18, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 16, + color: widget.user.avatarTextColor, + ), + ), + ), + ), + ], + ), + leadingWidth: 96, // Increase width to accommodate both icons + // Title + title: GestureDetector( + onTap: _openChatInfo, + behavior: HitTestBehavior.opaque, + child: Text(widget.user.username), + ), + // Action buttons + actions: [ + IconButton( + icon: const Icon(Icons.info), + tooltip: 'infoButton'.tr(), + onPressed: _openChatInfo, + ), + ], + ); + } + @override Widget build(BuildContext context) { return PopScope( @@ -856,49 +1366,7 @@ class _ChatPageState extends State { child: ClipRRect( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), - child: AppBar( - automaticallyImplyLeading: false, - backgroundColor: appBarBackground(), - leading: Row( - children: [ - IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.pop(context), - ), - GestureDetector( - onTap: _openChatInfo, - child: CircleAvatar( - radius: 18, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 16, - color: widget.user.avatarTextColor, - ), - ), - ), - ), - ], - ), - leadingWidth: 96, // Increase width to accommodate both icons - // Title - title: GestureDetector( - onTap: _openChatInfo, - behavior: HitTestBehavior.opaque, - child: Text(widget.user.username), - ), - // Action buttons - actions: [ - IconButton( - icon: const Icon(Icons.info), - tooltip: 'infoButton'.tr(), - onPressed: _openChatInfo, - ), - ], - ), + child: _buildAppBarContent(), ), ), ), @@ -908,25 +1376,59 @@ class _ChatPageState extends State { children: [ // Messages and avatar list Expanded( - child: _firstLoad - ? Center( - child: Transform.scale( - scale: 1.5, - child: CircularProgressIndicator(), + child: Stack( + children: [ + _firstLoad + ? Center( + child: Transform.scale( + scale: 1.5, + child: CircularProgressIndicator(), + ), + ) + : _getContent(_messages), + // Floating "down" button with the count of messages that + // arrived while the user was reading further up. + if (!_firstLoad && _unseenCount > 0) + Positioned( + right: 16, + bottom: 16, + child: FloatingActionButton.small( + heroTag: 'jumpToBottom', + tooltip: 'jumpToLatest'.tr(), + onPressed: () => _jumpToBottom(animate: true), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.arrow_downward, size: 16), + if (_unseenCount > 1) + Padding( + padding: const EdgeInsets.only(left: 2), + child: Text('$_unseenCount', + style: const TextStyle(fontSize: 11)), + ), + ], + ), ), - ) - : _getContent(_messages), + ), + ], + ), ), SafeArea( top: false, child: Padding( padding: const EdgeInsets.all(8.0), - child: Stack( - alignment: Alignment.center, + child: Column( + mainAxisSize: MainAxisSize.min, children: [ - _buildInputBar(), - if (_isRecording) - Positioned.fill(child: _buildRecordingBar()), + if (_replyTo != null) _buildReplyBar(), + Stack( + alignment: Alignment.center, + children: [ + _buildInputBar(), + if (_isRecording) + Positioned.fill(child: _buildRecordingBar()), + ], + ), ], ), ), @@ -939,3 +1441,62 @@ class _ChatPageState extends State { ); } } + +/// Sticky day label above the messages of one calendar day. +class _DayHeader extends SliverPersistentHeaderDelegate { + _DayHeader({ + required this.label, + required this.textColor, + required this.background, + }); + + final String label; + final Color textColor; + final Color background; + + @override + double get minExtent => 34; + + @override + double get maxExtent => 34; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: textColor, + ), + ), + ), + ); + } + + @override + bool shouldRebuild(covariant _DayHeader oldDelegate) => + oldDelegate.label != label || + oldDelegate.textColor != textColor || + oldDelegate.background != background; +} + +/// Fires [onMetricsChanged] when the keyboard opens or closes. +class _KeyboardObserver extends WidgetsBindingObserver { + _KeyboardObserver(this.onMetricsChanged); + + final VoidCallback onMetricsChanged; + + @override + void didChangeMetrics() { + onMetricsChanged(); + } +} diff --git a/lib/pages/forward_page.dart b/lib/pages/forward_page.dart index 90e857e..3ca1bf4 100644 --- a/lib/pages/forward_page.dart +++ b/lib/pages/forward_page.dart @@ -11,11 +11,11 @@ import '../widgets/user_list_item.dart'; import 'search_user_page.dart'; import '../utils/nav_transitions.dart'; -/// Picks the destination of a forwarded message: an existing conversation or a -/// user found by search. Sends the message and closes itself. +/// Picks the destination of forwarded messages: an existing conversation or a +/// user found by search. Sends the messages and closes itself. class ForwardPage extends StatefulWidget { - const ForwardPage(this.message, {super.key}); - final PrivateMessage message; + const ForwardPage(this.messages, {super.key}); + final List messages; @override State createState() => _ForwardPageState(); @@ -48,29 +48,33 @@ class _ForwardPageState extends State { _sending = true; }); try { - final message = widget.message; - bool sent; - if (message.isMedia) { - final path = message.localPath; - final type = message.mediaType; - if (path == null || type == null) { - // Save/forward are hidden for attachments that are not on disk - return; + var allSent = true; + for (final message in widget.messages) { + bool sent; + if (message.isMedia) { + final path = message.localPath; + final type = message.mediaType; + if (path == null || type == null) { + // Save/forward are hidden for attachments that are not on disk. + allSent = false; + continue; + } + final bytes = await MediaUtils.decryptAtRest(path); + sent = await ChatSender.sendMedia(to, type, bytes, + caption: message.message, + width: message.width, + height: message.height, + durationMs: message.durationMs, + fileName: message.fileName); + } else { + sent = await ChatSender.sendText(to, message.message); } - final bytes = await MediaUtils.decryptAtRest(path); - sent = await ChatSender.sendMedia(to, type, bytes, - caption: message.message, - width: message.width, - height: message.height, - durationMs: message.durationMs, - fileName: message.fileName); - } else { - sent = await ChatSender.sendText(to, message.message); + allSent = allSent && sent; } if (!mounted) { return; } - if (sent) { + if (allSent) { Fluttertoast.showToast(msg: 'forwarded'.tr()); Navigator.pop(context); } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 973bee2..95345b9 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -40,6 +40,12 @@ class _HomePageState extends State int _currentPageIndex = 0; List _serverInvites = []; List> _chatEntries = []; + + /// Unread incoming messages per conversation id, for the list badges. + Map _unreadCounts = {}; + + /// Conversation ids pinned to the top of the list. + Set _pinnedChats = {}; bool _firstLoad = true; String? _pendingFid; // Store pending FID @@ -184,15 +190,49 @@ class _HomePageState extends State /// Get all conversations with their last messages Future _getConversations() async { final chats = await CacheUtils.getLatestPrivateMessages(); + final unread = await CacheUtils.getUnreadCounts(); + final pinned = await CacheUtils.getPinnedConversations(); if (!mounted) { return; } setState(() { _chatEntries = chats.entries.toList(); + _unreadCounts = unread; + _pinnedChats = pinned; _firstLoad = false; }); } + /// Pin or unpin a conversation. Local only: nothing is sent to the server. + Future _togglePin(User user) async { + final pinned = _pinnedChats.contains(user.id); + await CacheUtils.setConversationPinned(user.id, !pinned); + if (!mounted) { + return; + } + Fluttertoast.showToast( + msg: pinned ? 'chatUnpinned'.tr() : 'chatPinned'.tr()); + await _getConversations(); + } + + /// Delete a conversation after the confirmation dialog confirmed it. + void _deleteChat(User user) { + DialogUtils.yesNoDialog( + context, 'deleteChatConfirm'.tr(), 'deleteChatConfirmText'.tr(), + () async { + await MessageNotifier().deleteChat(user.id); + }); + } + + /// Icon shown under a swiped chat row. + Widget _swipeBackground(Alignment alignment, IconData icon, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Icon(icon, color: color), + ); + } + /// Get server users Future _getServerUsers() async { if (!mounted) { @@ -305,12 +345,37 @@ class _HomePageState extends State // Indexed access: `Map.entries.elementAt` is O(n) and made the list // build O(n^2). final chat = chats[index]; + final scheme = Theme.of(context).colorScheme; return Padding( padding: EdgeInsets.only(right: 5, left: 5, bottom: 3), - child: ChatListItem(chat.key, chat.value, () { - // Push to chat - Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); - }), + // Swipe right pins, swipe left deletes. Both spring back: the gesture + // opens an action, it never removes a row on its own. + child: Dismissible( + key: ValueKey('chat|${chat.key.id}'), + direction: DismissDirection.horizontal, + background: _swipeBackground( + Alignment.centerLeft, Icons.push_pin, scheme.primary), + secondaryBackground: _swipeBackground( + Alignment.centerRight, Icons.delete, scheme.error), + confirmDismiss: (direction) async { + if (direction == DismissDirection.startToEnd) { + await _togglePin(chat.key); + } else { + _deleteChat(chat.key); + } + return false; + }, + child: ChatListItem( + chat.key, + chat.value, + () { + // Push to chat + Navigator.of(context).push(slideUpRoute(ChatPage(chat.key))); + }, + unreadCount: _unreadCounts[chat.key.id] ?? 0, + pinned: _pinnedChats.contains(chat.key.id), + ), + ), ); }, ); diff --git a/lib/pages/media_viewer_page.dart b/lib/pages/media_viewer_page.dart index 99a7894..82ee077 100644 --- a/lib/pages/media_viewer_page.dart +++ b/lib/pages/media_viewer_page.dart @@ -106,7 +106,7 @@ class _MediaViewerPageState extends State { MessageActions.save(_current); break; case 'forward': - MessageActions.forward(context, _current); + MessageActions.forward(context, [_current]); break; case 'delete': MessageActions.delete(context, _current, widget.conversationUserId, diff --git a/lib/utils/cache_utils.dart b/lib/utils/cache_utils.dart index a08cf6a..123a175 100644 --- a/lib/utils/cache_utils.dart +++ b/lib/utils/cache_utils.dart @@ -495,6 +495,9 @@ class CacheUtils { Box userBox = await _openUserBox(); await userBox.delete(userId); await deleteMessageConcept(userId); + // Pin state goes with the conversation. + final conversationsBox = await _openConversationsBox(); + await conversationsBox.delete(userId); } /// Delete the encrypted-at-rest media files of all messages with [userId]. @@ -713,10 +716,90 @@ class CacheUtils { await box.put(user.id, user); } + /// Local-only chat list state (pinned, and later archived). Nothing here + /// reaches the server: until F8 syncs it, it is this device's business. + static const String _conversationsKey = 'conversations'; + + static Future _openConversationsBox() async { + return Hive.openBox(_conversationsKey); + } + + static Map _metaOf(Box box, String userId) { + final stored = box.get(userId); + return stored is Map ? Map.from(stored) : {}; + } + + /// Whether [userId] is pinned to the top of the chat list. + static Future isConversationPinned(String userId) async { + final box = await _openConversationsBox(); + return _metaOf(box, userId)['pinned'] == true; + } + + /// Pins or unpins a conversation. The entry is dropped once it is empty, so + /// the box only holds chats that differ from the default. + static Future setConversationPinned(String userId, bool pinned) async { + final box = await _openConversationsBox(); + final meta = _metaOf(box, userId); + if (pinned) { + meta['pinned'] = true; + } else { + meta.remove('pinned'); + } + if (meta.isEmpty) { + await box.delete(userId); + } else { + await box.put(userId, meta); + } + } + + /// Ids of the pinned conversations. + static Future> getPinnedConversations() async { + final box = await _openConversationsBox(); + return { + for (final entry in box.toMap().entries) + if (entry.value is Map && (entry.value as Map)['pinned'] == true) + entry.key as String, + }; + } + + /// Unread incoming messages per conversation, for the chat list badge. + static Future> getUnreadCounts() async { + final box = await _openPrivateMessagesBox(); + final counts = {}; + for (final key in box.keys.whereType()) { + final userId = conversationOfKey(key); + if (userId == null) { + continue; + } + final value = box.get(key); + if (value is PrivateMessage && !value.read) { + counts[userId] = (counts[userId] ?? 0) + 1; + } + } + return counts; + } + + /// 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 { + final box = await _openPrivateMessagesBox(); + DateTime? first; + for (final key in _conversationKeys(box, userId)) { + final value = box.get(key); + if (value is! PrivateMessage || value.read) { + continue; + } + if (first == null || value.sentAt.isBefore(first)) { + first = value.sentAt; + } + } + return first; + } + /// Get Map of all conversations with their last messages. /// /// Only the newest message of each conversation is deserialized, so the list - /// does not pay for the whole history. + /// does not pay for the whole history. Pinned conversations come first. static Future> getLatestPrivateMessages() async { Box box = await _openPrivateMessagesBox(); await _migrateLegacyMessages(box); @@ -744,9 +827,17 @@ class CacheUtils { User? user = await getUserById(entry.key); conversations[user ?? User(entry.key, '', '', false)] = message; } - // Sort conversations by last message date + // Pinned conversations first, then by last message date + final pinnedIds = await getPinnedConversations(); var sortedEntries = conversations.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); + ..sort((a, b) { + final aPinned = pinnedIds.contains(a.key.id); + final bPinned = pinnedIds.contains(b.key.id); + if (aPinned != bPinned) { + return aPinned ? -1 : 1; + } + return b.value.receivedAt.compareTo(a.value.receivedAt); + }); return Map.fromEntries(sortedEntries); } @@ -756,10 +847,12 @@ class CacheUtils { Box userBox = await _openUserBox(); Box conceptBox = await _openMessageConceptBox(); Box pendingBox = await _openPendingSendsBox(); + Box conversationsBox = await _openConversationsBox(); await userBox.clear(); await messageBox.clear(); await conceptBox.clear(); await pendingBox.clear(); + await conversationsBox.clear(); // Remove every locally stored media file. await MediaUtils.clearMediaDir(); } diff --git a/lib/utils/chat_sender.dart b/lib/utils/chat_sender.dart index d9ecf09..c56a17f 100644 --- a/lib/utils/chat_sender.dart +++ b/lib/utils/chat_sender.dart @@ -18,6 +18,7 @@ import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import 'utils.dart'; /// One attachment of an outgoing album (or a single media message). @@ -56,12 +57,14 @@ class ChatSender { /// upgrade by persisting the transport key inside the encrypted profile box. static final Map> _outgoingReferences = {}; - /// Send a text message to [recipient]. - static Future sendText(User recipient, String text) async { + /// Send a text message to [recipient], optionally quoting [reply]. + static Future sendText(User recipient, String text, + {ReplyRef? reply}) async { final now = DateTime.now(); final message = PrivateMessage( Singleton().profile.user.id, text, now, now, true, - sendStatus: SendStatus.sending); + sendStatus: SendStatus.sending) + ..setReplyTo(reply); try { await _persist(recipient, [message]); if (!await _ensureConnected()) { @@ -395,9 +398,14 @@ class ChatSender { /// Encrypt [message] for [recipient] and hand it to the WebSocket. The /// original timestamp is kept so a resend maps onto the same server entry. static Future _sendText(User recipient, PrivateMessage message) async { + // A reply needs the quote next to the body; everything else stays raw text + // so an older client can still read it. + final reply = message.replyTo; + final plaintext = reply == null + ? utf8.encode(message.message) + : buildTextEnvelope(message.message, reply); final data = await CryptoUtils.encryptMessageData( - utf8.encode(message.message), - bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); + plaintext, bu.CryptoUtils.rsaPublicKeyFromPem(recipient.publicKey)); Singleton().wsClient.sendMessage(WsMessage.privateMessage(NewPrivateMessage( recipient.id, data['encryptedData']!, diff --git a/lib/utils/message_actions.dart b/lib/utils/message_actions.dart index 7c01170..af387fb 100644 --- a/lib/utils/message_actions.dart +++ b/lib/utils/message_actions.dart @@ -63,7 +63,7 @@ class MessageActions { title: Text('forwardMessage'.tr()), onTap: () { Navigator.pop(ctx); - forward(context, message); + forward(context, [message]); }, ), if (canSave(message)) @@ -122,10 +122,10 @@ class MessageActions { } } - /// Pick a chat (or a user) and send the message there. + /// Pick a chat (or a user) and send the messages there. static Future forward( - BuildContext context, PrivateMessage message) async { - await Navigator.of(context).push(stepRoute(ForwardPage(message))); + BuildContext context, List messages) async { + await Navigator.of(context).push(stepRoute(ForwardPage(messages))); } /// Delete the message only on this device, after a confirmation. diff --git a/lib/utils/message_format.dart b/lib/utils/message_format.dart new file mode 100644 index 0000000..99821ba --- /dev/null +++ b/lib/utils/message_format.dart @@ -0,0 +1,286 @@ +import 'link_utils.dart'; + +/// Inline formatting of a message body. +/// +/// The subset the app supports: `**bold**`, `*italic*`, `~~strike~~`, +/// `` `mono` ``, ```` ```block``` ```` and `||spoiler||`. Markers do not nest: +/// the first one that closes wins, which keeps the parser small and the result +/// predictable. +enum MessageStyle { + plain, + bold, + italic, + strike, + + /// Inline monospace (single backticks). + mono, + + /// Fenced code block (triple backticks) on its own lines. + code, + + /// Hidden until tapped. + spoiler, +} + +/// What a piece of a message is, for tap handling. +enum MessageKind { + text, + + /// Opens in the browser. + link, + + /// Opens the mail client. + email, + + /// Tapped to copy. + phone, +} + +/// One run of message text with one style and one tap action. +class MessagePiece { + const MessagePiece(this.text, this.style, this.kind); + + final String text; + final MessageStyle style; + final MessageKind kind; +} + +/// Splits [text] into styled, tappable pieces, in order. +List parseMessage(String text) { + if (text.isEmpty) { + return const []; + } + final pieces = []; + for (final segment in _splitCodeBlocks(text)) { + if (segment.block) { + pieces + .add(MessagePiece(segment.text, MessageStyle.code, MessageKind.text)); + } else { + _parseInline(segment.text, pieces); + } + } + return pieces; +} + +/// Whether [text] is only emoji, so it can be shown large and without a bubble. +/// +/// Keycaps (`1️⃣`) and skin-tone modifiers count as emoji. More than +/// [maxLargeEmoji] emoji are still emoji-only, the caller decides the size. +bool isEmojiOnly(String text) { + var emoji = 0; + var significant = 0; + for (final rune in text.runes) { + if (_isEmojiIgnorable(rune)) { + continue; + } + significant++; + if (_isEmojiRune(rune) || _isKeycapBase(rune)) { + if (_isEmojiRune(rune)) { + emoji++; + } + continue; + } + return false; + } + return emoji > 0 && significant > 0; +} + +/// Emoji in a message: used to cap the large rendering. +int emojiCount(String text) => text.runes.where(_isEmojiRune).length; + +// Whitespace, variation selectors, ZWJ and skin-tone modifiers carry no +// meaning on their own. +bool _isEmojiIgnorable(int rune) => + rune == 0x20 || + rune == 0x09 || + rune == 0x0A || + rune == 0x0D || + rune == 0xFE0F || + rune == 0xFE0E || + rune == 0x200D || + (rune >= 0x1F3FB && rune <= 0x1F3FF); + +bool _isEmojiRune(int rune) => + (rune >= 0x1F000 && rune <= 0x1FAFF) || + (rune >= 0x2600 && rune <= 0x27BF) || + (rune >= 0x2B00 && rune <= 0x2BFF) || + (rune >= 0x1F1E6 && rune <= 0x1F1FF) || + rune == 0x2764 || + rune == 0x203C || + rune == 0x2049; + +// Digits, `#` and `*` only appear in emoji when a keycap follows. +bool _isKeycapBase(int rune) => + rune == 0x23 || rune == 0x2A || (rune >= 0x30 && rune <= 0x39); + +class _Segment { + const _Segment(this.text, {required this.block}); + final String text; + final bool block; +} + +/// Splits fenced code blocks out of [text]. An unterminated fence runs to the +/// end of the message. +List<_Segment> _splitCodeBlocks(String text) { + const fence = '```'; + final segments = <_Segment>[]; + var index = 0; + while (true) { + final start = text.indexOf(fence, index); + if (start < 0) { + segments.add(_Segment(text.substring(index), block: false)); + break; + } + segments.add(_Segment(text.substring(index, start), block: false)); + final end = text.indexOf(fence, start + fence.length); + if (end < 0) { + segments.add(_Segment(_trimFence(text.substring(start + fence.length)), + block: true)); + break; + } + segments.add(_Segment(_trimFence(text.substring(start + fence.length, end)), + block: true)); + index = end + fence.length; + } + return segments.where((s) => s.block || s.text.isNotEmpty).toList(); +} + +// The newline that wraps a fence is part of the syntax, not the code. +String _trimFence(String text) { + var value = text; + while (value.startsWith('\n')) { + value = value.substring(1); + } + while (value.endsWith('\n')) { + value = value.substring(0, value.length - 1); + } + return value; +} + +class _Marker { + const _Marker(this.token, this.style); + final String token; + final MessageStyle style; +} + +// Longest first: `**` must win over `*` at the same position. +const List<_Marker> _markers = [ + _Marker('**', MessageStyle.bold), + _Marker('~~', MessageStyle.strike), + _Marker('||', MessageStyle.spoiler), + _Marker('`', MessageStyle.mono), + _Marker('*', MessageStyle.italic), +]; + +void _parseInline(String text, List out) { + final plain = StringBuffer(); + var index = 0; + while (index < text.length) { + _Marker? marker; + var at = -1; + for (final candidate in _markers) { + final found = text.indexOf(candidate.token, index); + if (found >= 0 && (at < 0 || found < at)) { + marker = candidate; + at = found; + } + } + if (marker == null) { + plain.write(text.substring(index)); + break; + } + final contentStart = at + marker.token.length; + final close = text.indexOf(marker.token, contentStart); + if (close <= contentStart) { + // No closing marker (or nothing between them): keep the text literal. + plain.write(text.substring(index, contentStart)); + index = contentStart; + continue; + } + plain.write(text.substring(index, at)); + _flushPlain(plain, out); + out.add(MessagePiece( + text.substring(contentStart, close), marker.style, MessageKind.text)); + index = close + marker.token.length; + } + _flushPlain(plain, out); +} + +void _flushPlain(StringBuffer buffer, List out) { + if (buffer.isEmpty) { + return; + } + out.addAll(_splitEntities(buffer.toString())); + buffer.clear(); +} + +/// Splits plain text into links, e-mail addresses, phone numbers and leftover +/// text. +List _splitEntities(String text) { + final pieces = []; + for (final link in splitLinks(text)) { + if (link.url != null) { + pieces.add(MessagePiece(link.text, MessageStyle.plain, MessageKind.link)); + continue; + } + pieces.addAll(_splitTappable(link.text)); + } + return pieces; +} + +/// Splits plain text into the things a tap can act on. When two patterns start +/// at the same character the one listed first wins. +List _splitTappable(String text) { + final patterns = <(RegExp, MessageKind)>[ + (_emailPattern, MessageKind.email), + (_phonePattern, MessageKind.phone), + ]; + final pieces = []; + var index = 0; + while (index < text.length) { + final rest = text.substring(index); + Match? best; + var kind = MessageKind.text; + for (final (pattern, candidateKind) in patterns) { + final match = pattern.firstMatch(rest); + if (match == null) { + continue; + } + if (candidateKind == MessageKind.phone && + !_isPhoneNumber(match.group(0)!)) { + continue; + } + if (best == null || match.start < best.start) { + best = match; + kind = candidateKind; + } + } + if (best == null) { + pieces.add(MessagePiece( + text.substring(index), MessageStyle.plain, MessageKind.text)); + break; + } + if (best.start > 0) { + pieces.add(MessagePiece(text.substring(index, index + best.start), + MessageStyle.plain, MessageKind.text)); + } + pieces.add(MessagePiece(best.group(0)!, MessageStyle.plain, kind)); + index += best.end; + } + return pieces; +} + +/// A single e-mail address, no display name and no surrounding punctuation. +final RegExp _emailPattern = RegExp( + r'(?= 7 && digits.length <= 15; +} diff --git a/lib/utils/message_notifier.dart b/lib/utils/message_notifier.dart index d26919b..1826181 100644 --- a/lib/utils/message_notifier.dart +++ b/lib/utils/message_notifier.dart @@ -201,10 +201,9 @@ class MessageNotifier extends ChangeNotifier { newMessages[e.key] = e.value; } } - // Sort conversations by last message date - var sortedEntries = newMessages.entries.toList() - ..sort((a, b) => b.value.receivedAt.compareTo(a.value.receivedAt)); - return Map.fromEntries(sortedEntries); + // The cache already ordered this map (pinned chats first, then by the + // newest message), so the entries are kept in the order they came in. + return newMessages; } /// Delete all chats diff --git a/lib/utils/text_envelope.dart b/lib/utils/text_envelope.dart new file mode 100644 index 0000000..81bad79 --- /dev/null +++ b/lib/utils/text_envelope.dart @@ -0,0 +1,96 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// The message a reply quotes. +/// +/// The preview is stored next to the pointer, so the quote still reads after +/// the original was deleted locally (deleting a message only removes it on +/// this device). +class ReplyRef { + const ReplyRef({ + required this.senderId, + required this.sentAt, + required this.preview, + }); + + final String senderId; + final DateTime sentAt; + + /// Truncated body of the quoted message. + final String preview; + + /// Longest preview kept in the envelope; the bubble shows two lines. + static const int maxPreviewLength = 160; + + Map toJson() => { + 'senderId': senderId, + 'sentAt': sentAt.microsecondsSinceEpoch, + 'preview': preview, + }; + + /// Null when [json] is not a usable reference. + static ReplyRef? fromJson(Object? json) { + if (json is! Map) { + return null; + } + final senderId = json['senderId']; + final sentAt = json['sentAt']; + if (senderId is! String || sentAt is! int) { + return null; + } + return ReplyRef( + senderId: senderId, + sentAt: DateTime.fromMicrosecondsSinceEpoch(sentAt), + preview: json['preview'] is String ? json['preview'] as String : '', + ); + } + + /// Shortens [text] for storage in the envelope. + static String previewOf(String text) => text.length <= maxPreviewLength + ? text + : '${text.substring(0, maxPreviewLength)}…'; +} + +/// Payload of a text message that quotes another one. +class ParsedTextEnvelope { + const ParsedTextEnvelope(this.body, this.reply); + + final String body; + final ReplyRef? reply; +} + +/// Envelope version of a text message carrying a quote. Versions 1 and 2 are +/// the media envelopes; plain text stays raw UTF-8, so a reader that never +/// quotes anything keeps writing what every older client can open. +const int textEnvelopeVersion = 3; + +/// Plaintext (pre-encryption) bytes of a reply. +Uint8List buildTextEnvelope(String body, ReplyRef reply) { + final map = { + 'whisperMsg': textEnvelopeVersion, + 'kind': 'text', + 'body': body, + 'replyTo': reply.toJson(), + }; + return Uint8List.fromList(utf8.encode(jsonEncode(map))); +} + +/// Parses [plaintext] as a quoting text envelope. Null for anything else, which +/// includes every plain text message. +ParsedTextEnvelope? tryParseTextEnvelope(Uint8List plaintext) { + try { + final decoded = jsonDecode(utf8.decode(plaintext)); + if (decoded is Map && + decoded['kind'] == 'text' && + decoded['whisperMsg'] == textEnvelopeVersion) { + final body = decoded['body']; + if (body is! String) { + return null; + } + return ParsedTextEnvelope(body, ReplyRef.fromJson(decoded['replyTo'])); + } + } catch (_) { + // Not JSON / not a text envelope -> plain text. + } + return null; +} diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart index 543471b..36a0d96 100644 --- a/lib/utils/utils.dart +++ b/lib/utils/utils.dart @@ -24,6 +24,7 @@ import 'crypto_utils.dart'; import 'media_utils.dart'; import 'message_notifier.dart'; import 'singleton.dart'; +import 'text_envelope.dart'; import '../models/private_message.dart' as pm; import '../models/user.dart'; @@ -357,13 +358,16 @@ class Utils { ); return (mediaMsg, [ref], message.peerId); } - // Plain text message (legacy/unchanged path). + // Plain text message (legacy/unchanged path), or a reply that carries + // its quote in a text envelope. + final textEnvelope = tryParseTextEnvelope(decryptedMessage); final textMsg = pm.PrivateMessage( message.senderId, - utf8.decode(decryptedMessage), + textEnvelope?.body ?? utf8.decode(decryptedMessage), message.sentAt, DateTime.now(), - false); + false) + ..setReplyTo(textEnvelope?.reply); return (textMsg, const [], message.peerId); } catch (e) { // Log individual message decryption errors diff --git a/lib/widgets/chat_bubble.dart b/lib/widgets/chat_bubble.dart index 271119a..6bf6257 100644 --- a/lib/widgets/chat_bubble.dart +++ b/lib/widgets/chat_bubble.dart @@ -2,12 +2,17 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import '../models/user.dart'; import '../models/private_message.dart'; -import '../utils/message_actions.dart'; +import '../utils/message_format.dart'; import '../utils/message_notifier.dart'; -import 'linkified_text.dart'; +import '../utils/singleton.dart'; +import 'formatted_text.dart'; import 'media_bubble.dart'; -// Long-press opens the message actions sheet (copy, forward, save, delete). +/// One message bubble. +/// +/// Long-press enters selection mode; double-tap (or a horizontal swipe) replies. +/// Everything the single-message sheet used to offer lives in the selection +/// app bar, which keeps one gesture per intent. class ChatBubble extends StatefulWidget { final PrivateMessage? previousMessage; final PrivateMessage message; @@ -16,9 +21,30 @@ class ChatBubble extends StatefulWidget { // Fixed for both light and dark mode (see ThemeUtils.bubbleAccent). final Color accentColor; + /// Whether the chat is in multi-select mode. + final bool selectionMode; + + /// Whether this bubble is part of the current selection. + final bool selected; + + /// Toggles this bubble in the selection (tap and long-press). + final VoidCallback? onSelect; + + /// Quotes this message in the composer (double-tap and swipe). + final VoidCallback? onReply; + + /// Jumps to the quoted message. + final VoidCallback? onTapQuote; + const ChatBubble( this.previousMessage, this.message, this.nextMessage, this.user, - {required this.accentColor, super.key}); + {required this.accentColor, + this.selectionMode = false, + this.selected = false, + this.onSelect, + this.onReply, + this.onTapQuote, + super.key}); @override State createState() => _ChatBubbleState(); @@ -27,16 +53,22 @@ class ChatBubble extends StatefulWidget { class _ChatBubbleState extends State { bool _showTooltip = false; - @override - void initState() { - super.initState(); - /* - if (!widget.message.read) { - widget.message.read = true; - widget.message.save(); - } - */ - } + /// Long messages start folded; this is set once the user unfolds one. + bool _expanded = false; + + /// Text longer than this is folded (about eight lines on a phone). + static const int _foldLength = 600; + + bool get _foldable => + !widget.message.isMedia && + !widget.message.isUndecryptable && + widget.message.message.length > _foldLength; + + bool get _isLargeEmoji => + !widget.message.isMedia && + !widget.message.isUndecryptable && + isEmojiOnly(widget.message.message) && + emojiCount(widget.message.message) <= 3; @override Widget build(BuildContext context) { @@ -114,191 +146,323 @@ class _ChatBubbleState extends State { return luminance > 0.5 ? Colors.black : Colors.white; } + /// Gesture handling: select in selection mode, otherwise tooltip + reply. + void onTap() { + if (widget.selectionMode) { + widget.onSelect?.call(); + return; + } + setState(() { + _showTooltip = !_showTooltip; + }); + } + + void onLongPress() { + // A long press in selection mode does nothing: tapping already toggles. + if (widget.selectionMode) { + return; + } + widget.onSelect?.call(); + } + + Widget content() { + if (widget.message.isMedia) { + return MediaBubble( + message: widget.message, + conversationUserId: widget.user.id, + bubbleColor: bubbleBackground(), + textColor: bubbleTextColor(), + canRetry: widget.message.mediaId != null && + MessageNotifier().canRetryMedia(widget.message.mediaId!), + onRetry: () { + if (widget.message.mediaId != null) { + MessageNotifier() + .retryMediaDownload(widget.user.id, widget.message.mediaId!); + } + }, + ); + } + + final color = bubbleTextColor(); + if (widget.message.isUndecryptable) { + return Text( + 'messageUndecryptable'.tr(), + style: TextStyle(color: color, fontStyle: FontStyle.italic), + ); + } + + final text = FormattedText( + widget.message.message, + style: TextStyle( + color: color, + fontSize: _isLargeEmoji ? 40 : null, + ), + maxLines: _foldable && !_expanded ? 8 : null, + ); + if (!_foldable) { + return text; + } + return Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + text, + GestureDetector( + onTap: () => setState(() => _expanded = !_expanded), + child: Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + _expanded ? 'showLess'.tr() : 'showFull'.tr(), + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ], + ); + } + + /// The quoted message above the body, tappable to jump to the original. + Widget quoteBlock() { + final reply = widget.message.replyTo; + if (reply == null) { + return const SizedBox.shrink(); + } + final color = bubbleTextColor(); + final fromMe = reply.senderId == Singleton().profile.user.id; + final author = fromMe + ? 'meText'.tr() + : (widget.user.username.isNotEmpty ? widget.user.username : '?'); + return Padding( + padding: const EdgeInsets.only(bottom: 6), + child: GestureDetector( + onTap: widget.onTapQuote, + child: Container( + constraints: const BoxConstraints(minWidth: 120), + padding: const EdgeInsets.only(left: 8, top: 4, bottom: 4), + decoration: BoxDecoration( + border: Border( + left: BorderSide(color: color.withValues(alpha: 0.8), width: 3), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + author, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.bold, + ), + ), + Text( + reply.preview.isEmpty ? 'mediaPhoto'.tr() : reply.preview, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: color.withValues(alpha: 0.8), + fontSize: 12, + ), + ), + ], + ), + ), + ), + ); + } + + final bubble = Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.message.isReply) quoteBlock(), + content(), + ], + ); + + // Emoji-only messages drop the bubble chrome and read large. + final bubbleBox = Container( + decoration: BoxDecoration( + color: _isLargeEmoji ? null : bubbleBackground(), + borderRadius: BorderRadius.circular(20), + border: widget.selected + ? Border.all( + color: Theme.of(context).colorScheme.primary, + width: 2, + ) + : null, + ), + padding: _isLargeEmoji + ? EdgeInsets.zero + : const EdgeInsets.symmetric(horizontal: 16, vertical: 10), + child: bubble, + ); + return Padding( padding: EdgeInsets.only( left: widget.message.isMe ? 96 : 16, right: widget.message.isMe ? 16 : 96, top: isFromSameUser() ? 4 : 16, ), - child: Column( - crossAxisAlignment: widget.message.isMe - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ - AnimatedSize( - duration: const Duration(milliseconds: 200), - curve: Curves.easeInOut, - child: SizedBox( - width: double.infinity, - child: Column( - children: [ - if (_showTooltip && !shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate(widget.message.isMe - ? widget.message.sentAt - : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - if (shouldShowTime()) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 8), - child: Center( - child: Text( - formatDate(widget.message.isMe - ? widget.message.sentAt - : widget.message.receivedAt), - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - ), - ], + if (widget.selectionMode) + Padding( + padding: const EdgeInsets.only(right: 6), + child: Icon( + widget.selected + ? Icons.check_circle + : Icons.radio_button_unchecked, + size: 20, + color: Theme.of(context).colorScheme.primary, ), ), - ), - GestureDetector( - onTap: () { - setState(() { - _showTooltip = !_showTooltip; - }); - }, - onLongPress: () => MessageActions.showSheet( - context, widget.message, widget.user.id), - child: Align( - alignment: widget.message.isMe - ? Alignment.centerRight - : Alignment.centerLeft, - child: Row( - mainAxisAlignment: widget.message.isMe - ? MainAxisAlignment.end - : MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - if (!widget.message.isMe) - SizedBox( - width: 40, // 32 (avatar) + 8 (padding) - child: showAvatar() - ? Padding( - padding: const EdgeInsets.only(right: 8), - child: CircleAvatar( - radius: 16, - backgroundColor: widget.user.avatarColor, - child: Text( - widget.user.username.isNotEmpty - ? widget.user.username[0].toUpperCase() - : '?', - style: TextStyle( - fontSize: 14, - color: widget.user.avatarTextColor, - ), - ), - ), - ) - : null, - ), - Flexible( - child: Column( - crossAxisAlignment: widget.message.isMe - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (_showTooltip && !shouldShowTime()) _tooltip(formatDate), + if (shouldShowTime()) _tooltip(formatDate), + GestureDetector( + onTap: onTap, + onLongPress: onLongPress, + onDoubleTap: widget.onReply, + child: Align( + alignment: widget.message.isMe + ? Alignment.centerRight + : Alignment.centerLeft, + child: Row( + mainAxisAlignment: widget.message.isMe + ? MainAxisAlignment.end + : MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.end, children: [ - /* - // Show nick if (!widget.message.isMe) - Padding( - padding: const EdgeInsets.only(left: 12, bottom: 4), - child: Text( - widget.user.username, - style: TextStyle( - fontSize: 12, - color: Colors.grey[600], - ), - ), - ), - */ - if (widget.message.isMedia) - MediaBubble( - message: widget.message, - conversationUserId: widget.user.id, - bubbleColor: bubbleBackground(), - textColor: bubbleTextColor(), - canRetry: widget.message.mediaId != null && - MessageNotifier() - .canRetryMedia(widget.message.mediaId!), - onRetry: () { - if (widget.message.mediaId != null) { - MessageNotifier().retryMediaDownload( - widget.user.id, widget.message.mediaId!); - } - }, - ) - else - Container( - decoration: BoxDecoration( - color: bubbleBackground(), - borderRadius: BorderRadius.circular(20), - ), - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - child: widget.message.isUndecryptable - ? Text( - 'messageUndecryptable'.tr(), - style: TextStyle( - color: bubbleTextColor(), - fontStyle: FontStyle.italic, + SizedBox( + width: 40, // 32 (avatar) + 8 (padding) + child: showAvatar() + ? Padding( + padding: const EdgeInsets.only(right: 8), + child: CircleAvatar( + radius: 16, + backgroundColor: widget.user.avatarColor, + child: Text( + widget.user.username.isNotEmpty + ? widget.user.username[0] + .toUpperCase() + : '?', + style: TextStyle( + fontSize: 14, + color: widget.user.avatarTextColor, + ), + ), ), ) - : LinkifiedText( - widget.message.message, - style: TextStyle( - color: bubbleTextColor(), + : null, + ), + Flexible( + child: Column( + crossAxisAlignment: widget.message.isMe + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, + children: [ + if (widget.onReply != null && + !widget.selectionMode) + Dismissible( + key: ValueKey( + 'reply|${widget.message.senderId}' + '|${widget.message.sentAt.microsecondsSinceEpoch}'), + direction: DismissDirection.horizontal, + // The swipe is an action, not a delete: the + // bubble always springs back. + confirmDismiss: (_) async { + widget.onReply?.call(); + return false; + }, + background: _swipeBackground( + Alignment.centerLeft, bubbleTextColor()), + secondaryBackground: _swipeBackground( + Alignment.centerRight, bubbleTextColor()), + child: bubbleBox, + ) + else + bubbleBox, + // Outgoing messages show a clock while they are + // being sent and an error when the send failed. + if (widget.message.isMe && + widget.message.sendStatus != SendStatus.sent) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Tooltip( + message: widget.message.sendStatus == + SendStatus.failed + ? 'messageSendFailed'.tr() + : 'messageSending'.tr(), + child: Icon( + widget.message.sendStatus == + SendStatus.failed + ? Icons.error_outline + : Icons.schedule, + size: 13, + color: widget.message.sendStatus == + SendStatus.failed + ? Colors.red + : Colors.grey, ), ), + ), + ], ), - // Outgoing messages show a clock while they are being - // sent and an error when the send failed. - if (widget.message.isMe && - widget.message.sendStatus != SendStatus.sent) - Padding( - padding: const EdgeInsets.only(top: 2), - child: Tooltip( - message: - widget.message.sendStatus == SendStatus.failed - ? 'messageSendFailed'.tr() - : 'messageSending'.tr(), - child: Icon( - widget.message.sendStatus == SendStatus.failed - ? Icons.error_outline - : Icons.schedule, - size: 13, - color: widget.message.sendStatus == - SendStatus.failed - ? Colors.red - : Colors.grey, - ), - ), - ), + ), ], ), ), - ], - ), + ), + ], ), ), ], ), ); } + + Widget _swipeBackground(Alignment alignment, Color color) { + return Container( + alignment: alignment, + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Icon(Icons.reply, color: color.withValues(alpha: 0.7)), + ); + } + + Widget _tooltip(String Function(DateTime) formatDate) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Center( + child: Text( + formatDate(widget.message.isMe + ? widget.message.sentAt + : widget.message.receivedAt), + style: TextStyle( + fontSize: 12, + color: Colors.grey[600], + ), + ), + ), + ); + } } diff --git a/lib/widgets/chat_list_item.dart b/lib/widgets/chat_list_item.dart index 4328e9d..87c5269 100644 --- a/lib/widgets/chat_list_item.dart +++ b/lib/widgets/chat_list_item.dart @@ -4,12 +4,19 @@ import '../models/private_message.dart'; import '../models/user.dart'; class ChatListItem extends StatefulWidget { - const ChatListItem(this.user, this.lastMessage, this.onPressed, {super.key}); + const ChatListItem(this.user, this.lastMessage, this.onPressed, + {this.unreadCount = 0, this.pinned = false, super.key}); final User user; final PrivateMessage lastMessage; final Function() onPressed; + /// Unread incoming messages of this conversation, for the badge. + final int unreadCount; + + /// Whether the conversation is pinned to the top of the list. + final bool pinned; + @override State createState() => _ChatListItemState(); } @@ -44,6 +51,26 @@ class _ChatListItemState extends State { } } + /// Rounded counter, capped the way every messenger does it. + Widget _unreadBadge() { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: scheme.primary, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + widget.unreadCount > 99 ? '99+' : '${widget.unreadCount}', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: scheme.onPrimary, + ), + ), + ); + } + @override Widget build(BuildContext context) { /// Return message with or without "me: " prefix @@ -56,6 +83,8 @@ class _ChatListItemState extends State { return meText + msg; } + final bool unread = widget.unreadCount > 0 || !widget.lastMessage.read; + return ListTile( onTap: widget.onPressed, tileColor: Colors.transparent, @@ -76,23 +105,48 @@ class _ChatListItemState extends State { ), ), ), - title: Text( - widget.user.username.isNotEmpty ? widget.user.username : '?', - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + title: Row( + children: [ + if (widget.pinned) + Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon(Icons.push_pin, + size: 14, color: Theme.of(context).colorScheme.primary), + ), + Expanded( + child: Text( + widget.user.username.isNotEmpty ? widget.user.username : '?', + overflow: TextOverflow.ellipsis, + style: + unread ? const TextStyle(fontWeight: FontWeight.bold) : null, + ), + ), + ], ), subtitle: Text( getTitle(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + style: unread ? const TextStyle(fontWeight: FontWeight.bold) : null, ), - trailing: Text( - formatDate(), - style: !widget.lastMessage.read - ? TextStyle(fontWeight: FontWeight.bold) - : null, + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + formatDate(), + style: unread + ? TextStyle( + fontWeight: FontWeight.bold, + color: Theme.of(context).colorScheme.primary, + ) + : null, + ), + if (widget.unreadCount > 0) + Padding( + padding: const EdgeInsets.only(top: 4), + child: _unreadBadge(), + ), + ], ), ); } diff --git a/lib/widgets/formatted_text.dart b/lib/widgets/formatted_text.dart new file mode 100644 index 0000000..e763b4e --- /dev/null +++ b/lib/widgets/formatted_text.dart @@ -0,0 +1,199 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:fluttertoast/fluttertoast.dart'; + +import '../utils/link_utils.dart'; +import '../utils/message_format.dart'; + +/// Message text with inline formatting, tappable links, phone numbers, +/// e-mail addresses and spoilers that stay covered until tapped. +class FormattedText extends StatefulWidget { + const FormattedText( + this.text, { + this.style, + this.maxLines, + this.textAlign, + super.key, + }); + + final String text; + final TextStyle? style; + final int? maxLines; + final TextAlign? textAlign; + + @override + State createState() => _FormattedTextState(); +} + +class _FormattedTextState extends State { + final Map _recognizers = {}; + + /// Indices of the spoiler pieces the user has opened this session. + final Set _revealed = {}; + + @override + void dispose() { + for (final recognizer in _recognizers.values) { + recognizer.dispose(); + } + super.dispose(); + } + + TapGestureRecognizer _recognizer(String key, VoidCallback onTap) { + return _recognizers.putIfAbsent( + key, () => TapGestureRecognizer()..onTap = onTap); + } + + Color get _color => + widget.style?.color ?? + DefaultTextStyle.of(context).style.color ?? + Colors.black; + + TextSpan _span(MessagePiece piece, int index) { + switch (piece.style) { + case MessageStyle.bold: + return TextSpan( + text: piece.text, + style: const TextStyle(fontWeight: FontWeight.bold)); + case MessageStyle.italic: + return TextSpan( + text: piece.text, + style: const TextStyle(fontStyle: FontStyle.italic)); + case MessageStyle.strike: + return TextSpan( + text: piece.text, + style: const TextStyle(decoration: TextDecoration.lineThrough)); + case MessageStyle.mono: + return TextSpan( + text: piece.text, + style: TextStyle( + fontFamily: 'monospace', + backgroundColor: _color.withValues(alpha: 0.12), + ), + ); + case MessageStyle.spoiler: + if (_revealed.contains(index)) { + return TextSpan( + text: piece.text, + style: + TextStyle(backgroundColor: _color.withValues(alpha: 0.15))); + } + return TextSpan( + text: List.filled(piece.text.length, '█').join(), + recognizer: _recognizer('spoiler:$index', () { + setState(() => _revealed.add(index)); + }), + ); + case MessageStyle.code: + case MessageStyle.plain: + break; + } + switch (piece.kind) { + case MessageKind.link: + return TextSpan( + text: piece.text, + recognizer: + _recognizer('link:${piece.text}', () => openLink(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.email: + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'mail:${piece.text}', () => openLink('mailto:${piece.text}')), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.phone: + // Underlined like a link: it is something the user taps, not just text. + return TextSpan( + text: piece.text, + recognizer: _recognizer( + 'copy:${piece.kind.name}:${piece.text}', () => _copy(piece.text)), + style: _inlineLink(TextDecorationStyle.solid), + ); + case MessageKind.text: + return TextSpan(text: piece.text); + } + } + + /// Underline for everything tappable: links, e-mails and phone numbers read + /// as a link. + TextStyle _inlineLink(TextDecorationStyle style) => TextStyle( + decoration: TextDecoration.underline, + decorationStyle: style, + decorationColor: _color, + ); + Future _copy(String value) async { + await Clipboard.setData(ClipboardData(text: value)); + Fluttertoast.showToast(msg: 'copiedText'.tr()); + } + + @override + Widget build(BuildContext context) { + final pieces = parseMessage(widget.text); + if (pieces.isEmpty) { + return Text('', style: widget.style); + } + // Code blocks read as their own block, so they get a container instead of + // an inline span. Whole-message maxLines cannot clip through a block. + // shortcut: a folded message with a code block still shows the block in + // full, upgrade with a real measurement pass when that shows up in practice. + final hasBlock = pieces.any((piece) => piece.style == MessageStyle.code); + if (!hasBlock) { + return Text.rich( + TextSpan(children: [ + for (var i = 0; i < pieces.length; i++) _span(pieces[i], i), + ]), + style: widget.style, + maxLines: widget.maxLines, + overflow: widget.maxLines == null ? null : TextOverflow.ellipsis, + textAlign: widget.textAlign, + ); + } + + final runs = []; + var inline = []; + void flushInline() { + if (inline.isEmpty) { + return; + } + runs.add(Text.rich(TextSpan(children: inline), style: widget.style)); + inline = []; + } + + for (var i = 0; i < pieces.length; i++) { + final piece = pieces[i]; + if (piece.style != MessageStyle.code) { + inline.add(_span(piece, i)); + continue; + } + flushInline(); + runs.add( + Container( + width: double.infinity, + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + decoration: BoxDecoration( + color: _color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + piece.text, + style: widget.style?.copyWith( + fontFamily: 'monospace', + fontSize: (widget.style?.fontSize ?? 14) * 0.9, + ), + ), + ), + ); + } + flushInline(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: runs, + ); + } +} diff --git a/lib/widgets/linkified_text.dart b/lib/widgets/linkified_text.dart deleted file mode 100644 index 3e4b493..0000000 --- a/lib/widgets/linkified_text.dart +++ /dev/null @@ -1,60 +0,0 @@ -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; - -import '../utils/link_utils.dart'; - -/// Message text where http(s) addresses are underlined and open in the -/// browser when tapped. -class LinkifiedText extends StatefulWidget { - const LinkifiedText(this.text, {this.style, super.key}); - - final String text; - final TextStyle? style; - - @override - State createState() => _LinkifiedTextState(); -} - -class _LinkifiedTextState extends State { - // Kept per address so a rebuild does not leak recognizers. - final Map _recognizers = {}; - - @override - void dispose() { - for (final recognizer in _recognizers.values) { - recognizer.dispose(); - } - super.dispose(); - } - - TapGestureRecognizer _recognizer(String url) { - return _recognizers.putIfAbsent( - url, - () => TapGestureRecognizer()..onTap = () => openLink(url), - ); - } - - @override - Widget build(BuildContext context) { - final color = - widget.style?.color ?? DefaultTextStyle.of(context).style.color; - return Text.rich( - TextSpan( - children: [ - for (final part in splitLinks(widget.text)) - part.url == null - ? TextSpan(text: part.text) - : TextSpan( - text: part.text, - recognizer: _recognizer(part.url!), - style: TextStyle( - decoration: TextDecoration.underline, - decorationColor: color, - ), - ), - ], - ), - style: widget.style, - ); - } -} diff --git a/test/chat_bubble_test.dart b/test/chat_bubble_test.dart new file mode 100644 index 0000000..2d7bf24 --- /dev/null +++ b/test/chat_bubble_test.dart @@ -0,0 +1,172 @@ +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +// easy_localization reads the locale from shared_preferences, its transitive dep +// ignore: depend_on_referenced_packages +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/models/profile.dart'; +import 'package:whisper/models/user.dart'; +import 'package:whisper/utils/singleton.dart'; +import 'package:whisper/utils/text_envelope.dart'; +import 'package:whisper/widgets/chat_bubble.dart'; + +/// Plain text of everything the bubble rendered, spans included. +String renderedText(WidgetTester tester) => tester + .widgetList(find.byType(RichText)) + .map((widget) => widget.text.toPlainText()) + .join('\n'); + +/// Style of the span that renders exactly [text], null when it is not there. +TextStyle? spanStyle(WidgetTester tester, String text) { + for (final widget in tester.widgetList(find.byType(RichText))) { + TextStyle? found; + widget.text.visitChildren((span) { + if (span is TextSpan && span.text == text) { + found = span.style; + return false; + } + return true; + }); + if (found != null) { + return found; + } + } + return null; +} + +void main() { + final peer = User('2', 'peer', '', false); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + await EasyLocalization.ensureInitialized(); + // isMe compares against the signed-in user. + Singleton().profile = + Profile('', User('1', 'me', '', false), '', '', '', '', false); + }); + + testWidgets('the bubble renders, quotes, selects and replies', + (tester) async { + // One app for the whole test: easy_localization loads its asset once, and a + // second pumpWidget would leave the tree without translations. + final shown = ValueNotifier(const SizedBox()); + await tester.pumpWidget(EasyLocalization( + path: 'assets/translations', + supportedLocales: const [Locale('en'), Locale('cs')], + fallbackLocale: const Locale('en'), + child: Builder(builder: (context) { + return MaterialApp( + localizationsDelegates: context.localizationDelegates, + supportedLocales: context.supportedLocales, + locale: context.locale, + home: Scaffold( + body: Center( + child: ValueListenableBuilder( + valueListenable: shown, + builder: (_, child, __) => child, + ), + ), + ), + ); + }), + )); + + Future show(Widget child) async { + shown.value = child; + await tester.pumpAndSettle(); + } + + // Formatting: the markers never reach the screen. + await show(ChatBubble( + null, + PrivateMessage( + '2', 'the **bold** part', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(renderedText(tester), contains('the bold part')); + expect(renderedText(tester), isNot(contains('**'))); + + // A reply shows what it quotes, and tapping the quote jumps to it. + var jumped = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'souhlas', DateTime(2026), DateTime(2026), true) + ..setReplyTo(ReplyRef( + senderId: '1', + sentAt: DateTime(2025), + preview: 'původní dotaz', + )), + null, + peer, + accentColor: Colors.blue, + onTapQuote: () => jumped = true, + )); + expect(renderedText(tester), contains('původní dotaz')); + expect(renderedText(tester), contains('souhlas')); + await tester.tap(find.text('původní dotaz')); + await tester.pumpAndSettle(); + expect(jumped, isTrue); + + // Selection mode marks the bubble. + await show(ChatBubble( + null, + PrivateMessage('2', 'x', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + selectionMode: true, + selected: true, + )); + expect(find.byIcon(Icons.check_circle), findsOneWidget); + + // Double tap quotes the message in the composer. + var replied = false; + await show(ChatBubble( + null, + PrivateMessage('2', 'ahoj', DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + onReply: () => replied = true, + )); + await tester.tap(find.text('ahoj')); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(find.text('ahoj')); + await tester.pumpAndSettle(); + expect(replied, isTrue); + + // A long message can be unfolded. + await show(ChatBubble( + null, + PrivateMessage('2', 'x' * 700, DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + expect(find.text('Show full message'), findsOneWidget); + await tester.tap(find.text('Show full message')); + await tester.pumpAndSettle(); + expect(find.text('Show less'), findsOneWidget); + + // Phone numbers and e-mails are underlined like a link. + await show(ChatBubble( + null, + PrivateMessage('2', 'volej +420 123 456 789 nebo piš na jan@example.com', + DateTime(2026), DateTime(2026), true), + null, + peer, + accentColor: Colors.blue, + )); + for (final tappable in ['+420 123 456 789', 'jan@example.com']) { + final style = spanStyle(tester, tappable); + expect(style, isNotNull, reason: tappable); + expect(style!.decoration, TextDecoration.underline, reason: tappable); + expect(style.decorationStyle ?? TextDecorationStyle.solid, + TextDecorationStyle.solid, + reason: tappable); + } + }); +} diff --git a/test/conversation_meta_test.dart b/test/conversation_meta_test.dart new file mode 100644 index 0000000..b1e2dac --- /dev/null +++ b/test/conversation_meta_test.dart @@ -0,0 +1,91 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:whisper/models/private_message.dart'; +import 'package:whisper/utils/cache_utils.dart'; + +PrivateMessage message(String senderId, DateTime sentAt, {bool read = false}) { + return PrivateMessage(senderId, 'text', sentAt, sentAt, read); +} + +void main() { + late Directory dir; + + setUpAll(() async { + dir = Directory.systemTemp.createTempSync('whisper_conversation_test'); + Hive.init(dir.path); + Hive.registerAdapter(PrivateMessageAdapter()); + }); + + setUp(() async { + for (final name in ['privateMessages', 'conversations', 'user']) { + await Hive.openBox(name); + await Hive.box(name).clear(); + } + }); + + tearDownAll(() async { + await Hive.close(); + dir.deleteSync(recursive: true); + }); + + test('unread counts only incoming unread messages', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('peer', [ + message('peer', base), + message('peer', base.add(const Duration(minutes: 1))), + message('peer', base.add(const Duration(minutes: 2)), read: true), + message('me', base.add(const Duration(minutes: 3)), read: true), + ]); + + final counts = await CacheUtils.getUnreadCounts(); + expect(counts['peer'], 2); + expect(await CacheUtils.firstUnreadSentAt('peer'), base); + }); + + test('a read conversation has no anchor', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1), read: true)]); + expect(await CacheUtils.firstUnreadSentAt('peer'), isNull); + }); + + test('pin and unpin keep the box clean', () async { + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + + await CacheUtils.setConversationPinned('peer', true); + expect(await CacheUtils.isConversationPinned('peer'), isTrue); + expect(await CacheUtils.getPinnedConversations(), {'peer'}); + + await CacheUtils.setConversationPinned('peer', false); + expect(await CacheUtils.isConversationPinned('peer'), isFalse); + expect(await CacheUtils.getPinnedConversations(), isEmpty); + // Unpinning removes the entry instead of storing a false flag. + expect(Hive.box('conversations').containsKey('peer'), isFalse); + }); + + test('pinned conversations sort before newer ones', () async { + final base = DateTime(2026, 5, 1, 12); + await CacheUtils.addPrivateMessages('old', [message('old', base)]); + await CacheUtils.addPrivateMessages('new', [ + message('new', base.add(const Duration(hours: 1))), + ]); + + var chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'new'); + + await CacheUtils.setConversationPinned('old', true); + chats = await CacheUtils.getLatestPrivateMessages(); + expect(chats.keys.first.id, 'old'); + }); + + test('deleting a chat drops its pin', () async { + await CacheUtils.addPrivateMessages( + 'peer', [message('peer', DateTime(2026, 5, 1))]); + await CacheUtils.setConversationPinned('peer', true); + + await CacheUtils.deletePrivateMessagesWithUser('peer'); + + expect(await CacheUtils.getPinnedConversations(), isEmpty); + }); +} diff --git a/test/message_format_test.dart b/test/message_format_test.dart new file mode 100644 index 0000000..f18dace --- /dev/null +++ b/test/message_format_test.dart @@ -0,0 +1,125 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/message_format.dart'; + +/// Renders the parsed pieces back as text, so a test can assert on the whole +/// message without caring how the parser grouped it. +String flat(List pieces) => pieces.map((p) => p.text).join(); + +List styled(List pieces, MessageStyle style) => + pieces.where((p) => p.style == style).toList(); + +void main() { + group('inline styles', () { + test('bold, italic, strike and mono', () { + final pieces = parseMessage('a **b** *c* ~~d~~ `e` f'); + expect(flat(pieces), 'a b c d e f'); + expect(styled(pieces, MessageStyle.bold).single.text, 'b'); + expect(styled(pieces, MessageStyle.italic).single.text, 'c'); + expect(styled(pieces, MessageStyle.strike).single.text, 'd'); + expect(styled(pieces, MessageStyle.mono).single.text, 'e'); + }); + + test('bold wins over italic at the same position', () { + final pieces = parseMessage('**bold**'); + expect(pieces.single.style, MessageStyle.bold); + expect(pieces.single.text, 'bold'); + }); + + test('spoiler is its own style', () { + final pieces = parseMessage('there is ||a secret|| here'); + expect(styled(pieces, MessageStyle.spoiler).single.text, 'a secret'); + }); + + test('an unclosed marker stays literal', () { + expect(flat(parseMessage('**unclosed')), '**unclosed'); + expect(flat(parseMessage('a *b')), 'a *b'); + }); + + test('empty markers are literal', () { + expect(flat(parseMessage('****')), '****'); + }); + + test('fenced code block becomes one code piece', () { + final pieces = parseMessage('before\n```\ncode line\n```\nafter'); + final code = styled(pieces, MessageStyle.code).single; + expect(code.text, 'code line'); + expect(flat(pieces), 'before\ncode line\nafter'); + }); + + test('an unterminated fence runs to the end', () { + final pieces = parseMessage('x\n```\nstill code'); + expect(styled(pieces, MessageStyle.code).single.text, 'still code'); + }); + }); + + group('tappable entities', () { + test('links keep their address', () { + final pieces = parseMessage('see https://example.com/a now'); + final link = pieces.singleWhere((p) => p.kind == MessageKind.link); + expect(link.text, 'https://example.com/a'); + }); + + test('a phone number is detected', () { + final pieces = parseMessage('volej +420 123 456 789 díky'); + final phone = pieces.singleWhere((p) => p.kind == MessageKind.phone); + expect(phone.text, '+420 123 456 789'); + }); + + test('a short number is not a phone number', () { + final pieces = parseMessage('mám 3 kusy'); + expect(pieces.any((p) => p.kind == MessageKind.phone), isFalse); + }); + + test('an e-mail address is detected', () { + final pieces = parseMessage('napiš na jan.novak@example.com prosím'); + final email = pieces.singleWhere((p) => p.kind == MessageKind.email); + expect(email.text, 'jan.novak@example.com'); + }); + + test('an @ without a dotted domain is not an e-mail', () { + final pieces = parseMessage('jsem @doma'); + expect(pieces.any((p) => p.kind == MessageKind.email), isFalse); + }); + + test('a link beats an e-mail that starts at the same place', () { + final pieces = parseMessage('https://example.com/a'); + expect(pieces.single.kind, MessageKind.link); + }); + + test('formatting and links combine', () { + final pieces = parseMessage('**přečti** https://example.com'); + expect(styled(pieces, MessageStyle.bold).single.text, 'přečti'); + expect(pieces.singleWhere((p) => p.kind == MessageKind.link).text, + 'https://example.com'); + }); + }); + + group('emoji only', () { + test('a single emoji', () { + expect(isEmojiOnly('😀'), isTrue); + expect(emojiCount('😀'), 1); + }); + + test('a short emoji run', () { + expect(isEmojiOnly('😀🎉👍'), isTrue); + expect(emojiCount('😀🎉👍'), 3); + }); + + test('skin tone and variation selectors count as one emoji', () { + expect(isEmojiOnly('👍🏽'), isTrue); + expect(isEmojiOnly('❤️'), isTrue); + }); + + test('text with an emoji is not emoji only', () { + expect(isEmojiOnly('ahoj 😀'), isFalse); + }); + + test('digits alone are not an emoji', () { + expect(isEmojiOnly('123'), isFalse); + }); + + test('empty text is not an emoji', () { + expect(isEmojiOnly(''), isFalse); + }); + }); +} diff --git a/test/text_envelope_test.dart b/test/text_envelope_test.dart new file mode 100644 index 0000000..d595b0d --- /dev/null +++ b/test/text_envelope_test.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:whisper/utils/text_envelope.dart'; + +Uint8List bytes(String text) => Uint8List.fromList(utf8.encode(text)); + +void main() { + test('a reply survives the round trip', () { + final sentAt = DateTime(2026, 3, 4, 5, 6, 7); + final envelope = buildTextEnvelope( + 'souhlasím', + ReplyRef( + senderId: 'peer', + sentAt: sentAt, + preview: ReplyRef.previewOf('původní zpráva'), + )); + + final parsed = tryParseTextEnvelope(envelope); + expect(parsed, isNotNull); + expect(parsed!.body, 'souhlasím'); + expect(parsed.reply!.senderId, 'peer'); + expect(parsed.reply!.sentAt, sentAt); + expect(parsed.reply!.preview, 'původní zpráva'); + }); + + test('the envelope is not a media envelope', () { + final envelope = buildTextEnvelope( + 'x', ReplyRef(senderId: 'a', sentAt: DateTime(2026), preview: 'y')); + final decoded = jsonDecode(utf8.decode(envelope)) as Map; + expect(decoded['kind'], 'text'); + expect(decoded['whisperMsg'], textEnvelopeVersion); + }); + + test('plain text is not an envelope', () { + expect(tryParseTextEnvelope(bytes('ahoj')), isNull); + }); + + test('a media envelope is not a text envelope', () { + final media = bytes('{"whisperMsg":1,"kind":"media","media":{}}'); + expect(tryParseTextEnvelope(media), isNull); + }); + + test('a broken body is not an envelope', () { + final broken = bytes('{"whisperMsg":3,"kind":"text","body":5}'); + expect(tryParseTextEnvelope(broken), isNull); + }); + + test('a broken quote is ignored, the body still reads', () { + final broken = + bytes('{"whisperMsg":3,"kind":"text","body":"a","replyTo":{"x":1}}'); + final parsed = tryParseTextEnvelope(broken); + expect(parsed!.body, 'a'); + expect(parsed.reply, isNull); + }); + + test('the preview is capped', () { + final long = 'x' * (ReplyRef.maxPreviewLength + 50); + final preview = ReplyRef.previewOf(long); + expect(preview.length, ReplyRef.maxPreviewLength + 1); + expect(preview.endsWith('…'), isTrue); + }); +}