From ccc80a9a8d8cc1c6fbf98ef57d6b722263731ec6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 13 Nov 2026 15:51:00 +0000 Subject: [PATCH] Add keyboard navigation to search results Keep the search field focused while selecting results with Control or arrow keys, and open the selected result with Enter. Document the field-scoped shortcuts and cover navigation, reset, submission, and typing behavior with regression tests. --- app/lib/features/search/search_screen.dart | 63 ++++++ .../search/ui/material_search_body.dart | 6 + .../search/ui/search_bar_controls.dart | 3 + .../features/search/ui/search_result_row.dart | 14 +- .../search/ui/search_result_slivers.dart | 38 +++- .../settings/keyboard_shortcuts_registry.dart | 14 +- app/lib/ui/input/app_search_field.dart | 69 +++--- .../features/search/search_screen_test.dart | 196 ++++++++++++++++++ .../keyboard_shortcuts_cheatsheet_test.dart | 13 ++ 9 files changed, 372 insertions(+), 44 deletions(-) diff --git a/app/lib/features/search/search_screen.dart b/app/lib/features/search/search_screen.dart index 6451a7ea..e4973d9f 100644 --- a/app/lib/features/search/search_screen.dart +++ b/app/lib/features/search/search_screen.dart @@ -1,4 +1,7 @@ +import 'dart:convert'; + import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; import '../../shell/shell_bar.dart'; @@ -6,6 +9,7 @@ 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'; @@ -38,6 +42,9 @@ 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() { @@ -57,9 +64,62 @@ class _SearchScreenState extends State { 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(''); @@ -140,6 +200,7 @@ class _SearchScreenState extends State { onSubmitted: _controller.submit, onCleared: _clear, onKind: _controller.selectKind, + onKeyEvent: _handleFieldKey, ); /// The server's result and scan bounds, only when they cut the answer @@ -173,6 +234,8 @@ class _SearchScreenState extends State { query: _controller.parsed.query, onOpen: widget.onOpen, header: header, + selectedIndex: _selectedIndex, + rowKeys: _rowKeys, ), ); } diff --git a/app/lib/features/search/ui/material_search_body.dart b/app/lib/features/search/ui/material_search_body.dart index 60254304..a9e7ffb3 100644 --- a/app/lib/features/search/ui/material_search_body.dart +++ b/app/lib/features/search/ui/material_search_body.dart @@ -14,12 +14,16 @@ class MaterialSearchBody extends StatelessWidget { required this.query, required this.onOpen, required this.header, + required this.selectedIndex, + required this.rowKeys, }); final OmniSearchController controller; final String query; final ValueChanged onOpen; final Widget header; + final int selectedIndex; + final Map rowKeys; @override Widget build(BuildContext context) { @@ -55,6 +59,8 @@ class MaterialSearchBody extends StatelessWidget { query: query, onOpen: onOpen, message: (text) => _SearchMessage(message: text), + selectedIndex: selectedIndex, + rowKeys: rowKeys, ); case SearchBodyKind.empty: return [ diff --git a/app/lib/features/search/ui/search_bar_controls.dart b/app/lib/features/search/ui/search_bar_controls.dart index fba770f3..d18c5c8e 100644 --- a/app/lib/features/search/ui/search_bar_controls.dart +++ b/app/lib/features/search/ui/search_bar_controls.dart @@ -28,6 +28,7 @@ class SearchBarControls extends StatelessWidget { required this.onKind, this.autofocus = true, this.focusNode, + this.onKeyEvent, }); final TextEditingController text; @@ -38,6 +39,7 @@ class SearchBarControls extends StatelessWidget { final ValueChanged onKind; final bool autofocus; final FocusNode? focusNode; + final FocusOnKeyEventCallback? onKeyEvent; @override // The pill grows with the bar, so the field and the results share both @@ -55,6 +57,7 @@ class SearchBarControls extends StatelessWidget { controller: text, autofocus: autofocus, focusNode: focusNode, + onKeyEvent: onKeyEvent, inBar: true, placeholder: 'Search pipelines, runs, artifacts and chats', onChanged: onChanged, diff --git a/app/lib/features/search/ui/search_result_row.dart b/app/lib/features/search/ui/search_result_row.dart index 6cfd6a7d..2a4b0127 100644 --- a/app/lib/features/search/ui/search_result_row.dart +++ b/app/lib/features/search/ui/search_result_row.dart @@ -20,19 +20,26 @@ class SearchResultRow extends StatelessWidget { required this.query, required this.onOpen, this.divider = true, + this.selected = false, + this.visibilityKey, + this.rowKey, }); final JsonMap hit; final String query; final ValueChanged onOpen; final bool divider; + final bool selected; + final GlobalKey? visibilityKey; + final Key? rowKey; @override Widget build(BuildContext context) { final row = searchRowView(hit, query); final kind = '${hit['kind'] ?? ''}'; - return AppListRow( - key: ValueKey('search.result.${hit['target']}'), + final listRow = AppListRow( + key: rowKey ?? ValueKey('search.result.${hit['target']}'), + selected: selected, divider: divider, onTap: row.openable ? () => onOpen(hit) : null, leading: @@ -55,6 +62,9 @@ class SearchResultRow extends StatelessWidget { : null, menu: searchArtifactActions(context, hit), ); + return visibilityKey == null + ? listRow + : KeyedSubtree(key: visibilityKey, child: listRow); } TextSpan _line(SearchRowView row) => row.snippet == null diff --git a/app/lib/features/search/ui/search_result_slivers.dart b/app/lib/features/search/ui/search_result_slivers.dart index 7d4731fb..ff7cc211 100644 --- a/app/lib/features/search/ui/search_result_slivers.dart +++ b/app/lib/features/search/ui/search_result_slivers.dart @@ -20,19 +20,39 @@ List searchResultSlivers({ required String query, required ValueChanged onOpen, required Widget Function(String message) message, + required int selectedIndex, + required Map rowKeys, }) { final chats = controller.shownChats; final others = controller.shownResults; + final allHits = [...chats, ...others]; + final targetCounts = {}; + for (final hit in allHits) { + final target = '${hit['target'] ?? ''}'; + targetCounts[target] = (targetCounts[target] ?? 0) + 1; + } final grouped = controller.showsChatSection; final note = controller.chatsNote; - Widget rows(List hits) => SliverList.builder( + Widget rows(List hits, int offset) => SliverList.builder( itemCount: hits.length, - itemBuilder: (context, index) => SearchResultRow( - hit: hits[index], - query: query, - onOpen: onOpen, - divider: index < hits.length - 1, - ), + itemBuilder: (context, index) { + final hit = hits[index]; + final target = '${hit['target'] ?? ''}'; + final indexInResults = offset + index; + final key = rowKeys.putIfAbsent(indexInResults, GlobalKey.new); + final rowKey = target.isEmpty || targetCounts[target]! > 1 + ? ValueKey('search.result.$target.$indexInResults') + : ValueKey('search.result.$target'); + return SearchResultRow( + rowKey: rowKey, + hit: hit, + query: query, + onOpen: onOpen, + divider: index < hits.length - 1, + selected: indexInResults == selectedIndex, + visibilityKey: key, + ); + }, ); final empty = controller.emptyMessage; return [ @@ -44,7 +64,7 @@ List searchResultSlivers({ header: true, ), ), - if (chats.isNotEmpty) rows(chats), + if (chats.isNotEmpty) rows(chats, 0), if (note != null) SliverToBoxAdapter( child: Padding( @@ -60,7 +80,7 @@ List searchResultSlivers({ header: true, ), ), - if (others.isNotEmpty) rows(others), + if (others.isNotEmpty) rows(others, chats.length), if (others.isEmpty && controller.parsed.kind != SearchKind.chat && empty != null) diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index e2d50aad..7e0aa75a 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -15,7 +15,8 @@ enum KeyboardShortcutGroup { chat('Chat'), windows('Windows'), terminal('Terminal'), - lists('Lists'); + lists('Lists'), + search('Search'); const KeyboardShortcutGroup(this.title); @@ -64,6 +65,7 @@ class KeyboardShortcutRegistry { ..._windows, ..._terminal, ..._lists, + ..._search, ]; String get _cheatsheetKeys => shellCheatsheetShortcutLabel(platform); @@ -265,4 +267,14 @@ class KeyboardShortcutRegistry { 'In an artifact or file-diff viewer. Esc closes an artifact viewer.', ), ]; + + List get _search => [ + const KeyboardShortcutEntry( + group: KeyboardShortcutGroup.search, + action: 'Move through Search results', + keys: 'Ctrl+N, Ctrl+P, Up, Down', + caveat: + 'While the Search field is focused. Uses Control rather than Cmd on macOS; Enter opens the highlighted result.', + ), + ]; } diff --git a/app/lib/ui/input/app_search_field.dart b/app/lib/ui/input/app_search_field.dart index a90a7afb..8755d70e 100644 --- a/app/lib/ui/input/app_search_field.dart +++ b/app/lib/ui/input/app_search_field.dart @@ -18,6 +18,7 @@ class AppSearchField extends StatelessWidget { this.onCleared, this.autofocus = false, this.focusNode, + this.onKeyEvent, this.inBar = false, }); @@ -37,6 +38,7 @@ class AppSearchField extends StatelessWidget { final VoidCallback? onCleared; final bool autofocus; final FocusNode? focusNode; + final FocusOnKeyEventCallback? onKeyEvent; final bool inBar; void _clear() { @@ -58,38 +60,41 @@ class AppSearchField extends StatelessWidget { ); return ValueListenableBuilder( valueListenable: controller, - builder: (context, value, _) => TextField( - key: fieldKey, - controller: controller, - focusNode: focusNode, - autofocus: autofocus, - textInputAction: TextInputAction.search, - onChanged: onChanged, - onSubmitted: onSubmitted, - decoration: InputDecoration( - hintText: placeholder, - prefixIcon: const Icon(Icons.search), - suffixIcon: value.text.isEmpty - ? null - : IconButton( - key: clearKey, - tooltip: 'Clear search', - onPressed: _clear, - icon: const Icon(Icons.close), - ), - filled: !inBar, - fillColor: scheme.surfaceContainerHigh, - isDense: true, - border: stadium, - enabledBorder: stadium, - // In the bar the pill is the field's outline; on a page the focused - // field shows the host's focus ring. - focusedBorder: inBar - ? stadium - : OutlineInputBorder( - borderRadius: radius, - borderSide: BorderSide(color: scheme.primary, width: 2), - ), + builder: (context, value, _) => Focus( + onKeyEvent: onKeyEvent, + child: TextField( + key: fieldKey, + controller: controller, + focusNode: focusNode, + autofocus: autofocus, + textInputAction: TextInputAction.search, + onChanged: onChanged, + onSubmitted: onSubmitted, + decoration: InputDecoration( + hintText: placeholder, + prefixIcon: const Icon(Icons.search), + suffixIcon: value.text.isEmpty + ? null + : IconButton( + key: clearKey, + tooltip: 'Clear search', + onPressed: _clear, + icon: const Icon(Icons.close), + ), + filled: !inBar, + fillColor: scheme.surfaceContainerHigh, + isDense: true, + border: stadium, + enabledBorder: stadium, + // In the bar the pill is the field's outline; on a page the focused + // field shows the host's focus ring. + focusedBorder: inBar + ? stadium + : OutlineInputBorder( + borderRadius: radius, + borderSide: BorderSide(color: scheme.primary, width: 2), + ), + ), ), ), ); diff --git a/app/test/features/search/search_screen_test.dart b/app/test/features/search/search_screen_test.dart index 661fa859..ed9c4c9a 100644 --- a/app/test/features/search/search_screen_test.dart +++ b/app/test/features/search/search_screen_test.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/search/search_screen.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; class ImmediateGateway implements ApiGateway { ImmediateGateway(this.reply); @@ -161,6 +163,200 @@ void main() { expect(opened, isNull); }); + testWidgets('field keys select results, retain focus, and Enter opens', ( + tester, + ) async { + useNarrowSurface(tester); + final second = hit( + kind: 'field', + target: 'run:11:4:output', + payload: { + 'matched_field': 'output', + 'field': { + 'run_id': 11, + 'sequence': 4, + 'field': 'output', + 'snippet': 'the release is ready', + }, + }, + ); + final gateway = ImmediateGateway((_, _) => response([pipeline, second])); + JsonMap? opened; + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (value) => opened = value), + ), + ); + await search(tester, 'release'); + final fieldFinder = find.byKey(const ValueKey('search.field')); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.pipeline:7')), + ) + .selected, + isTrue, + ); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.run:11:4:output')), + ) + .selected, + isTrue, + ); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'omni-search'); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyP); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.pipeline:7')), + ) + .selected, + isTrue, + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyN); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.run:11:4:output')), + ) + .selected, + isTrue, + ); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.run:11:4:output')), + ) + .selected, + isTrue, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.pipeline:7')), + ) + .selected, + isTrue, + ); + + await tester.tap(fieldFinder); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(opened?['target'], 'run:11:4:output'); + }); + + testWidgets( + 'selection resets when result data changes and typing remains active', + (tester) async { + useNarrowSurface(tester); + final changed = hit( + kind: 'pipeline', + target: 'pipeline:7', + payload: { + 'pipeline': { + 'id': 7, + 'name': 'Updated release', + 'version': 4, + 'stages': 5, + }, + }, + ); + final gateway = ImmediateGateway( + (query, _) => + response(query == 'updated' ? [changed, field] : [pipeline, field]), + ); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + + await search(tester, 'release'); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.run:11:4:output')), + ) + .selected, + isTrue, + ); + + await tester.enterText( + find.byKey(const ValueKey('search.field')), + 'updated', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect( + tester + .widget( + find.byKey(const ValueKey('search.result.pipeline:7')), + ) + .selected, + isTrue, + ); + expect( + tester + .widget(find.byKey(const ValueKey('search.field'))) + .controller! + .text, + 'updated', + ); + }, + ); + + testWidgets( + 'Enter submits with no results and targetless rows have unique keys', + (tester) async { + useNarrowSurface(tester); + tester.view.physicalSize = const Size(390, 2000); + final gateway = ImmediateGateway( + (query, _) => query == 'empty' + ? response([]) + : response([ + hit(kind: 'future_kind', target: '', payload: const {}), + hit(kind: 'future_kind', target: '', payload: const {}), + ]), + ); + await tester.pumpWidget( + MaterialApp( + home: SearchScreen(gateway: gateway, onOpen: (_) {}), + ), + ); + + await search(tester, 'empty'); + final callsBeforeSubmit = gateway.calls.length; + await tester.tap(find.byKey(const ValueKey('search.field'))); + await tester.testTextInput.receiveAction(TextInputAction.search); + await tester.pumpAndSettle(); + expect(gateway.calls.length, callsBeforeSubmit + 1); + + await search(tester, 'rows'); + expect(find.byKey(const ValueKey('search.result..0')), findsOneWidget); + expect(find.byKey(const ValueKey('search.result..1')), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + testWidgets('an unsupported server shows its sentence and retry recovers', ( tester, ) async { diff --git a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart index cddb5df7..a207bd55 100644 --- a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart @@ -30,6 +30,7 @@ const _implemented = [ 'Resize the terminal panel', 'Open a chat list item', 'Resize a list pane', + 'Move through Search results', 'Previous or next artifact or changed file', ]; @@ -130,6 +131,18 @@ void main() { expect(actions, isNot(contains('Move between terminal tabs'))); }); + test('Search documents field-scoped Control navigation', () { + final registry = KeyboardShortcutRegistry( + platform: TargetPlatform.macOS, + web: true, + ); + final entry = _entry(registry, 'Move through Search results'); + expect(entry.group, KeyboardShortcutGroup.search); + expect(entry.keys, 'Ctrl+N, Ctrl+P, Up, Down'); + expect(entry.caveat, contains('Search field')); + expect(entry.caveat, contains('Control rather than Cmd')); + }); + testWidgets('groups stack in one column with their keys right-aligned', ( tester, ) async {