Merge: Ctrl+1-9 focuses the opened chat's composer

This commit is contained in:
2026-11-03 12:45:14 +00:00
7 changed files with 209 additions and 8 deletions
@@ -24,6 +24,7 @@ import '../ui/transcript/chat_attachment_frame.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/glass_pill.dart';
import 'chat_reading_width.dart';
import 'composer_focus_request.dart';
import 'composer_focus_restore.dart';
/// The composer's placeholder when the chat names no working directory.
@@ -143,6 +144,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// view as soon as it exists (see [_revealCaretLine]).
final ScrollController _fieldScroll = ScrollController();
late final ComposerFocusRestorer _focusRestorer;
late final ComposerFocusRequestListener _focusRequests =
ComposerFocusRequestListener(focus: _focus, canFocus: _composerIsCurrent);
final ChatAttachmentDraft _attachments = ChatAttachmentDraft();
/// The picked bytes behind each chip, positionally aligned with the draft's
@@ -192,6 +195,12 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
unawaited(widget.composer.loadDraft());
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_focusRequests.attach(context);
}
/// Whether the composer is still where the operator works: mounted, shown,
/// and not covered by a dialog, sheet or another pushed route.
bool _composerIsCurrent() =>
@@ -638,6 +647,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
_stopListeningForPaste();
widget.composer.removeListener(_syncDraft);
_focusRestorer.dispose();
_focusRequests.dispose();
_text.dispose();
_focus.dispose();
_fieldScroll.dispose();
@@ -0,0 +1,90 @@
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
/// One pending request to give a chat's composer keyboard focus, made when
/// the operator opens that chat from the keyboard (Ctrl+1…Ctrl+9) so they can
/// type at once. The composer takes it once it is built: at once when the
/// chat is already open, after the switch when the detail pane or page still
/// has to build it. A tap or any other way of opening a chat cancels it, so
/// only the keyboard path moves focus.
class ChatComposerFocusRequests extends ChangeNotifier {
String? _pending;
/// Asks the composer of [sessionId] to take focus once it is built.
void request(String sessionId) {
_pending = sessionId;
notifyListeners();
}
/// Drops a request no composer has taken yet.
void cancel() => _pending = null;
/// Consumes the request when it names [sessionId]; true when it did.
bool take(String sessionId) {
if (_pending != sessionId) return false;
_pending = null;
return true;
}
}
/// Tells the composer below which chat it belongs to and where its focus
/// requests come from. The Chat destination wraps each open conversation in
/// one; a composer outside it never takes focus on its own.
class ChatComposerFocusScope extends InheritedWidget {
const ChatComposerFocusScope({
super.key,
required this.sessionId,
required this.requests,
required super.child,
});
final String sessionId;
final ChatComposerFocusRequests requests;
static ChatComposerFocusScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ChatComposerFocusScope>();
@override
bool updateShouldNotify(ChatComposerFocusScope oldWidget) =>
sessionId != oldWidget.sessionId || requests != oldWidget.requests;
}
/// Connects a composer's [focus] to the nearest [ChatComposerFocusScope]:
/// a request for its chat focuses it after the current frame, so the switch
/// (a new detail pane or page and its route focus) has settled first.
/// [canFocus] says whether the composer is still the operator's place then.
class ComposerFocusRequestListener {
ComposerFocusRequestListener({required this.focus, required this.canFocus});
final FocusNode focus;
final bool Function() canFocus;
ChatComposerFocusScope? _scope;
bool _disposed = false;
/// Call from the composer's `didChangeDependencies`.
void attach(BuildContext context) {
final scope = ChatComposerFocusScope.maybeOf(context);
if (scope?.requests != _scope?.requests) {
_scope?.requests.removeListener(_onRequest);
scope?.requests.addListener(_onRequest);
}
_scope = scope;
_onRequest();
}
void _onRequest() {
final scope = _scope;
if (scope == null || !scope.requests.take(scope.sessionId)) return;
SchedulerBinding.instance
..addPostFrameCallback((_) {
if (!_disposed && canFocus()) focus.requestFocus();
})
..ensureVisualUpdate();
}
void dispose() {
_disposed = true;
_scope?.requests.removeListener(_onRequest);
_scope = null;
}
}
+23 -2
View File
@@ -13,6 +13,7 @@ import 'conversation/chat_row_widgets.dart';
import 'conversation/chat_scroll.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/chat_transcript_cache.dart';
import 'conversation/composer_focus_request.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'ui/sessions/chat_sessions_screen.dart';
@@ -90,15 +91,27 @@ class _ChatScreenState extends State<ChatScreen> {
String? _standaloneSelection;
/// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer.
final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests();
String? get _selected {
final routed = widget.initialSessionId;
if (routed != null && routed.isNotEmpty) return routed;
return _standaloneSelection;
}
void _open(JsonMap session) {
/// Opens [session] from the keyboard: its composer takes focus once built,
/// also when it is the chat already open.
void _openByShortcut(JsonMap session) => _open(session, focusComposer: true);
void _open(JsonMap session, {bool focusComposer = false}) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
if (focusComposer) {
_composerFocus.request(id);
} else {
_composerFocus.cancel();
}
_openedSessions[id] = session;
if (_startNotice?.id != id) _startNotice = null;
final select = widget.onSessionSelected;
@@ -206,6 +219,7 @@ class _ChatScreenState extends State<ChatScreen> {
void _back() {
_startNotice = null;
_composerFocus.cancel();
final back = widget.onBack;
if (back != null) {
back();
@@ -228,13 +242,14 @@ class _ChatScreenState extends State<ChatScreen> {
void dispose() {
_page.dispose();
_sessions.dispose();
_composerFocus.dispose();
super.dispose();
}
Widget _thread(String selected, VoidCallback onBack) {
final row = _rowFor(selected);
final start = _startNotice;
return ChatThreadView(
final thread = ChatThreadView(
key: ValueKey<String>('chat-session-$selected'),
gateway: widget.gateway,
sessionId: selected,
@@ -254,6 +269,11 @@ class _ChatScreenState extends State<ChatScreen> {
onSessionClosed: _closed,
onColorSelected: (color) => _sessions.setColor(selected, color),
);
return ChatComposerFocusScope(
sessionId: selected,
requests: _composerFocus,
child: thread,
);
}
@override
@@ -280,6 +300,7 @@ class _ChatScreenState extends State<ChatScreen> {
syncToken: widget.syncToken,
controller: _sessions,
onOpen: _open,
onShortcutOpen: _openByShortcut,
onSessions: _adoptRows,
activeSessionId: selected,
publishShellBar: true,
@@ -27,6 +27,7 @@ class ChatSessionsScreen extends StatefulWidget {
super.key,
required this.gateway,
required this.onOpen,
this.onShortcutOpen,
this.embedded = false,
this.syncToken = 0,
this.onSessions,
@@ -38,6 +39,10 @@ class ChatSessionsScreen extends StatefulWidget {
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
/// Opens a row the shell's Ctrl+1…Ctrl+9 named, so the destination can put
/// the keyboard in its composer; null opens it like a tap ([onOpen]).
final void Function(JsonMap session)? onShortcutOpen;
/// True under the application shell, which owns the single navigation bar.
final bool embedded;
@@ -174,10 +179,11 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
if (session != null && mounted) widget.onOpen(session);
}
void _open(JsonMap session) {
void _open(JsonMap session, {bool byShortcut = false}) {
_markedActiveSessionId = _sessionId(session);
unawaited(_controller.markOpened(session));
widget.onOpen(session);
final open = byShortcut ? widget.onShortcutOpen : null;
(open ?? widget.onOpen)(session);
}
// Methods rather than closures, so the list's memoized rows see the same
@@ -203,7 +209,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
isOpen: _folds.isOpen,
);
if (index < 0 || index >= rows.length) return false;
_open(rows[index]);
_open(rows[index], byShortcut: true);
return true;
}
@@ -82,6 +82,20 @@ Future<void> _ctrl(WidgetTester tester, LogicalKeyboardKey digit) async {
Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id'));
EditableText _composer(WidgetTester tester, String id) =>
tester.widget<EditableText>(
find.descendant(
of: find.byKey(ValueKey('chat-composer-$id')),
matching: find.byType(EditableText),
),
);
bool _composerFocused(WidgetTester tester, String id) =>
_composer(tester, id).focusNode.hasPrimaryFocus;
String _composerText(WidgetTester tester, String id) =>
_composer(tester, id).controller.text;
void main() {
testWidgets('starred chats lead the list alphabetically', (tester) async {
await _pumpShell(tester, const Size(1280, 800));
@@ -122,6 +136,51 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Ctrl+N puts the keyboard in the opened chat\'s composer', (
tester,
) async {
await _pumpShell(tester, const Size(1280, 800));
// A tap opens a chat without moving focus into its composer.
await tester.tap(find.byKey(const Key('chat-row-r')));
await tester.pumpAndSettle();
expect(_thread('r'), findsOneWidget);
expect(_composerFocused(tester, 'r'), isFalse);
// From the keyboard another chat opens with its composer focused, and
// typing lands there at once.
await _ctrl(tester, LogicalKeyboardKey.digit2);
expect(_thread('z'), findsOneWidget);
expect(_composerFocused(tester, 'z'), isTrue);
// The text connection the focused field opened receives the typing.
tester.testTextInput.enterText('h');
await tester.pump();
expect(_composerText(tester, 'z'), 'h');
// The chat already open: focus returns from elsewhere to its composer.
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
expect(_composerFocused(tester, 'z'), isFalse);
await _ctrl(tester, LogicalKeyboardKey.digit2);
expect(_composerFocused(tester, 'z'), isTrue);
// A later tap on another row leaves focus alone.
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_thread('a'), findsOneWidget);
expect(_composerFocused(tester, 'a'), isFalse);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Ctrl+N focuses the composer of the chat page on a phone', (
tester,
) async {
await _pumpShell(tester, const Size(390, 844));
await _ctrl(tester, LogicalKeyboardKey.digit3);
expect(_thread('r'), findsOneWidget);
expect(_composerFocused(tester, 'r'), isTrue);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Ctrl+N opens the chat as its own page on a phone', (
tester,
) async {
+1 -1
View File
@@ -45,7 +45,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `click=<target>` | click the centre of the target, then wait `--wait` ms (default 1000) |
| `waitfor=<target>` | wait up to 10 s for the target to appear |
| `type=text` | type into the focused field (or the first visible one) |
| `press=Enter` | press a key: Enter, Escape, Tab, Backspace, ArrowUp or ArrowDown |
| `press=Enter` | press a key: Enter, Escape, Tab, Backspace, ArrowUp, ArrowDown, a letter or a digit, optionally after `Control+`, `Shift+`, `Alt+` or `Meta+` (`press=Control+2`) |
| `scroll=600` | scroll with the mouse wheel at the centre (JSON `at` sets a target, `dx` a horizontal delta, `repeat` and `gap` a run of ticks) |
| `hover=<target>` | move the mouse onto the target without pressing (hover states) |
| `drag=<target>>dx,dy` | press on the target, move by dx,dy in `steps` (12) moves `gap` (16) ms apart, release (JSON `dx`, `dy`, `steps`, `gap`; `hold: true` keeps the button down to capture mid-drag) |
+17 -2
View File
@@ -127,11 +127,26 @@ export function flutterPage(browser, log) {
if (!focused) throw new Error('No text field to type into; click the field first');
await send('Input.insertText', { text });
},
async press(key) {
/** Presses [chord]: a key, optionally after `Control+`, `Shift+`, `Alt+` or `Meta+` (e.g. `Control+2`). */
async press(chord) {
const parts = String(chord).split('+');
const key = parts.pop();
const bits = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
const modifiers = parts.reduce((m, p) => m | (bits[p] ?? 0), 0);
const codes = { Enter: 13, Escape: 27, Tab: 9, Backspace: 8, ArrowDown: 40, ArrowUp: 38 };
const base = { key, code: key, windowsVirtualKeyCode: codes[key] ?? 0, text: key === 'Enter' ? '\r' : undefined };
const digit = /^\d$/.test(key);
const code = digit ? `Digit${key}` : /^[a-z]$/i.test(key) ? `Key${key.toUpperCase()}` : key;
const vk = codes[key] ?? (key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0);
const text = key === 'Enter' ? '\r' : key.length === 1 && !modifiers ? key : undefined;
const base = { key, code, windowsVirtualKeyCode: vk, modifiers, text };
for (const p of parts) {
await send('Input.dispatchKeyEvent', { type: 'keyDown', key: p, code: `${p}Left`, modifiers });
}
await send('Input.dispatchKeyEvent', { type: 'keyDown', ...base });
await send('Input.dispatchKeyEvent', { type: 'keyUp', ...base, text: undefined });
for (const p of parts.reverse()) {
await send('Input.dispatchKeyEvent', { type: 'keyUp', key: p, code: `${p}Left`, modifiers: 0 });
}
},
/** Wheel ticks at [target] (default the centre): [repeat] events of dx/dy each, [gap] ms apart. */
async scroll(dy, target, { dx = 0, repeat = 1, gap = 16 } = {}) {