Keep chat reading position during sync, selection and app switches
- Room chats: keep the visible message in place when synced messages arrive, don't pull a scrolling reader back to the bottom, and keep loaded older pages while the chat is open. - Selecting messages no longer jumps to the newest message. - Focus returning after a sheet, dialog or app switch no longer counts as opening the keyboard.
This commit is contained in:
1 parent
34ea0cb7ca
commit
ffbb61bc3d
11 files changed
+1431
-10
No files matched your search
@@ -35,7 +35,8 @@ From the Contacts screen, tap any Chat-type contact to open the ChatScreen.
|
|||||||
- Message text follows the system font size (Android/iOS accessibility text size); pinch-to-zoom scales on top of it
|
- 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
|
- **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
|
- **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
|
- **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
|
### Input Bar
|
||||||
|
|||||||
@@ -9191,8 +9191,13 @@ class MeshCoreConnector extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
messages.add(message);
|
messages.add(message);
|
||||||
if (messages.length > _messageWindowSize) {
|
// The open chat keeps the older pages its reader scrolled back to;
|
||||||
final trimCount = messages.length - _messageWindowSize;
|
// 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));
|
_messageStore.archive(pubKeyHex, messages.sublist(0, trimCount));
|
||||||
messages.removeRange(0, trimCount);
|
messages.removeRange(0, trimCount);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
/// Tells the user focusing the chat composer apart from Flutter handing focus
|
||||||
|
/// back after an app switch or after a sheet, dialog or menu closes.
|
||||||
|
///
|
||||||
|
/// On desktop and web the focus manager takes focus off the composer when the
|
||||||
|
/// window goes inactive and puts it back on resume. That is not the user
|
||||||
|
/// starting to type, so the chat must not jump to the newest message and lose
|
||||||
|
/// the reading position. Mobile keeps focus across an app switch. On every
|
||||||
|
/// platform a sheet, dialog or menu opened over the chat takes focus and the
|
||||||
|
/// composer gets it back when that closes, which is not a tap either.
|
||||||
|
class ComposerFocusIntent with WidgetsBindingObserver {
|
||||||
|
ComposerFocusIntent() {
|
||||||
|
WidgetsBinding.instance.addObserver(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _lostWhileAway = false;
|
||||||
|
bool _lostToRoute = false;
|
||||||
|
|
||||||
|
/// Call from the composer focus node's listener. Returns true when focus
|
||||||
|
/// was just gained by a tap or by app code, false for a loss of focus or a
|
||||||
|
/// focus restored on resume or when a route on top closes.
|
||||||
|
///
|
||||||
|
/// [coveredByRoute] is whether the chat's route is no longer the current
|
||||||
|
/// one (a sheet, dialog or menu is open on top).
|
||||||
|
bool isUserFocusGain(bool hasFocus, {bool coveredByRoute = false}) {
|
||||||
|
if (!hasFocus) {
|
||||||
|
final state = WidgetsBinding.instance.lifecycleState;
|
||||||
|
_lostWhileAway = state != null && state != AppLifecycleState.resumed;
|
||||||
|
_lostToRoute = coveredByRoute;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
final restored = _lostWhileAway || _lostToRoute;
|
||||||
|
_lostWhileAway = false;
|
||||||
|
_lostToRoute = false;
|
||||||
|
return !restored;
|
||||||
|
}
|
||||||
|
|
||||||
|
@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(() => _lostWhileAway = false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void dispose() => WidgetsBinding.instance.removeObserver(this);
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import '../storage/community_store.dart';
|
|||||||
import '../utils/platform_info.dart';
|
import '../utils/platform_info.dart';
|
||||||
import '../helpers/chat_jump.dart';
|
import '../helpers/chat_jump.dart';
|
||||||
import '../helpers/chat_scroll_controller.dart';
|
import '../helpers/chat_scroll_controller.dart';
|
||||||
|
import '../helpers/composer_focus_intent.dart';
|
||||||
import '../connector/meshcore_protocol.dart';
|
import '../connector/meshcore_protocol.dart';
|
||||||
import '../helpers/cyr2lat.dart';
|
import '../helpers/cyr2lat.dart';
|
||||||
import '../helpers/gif_helper.dart';
|
import '../helpers/gif_helper.dart';
|
||||||
@@ -104,6 +105,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|||||||
final TextEditingController _textController = TextEditingController();
|
final TextEditingController _textController = TextEditingController();
|
||||||
final ChatScrollController _scrollController = ChatScrollController();
|
final ChatScrollController _scrollController = ChatScrollController();
|
||||||
final FocusNode _textFieldFocusNode = FocusNode();
|
final FocusNode _textFieldFocusNode = FocusNode();
|
||||||
|
final _composerFocusIntent = ComposerFocusIntent();
|
||||||
ChannelMessage? _replyingToMessage;
|
ChannelMessage? _replyingToMessage;
|
||||||
bool _useReplyRegion = false;
|
bool _useReplyRegion = false;
|
||||||
final CommunityStore _communityStore = CommunityStore();
|
final CommunityStore _communityStore = CommunityStore();
|
||||||
@@ -134,6 +136,13 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|||||||
MeshCoreConnector? _connector;
|
MeshCoreConnector? _connector;
|
||||||
final ChatSendGuard _sendGuard = ChatSendGuard();
|
final ChatSendGuard _sendGuard = ChatSendGuard();
|
||||||
bool _channelSkipNextBottomSnap = false;
|
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;
|
String? _unreadDividerMessageId;
|
||||||
_TranscriptLayout? _transcriptLayout;
|
_TranscriptLayout? _transcriptLayout;
|
||||||
ReceivedImageStore? _watchedImageStore;
|
ReceivedImageStore? _watchedImageStore;
|
||||||
@@ -263,9 +272,12 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _onTextFieldFocusChange() {
|
void _onTextFieldFocusChange() {
|
||||||
if (_textFieldFocusNode.hasFocus && mounted) {
|
if (!mounted) return;
|
||||||
_scrollController.handleKeyboardOpen();
|
final userFocus = _composerFocusIntent.isUserFocusGain(
|
||||||
}
|
_textFieldFocusNode.hasFocus,
|
||||||
|
coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true),
|
||||||
|
);
|
||||||
|
if (userFocus) _scrollController.handleKeyboardOpen();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadOlderMessages() async {
|
Future<void> _loadOlderMessages() async {
|
||||||
@@ -351,6 +363,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|||||||
_unregisterActive();
|
_unregisterActive();
|
||||||
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
||||||
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
||||||
|
_composerFocusIntent.dispose();
|
||||||
_textFieldFocusNode.dispose();
|
_textFieldFocusNode.dispose();
|
||||||
_textController.dispose();
|
_textController.dispose();
|
||||||
_searchController.dispose();
|
_searchController.dispose();
|
||||||
@@ -923,12 +936,25 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
|||||||
rowCount + (_isLoadingOlder ? 1 : 0);
|
rowCount + (_isLoadingOlder ? 1 : 0);
|
||||||
|
|
||||||
// Auto-scroll to bottom if user is already at bottom
|
// Auto-scroll to bottom if user is already at bottom
|
||||||
|
final newestEntryId = layout.ids.first;
|
||||||
|
final selectionCount = _selectedIds.length;
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
final newEntry =
|
||||||
|
newestEntryId != _snapNewestEntryId;
|
||||||
|
final selectionChanged =
|
||||||
|
selectionCount != _snapSelectionCount;
|
||||||
|
_snapNewestEntryId = newestEntryId;
|
||||||
|
_snapSelectionCount = selectionCount;
|
||||||
if (_channelSkipNextBottomSnap) {
|
if (_channelSkipNextBottomSnap) {
|
||||||
_channelSkipNextBottomSnap = false;
|
_channelSkipNextBottomSnap = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Picking or clearing messages is not a new
|
||||||
|
// message: keep the reading position.
|
||||||
|
if (!newEntry && (_selecting || selectionChanged)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
_scrollController.scrollToBottomIfAtBottom();
|
_scrollController.scrollToBottomIfAtBottom();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ import '../helpers/path_helper.dart';
|
|||||||
import '../helpers/reaction_helper.dart';
|
import '../helpers/reaction_helper.dart';
|
||||||
import '../widgets/message_status_icon.dart';
|
import '../widgets/message_status_icon.dart';
|
||||||
import '../widgets/empty_state.dart';
|
import '../widgets/empty_state.dart';
|
||||||
|
import '../helpers/chat_scroll_anchor.dart';
|
||||||
import '../helpers/chat_scroll_controller.dart';
|
import '../helpers/chat_scroll_controller.dart';
|
||||||
|
import '../helpers/composer_focus_intent.dart';
|
||||||
import '../helpers/gif_helper.dart';
|
import '../helpers/gif_helper.dart';
|
||||||
import '../helpers/ipfs_link_attach_flow.dart';
|
import '../helpers/ipfs_link_attach_flow.dart';
|
||||||
import '../helpers/contact_share_message.dart';
|
import '../helpers/contact_share_message.dart';
|
||||||
@@ -94,7 +96,10 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final _messageAreaKey = GlobalKey();
|
final _messageAreaKey = GlobalKey();
|
||||||
final _textController = TextEditingController();
|
final _textController = TextEditingController();
|
||||||
final _scrollController = ChatScrollController();
|
final _scrollController = ChatScrollController();
|
||||||
|
final _scrollAnchor = ChatScrollAnchor();
|
||||||
|
({String id, bool bookmarksOnly})? _newestRow;
|
||||||
final _textFieldFocusNode = FocusNode();
|
final _textFieldFocusNode = FocusNode();
|
||||||
|
final _composerFocusIntent = ComposerFocusIntent();
|
||||||
final GlobalKey _unreadScrollKey = GlobalKey();
|
final GlobalKey _unreadScrollKey = GlobalKey();
|
||||||
bool _isLoadingOlder = false;
|
bool _isLoadingOlder = false;
|
||||||
bool _showBookmarkedOnly = false;
|
bool _showBookmarkedOnly = false;
|
||||||
@@ -218,9 +223,12 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _onTextFieldFocusChange() {
|
void _onTextFieldFocusChange() {
|
||||||
if (_textFieldFocusNode.hasFocus && mounted) {
|
if (!mounted) return;
|
||||||
_scrollController.handleKeyboardOpen();
|
final userFocus = _composerFocusIntent.isUserFocusGain(
|
||||||
}
|
_textFieldFocusNode.hasFocus,
|
||||||
|
coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true),
|
||||||
|
);
|
||||||
|
if (userFocus) _scrollController.handleKeyboardOpen();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _loadOlderMessages() async {
|
Future<void> _loadOlderMessages() async {
|
||||||
@@ -241,6 +249,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
_unregisterActive();
|
_unregisterActive();
|
||||||
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
||||||
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
||||||
|
_composerFocusIntent.dispose();
|
||||||
_textFieldFocusNode.dispose();
|
_textFieldFocusNode.dispose();
|
||||||
_textController.dispose();
|
_textController.dispose();
|
||||||
_searchController.dispose();
|
_searchController.dispose();
|
||||||
@@ -678,15 +687,41 @@ class _ChatScreenState extends State<ChatScreen> {
|
|||||||
final reversedMessages = visibleMessages.reversed.toList();
|
final reversedMessages = visibleMessages.reversed.toList();
|
||||||
final itemCount = reversedMessages.length + (_isLoadingOlder ? 1 : 0);
|
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
|
// Auto-scroll to bottom if user is already at bottom
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
if (_pendingUnreadScrollTarget != null) 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();
|
_scrollController.scrollToBottomIfAtBottom();
|
||||||
});
|
});
|
||||||
|
|
||||||
return ChatZoomWrapper(
|
return ChatZoomWrapper(
|
||||||
child: ListView.builder(
|
child: AnchoredChatListView.builder(
|
||||||
|
scrollAnchor: _scrollAnchor,
|
||||||
reverse: true, // List grows from bottom up
|
reverse: true, // List grows from bottom up
|
||||||
controller: _scrollController,
|
controller: _scrollController,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_open/helpers/composer_focus_intent.dart';
|
||||||
|
|
||||||
|
void _setLifecycle(WidgetTester tester, List<AppLifecycleState> states) {
|
||||||
|
for (final state in states) {
|
||||||
|
tester.binding.handleAppLifecycleStateChanged(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _away = [
|
||||||
|
AppLifecycleState.inactive,
|
||||||
|
AppLifecycleState.hidden,
|
||||||
|
AppLifecycleState.paused,
|
||||||
|
];
|
||||||
|
const _back = [
|
||||||
|
AppLifecycleState.hidden,
|
||||||
|
AppLifecycleState.inactive,
|
||||||
|
AppLifecycleState.resumed,
|
||||||
|
];
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('focus gained while in the foreground is user focus', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final intent = ComposerFocusIntent();
|
||||||
|
addTearDown(intent.dispose);
|
||||||
|
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
expect(intent.isUserFocusGain(false), isFalse);
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('focus lost while away and given back on resume is not', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final intent = ComposerFocusIntent();
|
||||||
|
addTearDown(intent.dispose);
|
||||||
|
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
_setLifecycle(tester, _away.sublist(0, 1));
|
||||||
|
expect(intent.isUserFocusGain(false), isFalse);
|
||||||
|
_setLifecycle(tester, [..._away.sublist(1), ..._back]);
|
||||||
|
// The restore lands before the resume microtask clears the flag.
|
||||||
|
expect(intent.isUserFocusGain(true), isFalse);
|
||||||
|
// The next tap counts again.
|
||||||
|
expect(intent.isUserFocusGain(false), isFalse);
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('focus not restored on resume does not swallow the next tap', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final intent = ComposerFocusIntent();
|
||||||
|
addTearDown(intent.dispose);
|
||||||
|
|
||||||
|
_setLifecycle(tester, _away.sublist(0, 1));
|
||||||
|
expect(intent.isUserFocusGain(false), isFalse);
|
||||||
|
_setLifecycle(tester, [..._away.sublist(1), ..._back]);
|
||||||
|
await tester.pump(); // Resume microtasks run; nothing restored focus.
|
||||||
|
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('focus given back when a sheet or dialog closes is not', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final intent = ComposerFocusIntent();
|
||||||
|
addTearDown(intent.dispose);
|
||||||
|
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
expect(intent.isUserFocusGain(false, coveredByRoute: true), isFalse);
|
||||||
|
expect(intent.isUserFocusGain(true), isFalse);
|
||||||
|
// Losing focus with nothing on top, then tapping, counts again.
|
||||||
|
expect(intent.isUserFocusGain(false), isFalse);
|
||||||
|
expect(intent.isUserFocusGain(true), isTrue);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
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);
|
||||||
|
|
||||||
|
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<ListView>(
|
||||||
|
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<void> _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<void> _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<void> _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<void> _settle(WidgetTester tester) async {
|
||||||
|
for (var i = 0; i < 10; i++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _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<SingleChildWidget>)? _shared;
|
||||||
|
|
||||||
|
/// Connects the review radio (once), seeds a long history and shows the
|
||||||
|
/// first channel's chat.
|
||||||
|
Future<MeshCoreConnector> _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<SingleChildWidget>)> _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<void>.delayed(const Duration(milliseconds: 25));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
expect(connector.channels.length, greaterThanOrEqualTo(2));
|
||||||
|
|
||||||
|
return (
|
||||||
|
connector,
|
||||||
|
<SingleChildWidget>[
|
||||||
|
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()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
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/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';
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
final _composerField = find.descendant(
|
||||||
|
of: find.byType(ChatComposer),
|
||||||
|
matching: find.byType(EditableText),
|
||||||
|
);
|
||||||
|
|
||||||
|
EditableText _composer(WidgetTester tester) =>
|
||||||
|
tester.widget<EditableText>(_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<ListView>(find.byType(ListView).first).controller!;
|
||||||
|
|
||||||
|
double _composerBottom(WidgetTester tester) =>
|
||||||
|
tester.getBottomLeft(find.byType(ChatComposer)).dy;
|
||||||
|
|
||||||
|
Future<void> _settle(WidgetTester tester) async {
|
||||||
|
for (var i = 0; i < 10; i++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _tearDown(WidgetTester tester) async {
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
await tester.pump(const Duration(minutes: 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
(MeshCoreConnector, List<SingleChildWidget>)? _shared;
|
||||||
|
|
||||||
|
Future<MeshCoreConnector> _pumpChannelChat(WidgetTester tester) async {
|
||||||
|
final (connector, providers) = _shared ??= await _connect(tester);
|
||||||
|
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<SingleChildWidget>)> _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<void>.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<void>.delayed(const Duration(milliseconds: 25));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
expect(connector.channels, isNotEmpty);
|
||||||
|
|
||||||
|
return (
|
||||||
|
connector,
|
||||||
|
<SingleChildWidget>[
|
||||||
|
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()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<ListView>(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<void> _settle(WidgetTester tester) async {
|
||||||
|
for (var i = 0; i < 10; i++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _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<SingleChildWidget>, AppSettingsService)? _shared;
|
||||||
|
|
||||||
|
Future<(MeshCoreConnector, List<SingleChildWidget>, 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<void>.delayed(const Duration(milliseconds: 25));
|
||||||
|
}
|
||||||
|
// Let the connect-time message sync finish so test frames are not held.
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||||
|
});
|
||||||
|
expect(connector.contacts.any((c) => c.type == advTypeRoom), isTrue);
|
||||||
|
|
||||||
|
return (
|
||||||
|
connector,
|
||||||
|
<SingleChildWidget>[
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user