import 'package:flutter/widgets.dart'; /// The terminal surface's keyboard focus: the selected terminal takes it /// whenever the terminal shows (or its tab changes), and hiding gives it back /// to what had it before (the chat composer, a field), else to the screen. class TerminalFocus { /// The scope around the selected terminal (see `TerminalBody.focus`). Its /// emulator autofocuses inside it, so focusing the scope focuses it. final FocusScopeNode scope = FocusScopeNode(debugLabel: 'terminal'); FocusNode? _previous; bool _inside(FocusNode node) => identical(node, scope) || node.ancestors.contains(scope); /// Notes what has the keyboard now, before the terminal takes it. void remember() { final current = FocusManager.instance.primaryFocus; if (current == null || _inside(current)) return; _previous = identical(current, FocusManager.instance.rootScope) ? null : current; } /// Focuses the selected terminal once this frame has built it. void focusSoon() { WidgetsBinding.instance ..addPostFrameCallback((_) { if (scope.context != null && scope.canRequestFocus) { scope.requestFocus(); } }) ..ensureVisualUpdate(); } /// Gives the keyboard back to what had it before the terminal showed, if /// the terminal has it now. void release() { final previous = _previous; _previous = null; if (!scope.hasFocus) return; if (previous != null && previous.context != null && previous.canRequestFocus) { previous.requestFocus(); } else { scope.unfocus(); } } void dispose() => scope.dispose(); }