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/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<SearchScreen> {
late final OmniSearchController _controller;
late final TextEditingController _text;
final FocusNode _focus = FocusNode(debugLabel: 'omni-search');
final Map<int, GlobalKey> _rowKeys = {};
var _selectedIndex = 0;
String _resultIdentity = '';
@override
void initState() {
@@ -57,9 +64,62 @@ class _SearchScreenState extends State<SearchScreen> {
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<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() {
_text.clear();
_controller.updateQuery('');
@@ -140,6 +200,7 @@ class _SearchScreenState extends State<SearchScreen> {
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<SearchScreen> {
query: _controller.parsed.query,
onOpen: widget.onOpen,
header: header,
selectedIndex: _selectedIndex,
rowKeys: _rowKeys,
),
);
}
@@ -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<JsonMap> onOpen;
final Widget header;
final int selectedIndex;
final Map<int, GlobalKey> 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 [
@@ -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<SearchKind> 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,
@@ -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<JsonMap> 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
@@ -20,19 +20,39 @@ List<Widget> searchResultSlivers({
required String query,
required ValueChanged<JsonMap> onOpen,
required Widget Function(String message) message,
required int selectedIndex,
required Map<int, GlobalKey> rowKeys,
}) {
final chats = controller.shownChats;
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 note = controller.chatsNote;
Widget rows(List<JsonMap> hits) => SliverList.builder(
Widget rows(List<JsonMap> 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<Widget> 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<Widget> 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)
@@ -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<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.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<TextEditingValue>(
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),
),
),
),
),
);
@@ -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<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', (
tester,
) async {
@@ -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 {