diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 1378c991..acd1eae9 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -39,7 +39,8 @@ Below the app bar, above the messages, a strip shows **Compression: Off**, **SMA - Message text follows the system font size (Android/iOS accessibility text size); pinch-to-zoom scales on top of it - **Pinch-to-zoom**: Two-finger zoom (0.8x–1.8x) and double-tap to reset - **Jump to bottom**: Floating button appears when scrolled away from the bottom -- **Lazy loading**: Scrolling to top loads older messages from storage. The newest 200 messages are kept in memory; up to 1000 per conversation are kept in storage +- **Lazy loading**: Scrolling to top loads older messages from storage. The newest 200 messages are kept in memory, plus any older pages loaded while the chat is open; up to 1000 per conversation are kept in storage +- **Reading position**: Near the bottom, the chat follows new messages. Scrolled up, it stays on the messages you are reading while new ones arrive below, such as a room's backlog right after login, and never pulls a scroll in progress back to the bottom - **Arrival order**: Messages are ordered by when they arrived on this device, not by the sender's clock. If a message's time is more than 5 minutes in the future, a small clock-warning icon appears next to its time (the sender's clock is probably wrong); tap it for an explanation ### Input Bar diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 5df949aa..04197e69 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -9263,8 +9263,13 @@ class MeshCoreConnector extends ChangeNotifier { } messages.add(message); - if (messages.length > _messageWindowSize) { - final trimCount = messages.length - _messageWindowSize; + // The open chat keeps the older pages its reader scrolled back to; + // trimming them would pull the history out from under the reader. + final windowSize = pubKeyHex == _activeContactKey + ? MessageStore.maxStoredMessages + : _messageWindowSize; + if (messages.length > windowSize) { + final trimCount = messages.length - windowSize; _messageStore.archive(pubKeyHex, messages.sublist(0, trimCount)); messages.removeRange(0, trimCount); } diff --git a/lib/helpers/chat_scroll_anchor.dart b/lib/helpers/chat_scroll_anchor.dart new file mode 100644 index 00000000..20f489e7 --- /dev/null +++ b/lib/helpers/chat_scroll_anchor.dart @@ -0,0 +1,192 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Keeps the rows a reader is looking at in place when messages are added +/// below them in a reversed chat list. +/// +/// In a `reverse: true` list the newest message is index 0, so every new +/// message moves the older ones up an index. The list keeps layout offsets by +/// index, which leaves the scroll offset unchanged and shifts what is on +/// screen up by the new rows' height. Call [rowsInsertedBelow] while building +/// the list, before it lays out the new rows; [AnchoredChatListView] then +/// scrolls by however far the lowest row on screen moved, in the same layout +/// pass, so nothing visibly jumps. +class ChatScrollAnchor { + _RenderAnchorSliver? _sliver; + _Anchor? _pending; + + /// Notes that [count] rows are being added at index 0, below every row + /// currently laid out, and remembers the lowest row on screen. + void rowsInsertedBelow(int count) { + _pending = null; + final list = _sliver?.child; + if (count <= 0 || list is! RenderSliverMultiBoxAdaptor) return; + if (list.geometry == null) return; + final start = list.constraints.scrollOffset; + final end = start + list.constraints.remainingPaintExtent; + for (var row = list.firstChild; row != null; row = list.childAfter(row)) { + final offset = list.childScrollOffset(row); + if (offset == null || !row.hasSize) continue; + if (offset >= end) break; + if (offset + _extentOf(row, list) > start) { + _pending = _Anchor(list.indexOf(row) + count, offset); + // Rows of equal height would not relayout the list on their own. + _sliver!.markNeedsLayout(); + return; + } + } + } + + /// The scroll correction that puts the remembered row back where it was, + /// or null when none is needed (yet). + double? _correctionAfterLayout( + RenderSliverMultiBoxAdaptor list, + double? listCorrection, + ) { + final pending = _pending; + if (pending == null) return null; + if (listCorrection != null) { + // The list shifts every row by this itself; measure on the next pass. + pending.offset += listCorrection; + return null; + } + double? target; + final first = list.firstChild; + final last = list.lastChild; + if (first == null || last == null) { + _pending = null; + return null; + } + for (RenderBox? row = first; row != null; row = list.childAfter(row)) { + if (list.indexOf(row) == pending.index) { + target = list.childScrollOffset(row); + break; + } + } + if (target != null) { + _pending = null; + final delta = target - pending.offset; + return delta.abs() < 0.5 ? null : delta; + } + // The row is not laid out at this offset: scroll to an estimate of where + // it is, which lays out the rows there, and correct exactly next pass. + if (++pending.passes > 3) { + _pending = null; + return null; + } + final firstIndex = list.indexOf(first); + final lastIndex = list.indexOf(last); + final firstOffset = list.childScrollOffset(first); + final lastOffset = list.childScrollOffset(last); + if (firstOffset == null || lastOffset == null) { + _pending = null; + return null; + } + // Child sizes are off limits here, so space rows by their mean pitch. + final average = lastIndex > firstIndex + ? (lastOffset - firstOffset) / (lastIndex - firstIndex) + : 50.0; + final estimate = pending.index > lastIndex + ? lastOffset + (pending.index - lastIndex) * average + : firstOffset - (firstIndex - pending.index) * average; + final delta = estimate - pending.offset; + pending.offset = estimate; + return delta.abs() < 0.5 ? null : delta; + } + + static double _extentOf(RenderBox row, RenderSliver list) => + list.constraints.axis == Axis.vertical ? row.size.height : row.size.width; +} + +class _Anchor { + _Anchor(this.index, this.offset); + + /// The remembered row's index once the new rows are in. + final int index; + + /// Where the row has to be laid out for the reader to see no movement. + double offset; + int passes = 0; +} + +/// A [ListView.builder] whose on-screen rows stay put when a +/// [ChatScrollAnchor] is told rows were added below them. +class AnchoredChatListView extends ListView { + AnchoredChatListView.builder({ + super.key, + required this.scrollAnchor, + super.reverse, + super.controller, + super.padding, + required super.itemBuilder, + super.itemCount, + }) : super.builder(); + + final ChatScrollAnchor scrollAnchor; + + @override + Widget buildChildLayout(BuildContext context) => _AnchorSliver( + anchor: scrollAnchor, + child: super.buildChildLayout(context), + ); +} + +class _AnchorSliver extends SingleChildRenderObjectWidget { + const _AnchorSliver({required this.anchor, required Widget super.child}); + + final ChatScrollAnchor anchor; + + @override + RenderObject createRenderObject(BuildContext context) => + _RenderAnchorSliver(anchor); + + @override + void updateRenderObject( + BuildContext context, + _RenderAnchorSliver renderObject, + ) { + renderObject.anchor = anchor; + } +} + +class _RenderAnchorSliver extends RenderProxySliver { + _RenderAnchorSliver(this._anchor); + + ChatScrollAnchor _anchor; + set anchor(ChatScrollAnchor value) { + if (identical(value, _anchor)) return; + if (attached) { + if (identical(_anchor._sliver, this)) _anchor._sliver = null; + value._sliver = this; + } + _anchor = value; + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _anchor._sliver = this; + } + + @override + void detach() { + if (identical(_anchor._sliver, this)) _anchor._sliver = null; + super.detach(); + } + + @override + void performLayout() { + final list = child!; + list.layout(constraints, parentUsesSize: true); + final listGeometry = list.geometry!; + final correction = list is RenderSliverMultiBoxAdaptor + ? _anchor._correctionAfterLayout( + list, + listGeometry.scrollOffsetCorrection, + ) + : null; + geometry = correction == null + ? listGeometry + : SliverGeometry(scrollOffsetCorrection: correction); + } +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index acc29664..19aaf887 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -99,12 +99,15 @@ class ChannelChatScreen extends StatefulWidget { State createState() => _ChannelChatScreenState(); } -class _ChannelChatScreenState extends State { +class _ChannelChatScreenState extends State + with WidgetsBindingObserver { final _holidayWatcher = HolidayTriggerWatcher(); final _messageAreaKey = GlobalKey(); final TextEditingController _textController = TextEditingController(); final ChatScrollController _scrollController = ChatScrollController(); final FocusNode _textFieldFocusNode = FocusNode(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; ChannelMessage? _replyingToMessage; bool _useReplyRegion = false; final CommunityStore _communityStore = CommunityStore(); @@ -135,6 +138,13 @@ class _ChannelChatScreenState extends State { MeshCoreConnector? _connector; final ChatSendGuard _sendGuard = ChatSendGuard(); bool _channelSkipNextBottomSnap = false; + + /// Newest entry and selection size seen by the last bottom-snap check, so + /// a rebuild that only changed the selection is not mistaken for a new + /// message. + String? _snapNewestEntryId; + int _snapSelectionCount = 0; + String? _unreadDividerMessageId; _TranscriptLayout? _transcriptLayout; ReceivedImageStore? _watchedImageStore; @@ -173,6 +183,7 @@ class _ChannelChatScreenState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); _textFieldFocusNode.addListener(_onTextFieldFocusChange); _scrollController.onScrollNearTop = _loadOlderMessages; _scrollController.showJumpToBottom.addListener(_clearDividerAtBottom); @@ -263,10 +274,28 @@ class _ChannelChatScreenState extends State { } } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) return; + // The focus manager observes the lifecycle from app start, so its restore + // is already queued and runs first. Clearing afterwards keeps a focus + // that was not restored (the user clicked elsewhere) from swallowing the + // next real tap on the composer. + scheduleMicrotask(() => _focusLostWhileAway = false); + } + void _onTextFieldFocusChange() { - if (_textFieldFocusNode.hasFocus && mounted) { - _scrollController.handleKeyboardOpen(); + if (!mounted) return; + if (!_textFieldFocusNode.hasFocus) { + final state = WidgetsBinding.instance.lifecycleState; + _focusLostWhileAway = state != null && state != AppLifecycleState.resumed; + _focusLostToRoute = !(ModalRoute.of(context)?.isCurrent ?? true); + return; } + final restored = _focusLostWhileAway || _focusLostToRoute; + _focusLostWhileAway = false; + _focusLostToRoute = false; + if (!restored) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -347,6 +376,7 @@ class _ChannelChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _watchedImageStore?.removeListener(_onImageStoreChanged); _unregisterActive(); @@ -929,12 +959,25 @@ class _ChannelChatScreenState extends State { rowCount + (_isLoadingOlder ? 1 : 0); // Auto-scroll to bottom if user is already at bottom + final newestEntryId = layout.ids.first; + final selectionCount = _selectedIds.length; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; + final newEntry = + newestEntryId != _snapNewestEntryId; + final selectionChanged = + selectionCount != _snapSelectionCount; + _snapNewestEntryId = newestEntryId; + _snapSelectionCount = selectionCount; if (_channelSkipNextBottomSnap) { _channelSkipNextBottomSnap = false; return; } + // Picking or clearing messages is not a new + // message: keep the reading position. + if (!newEntry && (_selecting || selectionChanged)) { + return; + } _scrollController.scrollToBottomIfAtBottom(); }); diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 2136b488..4ad21654 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -20,6 +20,7 @@ import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; +import '../helpers/chat_scroll_anchor.dart'; import '../helpers/chat_scroll_controller.dart'; import '../helpers/gif_helper.dart'; import '../helpers/ipfs_link_attach_flow.dart'; @@ -90,12 +91,16 @@ class ChatScreen extends StatefulWidget { State createState() => _ChatScreenState(); } -class _ChatScreenState extends State { +class _ChatScreenState extends State with WidgetsBindingObserver { final _holidayWatcher = HolidayTriggerWatcher(); final _messageAreaKey = GlobalKey(); final _textController = TextEditingController(); final _scrollController = ChatScrollController(); + final _scrollAnchor = ChatScrollAnchor(); + ({String id, bool bookmarksOnly})? _newestRow; final _textFieldFocusNode = FocusNode(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; final GlobalKey _unreadScrollKey = GlobalKey(); bool _isLoadingOlder = false; bool _showBookmarkedOnly = false; @@ -151,6 +156,7 @@ class _ChatScreenState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); _textFieldFocusNode.addListener(_onTextFieldFocusChange); _scrollController.onScrollNearTop = _loadOlderMessages; _scrollController.showJumpToBottom.addListener(_clearDividerAtBottom); @@ -218,10 +224,28 @@ class _ChatScreenState extends State { } } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) return; + // The focus manager observes the lifecycle from app start, so its restore + // is already queued and runs first. Clearing afterwards keeps a focus + // that was not restored (the user clicked elsewhere) from swallowing the + // next real tap on the composer. + scheduleMicrotask(() => _focusLostWhileAway = false); + } + void _onTextFieldFocusChange() { - if (_textFieldFocusNode.hasFocus && mounted) { - _scrollController.handleKeyboardOpen(); + if (!mounted) return; + if (!_textFieldFocusNode.hasFocus) { + final state = WidgetsBinding.instance.lifecycleState; + _focusLostWhileAway = state != null && state != AppLifecycleState.resumed; + _focusLostToRoute = !(ModalRoute.of(context)?.isCurrent ?? true); + return; } + final restored = _focusLostWhileAway || _focusLostToRoute; + _focusLostWhileAway = false; + _focusLostToRoute = false; + if (!restored) _scrollController.handleKeyboardOpen(); } Future _loadOlderMessages() async { @@ -238,6 +262,7 @@ class _ChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); @@ -701,15 +726,41 @@ class _ChatScreenState extends State { final reversedMessages = visibleMessages.reversed.toList(); final itemCount = reversedMessages.length + (_isLoadingOlder ? 1 : 0); + // A reader scrolled up keeps their place when messages arrive below, as + // a room's backlog does in a burst right after login. + final previous = _newestRow; + final newest = ( + id: reversedMessages.first.messageId, + bookmarksOnly: _showBookmarkedOnly, + ); + _newestRow = newest; + if (previous != null && + previous.bookmarksOnly == newest.bookmarksOnly && + previous.id != newest.id && + _pendingUnreadScrollTarget == null && + _scrollController.showJumpToBottom.value) { + final inserted = reversedMessages.indexWhere( + (m) => m.messageId == previous.id, + ); + if (inserted > 0) _scrollAnchor.rowsInsertedBelow(inserted); + } + // Auto-scroll to bottom if user is already at bottom WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; if (_pendingUnreadScrollTarget != null) return; + // Never take over a drag or fling: during a sync every update would + // pull a reader who starts scrolling up back to the newest message. + if (_scrollController.hasClients && + _scrollController.position.isScrollingNotifier.value) { + return; + } _scrollController.scrollToBottomIfAtBottom(); }); return ChatZoomWrapper( - child: ListView.builder( + child: AnchoredChatListView.builder( + scrollAnchor: _scrollAnchor, reverse: true, // List grows from bottom up controller: _scrollController, padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), diff --git a/test/helpers/chat_scroll_anchor_test.dart b/test/helpers/chat_scroll_anchor_test.dart new file mode 100644 index 00000000..3514cf9e --- /dev/null +++ b/test/helpers/chat_scroll_anchor_test.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/chat_scroll_anchor.dart'; + +/// A reversed chat list of rows with uneven heights. [add] appends newer +/// rows, which land at index 0 below everything else. +class _Harness { + final controller = ScrollController(); + final anchor = ChatScrollAnchor(); + var items = List.generate(100, (i) => 'm$i'); + late StateSetter _setState; + + Widget build() => MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + _setState = setState; + final rows = items.reversed.toList(); + return AnchoredChatListView.builder( + scrollAnchor: anchor, + reverse: true, + controller: controller, + padding: const EdgeInsets.all(16), + itemCount: rows.length, + itemBuilder: (context, i) => SizedBox( + height: 40.0 + (int.parse(rows[i].substring(1)) % 5) * 20, + child: Text(rows[i]), + ), + ); + }, + ), + ), + ); + + void add(int count, {bool anchored = true}) { + _setState(() { + final start = items.length; + items = [...items, for (var i = 0; i < count; i++) 'n${start + i}']; + if (anchored) anchor.rowsInsertedBelow(count); + }); + } +} + +void main() { + for (final count in [1, 3, 30, 300]) { + testWidgets('$count rows added below keep the visible rows in place', ( + tester, + ) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + harness.controller.jumpTo(2000); + await tester.pump(); + final row = find.text('m72'); + expect(row, findsOneWidget); + final before = tester.getTopLeft(row).dy; + + harness.add(count); + await tester.pump(); + + expect(row, findsOneWidget); + expect(tester.getTopLeft(row).dy, moreOrLessEquals(before)); + expect(harness.controller.position.pixels, greaterThan(2000)); + }); + } + + testWidgets('without the anchor the rows on screen move', (tester) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + harness.controller.jumpTo(2000); + await tester.pump(); + final before = tester.getTopLeft(find.text('m72')).dy; + + harness.add(3, anchored: false); + await tester.pump(); + + expect(tester.getTopLeft(find.text('m72')).dy, isNot(before)); + }); + + testWidgets('a list at the bottom is left at the bottom', (tester) async { + final harness = _Harness(); + addTearDown(harness.controller.dispose); + await tester.pumpWidget(harness.build()); + + harness.add(3, anchored: false); + await tester.pump(); + + expect(harness.controller.position.pixels, 0); + expect(find.text('n102'), findsOneWidget); + }); +} diff --git a/test/screens/channel_chat_selection_scroll_test.dart b/test/screens/channel_chat_selection_scroll_test.dart new file mode 100644 index 00000000..0aaa4143 --- /dev/null +++ b/test/screens/channel_chat_selection_scroll_test.dart @@ -0,0 +1,331 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/helpers/chat_scroll_controller.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; + +/// Selecting messages must not move the transcript: picking, selecting all +/// and clearing are not new messages, and the composer getting its focus back +/// when the action sheet closes is not the user opening the keyboard. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('selection_scroll_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + testWidgets('selecting from far up the history keeps the scroll offset', ( + tester, + ) async { + _useSmallView(tester); + await _pumpChannelChat(tester); + + // The composer has focus (keyboard open) while the user reads back. + await tester.tap(find.byType(TextField).last); + await _settle(tester); + await _scrollTo(tester, 600); + + await _startSelection(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, 600); + + // Select a few more. + for (var i = 0; i < 2; i++) { + await _tapVisibleUnselected(tester); + expect(_position(tester).pixels, 600); + } + expect(find.text('3 selected'), findsOneWidget); + + // Select all from the selection app bar's menu. + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.text('Select all')); + await _settle(tester); + expect(find.byIcon(Icons.radio_button_unchecked), findsNothing); + expect(_position(tester).pixels, 600); + + // End selection. + await tester.tap(find.byTooltip('Clear selection')); + await _settle(tester); + expect(find.byTooltip('Clear selection'), findsNothing); + expect(_position(tester).pixels, 600); + + // Losing focus with nothing on top, then tapping the composer, still jumps + // to the newest message. + FocusManager.instance.primaryFocus?.unfocus(); + await _settle(tester); + await tester.tap(find.byType(TextField).last); + await _settle(tester); + expect(_position(tester).pixels, 0); + + await _tearDown(tester); + }); + + testWidgets('selection near the bottom does not snap to the newest message', ( + tester, + ) async { + _useSmallView(tester); + await _pumpChannelChat(tester); + await _scrollTo(tester, 600); + await _startSelection(tester); + + // Inside the "at bottom" threshold, where a new message would snap. + await _scrollTo(tester, 60); + + await _tapVisibleUnselected(tester); + expect(find.text('2 selected'), findsOneWidget); + expect(_position(tester).pixels, 60); + + await tester.tap(find.byTooltip('Clear selection')); + await _settle(tester); + expect(_position(tester).pixels, 60); + + await _tearDown(tester); + }); + + testWidgets('incoming messages during selection behave as before', ( + tester, + ) async { + _useSmallView(tester); + final connector = await _pumpChannelChat(tester); + final channelIndex = connector.channels[0].index; + + await _scrollTo(tester, 600); + await _startSelection(tester); + + // Reading back: a new message must not pull the view down. + _receive(connector, channelIndex, 'Arrives while reading back'); + await _settle(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, greaterThanOrEqualTo(600)); + + // Near the bottom: a new message still scrolls into view. + await _scrollTo(tester, 60); + _receive(connector, channelIndex, 'Arrives while at the bottom'); + await _settle(tester); + expect(find.text('1 selected'), findsOneWidget); + expect(_position(tester).pixels, 0); + + await _tearDown(tester); + }); +} + +void _useSmallView(WidgetTester tester) { + tester.view.physicalSize = const Size(400, 700); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); +} + +ScrollPosition _position(WidgetTester tester) => tester + .widget( + find.byWidgetPredicate( + (w) => w is ListView && w.controller is ChatScrollController, + ), + ) + .controller! + .position; + +/// Jumps to [pixels] from the bottom. Jumps twice: the first lays out +/// messages whose heights were only estimated, which can correct the offset. +Future _scrollTo(WidgetTester tester, double pixels) async { + for (var i = 0; i < 2; i++) { + _position(tester).jumpTo(pixels); + await _settle(tester); + } + expect(_position(tester).pixels, pixels); +} + +/// Long-presses a message in the middle of the screen and picks "Select +/// messages" from its action sheet. The long-press callback is invoked +/// directly: in tests a real long press on the bubble text starts text +/// selection instead. +Future _startSelection(WidgetTester tester) async { + final detector = find + .byWidgetPredicate((w) => w is GestureDetector && w.onLongPress != null) + .evaluate() + .firstWhere((e) { + final box = e.renderObject! as RenderBox; + final y = box.localToGlobal(box.size.center(Offset.zero)).dy; + return y > 150 && y < 450; + }); + (detector.widget as GestureDetector).onLongPress!(); + await _settle(tester); + await tester.ensureVisible(find.text('Select messages')); + await tester.pump(); + await tester.tap(find.text('Select messages')); + await _settle(tester); +} + +/// Taps the selection circle of an unselected message on screen. +Future _tapVisibleUnselected(WidgetTester tester) async { + final list = tester.getRect( + find.byWidgetPredicate( + (w) => w is ListView && w.controller is ChatScrollController, + ), + ); + final circle = find + .byIcon(Icons.radio_button_unchecked) + .evaluate() + .firstWhere((e) { + final box = e.renderObject! as RenderBox; + return list.contains(box.localToGlobal(box.size.center(Offset.zero))); + }); + await tester.tap(find.byWidget(circle.widget)); + await _settle(tester); +} + +var _received = 0; + +void _receive(MeshCoreConnector connector, int channelIndex, String text) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: channelIndex, + sender: 'Alice', + message: text, + timestampSecs: + DateTime.now().millisecondsSinceEpoch ~/ 1000 + 60 * ++_received, + ), + ); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// One review-radio connection shared by the tests: reconnecting it in the +/// same run does not resend the channel list. +(MeshCoreConnector, List)? _shared; + +/// Connects the review radio (once), seeds a long history and shows the +/// first channel's chat. +Future _pumpChannelChat(WidgetTester tester) async { + final firstRun = _shared == null; + final (connector, providers) = _shared ??= await _connect(tester); + if (firstRun) { + final base = DateTime.now().millisecondsSinceEpoch ~/ 1000 - 10000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: connector.channels[0].index, + sender: 'Alice', + message: 'History message $i with enough words to wrap a line', + timestampSecs: base + i * 60, + ), + ); + } + } + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChannelChatScreen(channel: connector.channels[0]), + ), + ), + ); + await _settle(tester); + return connector; +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || connector.channels.length < 2) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels.length, greaterThanOrEqualTo(2)); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/chat_app_switch_keyboard_test.dart b/test/screens/chat_app_switch_keyboard_test.dart new file mode 100644 index 00000000..e6061787 --- /dev/null +++ b/test/screens/chat_app_switch_keyboard_test.dart @@ -0,0 +1,399 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; + +const _screen = Size(400, 800); +const _keyboard = 300.0; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('app_switch_kb_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + // Android/iOS keep focus on the composer across an app switch; the OS may + // or may not bring the keyboard back. Layout must follow the reported + // inset, and the draft, focus and reading position must survive. + for (final keyboardBack in [true, false]) { + for (final atBottom in [false, true]) { + final keyboard = keyboardBack ? 'keyboard back' : 'OS closed keyboard'; + final reading = atBottom ? 'at the bottom' : 'reading history'; + testWidgets('mobile app switch: $keyboard, $reading', (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + await _settle(tester); + await tester.enterText(_composerField, 'half written'); + await _settle(tester); + + if (!atBottom) { + await tester.drag(find.byType(ListView).first, const Offset(0, 300)); + await _settle(tester); + } + final offsetBefore = _list(tester).position.pixels; + expect(offsetBefore, atBottom ? 0 : greaterThan(100)); + expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1)); + + // Switch away; the OS hides the keyboard while the app is hidden. + _goBackground(tester); + tester.view.viewInsets = FakeViewPadding.zero; + await tester.pump(); + + _goForeground(tester); + if (keyboardBack) { + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + } + await _settle(tester); + + final inset = keyboardBack ? _keyboard : 0.0; + expect(_composerBottom(tester), closeTo(_screen.height - inset, 1)); + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_composer(tester).controller.text, 'half written'); + expect(_list(tester).position.pixels, closeTo(offsetBefore, 1)); + + // Tapping the field opens the keyboard again above the composer. + await tester.tap(_composerField); + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboard); + await _settle(tester); + expect(_composerBottom(tester), closeTo(_screen.height - _keyboard, 1)); + expect(_composer(tester).controller.text, 'half written'); + + await _tearDown(tester); + }); + } + } + + // Desktop and web take focus away when the window goes inactive and restore + // it on resume. That restore used to count as "keyboard opened" and jumped + // the transcript to the newest message. + testWidgets('desktop app switch keeps the reading position', (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + await _settle(tester); + await tester.enterText(_composerField, 'half written'); + // Mouse-wheel up through the history; the composer keeps focus. + _list(tester).jumpTo(300); + await _settle(tester); + + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + _goForeground(tester); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_composer(tester).controller.text, 'half written'); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // A real click on the composer still jumps to the newest message. + _composer(tester).focusNode.unfocus(); + await _settle(tester); + await tester.tap(_composerField); + await _settle(tester); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); + + testWidgets( + 'desktop app switch when focus is not restored does not swallow the next tap', + (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpChannelChat(tester); + await tester.tap(_composerField); + await _settle(tester); + _list(tester).jumpTo(300); + await _settle(tester); + + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + // User returns and interacts elsewhere (e.g. opens search) so focus is + // not restored to the composer on resume. + await tester.tap(find.byIcon(Icons.search)); + await tester.pump(); + _goForeground(tester); + await _settle(tester); + await tester.tap(find.byIcon(Icons.arrow_back)); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isFalse); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + await tester.tap(_composerField); + await _settle(tester); + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets( + 'DM chat: desktop app switch and dialog close keep reading position', + (tester) async { + tester.view.physicalSize = _screen; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + await _pumpDirectChat(tester); + await tester.tap(_composerField); + await _settle(tester); + _list(tester).jumpTo(300); + await _settle(tester); + + // App switch away and back restores focus without jumping to bottom. + _goBackground(tester); + await tester.pump(); + expect(_composer(tester).focusNode.hasFocus, isFalse); + _goForeground(tester); + await _settle(tester); + + expect(_composer(tester).focusNode.hasFocus, isTrue); + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // Opening and closing a dialog over the chat returns focus without jumping. + await tester.tap(find.byIcon(Icons.more_vert)); + await _settle(tester); + await tester.tap(find.byIcon(Icons.info_outline)); + await _settle(tester); + expect(find.byType(AlertDialog), findsOneWidget); + Navigator.of(tester.element(find.byType(AlertDialog))).pop(); + await _settle(tester); + + expect(_list(tester).position.pixels, closeTo(300, 1)); + + // Losing focus in the foreground and tapping again still jumps to bottom. + _composer(tester).focusNode.unfocus(); + await _settle(tester); + await tester.tap(_composerField); + await _settle(tester); + expect(_list(tester).position.pixels, 0); + + await _tearDown(tester); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); +} + +final _composerField = find.descendant( + of: find.byType(ChatComposer), + matching: find.byType(EditableText), +); + +EditableText _composer(WidgetTester tester) => + tester.widget(_composerField); + +void _goBackground(WidgetTester tester) { + for (final state in const [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + } +} + +void _goForeground(WidgetTester tester) { + for (final state in const [ + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + } +} + +ScrollController _list(WidgetTester tester) => tester + .widget(find.byWidgetPredicate((w) => w is ListView).first) + .controller!; + +double _composerBottom(WidgetTester tester) => + tester.getBottomLeft(find.byType(ChatComposer)).dy; + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +(MeshCoreConnector, List)? _shared; + +Future _pumpChannelChat(WidgetTester tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + await _pumpScreen( + tester, + providers, + ChannelChatScreen(channel: connector.channels[0]), + ); + return connector; +} + +Future _pumpDirectChat(WidgetTester tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat); + if (connector.getMessages(contact).length < 40) { + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: contact.publicKey, + text: 'Direct history line $i about the weather on the hill', + timestampSecs: now - 4000 + i, + ), + ); + } + } + await _pumpScreen(tester, providers, ChatScreen(contact: contact)); + return connector; +} + +Future _pumpScreen( + WidgetTester tester, + List providers, + Widget screen, +) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: screen, + ), + ), + ); + await _settle(tester); +} + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while (connector.channels.isEmpty && DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + // Enough history that the transcript scrolls with or without a keyboard. + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + for (var i = 0; i < 40; i++) { + connector.handleFrameForTest( + ReviewFrames.channelMessage( + channelIndex: 0, + sender: 'Tester', + message: 'History line number $i about the weather on the hill', + timestampSecs: now - 4000 + i, + ), + ); + } + while (connector.getChannelMessages(connector.channels[0]).length < 40 && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels, isNotEmpty); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/screens/room_chat_scroll_test.dart b/test/screens/room_chat_scroll_test.dart new file mode 100644 index 00000000..ffc9bce9 --- /dev/null +++ b/test/screens/room_chat_scroll_test.dart @@ -0,0 +1,336 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/review_mode/review_frames.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/unread_divider.dart'; + +/// Room chats receive their backlog as a burst of messages right after login. +/// These tests feed such a burst into an open room chat and check that the +/// reader's place holds, and that opening the chat still lands where the +/// unread preference says. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('room_scroll_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + setUp(() { + final view = + TestWidgetsFlutterBinding.instance.platformDispatcher.views.first; + view.physicalSize = const Size(400, 800); + view.devicePixelRatio = 1.0; + }); + tearDown( + () => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first + .reset(), + ); + + testWidgets('a sync burst keeps the reader on the message they were ' + 'reading', (tester) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + + controller.jumpTo(1500); + await _settle(tester); + final reading = _lowestVisibleMessage(tester); + final before = tester.getTopLeft(reading).dy; + + // One at a time, as the radio hands queued posts over, then a batch + // that lands within a single frame. + for (var i = 0; i < 5; i++) { + _receive(connector, room, 'synced single $i'); + await tester.pump(); + } + for (var i = 0; i < 25; i++) { + _receive(connector, room, 'synced batch $i'); + } + await _settle(tester); + + expect(connector.getMessages(room), hasLength(90)); + expect(reading, findsOneWidget); + expect(tester.getTopLeft(reading).dy, moreOrLessEquals(before)); + await _tearDown(tester); + }); + + testWidgets('a reader starting to scroll up during sync is not pulled ' + 'back to the newest message', (tester) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + expect(controller.position.pixels, 0); + + final gesture = await tester.startGesture(const Offset(200, 400)); + for (var i = 0; i < 12; i++) { + await gesture.moveBy(const Offset(0, 25)); + _receive(connector, room, 'during drag $i'); + await tester.pump(const Duration(milliseconds: 16)); + } + await gesture.up(); + await _settle(tester); + + expect(connector.getMessages(room), hasLength(72)); + expect(controller.position.pixels, greaterThan(200)); + await _tearDown(tester); + }); + + testWidgets('first open at the bottom still follows new messages', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 60); + final controller = _listController(tester); + expect(controller.position.pixels, 0); + + for (var i = 0; i < 5; i++) { + _receive(connector, room, 'newest $i'); + await tester.pump(); + } + await _settle(tester); + + expect(connector.getMessages(room), hasLength(65)); + expect(controller.position.pixels, 0); + expect(find.text('newest 4', findRichText: true), findsOneWidget); + await _tearDown(tester); + }); + + testWidgets('jump to oldest unread lands on the divider and holds through ' + 'a sync burst', (tester) async { + final (connector, room) = await _openRoom( + tester, + history: 60, + unread: 30, + jumpToOldestUnread: true, + ); + final controller = _listController(tester); + // history 30 is the oldest of the 30 unread messages. + final anchor = find.text('history 30', findRichText: true); + expect(anchor, findsOneWidget); + expect(find.byType(UnreadDivider), findsOneWidget); + expect(controller.position.pixels, greaterThan(100)); + final before = tester.getTopLeft(anchor).dy; + expect(before, inInclusiveRange(0, 800)); + + for (var i = 0; i < 10; i++) { + _receive(connector, room, 'after open $i'); + await tester.pump(); + } + await _settle(tester); + expect(connector.getMessages(room), hasLength(70)); + expect(tester.getTopLeft(anchor).dy, moreOrLessEquals(before)); + await _tearDown(tester); + }); + + testWidgets('older pages loaded in an open chat survive new messages', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 230); + final window = connector.getMessages(room); + expect(window, hasLength(200)); + final older = await tester.runAsync( + () => connector.loadOlderMessages(room.publicKeyHex), + ); + expect(older, isNotEmpty); + final paged = connector.getMessages(room).length; + expect(paged, greaterThan(200)); + + _receive(connector, room, 'arrives while reading history'); + await _settle(tester); + expect(connector.getMessages(room), hasLength(paged + 1)); + expect(connector.getMessages(room).first.text, older!.first.text); + await _tearDown(tester); + }); + + testWidgets('an open chat still caps its window at the stored limit', ( + tester, + ) async { + final (connector, room) = await _openRoom(tester, history: 0); + for (var i = 0; i < MessageStore.maxStoredMessages + 10; i++) { + _receive(connector, room, 'flood $i'); + } + final window = connector.getMessages(room); + expect(window, hasLength(MessageStore.maxStoredMessages)); + expect(window.last.text, 'flood ${MessageStore.maxStoredMessages + 9}'); + await _tearDown(tester); + }); +} + +var _timestamp = 1700000000; + +void _receive(MeshCoreConnector connector, Contact room, String text) { + connector.handleFrameForTest( + ReviewFrames.contactMessage( + senderPublicKey: room.publicKey, + text: text, + timestampSecs: _timestamp++, + ), + ); +} + +ScrollController _listController(WidgetTester tester) => tester + .widget(find.byWidgetPredicate((w) => w is ListView)) + .controller!; + +/// The on-screen history message nearest the bottom of the list. +Finder _lowestVisibleMessage(WidgetTester tester) { + Finder? best; + var bestY = double.negativeInfinity; + for (var i = 0; i < 60; i++) { + final finder = find.text('history $i', findRichText: true); + if (finder.evaluate().isEmpty) continue; + final y = tester.getTopLeft(finder).dy; + if (y > 80 && y < 600 && y > bestY) { + bestY = y; + best = finder; + } + } + expect(best, isNotNull, reason: 'a history message should be on screen'); + return best!; +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// Connects the review radio, gives its room [history] messages and opens +/// the room chat as a login does, with [unread] of them unread. +Future<(MeshCoreConnector, Contact)> _openRoom( + WidgetTester tester, { + required int history, + int unread = 0, + bool jumpToOldestUnread = false, +}) async { + final (connector, providers, settings) = _shared ??= await _connect(tester); + await tester.runAsync( + () => settings.setJumpToOldestUnread(jumpToOldestUnread), + ); + final room = connector.contacts.firstWhere((c) => c.type == advTypeRoom); + connector.clearMessagesForContact(room); + await tester.runAsync(() => connector.flushPendingWrites()); + for (var i = 0; i < history; i++) { + _receive(connector, room, 'history $i'); + } + expect(connector.getMessages(room), hasLength(history.clamp(0, 200))); + connector.markContactRead(room.publicKeyHex); + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: ChatScreen(contact: room, initialUnreadCount: unread), + ), + ), + ); + await _settle(tester); + return (connector, room); +} + +/// One review-radio connection shared by the tests: reconnecting it in the +/// same run does not resend the contact list. +(MeshCoreConnector, List, AppSettingsService)? _shared; + +Future<(MeshCoreConnector, List, AppSettingsService)> +_connect(WidgetTester tester) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while (!connector.contacts.any((c) => c.type == advTypeRoom) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + // Let the connect-time message sync finish so test frames are not held. + await Future.delayed(const Duration(milliseconds: 500)); + }); + expect(connector.contacts.any((c) => c.type == advTypeRoom), isTrue); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + settings, + ); +}