Return focus to the chat composer when the desktop window comes back

On web the engine closes the text connection on the editing element's blur,
which the browser fires just before the window blur, so the field is already
unfocused when lifecycle inactive arrives and FocusManager's own suspend and
resume restores only the route scope. Remember whether the composer held (or
had just lost) focus when the window left, and refocus it on resume, keeping
the caret and selection, unless another control took focus or a dialog,
sheet or route covers the chat. Desktop hosts only, so phones never get an
unasked on-screen keyboard.
This commit is contained in:
2026-10-31 22:16:21 +00:00
parent 063c1144a1
commit 7ec92e1de5
4 changed files with 487 additions and 0 deletions
@@ -23,6 +23,7 @@ import 'chat_composer_controller.dart';
import '../ui/transcript/chat_attachment_frame.dart';
import '../../../ui/adaptive/glass_pill.dart';
import 'chat_reading_width.dart';
import 'composer_focus_restore.dart';
/// The composer's placeholder when the chat names no working directory.
const String chatComposerPlaceholder = 'Message the agent';
@@ -136,6 +137,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
text: widget.composer.draft,
);
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
late final ComposerFocusRestorer _focusRestorer;
final ChatAttachmentDraft _attachments = ChatAttachmentDraft();
/// The picked bytes behind each chip, positionally aligned with the draft's
@@ -176,11 +178,22 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
@override
void initState() {
super.initState();
_focusRestorer = ComposerFocusRestorer(
focus: _focus,
canRestore: _composerIsCurrent,
);
widget.composer.addListener(_syncDraft);
_listenForPaste();
unawaited(widget.composer.loadDraft());
}
/// Whether the composer is still where the operator works: mounted, shown,
/// and not covered by a dialog, sheet or another pushed route.
bool _composerIsCurrent() =>
mounted &&
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
@override
void didUpdateWidget(covariant ChatComposerBar oldWidget) {
super.didUpdateWidget(oldWidget);
@@ -603,6 +616,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
void dispose() {
_stopListeningForPaste();
widget.composer.removeListener(_syncDraft);
_focusRestorer.dispose();
_text.dispose();
_focus.dispose();
super.dispose();
@@ -0,0 +1,85 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// How long before the window loses focus a composer blur still counts as
/// caused by that switch. The web engine closes the text connection (and so
/// unfocuses the field) on the input's own `blur`, which the browser fires
/// just before the window's `blur` that Flutter reports as `inactive`.
const Duration composerBlurGrace = Duration(milliseconds: 250);
/// Whether this host restores composer focus when its window comes back.
/// Only desktop hosts (native or a desktop browser): on phones, focusing the
/// field on resume would pop the on-screen keyboard unasked.
bool get composerFocusRestoreSupported => switch (defaultTargetPlatform) {
TargetPlatform.macOS ||
TargetPlatform.windows ||
TargetPlatform.linux => true,
_ => false,
};
/// Returns focus to the composer [focus] when the app window regains focus,
/// if the composer held it when the window lost it, like chat web apps do.
///
/// On web the engine reports window `blur` as [AppLifecycleState.inactive]
/// and window `focus` (or the tab becoming visible) as `resumed`. Nothing is
/// restored when, by then, another control holds focus or [canRestore] says
/// the composer is no longer the operator's place (a dialog, sheet or other
/// route covers it). The text controller keeps the caret and selection while
/// unfocused, so requesting focus puts them back as they were.
class ComposerFocusRestorer {
ComposerFocusRestorer({
required this.focus,
required this.canRestore,
bool? enabled,
DateTime Function()? now,
}) : _now = now ?? DateTime.now {
if (!(enabled ?? composerFocusRestoreSupported)) return;
focus.addListener(_onFocusChange);
_listener = AppLifecycleListener(onStateChange: _onStateChange);
}
final FocusNode focus;
final bool Function() canRestore;
final DateTime Function() _now;
AppLifecycleListener? _listener;
bool _away = false;
bool _restore = false;
DateTime? _blurredAt;
void _onFocusChange() {
_blurredAt = focus.hasPrimaryFocus ? null : _now();
}
bool get _blurredJustNow {
final at = _blurredAt;
return at != null && _now().difference(at) <= composerBlurGrace;
}
void _onStateChange(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) {
// Only the first step away from resumed decides; later inactive/hidden
// steps of the same absence must not overwrite it.
if (!_away) {
_away = true;
_restore = focus.hasPrimaryFocus || _blurredJustNow;
}
return;
}
final restore = _away && _restore;
_away = false;
_restore = false;
if (restore && _focusIsFree && canRestore()) focus.requestFocus();
}
/// True when no other control took focus while the window was away.
bool get _focusIsFree {
final current = FocusManager.instance.primaryFocus;
return current == null || current == focus || current is FocusScopeNode;
}
void dispose() {
_listener?.dispose();
if (_listener != null) focus.removeListener(_onFocusChange);
}
}