import 'package:flutter/widgets.dart'; /// The floating windows' keyboard focus: each window has a focus scope; the /// window that shows or comes to the top takes the keyboard, and when the /// last one hides it goes back to what had it before (a composer, a field), /// else to the screen. class WindowFocus { final Map _scopes = {}; FocusNode? _previous; FocusScopeNode scopeFor(String id) => _scopes[id] ??= FocusScopeNode(debugLabel: 'window $id'); /// Forgets the scopes of windows no longer in [ids]. void retain(Set ids) { for (final id in _scopes.keys.where((id) => !ids.contains(id)).toList()) { _scopes.remove(id)!.dispose(); } } bool _within(FocusNode node, FocusScopeNode scope) => identical(node, scope) || node.ancestors.contains(scope); /// Whether [id]'s window has the keyboard. bool has(String id) { final current = FocusManager.instance.primaryFocus; final scope = _scopes[id]; return current != null && scope != null && _within(current, scope); } /// The window that has the keyboard, if one does. String? get focused => _scopes.keys.where(has).firstOrNull; /// Notes what has the keyboard now, before a window takes it. void remember() { final current = FocusManager.instance.primaryFocus; if (current == null || focused != null) return; _previous = identical(current, FocusManager.instance.rootScope) ? null : current; } /// Whether something covers the windows and owns the keyboard (a sheet, /// dialog or page over the app); set by the host. bool Function()? covered; /// Focuses [id]'s window once this frame has built it, unless a popup the /// same press opened has covered the windows meanwhile. void focusSoon(String id) { WidgetsBinding.instance ..addPostFrameCallback((_) { if (covered?.call() ?? false) return; focusNow(id); }) ..ensureVisualUpdate(); } /// Focuses [id]'s window if it is built. void focusNow(String id) { final scope = _scopes[id]; if (scope != null && scope.context != null && scope.canRequestFocus) { scope.requestFocus(); } } /// Gives the keyboard back to what had it before the windows showed, if /// a window has it now. void release() { final previous = _previous; _previous = null; final current = FocusManager.instance.primaryFocus; if (current == null || focused == null) return; if (previous != null && previous.context != null && previous.canRequestFocus) { previous.requestFocus(); } else { current.unfocus(); } } void dispose() { for (final scope in _scopes.values) { scope.dispose(); } _scopes.clear(); } }