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.
This commit is contained in:
2026-11-13 15:51:00 +00:00
parent eeb07e5645
commit ccc80a9a8d
9 changed files with 372 additions and 44 deletions
@@ -1,4 +1,7 @@
import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/api_gateway.dart'; import '../../core/api_gateway.dart';
import '../../shell/shell_bar.dart'; import '../../shell/shell_bar.dart';
@@ -6,6 +9,7 @@ import '../../shell/shell_search_focus.dart';
import '../../ui/adaptive/segmented_bar.dart'; import '../../ui/adaptive/segmented_bar.dart';
import 'data/search_repository.dart'; import 'data/search_repository.dart';
import 'domain/search_controller.dart'; import 'domain/search_controller.dart';
import 'domain/search_row.dart';
import 'ui/material_search_body.dart'; import 'ui/material_search_body.dart';
import 'ui/search_bar_controls.dart'; import 'ui/search_bar_controls.dart';
import 'ui/search_bounds_note.dart'; import 'ui/search_bounds_note.dart';
@@ -38,6 +42,9 @@ class _SearchScreenState extends State<SearchScreen> {
late final OmniSearchController _controller; late final OmniSearchController _controller;
late final TextEditingController _text; late final TextEditingController _text;
final FocusNode _focus = FocusNode(debugLabel: 'omni-search'); final FocusNode _focus = FocusNode(debugLabel: 'omni-search');
final Map<int, GlobalKey> _rowKeys = {};
var _selectedIndex = 0;
String _resultIdentity = '';
@override @override
void initState() { void initState() {
@@ -57,9 +64,62 @@ class _SearchScreenState extends State<SearchScreen> {
selection: TextSelection.collapsed(offset: query.length), 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(() {}); if (mounted) setState(() {});
} }
List<JsonMap> 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() { void _clear() {
_text.clear(); _text.clear();
_controller.updateQuery(''); _controller.updateQuery('');
@@ -140,6 +200,7 @@ class _SearchScreenState extends State<SearchScreen> {
onSubmitted: _controller.submit, onSubmitted: _controller.submit,
onCleared: _clear, onCleared: _clear,
onKind: _controller.selectKind, onKind: _controller.selectKind,
onKeyEvent: _handleFieldKey,
); );
/// The server's result and scan bounds, only when they cut the answer /// The server's result and scan bounds, only when they cut the answer
@@ -173,6 +234,8 @@ class _SearchScreenState extends State<SearchScreen> {
query: _controller.parsed.query, query: _controller.parsed.query,
onOpen: widget.onOpen, onOpen: widget.onOpen,
header: header, header: header,
selectedIndex: _selectedIndex,
rowKeys: _rowKeys,
), ),
); );
} }
@@ -14,12 +14,16 @@ class MaterialSearchBody extends StatelessWidget {
required this.query, required this.query,
required this.onOpen, required this.onOpen,
required this.header, required this.header,
required this.selectedIndex,
required this.rowKeys,
}); });
final OmniSearchController controller; final OmniSearchController controller;
final String query; final String query;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final Widget header; final Widget header;
final int selectedIndex;
final Map<int, GlobalKey> rowKeys;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -55,6 +59,8 @@ class MaterialSearchBody extends StatelessWidget {
query: query, query: query,
onOpen: onOpen, onOpen: onOpen,
message: (text) => _SearchMessage(message: text), message: (text) => _SearchMessage(message: text),
selectedIndex: selectedIndex,
rowKeys: rowKeys,
); );
case SearchBodyKind.empty: case SearchBodyKind.empty:
return [ return [
@@ -28,6 +28,7 @@ class SearchBarControls extends StatelessWidget {
required this.onKind, required this.onKind,
this.autofocus = true, this.autofocus = true,
this.focusNode, this.focusNode,
this.onKeyEvent,
}); });
final TextEditingController text; final TextEditingController text;
@@ -38,6 +39,7 @@ class SearchBarControls extends StatelessWidget {
final ValueChanged<SearchKind> onKind; final ValueChanged<SearchKind> onKind;
final bool autofocus; final bool autofocus;
final FocusNode? focusNode; final FocusNode? focusNode;
final FocusOnKeyEventCallback? onKeyEvent;
@override @override
// The pill grows with the bar, so the field and the results share both // The pill grows with the bar, so the field and the results share both
@@ -55,6 +57,7 @@ class SearchBarControls extends StatelessWidget {
controller: text, controller: text,
autofocus: autofocus, autofocus: autofocus,
focusNode: focusNode, focusNode: focusNode,
onKeyEvent: onKeyEvent,
inBar: true, inBar: true,
placeholder: 'Search pipelines, runs, artifacts and chats', placeholder: 'Search pipelines, runs, artifacts and chats',
onChanged: onChanged, onChanged: onChanged,
@@ -20,19 +20,26 @@ class SearchResultRow extends StatelessWidget {
required this.query, required this.query,
required this.onOpen, required this.onOpen,
this.divider = true, this.divider = true,
this.selected = false,
this.visibilityKey,
this.rowKey,
}); });
final JsonMap hit; final JsonMap hit;
final String query; final String query;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final bool divider; final bool divider;
final bool selected;
final GlobalKey? visibilityKey;
final Key? rowKey;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final row = searchRowView(hit, query); final row = searchRowView(hit, query);
final kind = '${hit['kind'] ?? ''}'; final kind = '${hit['kind'] ?? ''}';
return AppListRow( final listRow = AppListRow(
key: ValueKey('search.result.${hit['target']}'), key: rowKey ?? ValueKey('search.result.${hit['target']}'),
selected: selected,
divider: divider, divider: divider,
onTap: row.openable ? () => onOpen(hit) : null, onTap: row.openable ? () => onOpen(hit) : null,
leading: leading:
@@ -55,6 +62,9 @@ class SearchResultRow extends StatelessWidget {
: null, : null,
menu: searchArtifactActions(context, hit), menu: searchArtifactActions(context, hit),
); );
return visibilityKey == null
? listRow
: KeyedSubtree(key: visibilityKey, child: listRow);
} }
TextSpan _line(SearchRowView row) => row.snippet == null TextSpan _line(SearchRowView row) => row.snippet == null
@@ -20,19 +20,39 @@ List<Widget> searchResultSlivers({
required String query, required String query,
required ValueChanged<JsonMap> onOpen, required ValueChanged<JsonMap> onOpen,
required Widget Function(String message) message, required Widget Function(String message) message,
required int selectedIndex,
required Map<int, GlobalKey> rowKeys,
}) { }) {
final chats = controller.shownChats; final chats = controller.shownChats;
final others = controller.shownResults; final others = controller.shownResults;
final allHits = [...chats, ...others];
final targetCounts = <String, int>{};
for (final hit in allHits) {
final target = '${hit['target'] ?? ''}';
targetCounts[target] = (targetCounts[target] ?? 0) + 1;
}
final grouped = controller.showsChatSection; final grouped = controller.showsChatSection;
final note = controller.chatsNote; final note = controller.chatsNote;
Widget rows(List<JsonMap> hits) => SliverList.builder( Widget rows(List<JsonMap> hits, int offset) => SliverList.builder(
itemCount: hits.length, itemCount: hits.length,
itemBuilder: (context, index) => SearchResultRow( itemBuilder: (context, index) {
hit: hits[index], final hit = hits[index];
query: query, final target = '${hit['target'] ?? ''}';
onOpen: onOpen, final indexInResults = offset + index;
divider: index < hits.length - 1, 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; final empty = controller.emptyMessage;
return [ return [
@@ -44,7 +64,7 @@ List<Widget> searchResultSlivers({
header: true, header: true,
), ),
), ),
if (chats.isNotEmpty) rows(chats), if (chats.isNotEmpty) rows(chats, 0),
if (note != null) if (note != null)
SliverToBoxAdapter( SliverToBoxAdapter(
child: Padding( child: Padding(
@@ -60,7 +80,7 @@ List<Widget> searchResultSlivers({
header: true, header: true,
), ),
), ),
if (others.isNotEmpty) rows(others), if (others.isNotEmpty) rows(others, chats.length),
if (others.isEmpty && if (others.isEmpty &&
controller.parsed.kind != SearchKind.chat && controller.parsed.kind != SearchKind.chat &&
empty != null) empty != null)
@@ -15,7 +15,8 @@ enum KeyboardShortcutGroup {
chat('Chat'), chat('Chat'),
windows('Windows'), windows('Windows'),
terminal('Terminal'), terminal('Terminal'),
lists('Lists'); lists('Lists'),
search('Search');
const KeyboardShortcutGroup(this.title); const KeyboardShortcutGroup(this.title);
@@ -64,6 +65,7 @@ class KeyboardShortcutRegistry {
..._windows, ..._windows,
..._terminal, ..._terminal,
..._lists, ..._lists,
..._search,
]; ];
String get _cheatsheetKeys => shellCheatsheetShortcutLabel(platform); String get _cheatsheetKeys => shellCheatsheetShortcutLabel(platform);
@@ -265,4 +267,14 @@ class KeyboardShortcutRegistry {
'In an artifact or file-diff viewer. Esc closes an artifact viewer.', 'In an artifact or file-diff viewer. Esc closes an artifact viewer.',
), ),
]; ];
List<KeyboardShortcutEntry> 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.',
),
];
} }
+37 -32
View File
@@ -18,6 +18,7 @@ class AppSearchField extends StatelessWidget {
this.onCleared, this.onCleared,
this.autofocus = false, this.autofocus = false,
this.focusNode, this.focusNode,
this.onKeyEvent,
this.inBar = false, this.inBar = false,
}); });
@@ -37,6 +38,7 @@ class AppSearchField extends StatelessWidget {
final VoidCallback? onCleared; final VoidCallback? onCleared;
final bool autofocus; final bool autofocus;
final FocusNode? focusNode; final FocusNode? focusNode;
final FocusOnKeyEventCallback? onKeyEvent;
final bool inBar; final bool inBar;
void _clear() { void _clear() {
@@ -58,38 +60,41 @@ class AppSearchField extends StatelessWidget {
); );
return ValueListenableBuilder<TextEditingValue>( return ValueListenableBuilder<TextEditingValue>(
valueListenable: controller, valueListenable: controller,
builder: (context, value, _) => TextField( builder: (context, value, _) => Focus(
key: fieldKey, onKeyEvent: onKeyEvent,
controller: controller, child: TextField(
focusNode: focusNode, key: fieldKey,
autofocus: autofocus, controller: controller,
textInputAction: TextInputAction.search, focusNode: focusNode,
onChanged: onChanged, autofocus: autofocus,
onSubmitted: onSubmitted, textInputAction: TextInputAction.search,
decoration: InputDecoration( onChanged: onChanged,
hintText: placeholder, onSubmitted: onSubmitted,
prefixIcon: const Icon(Icons.search), decoration: InputDecoration(
suffixIcon: value.text.isEmpty hintText: placeholder,
? null prefixIcon: const Icon(Icons.search),
: IconButton( suffixIcon: value.text.isEmpty
key: clearKey, ? null
tooltip: 'Clear search', : IconButton(
onPressed: _clear, key: clearKey,
icon: const Icon(Icons.close), tooltip: 'Clear search',
), onPressed: _clear,
filled: !inBar, icon: const Icon(Icons.close),
fillColor: scheme.surfaceContainerHigh, ),
isDense: true, filled: !inBar,
border: stadium, fillColor: scheme.surfaceContainerHigh,
enabledBorder: stadium, isDense: true,
// In the bar the pill is the field's outline; on a page the focused border: stadium,
// field shows the host's focus ring. enabledBorder: stadium,
focusedBorder: inBar // In the bar the pill is the field's outline; on a page the focused
? stadium // field shows the host's focus ring.
: OutlineInputBorder( focusedBorder: inBar
borderRadius: radius, ? stadium
borderSide: BorderSide(color: scheme.primary, width: 2), : OutlineInputBorder(
), borderRadius: radius,
borderSide: BorderSide(color: scheme.primary, width: 2),
),
),
), ),
), ),
); );
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/search/search_screen.dart'; import 'package:pipelines_app/features/search/search_screen.dart';
import 'package:pipelines_app/ui/layout/app_list_row.dart';
class ImmediateGateway implements ApiGateway { class ImmediateGateway implements ApiGateway {
ImmediateGateway(this.reply); ImmediateGateway(this.reply);
@@ -161,6 +163,200 @@ void main() {
expect(opened, isNull); 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<AppListRow>(
find.byKey(const ValueKey('search.result.pipeline:7')),
)
.selected,
isTrue,
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(
tester
.widget<AppListRow>(
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<AppListRow>(
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<AppListRow>(
find.byKey(const ValueKey('search.result.run:11:4:output')),
)
.selected,
isTrue,
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(
tester
.widget<AppListRow>(
find.byKey(const ValueKey('search.result.run:11:4:output')),
)
.selected,
isTrue,
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(
tester
.widget<AppListRow>(
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<AppListRow>(
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<AppListRow>(
find.byKey(const ValueKey('search.result.pipeline:7')),
)
.selected,
isTrue,
);
expect(
tester
.widget<TextField>(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', ( testWidgets('an unsupported server shows its sentence and retry recovers', (
tester, tester,
) async { ) async {
@@ -30,6 +30,7 @@ const _implemented = [
'Resize the terminal panel', 'Resize the terminal panel',
'Open a chat list item', 'Open a chat list item',
'Resize a list pane', 'Resize a list pane',
'Move through Search results',
'Previous or next artifact or changed file', 'Previous or next artifact or changed file',
]; ];
@@ -130,6 +131,18 @@ void main() {
expect(actions, isNot(contains('Move between terminal tabs'))); 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', ( testWidgets('groups stack in one column with their keys right-aligned', (
tester, tester,
) async { ) async {