import 'package:flutter/widgets.dart'; import 'destination.dart'; import 'shell_bar.dart'; /// The mounted Search screen publishes its field focus without clearing query /// state. The shell requests it after switching destinations has settled. class ShellSearchFocus { Object? _owner; VoidCallback? _focus; bool Function()? _hasFocus; bool get available => _focus != null; bool get focused => _hasFocus?.call() ?? false; void request() => _focus?.call(); void _set(Object owner, VoidCallback focus, bool Function() hasFocus) { _owner = owner; _focus = focus; _hasFocus = hasFocus; } void _clear(Object owner) { if (_owner != owner) return; _owner = null; _focus = null; _hasFocus = null; } } class ShellSearchShortcut extends StatefulWidget { const ShellSearchShortcut({ super.key, required this.onFocus, required this.hasFocus, required this.child, }); final VoidCallback onFocus; final bool Function() hasFocus; final Widget child; @override State createState() => _ShellSearchShortcutState(); } class _ShellSearchShortcutState extends State { final _owner = Object(); ShellBarScope? _scope; @override void didChangeDependencies() { super.didChangeDependencies(); final scope = ShellBarScope.maybeOf(context); if (scope == _scope) return; _scope?.registry.searchFocus._clear(_owner); _scope = scope; if (scope?.destination == AppDestination.search) { scope!.registry.searchFocus._set( _owner, () => widget.onFocus(), () => widget.hasFocus(), ); } } @override void dispose() { _scope?.registry.searchFocus._clear(_owner); super.dispose(); } @override Widget build(BuildContext context) => widget.child; }