From aa621526ecbfc9bd1aa5f7e11e748f48a1a7c565 Mon Sep 17 00:00:00 2001 From: zjs81 <30362347+zjs81@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:09:48 -0700 Subject: [PATCH] Keep composer focus-intent tracking local to chat screens --- lib/helpers/composer_focus_intent.dart | 52 -------- lib/screens/channel_chat_screen.dart | 35 +++-- lib/screens/chat_screen.dart | 34 +++-- test/helpers/composer_focus_intent_test.dart | 78 ----------- .../channel_chat_selection_scroll_test.dart | 8 ++ .../chat_app_switch_keyboard_test.dart | 126 +++++++++++++++++- 6 files changed, 181 insertions(+), 152 deletions(-) delete mode 100644 lib/helpers/composer_focus_intent.dart delete mode 100644 test/helpers/composer_focus_intent_test.dart diff --git a/lib/helpers/composer_focus_intent.dart b/lib/helpers/composer_focus_intent.dart deleted file mode 100644 index baa698db..00000000 --- a/lib/helpers/composer_focus_intent.dart +++ /dev/null @@ -1,52 +0,0 @@ -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); -} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 4255146e..0702f3a1 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -16,7 +16,6 @@ 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'; @@ -100,13 +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(); - final _composerFocusIntent = ComposerFocusIntent(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; ChannelMessage? _replyingToMessage; bool _useReplyRegion = false; final CommunityStore _communityStore = CommunityStore(); @@ -182,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); @@ -272,13 +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 (!mounted) return; - final userFocus = _composerFocusIntent.isUserFocusGain( - _textFieldFocusNode.hasFocus, - coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), - ); - if (userFocus) _scrollController.handleKeyboardOpen(); + 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 { @@ -359,12 +376,12 @@ class _ChannelChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _watchedImageStore?.removeListener(_onImageStoreChanged); _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); - _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 6e3c0d05..617b44c4 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -22,7 +22,6 @@ 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'; @@ -92,7 +91,7 @@ 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(); @@ -100,7 +99,8 @@ class _ChatScreenState extends State { final _scrollAnchor = ChatScrollAnchor(); ({String id, bool bookmarksOnly})? _newestRow; final _textFieldFocusNode = FocusNode(); - final _composerFocusIntent = ComposerFocusIntent(); + bool _focusLostWhileAway = false; + bool _focusLostToRoute = false; final GlobalKey _unreadScrollKey = GlobalKey(); bool _isLoadingOlder = false; bool _showBookmarkedOnly = false; @@ -156,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); @@ -223,13 +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 (!mounted) return; - final userFocus = _composerFocusIntent.isUserFocusGain( - _textFieldFocusNode.hasFocus, - coveredByRoute: !(ModalRoute.of(context)?.isCurrent ?? true), - ); - if (userFocus) _scrollController.handleKeyboardOpen(); + 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 { @@ -246,11 +262,11 @@ class _ChatScreenState extends State { @override void dispose() { + WidgetsBinding.instance.removeObserver(this); _route?.secondaryAnimation?.removeStatusListener(_onCoveringRouteStatus); _unregisterActive(); _scrollController.showJumpToBottom.removeListener(_clearDividerAtBottom); _textFieldFocusNode.removeListener(_onTextFieldFocusChange); - _composerFocusIntent.dispose(); _textFieldFocusNode.dispose(); _textController.dispose(); _searchController.dispose(); diff --git a/test/helpers/composer_focus_intent_test.dart b/test/helpers/composer_focus_intent_test.dart deleted file mode 100644 index e1705d42..00000000 --- a/test/helpers/composer_focus_intent_test.dart +++ /dev/null @@ -1,78 +0,0 @@ -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 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); - }); -} diff --git a/test/screens/channel_chat_selection_scroll_test.dart b/test/screens/channel_chat_selection_scroll_test.dart index 39c12447..0aaa4143 100644 --- a/test/screens/channel_chat_selection_scroll_test.dart +++ b/test/screens/channel_chat_selection_scroll_test.dart @@ -85,6 +85,14 @@ void main() { 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); }); diff --git a/test/screens/chat_app_switch_keyboard_test.dart b/test/screens/chat_app_switch_keyboard_test.dart index f586ad68..e6061787 100644 --- a/test/screens/chat_app_switch_keyboard_test.dart +++ b/test/screens/chat_app_switch_keyboard_test.dart @@ -9,10 +9,12 @@ 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'; @@ -140,6 +142,90 @@ void main() { 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( @@ -170,8 +256,9 @@ void _goForeground(WidgetTester tester) { } } -ScrollController _list(WidgetTester tester) => - tester.widget(find.byType(ListView).first).controller!; +ScrollController _list(WidgetTester tester) => tester + .widget(find.byWidgetPredicate((w) => w is ListView).first) + .controller!; double _composerBottom(WidgetTester tester) => tester.getBottomLeft(find.byType(ChatComposer)).dy; @@ -191,6 +278,38 @@ Future _tearDown(WidgetTester tester) async { 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, @@ -204,12 +323,11 @@ Future _pumpChannelChat(WidgetTester tester) async { GlobalCupertinoLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, - home: ChannelChatScreen(channel: connector.channels[0]), + home: screen, ), ), ); await _settle(tester); - return connector; } Future<(MeshCoreConnector, List)> _connect(