diff --git a/app/lib/features/chat/conversation/composer_focus_request.dart b/app/lib/features/chat/conversation/composer_focus_request.dart index c8f7ece7..ec5f06e6 100644 --- a/app/lib/features/chat/conversation/composer_focus_request.dart +++ b/app/lib/features/chat/conversation/composer_focus_request.dart @@ -75,13 +75,27 @@ class ComposerFocusRequestListener { void _onRequest() { final scope = _scope; if (scope == null || !scope.requests.take(scope.sessionId)) return; + final before = FocusManager.instance.primaryFocus; SchedulerBinding.instance ..addPostFrameCallback((_) { - if (!_disposed && canFocus()) focus.requestFocus(); + if (!_disposed && _focusIsFree(before) && canFocus()) { + focus.requestFocus(); + } }) ..ensureVisualUpdate(); } + /// False when, since the request, another control took focus (the + /// operator moved on before the chat was built); the composer then leaves + /// it there. + bool _focusIsFree(FocusNode? before) { + final current = FocusManager.instance.primaryFocus; + return current == null || + current == before || + current == focus || + current is FocusScopeNode; + } + void dispose() { _disposed = true; _scope?.requests.removeListener(_onRequest); diff --git a/app/lib/features/chat/conversation/composer_selection_focus.dart b/app/lib/features/chat/conversation/composer_selection_focus.dart new file mode 100644 index 00000000..58e929ba --- /dev/null +++ b/app/lib/features/chat/conversation/composer_selection_focus.dart @@ -0,0 +1,52 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; + +import '../../../core/api_gateway.dart'; + +/// Whether choosing a chat (a row tap or click, Next chat, a created chat) +/// puts the keyboard in its composer, as Ctrl+1…Ctrl+9 always does. +/// +/// Desktop hosts (native or a desktop browser, whatever the window width) +/// focus it. Phones and tablets do not, since focusing would raise the +/// on-screen keyboard over the transcript, unless the choice was made with a +/// mouse or trackpad, which means hardware input is attached. On the web the +/// platform comes from the browser, so a mobile browser counts as mobile. +/// A closed chat is only read, so its composer is left alone. +bool chatSelectionFocusesComposer( + JsonMap session, { + TargetPlatform? platform, + PointerDeviceKind? pointer, +}) { + if (session['closed_at'] != null || session['closed'] == true) return false; + final desktop = switch (platform ?? defaultTargetPlatform) { + TargetPlatform.macOS || + TargetPlatform.windows || + TargetPlatform.linux => true, + _ => false, + }; + if (desktop) return true; + final kind = pointer ?? LastPointerKind.instance.kind; + return kind == PointerDeviceKind.mouse || kind == PointerDeviceKind.trackpad; +} + +/// The kind of the latest pointer press anywhere in the app, so a choice +/// made through a plain callback can tell a mouse click from a finger tap. +class LastPointerKind { + LastPointerKind._() { + GestureBinding.instance.pointerRouter.addGlobalRoute(_route); + } + + static LastPointerKind? _instance; + + /// Starts listening on first use; call once early (the Chat destination + /// does) so the press that makes the first choice is seen. + static LastPointerKind get instance => _instance ??= LastPointerKind._(); + + PointerDeviceKind? kind; + + void _route(PointerEvent event) { + if (event is PointerDownEvent || event is PointerPanZoomStartEvent) { + kind = event.kind; + } + } +} diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 5ac58d51..bd2e5b32 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -15,6 +15,7 @@ import 'conversation/chat_scroll.dart'; import 'conversation/chat_thread_view.dart'; import 'conversation/chat_transcript_cache.dart'; import 'conversation/composer_focus_request.dart'; +import 'conversation/composer_selection_focus.dart'; import 'data/chat_repository.dart'; import 'domain/chat_commands.dart'; import 'domain/chat_cycle.dart'; @@ -95,7 +96,8 @@ class _ChatScreenState extends State { String? _standaloneSelection; - /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer. + /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a + /// chat does too where [chatSelectionFocusesComposer] allows. final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); /// The list's folded sections, kept here so Next chat counts the rows the @@ -109,6 +111,8 @@ class _ChatScreenState extends State { @override void initState() { super.initState(); + // Seen from now on, so the press that chooses the first chat counts. + LastPointerKind.instance; _sessions.addListener(_nextChanged); _folds.addListener(_nextChanged); } @@ -124,7 +128,7 @@ class _ChatScreenState extends State { /// Next chat opens that row exactly as a tap on it would. void _openNext(String id) { final next = _nextAfter(id); - if (next != null) _open(next); + if (next != null) _openBySelection(next); } void _nextChanged() { @@ -153,6 +157,12 @@ class _ChatScreenState extends State { /// also when it is the chat already open. void _openByShortcut(JsonMap session) => _open(session, focusComposer: true); + /// Opens [session] chosen by a tap, click or Next chat: its composer takes + /// focus on a desktop host or after a mouse click, not from a finger on a + /// phone or tablet (see [chatSelectionFocusesComposer]). + void _openBySelection(JsonMap session) => + _open(session, focusComposer: chatSelectionFocusesComposer(session)); + void _open(JsonMap session, {bool focusComposer = false}) { final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; @@ -370,7 +380,7 @@ class _ChatScreenState extends State { syncToken: widget.syncToken, controller: _sessions, folds: _folds, - onOpen: _open, + onOpen: _openBySelection, onShortcutOpen: _openByShortcut, onSessions: _adoptRows, activeSessionId: selected, diff --git a/app/test/features/chat/chat_selection_focus_test.dart b/app/test/features/chat/chat_selection_focus_test.dart new file mode 100644 index 00000000..54699bba --- /dev/null +++ b/app/test/features/chat/chat_selection_focus_test.dart @@ -0,0 +1,198 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/composer_selection_focus.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +/// The list shows Starred (apple), then Chats (Recent, Second), then Closed. +const _rows = [ + {'id': 'r', 'title': 'Recent', 'directory': '/w'}, + {'id': 'c', 'title': 'Done', 'directory': '/w', 'closed_at': 1}, + {'id': 's', 'title': 'Second', 'directory': '/w'}, + {'id': 'a', 'title': 'apple', 'directory': '/w', 'starred': true}, +]; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final row in _rows) {...row}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Future _pump(WidgetTester tester, Size size) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + final route = ValueNotifier(null); + addTearDown(route.dispose); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ValueListenableBuilder( + valueListenable: route, + builder: (context, id, _) => ChatScreen( + gateway: gateway, + initialSessionId: id, + onSessionSelected: (next) => route.value = next, + onBack: () => route.value = null, + ), + ), + }, + ), + ), + ); + await tester.pumpAndSettle(); +} + +Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id')); + +bool _composerFocused(WidgetTester tester, String id) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey('chat-composer-$id')), + matching: find.byType(EditableText), + ), + ) + .focusNode + .hasPrimaryFocus; + +Future _tap( + WidgetTester tester, + Finder finder, { + PointerDeviceKind kind = PointerDeviceKind.touch, +}) async { + await tester.tap(finder, kind: kind); + await tester.pumpAndSettle(); +} + +Finder _row(String id) => find.byKey(Key('chat-row-$id')); +final _next = find.byKey(const Key('chat-next')); + +final _desktop = TargetPlatformVariant.only(TargetPlatform.macOS); +final _mobile = TargetPlatformVariant.only(TargetPlatform.android); + +void main() { + testWidgets( + 'desktop, wide: a clicked row and Next chat focus the composer', + (tester) async { + await _pump(tester, const Size(1280, 800)); + await _tap(tester, _row('r'), kind: PointerDeviceKind.mouse); + expect(_thread('r'), findsOneWidget); + expect(_composerFocused(tester, 'r'), isTrue); + + // Focus elsewhere, then the chat already open: clicking returns it. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + await _tap(tester, _row('r'), kind: PointerDeviceKind.mouse); + expect(_composerFocused(tester, 'r'), isTrue); + + await _tap(tester, _next, kind: PointerDeviceKind.mouse); + expect(_thread('s'), findsOneWidget); + expect(_composerFocused(tester, 's'), isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + }, + variant: _desktop, + ); + + testWidgets( + 'desktop, narrow window: a tapped row focuses the chat page composer', + (tester) async { + await _pump(tester, const Size(390, 844)); + await _tap(tester, find.text('Second')); + expect(_thread('s'), findsOneWidget); + expect(_composerFocused(tester, 's'), isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + }, + variant: _desktop, + ); + + testWidgets( + 'desktop: a closed chat leaves its composer unfocused', + (tester) async { + await _pump(tester, const Size(1280, 800)); + await _tap(tester, find.text('Closed')); + await _tap(tester, _row('c'), kind: PointerDeviceKind.mouse); + expect(_thread('c'), findsOneWidget); + expect(_composerFocused(tester, 'c'), isFalse); + await tester.pumpWidget(const SizedBox.shrink()); + }, + variant: _desktop, + ); + + testWidgets( + 'mobile: a finger tap and Next chat do not raise the keyboard', + (tester) async { + await _pump(tester, const Size(390, 844)); + await _tap(tester, find.text('Recent')); + expect(_thread('r'), findsOneWidget); + expect(_composerFocused(tester, 'r'), isFalse); + await _tap(tester, _next); + expect(_thread('s'), findsOneWidget); + expect(_composerFocused(tester, 's'), isFalse); + await tester.pumpWidget(const SizedBox.shrink()); + }, + variant: _mobile, + ); + + testWidgets( + 'mobile, wide: a touch tap leaves focus, a mouse click focuses', + (tester) async { + await _pump(tester, const Size(1280, 800)); + await _tap(tester, _row('r')); + expect(_composerFocused(tester, 'r'), isFalse); + await _tap(tester, _row('s'), kind: PointerDeviceKind.mouse); + expect(_composerFocused(tester, 's'), isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + }, + variant: _mobile, + ); + + test('the rule: desktop or a mouse, never a closed chat', () { + const open = {'id': 'x'}; + const closed = {'id': 'x', 'closed_at': 1}; + for (final platform in TargetPlatform.values) { + final desktop = { + TargetPlatform.macOS, + TargetPlatform.windows, + TargetPlatform.linux, + }.contains(platform); + for (final kind in PointerDeviceKind.values) { + final mouse = + kind == PointerDeviceKind.mouse || + kind == PointerDeviceKind.trackpad; + expect( + chatSelectionFocusesComposer(open, platform: platform, pointer: kind), + desktop || mouse, + reason: '$platform $kind', + ); + expect( + chatSelectionFocusesComposer( + closed, + platform: platform, + pointer: kind, + ), + isFalse, + ); + } + } + }); +}