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
@@ -9191,8 +9191,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);
|
||||
}
|
||||
|
||||
@@ -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 '../helpers/chat_jump.dart';
|
||||
import '../helpers/chat_scroll_controller.dart';
|
||||
import '../helpers/composer_focus_intent.dart';
|
||||
import '../connector/meshcore_protocol.dart';
|
||||
import '../helpers/cyr2lat.dart';
|
||||
import '../helpers/gif_helper.dart';
|
||||
@@ -104,6 +105,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
||||
final TextEditingController _textController = TextEditingController();
|
||||
final ChatScrollController _scrollController = ChatScrollController();
|
||||
final FocusNode _textFieldFocusNode = FocusNode();
|
||||
final _composerFocusIntent = ComposerFocusIntent();
|
||||
ChannelMessage? _replyingToMessage;
|
||||
bool _useReplyRegion = false;
|
||||
final CommunityStore _communityStore = CommunityStore();
|
||||
@@ -134,6 +136,13 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
||||
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;
|
||||
@@ -263,9 +272,12 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
||||
}
|
||||
|
||||
void _onTextFieldFocusChange() {
|
||||
if (_textFieldFocusNode.hasFocus && mounted) {
|
||||
_scrollController.handleKeyboardOpen();
|
||||
}
|
||||
if (!mounted) return;
|
||||
final userFocus = _composerFocusIntent.isUserFocusGain(
|
||||
_textFieldFocusNode.hasFocus,
|
||||
coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true),
|
||||
);
|
||||
if (userFocus) _scrollController.handleKeyboardOpen();
|
||||
}
|
||||
|
||||
Future<void> _loadOlderMessages() async {
|
||||
@@ -351,6 +363,7 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
||||
_unregisterActive();
|
||||
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
||||
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
||||
_composerFocusIntent.dispose();
|
||||
_textFieldFocusNode.dispose();
|
||||
_textController.dispose();
|
||||
_searchController.dispose();
|
||||
@@ -923,12 +936,25 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
|
||||
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();
|
||||
});
|
||||
|
||||
|
||||
@@ -20,7 +20,9 @@ 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/composer_focus_intent.dart';
|
||||
import '../helpers/gif_helper.dart';
|
||||
import '../helpers/ipfs_link_attach_flow.dart';
|
||||
import '../helpers/contact_share_message.dart';
|
||||
@@ -94,7 +96,10 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
final _messageAreaKey = GlobalKey();
|
||||
final _textController = TextEditingController();
|
||||
final _scrollController = ChatScrollController();
|
||||
final _scrollAnchor = ChatScrollAnchor();
|
||||
({String id, bool bookmarksOnly})? _newestRow;
|
||||
final _textFieldFocusNode = FocusNode();
|
||||
final _composerFocusIntent = ComposerFocusIntent();
|
||||
final GlobalKey _unreadScrollKey = GlobalKey();
|
||||
bool _isLoadingOlder = false;
|
||||
bool _showBookmarkedOnly = false;
|
||||
@@ -218,9 +223,12 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
}
|
||||
|
||||
void _onTextFieldFocusChange() {
|
||||
if (_textFieldFocusNode.hasFocus && mounted) {
|
||||
_scrollController.handleKeyboardOpen();
|
||||
}
|
||||
if (!mounted) return;
|
||||
final userFocus = _composerFocusIntent.isUserFocusGain(
|
||||
_textFieldFocusNode.hasFocus,
|
||||
coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true),
|
||||
);
|
||||
if (userFocus) _scrollController.handleKeyboardOpen();
|
||||
}
|
||||
|
||||
Future<void> _loadOlderMessages() async {
|
||||
@@ -241,6 +249,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
_unregisterActive();
|
||||
_scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom);
|
||||
_textFieldFocusNode.removeListener(_onTextFieldFocusChange);
|
||||
_composerFocusIntent.dispose();
|
||||
_textFieldFocusNode.dispose();
|
||||
_textController.dispose();
|
||||
_searchController.dispose();
|
||||
@@ -678,15 +687,41 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
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),
|
||||
|
||||
Reference in new issue
Block a user