import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; import '../../shell/shell_bar.dart'; import '../../shell/shell_search_focus.dart'; import '../../ui/adaptive/segmented_bar.dart'; import 'data/search_repository.dart'; import 'domain/search_controller.dart'; import 'domain/search_row.dart'; import 'ui/material_search_body.dart'; import 'ui/search_bar_controls.dart'; import 'ui/search_bounds_note.dart'; import 'ui/search_result_view.dart'; /// Native omni-search over the Pipelines server: the search field, a compact /// kind menu and the syntax help as the top bar's main pill (no title), and a /// flat result list whose rows open the server's own target through [onOpen]. /// The screen never mutates server state and never guesses a route for an /// unknown or targetless hit. class SearchScreen extends StatefulWidget { const SearchScreen({ super.key, required this.gateway, required this.onOpen, this.embedded = false, }); final ApiGateway gateway; final ValueChanged onOpen; /// True as the Search tab: the controls go into the shell's bar. final bool embedded; @override State createState() => _SearchScreenState(); } class _SearchScreenState extends State { late final OmniSearchController _controller; late final TextEditingController _text; final FocusNode _focus = FocusNode(debugLabel: 'omni-search'); final Map _rowKeys = {}; var _selectedIndex = 0; String _resultIdentity = ''; @override void initState() { super.initState(); _controller = OmniSearchController( repository: SearchRepository(widget.gateway), ); _text = TextEditingController(); _controller.addListener(_onState); } void _onState() { final query = _controller.query; if (_text.text != query) { _text.value = TextEditingValue( text: query, selection: TextSelection.collapsed(offset: query.length), ); } final identity = jsonEncode({ 'query': _controller.parsed.query, 'kind': _controller.parsed.kind.wire, 'results': _results, }); if (identity != _resultIdentity) { _resultIdentity = identity; _selectedIndex = 0; } if (mounted) setState(() {}); } List get _results => [ ..._controller.shownChats, ..._controller.shownResults, ]; KeyEventResult _handleFieldKey(FocusNode _, KeyEvent event) { if (event is! KeyDownEvent && event is! KeyRepeatEvent) { return KeyEventResult.ignored; } final key = event.logicalKey; var delta = 0; final keyboard = HardwareKeyboard.instance; if (!keyboard.isAltPressed && !keyboard.isMetaPressed && !keyboard.isShiftPressed && (key == LogicalKeyboardKey.arrowDown || (keyboard.isControlPressed && key == LogicalKeyboardKey.keyN))) { delta = 1; } else if (!keyboard.isAltPressed && !keyboard.isMetaPressed && !keyboard.isShiftPressed && (key == LogicalKeyboardKey.arrowUp || (keyboard.isControlPressed && key == LogicalKeyboardKey.keyP))) { delta = -1; } else if (key == LogicalKeyboardKey.enter && _results.isNotEmpty) { final hit = _results[_selectedIndex.clamp(0, _results.length - 1)]; if (searchRowView(hit, _controller.parsed.query).openable) { widget.onOpen(hit); } return KeyEventResult.handled; } else { return KeyEventResult.ignored; } if (_results.isEmpty) return KeyEventResult.handled; final next = (_selectedIndex + delta).clamp(0, _results.length - 1); if (next == _selectedIndex) return KeyEventResult.handled; setState(() => _selectedIndex = next); WidgetsBinding.instance.addPostFrameCallback((_) { final context = _rowKeys[next]?.currentContext; if (context != null) Scrollable.ensureVisible(context); }); return KeyEventResult.handled; } void _clear() { _text.clear(); _controller.updateQuery(''); } @override void dispose() { _controller.removeListener(_onState); _controller.dispose(); _text.dispose(); _focus.dispose(); super.dispose(); } bool get _activeSearch { final scope = ShellBarScope.maybeOf(context); return scope == null || scope.registry.focus == null || scope.registry.focus == scope.destination; } void _focusSearch() { final before = FocusManager.instance.primaryFocus; // The shell moves Search's field into its bar after changing tabs. End an // old browser edit only after that layout, then hand focus to the mounted // field. Ordinary query changes never reset focus or the input connection. WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || !_activeSearch || !_focus.canRequestFocus) return; final current = FocusManager.instance.primaryFocus; if (current != null && current != before && current != _focus && current is! FocusScopeNode) { return; } _focus.unfocus(); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted || !_activeSearch || !_focus.canRequestFocus) return; final current = FocusManager.instance.primaryFocus; if (current == null || current == _focus || current == before || current is FocusScopeNode) { _focus.requestFocus(); } }); WidgetsBinding.instance.ensureVisualUpdate(); }); WidgetsBinding.instance.ensureVisualUpdate(); } @override Widget build(BuildContext context) => ShellSearchShortcut( onFocus: _focusSearch, hasFocus: () => _focus.hasPrimaryFocus, child: _build(context), ); Widget _build(BuildContext context) { if (widget.embedded) { // The shell's bar carries the controls; without a shell (a bare embed) // they lead the results instead. if (!ShellBar.available(context)) { return _body(controls: _controls()); } // The field takes the title's place and fills the bar. return ShellBar(titleWidget: _controls(), child: _body()); } final bar = SegmentedBar(title: 'Search', titleWidget: _controls()); return Scaffold(extendBodyBehindAppBar: true, appBar: bar, body: _body()); } Widget _controls() => SearchBarControls( focusNode: _focus, text: _text, kind: _controller.parsed.kind, onChanged: _controller.updateQuery, onSubmitted: _controller.submit, onCleared: _clear, onKind: _controller.selectKind, onKeyEvent: _handleFieldKey, ); /// The server's result and scan bounds, only when they cut the answer /// short: a complete answer needs no statistics. Widget _header({Widget? controls}) { final bounds = _controller.truncated ? _controller.boundsText : null; if (bounds == null && controls == null) return const SizedBox.shrink(); return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, spacing: 8, children: [ ?controls, if (bounds != null) SearchBoundsNote(key: searchBoundsKey, text: bounds), ], ), ); } /// No top safe area: the results run behind the floating bar and the /// scroll view starts them below it. Widget _body({Widget? controls}) { final header = _header(controls: controls); return SearchArtifactScope( gateway: widget.gateway, onOpen: widget.onOpen, child: MaterialSearchBody( controller: _controller, query: _controller.parsed.query, onOpen: widget.onOpen, header: header, selectedIndex: _selectedIndex, rowKeys: _rowKeys, ), ); } }