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); } }