From 3b0da38f7013110b3e69c384733ea536b449765d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 12 Nov 2026 15:02:11 +0000 Subject: [PATCH] Redesign the keyboard shortcuts cheatsheet with fuzzy search One fixed-size list of grouped cards: actions and notes on the leading side, keys drawn as keycaps in an aligned trailing column that never ends a line on a joining word. A search field, focused when Ctrl+? opens it, filters fuzzily by action and keys (exactly by group and note) and highlights the matched letters. --- .../settings/keyboard_shortcut_keys.dart | 115 +++++ .../settings/keyboard_shortcuts_filter.dart | 157 ++++++ .../settings/keyboard_shortcuts_help.dart | 477 +++++++++++------- .../settings_keyboard_shortcuts_section.dart | 8 +- app/lib/shell/shell_cheatsheet.dart | 2 +- .../keyboard_shortcuts_cheatsheet_test.dart | 50 +- .../keyboard_shortcuts_filter_test.dart | 62 +++ .../keyboard_shortcuts_help_test.dart | 103 +++- 8 files changed, 745 insertions(+), 229 deletions(-) create mode 100644 app/lib/features/settings/keyboard_shortcut_keys.dart create mode 100644 app/lib/features/settings/keyboard_shortcuts_filter.dart create mode 100644 app/test/features/settings/keyboard_shortcuts_filter_test.dart diff --git a/app/lib/features/settings/keyboard_shortcut_keys.dart b/app/lib/features/settings/keyboard_shortcut_keys.dart new file mode 100644 index 00000000..526c3a9a --- /dev/null +++ b/app/lib/features/settings/keyboard_shortcut_keys.dart @@ -0,0 +1,115 @@ +import 'package:flutter/material.dart'; + +/// The chords of a shortcut's [keys] text, as the registry writes them: +/// alternatives separated by `, ` and the keys of one chord joined by `+` +/// (`Option+K, Ctrl+K` is two chords of two keys each). +List> shortcutChords(String keys) => [ + for (final chord in keys.split(', ')) + if (chord.trim().isNotEmpty) + [ + for (final key in chord.trim().split('+')) + if (key.isNotEmpty) key, + ], +]; + +/// A shortcut's keys drawn as keycaps. Each chord stays on one line; the +/// chords wrap as a whole and line up at the trailing edge. Between two chords +/// a muted word says how they relate: `then` for a key pressed again +/// (`Esc, Esc`), otherwise `or`. +class ShortcutKeys extends StatelessWidget { + const ShortcutKeys({super.key, required this.keys}); + + final String keys; + + @override + Widget build(BuildContext context) { + final chords = shortcutChords(keys); + final muted = Theme.of(context).textTheme.labelSmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ); + return ExcludeSemantics( + child: Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 6, + runSpacing: 6, + children: [ + // The joining word travels with the chord after it, so a line + // never ends on a dangling `or`. + for (final (index, chord) in chords.indexed) + index == 0 + ? _Chord(keys: chord) + : Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 6, + runSpacing: 6, + children: [ + Text( + _sameChord(chord, chords[index - 1]) ? 'then' : 'or', + style: muted, + ), + _Chord(keys: chord), + ], + ), + ], + ), + ); + } + + static bool _sameChord(List a, List b) => + a.length == b.length && a.indexed.every((e) => e.$2 == b[e.$1]); +} + +/// One chord's keys side by side. A chord too wide for the keys column (very +/// large text) breaks between its keys rather than overflowing. +class _Chord extends StatelessWidget { + const _Chord({required this.keys}); + + final List keys; + + @override + Widget build(BuildContext context) => Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 3, + runSpacing: 3, + children: [for (final key in keys) ShortcutKeycap(label: key)], + ); +} + +/// One key, drawn as a small raised cap in the theme's surface colours. +class ShortcutKeycap extends StatelessWidget { + const ShortcutKeycap({super.key, required this.label}); + + final String label; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final edge = scheme.outlineVariant; + return Container( + constraints: const BoxConstraints(minWidth: 26), + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), + border: Border( + top: BorderSide(color: edge), + left: BorderSide(color: edge), + right: BorderSide(color: edge), + // A heavier lower edge reads as a key, not a chip. + bottom: BorderSide(color: edge, width: 2), + ), + ), + child: Text( + label, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.labelMedium?.copyWith( + color: scheme.onSurface, + fontWeight: FontWeight.w600, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ); + } +} diff --git a/app/lib/features/settings/keyboard_shortcuts_filter.dart b/app/lib/features/settings/keyboard_shortcuts_filter.dart new file mode 100644 index 00000000..c8221447 --- /dev/null +++ b/app/lib/features/settings/keyboard_shortcuts_filter.dart @@ -0,0 +1,157 @@ +import 'keyboard_shortcuts_registry.dart'; + +/// One shortcut that matched the cheatsheet's filter: its [score] (higher is a +/// better match) and the [actionMatches] — indexes into the entry's action that +/// the query matched, for highlighting. +typedef ShortcutMatch = ({ + KeyboardShortcutEntry entry, + int score, + Set actionMatches, +}); + +/// Filters [entries] by a fuzzy [query]: each whitespace-separated word must +/// appear, in order but not necessarily contiguously, in the entry's action, +/// keys, group or note. Matches in the action rank highest, then the keys, the +/// group and the note. An empty query keeps every entry with score zero, in +/// the given order; otherwise the best matches come first. +List filterShortcuts( + List entries, + String query, +) { + final words = query.toLowerCase().split(RegExp(r'\s+')) + ..removeWhere((word) => word.isEmpty); + if (words.isEmpty) { + return [ + for (final entry in entries) + (entry: entry, score: 0, actionMatches: const {}), + ]; + } + final matches = []; + for (final (index, entry) in entries.indexed) { + // The action and keys match fuzzily; the group and the longer note only + // by their exact text, so scattered letters in a sentence never match. + final fields = [ + (text: entry.action, weight: 4, fuzzy: true), + // `Ctrl+K` is found by `ctrl k` and `ctrlk` alike. + (text: entry.keys.replaceAll('+', ' '), weight: 3, fuzzy: true), + (text: entry.group.title, weight: 2, fuzzy: false), + (text: entry.caveat ?? '', weight: 1, fuzzy: false), + ]; + var total = 0; + final highlight = {}; + for (final word in words) { + ({int score, List positions})? best; + var bestField = -1; + for (final (fieldIndex, field) in fields.indexed) { + final found = field.fuzzy + ? fuzzyMatch(word, field.text) + : substringMatch(word, field.text); + if (found == null) continue; + final weighted = found.score * field.weight; + if (best == null || weighted > best.score) { + best = (score: weighted, positions: found.positions); + bestField = fieldIndex; + } + } + if (best == null) { + total = -1; + break; + } + total += best.score; + if (bestField == 0) highlight.addAll(best.positions); + } + // A tiny bias keeps equally good matches in registry order. + if (total >= 0) { + matches.add(( + entry: entry, + score: total * 1000 - index, + actionMatches: highlight, + )); + } + } + matches.sort((a, b) => b.score.compareTo(a.score)); + return matches; +} + +/// Matches the lowercase [word] against [text] as a subsequence, preferring +/// characters that continue a run and characters at word starts. Null when +/// [word] does not occur, or only spread so thinly that it is no real match: +/// the matched characters may span at most about twice the word's length. +({int score, List positions})? fuzzyMatch(String word, String text) { + final lower = text.toLowerCase(); + final found = + _match(word, lower, preferWordStarts: true) ?? + _match(word, lower, preferWordStarts: false); + if (found == null) return null; + final span = found.positions.last - found.positions.first + 1; + return span <= word.length * 2 + 2 ? found : null; +} + +/// Matches the lowercase [word] as a contiguous piece of [text], ranking a +/// piece at a word start higher. Null when it does not occur. +({int score, List positions})? substringMatch(String word, String text) { + final lower = text.toLowerCase(); + var at = lower.indexOf(word); + if (at < 0) return null; + for (var i = at; i >= 0; i = lower.indexOf(word, i + 1)) { + if (_wordStart(lower, i)) { + at = i; + break; + } + } + return ( + score: word.length * 6 + (_wordStart(lower, at) ? 8 : 0), + positions: [for (var i = at; i < at + word.length; i++) i], + ); +} + +({int score, List positions})? _match( + String word, + String lower, { + required bool preferWordStarts, +}) { + final positions = []; + var score = 0; + var from = 0; + for (final char in word.split('')) { + var at = -1; + if (positions.isNotEmpty && lower.startsWith(char, from)) { + at = from; + } else { + for ( + var i = lower.indexOf(char, from); + i >= 0; + i = lower.indexOf(char, i + 1) + ) { + if (at < 0) at = i; + if (!preferWordStarts || _wordStart(lower, i)) { + at = i; + break; + } + } + } + if (at < 0) return null; + final consecutive = positions.isNotEmpty && positions.last == at - 1; + score += 1; + if (consecutive) score += 5; + if (_wordStart(lower, at)) score += 8; + if (at == 0) score += 4; + if (positions.isNotEmpty && !consecutive) { + score -= (at - positions.last - 1).clamp(0, 3); + } + positions.add(at); + from = at + 1; + } + return (score: score, positions: positions); +} + +bool _wordStart(String text, int index) { + if (index == 0) return true; + final before = text.codeUnitAt(index - 1); + return !_isAlphanumeric(before); +} + +bool _isAlphanumeric(int unit) => + (unit >= 0x30 && unit <= 0x39) || + (unit >= 0x41 && unit <= 0x5a) || + (unit >= 0x61 && unit <= 0x7a); diff --git a/app/lib/features/settings/keyboard_shortcuts_help.dart b/app/lib/features/settings/keyboard_shortcuts_help.dart index d2b82138..9a4ab008 100644 --- a/app/lib/features/settings/keyboard_shortcuts_help.dart +++ b/app/lib/features/settings/keyboard_shortcuts_help.dart @@ -1,200 +1,333 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import '../../ui/adaptive/app_popups.dart'; +import 'keyboard_shortcut_keys.dart'; +import 'keyboard_shortcuts_filter.dart'; import 'keyboard_shortcuts_registry.dart'; const keyboardShortcutsLabel = 'Keyboard shortcuts'; -/// The narrowest content width (after the page padding) that shows the groups -/// in two columns. Narrower content, such as a phone sheet, stacks them. -const _twoColumnMinWidth = 520.0; - -Future showKeyboardShortcutsHelp(BuildContext context) => - showAppDetails( - context, - maxWidth: 640, - builder: (_) => const KeyboardShortcutsHelp(), - ); - -class KeyboardShortcutsHelp extends StatelessWidget { - const KeyboardShortcutsHelp({super.key, this.registry}); - - final KeyboardShortcutRegistry? registry; - - @override - Widget build(BuildContext context) { - final source = registry ?? KeyboardShortcutRegistry.current(); - final groups = [ - for (final group in KeyboardShortcutGroup.values) - if (source.inGroup(group) case final entries when entries.isNotEmpty) - (group: group, entries: entries), - ]; - final content = Semantics( - scopesRoute: true, - namesRoute: true, - explicitChildNodes: true, - label: 'Keyboard shortcuts help', - child: Padding( - padding: const EdgeInsets.fromLTRB(24, 8, 24, 24), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - children: [ - Expanded( - child: Text( - keyboardShortcutsLabel, - style: Theme.of(context).textTheme.headlineSmall, - ), - ), - IconButton( - tooltip: 'Close keyboard shortcuts', - onPressed: () => Navigator.of(context).pop(), - icon: const Icon(Icons.close), - ), - ], - ), - const SizedBox(height: 8), - Text( - 'Shortcuts available in the current app and browser environment.', - style: Theme.of(context).textTheme.bodyMedium, - ), - const SizedBox(height: 16), - _ShortcutGroups(groups: groups), - const SizedBox(height: 4), - Text( - 'On macOS, Option is shown for Alt. Browsers can reserve system or tab shortcuts.', - style: Theme.of(context).textTheme.bodySmall, - ), - ], - ), +/// Opens the cheatsheet: a fixed-size dialog on a desktop layout, a tall +/// bottom sheet on a phone. [focusSearch] puts the keyboard in its filter +/// field, as the Ctrl+? shortcut does. +Future showKeyboardShortcutsHelp( + BuildContext context, { + bool focusSearch = false, +}) { + final help = KeyboardShortcutsHelp(focusSearch: focusSearch); + if (!usesDesktopPopups(context)) { + return showModalBottomSheet( + context: context, + useRootNavigator: true, + showDragHandle: true, + isScrollControlled: true, + useSafeArea: true, + builder: (sheet) => Padding( + padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(sheet).bottom), + child: FractionallySizedBox(heightFactor: 0.92, child: help), ), ); - // The desktop details dialog supplies its own bounded scroll view. The - // narrow details sheet does not, so keep the help readable at large text - // scales and on short phone screens there as well. - return usesDesktopPopups(context) - ? content - : SingleChildScrollView(child: content); } -} - -typedef _Group = ({ - KeyboardShortcutGroup group, - List entries, -}); - -/// The groups in display order: one column when narrow, otherwise two. Each -/// group goes to the shorter column so the two stay about the same height. -class _ShortcutGroups extends StatelessWidget { - const _ShortcutGroups({required this.groups}); - - final List<_Group> groups; - - @override - Widget build(BuildContext context) => LayoutBuilder( - builder: (context, constraints) { - if (constraints.maxWidth < _twoColumnMinWidth) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [for (final group in groups) _GroupBlock(group: group)], - ); - } - final left = <_Group>[]; - final right = <_Group>[]; - var leftRows = 0; - var rightRows = 0; - for (final group in groups) { - if (leftRows <= rightRows) { - left.add(group); - leftRows += group.entries.length + 1; - } else { - right.add(group); - rightRows += group.entries.length + 1; - } - } - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded(child: _GroupColumn(groups: left)), - const SizedBox(width: 24), - Expanded(child: _GroupColumn(groups: right)), - ], + return showDialog( + context: context, + useRootNavigator: true, + builder: (dialog) { + // A fixed size, so the dialog does not jump while the filter narrows it. + final height = math.min(MediaQuery.sizeOf(dialog).height * 0.85, 760.0); + return Dialog( + clipBehavior: Clip.antiAlias, + child: SizedBox(width: 720, height: height, child: help), ); }, ); } -class _GroupColumn extends StatelessWidget { - const _GroupColumn({required this.groups}); +/// Every shortcut of this platform, grouped, with a fuzzy filter field above +/// them. It fills the height it is given: the header and field stay put and +/// the list scrolls under them. +class KeyboardShortcutsHelp extends StatefulWidget { + const KeyboardShortcutsHelp({ + super.key, + this.registry, + this.focusSearch = false, + }); - final List<_Group> groups; + final KeyboardShortcutRegistry? registry; + final bool focusSearch; @override - Widget build(BuildContext context) => Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [for (final group in groups) _GroupBlock(group: group)], - ); + State createState() => _KeyboardShortcutsHelpState(); } -class _GroupBlock extends StatelessWidget { - const _GroupBlock({required this.group}); - - final _Group group; +class _KeyboardShortcutsHelpState extends State { + final _query = TextEditingController(); + final _field = FocusNode(debugLabel: 'keyboard-shortcuts-search'); @override - Widget build(BuildContext context) => Padding( - padding: const EdgeInsets.only(bottom: 12), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text(group.group.title, style: Theme.of(context).textTheme.titleSmall), - const SizedBox(height: 4), - for (final (index, entry) in group.entries.indexed) ...[ - if (index > 0) const Divider(height: 1), + void dispose() { + _query.dispose(); + _field.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final source = widget.registry ?? KeyboardShortcutRegistry.current(); + return Semantics( + scopesRoute: true, + namesRoute: true, + explicitChildNodes: true, + label: 'Keyboard shortcuts help', + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ Padding( - padding: const EdgeInsets.symmetric(vertical: 10), - child: _ShortcutRow(entry: entry), + padding: const EdgeInsets.fromLTRB(24, 16, 12, 0), + child: Row( + children: [ + Expanded( + child: Text( + keyboardShortcutsLabel, + style: theme.textTheme.headlineSmall, + ), + ), + IconButton( + tooltip: 'Close keyboard shortcuts', + onPressed: () => Navigator.of(context).maybePop(), + icon: const Icon(Icons.close), + ), + ], + ), ), - ], - ], - ), - ); -} - -class _ShortcutRow extends StatelessWidget { - const _ShortcutRow({required this.entry}); - - final KeyboardShortcutEntry entry; - - @override - Widget build(BuildContext context) => Semantics( - container: true, - label: - '${entry.action}: ${entry.keys}${entry.caveat == null ? '' : '. ${entry.caveat}'}', - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded(child: Text(entry.action)), - const SizedBox(width: 16), - Flexible( - child: Text( - entry.keys, - textAlign: TextAlign.end, - style: const TextStyle(fontWeight: FontWeight.w600), + Padding( + padding: const EdgeInsets.fromLTRB(24, 12, 24, 8), + child: ListenableBuilder( + listenable: _query, + builder: (context, _) => SearchBar( + key: const Key('keyboard-shortcuts-search'), + controller: _query, + focusNode: _field, + autoFocus: widget.focusSearch, + hintText: 'Search shortcuts', + elevation: const WidgetStatePropertyAll(0), + backgroundColor: WidgetStatePropertyAll( + theme.colorScheme.surfaceContainerHighest, + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 16), + ), + leading: const Icon(Icons.search), + trailing: [ + if (_query.text.isNotEmpty) + IconButton( + tooltip: 'Clear search', + onPressed: () { + _query.clear(); + _field.requestFocus(); + }, + icon: const Icon(Icons.close), + ), + ], ), ), - ], - ), - if (entry.caveat case final caveat?) ...[ - const SizedBox(height: 4), - Text(caveat, style: Theme.of(context).textTheme.bodySmall), + ), + Expanded( + child: ListenableBuilder( + listenable: _query, + builder: (context, _) => _ShortcutList( + matches: filterShortcuts(source.entries, _query.text), + query: _query.text.trim(), + ), + ), + ), ], - ], - ), - ); + ), + ); + } +} + +/// The matching shortcuts under their group headings. Groups keep their +/// usual order; while filtering, the group with the best match comes first. +class _ShortcutList extends StatelessWidget { + const _ShortcutList({required this.matches, required this.query}); + + final List matches; + final String query; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + if (matches.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.search_off, + size: 32, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(height: 12), + Text( + 'No shortcuts match “$query”', + textAlign: TextAlign.center, + style: theme.textTheme.bodyLarge, + ), + ], + ), + ), + ); + } + final groups = >{}; + for (final match in matches) { + (groups[match.entry.group] ??= []).add(match); + } + final order = query.isEmpty + ? KeyboardShortcutGroup.values.where(groups.containsKey).toList() + : groups.keys.toList(); + return ListView( + key: const Key('keyboard-shortcuts-list'), + padding: const EdgeInsets.fromLTRB(24, 0, 24, 24), + children: [ + for (final group in order) + _GroupCard(group: group, matches: groups[group]!), + Padding( + padding: const EdgeInsets.only(top: 16), + child: Text( + 'On macOS, Option is shown for Alt. Browsers can reserve system ' + 'or tab shortcuts.', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ); + } +} + +class _GroupCard extends StatelessWidget { + const _GroupCard({required this.group, required this.matches}); + + final KeyboardShortcutGroup group; + final List matches; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(4, 16, 4, 8), + child: Text( + group.title, + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.primary, + ), + ), + ), + DecoratedBox( + decoration: BoxDecoration( + border: Border.all(color: theme.colorScheme.outlineVariant), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + for (final (index, match) in matches.indexed) ...[ + if (index > 0) + Divider( + height: 1, + indent: 16, + endIndent: 16, + color: theme.colorScheme.outlineVariant, + ), + _ShortcutRow(match: match), + ], + ], + ), + ), + ], + ); + } +} + +/// The action and its note on the leading side; the keys in a column of +/// their own on the trailing side, so every row's keys line up. +class _ShortcutRow extends StatelessWidget { + const _ShortcutRow({required this.match}); + + final ShortcutMatch match; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final entry = match.entry; + return Semantics( + container: true, + label: + '${entry.action}: ${entry.keys}${entry.caveat == null ? '' : '. ${entry.caveat}'}', + child: ExcludeSemantics( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: LayoutBuilder( + builder: (context, constraints) => Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text.rich( + _highlighted( + context, + entry.action, + match.actionMatches, + ), + style: theme.textTheme.bodyLarge, + ), + if (entry.caveat case final caveat?) ...[ + const SizedBox(height: 2), + Text( + caveat, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + const SizedBox(width: 16), + SizedBox( + // The keys column is the same width on every row. + width: math.min(300, constraints.maxWidth * 0.45), + child: ShortcutKeys(keys: entry.keys), + ), + ], + ), + ), + ), + ), + ); + } + + TextSpan _highlighted(BuildContext context, String text, Set marks) { + if (marks.isEmpty) return TextSpan(text: text); + final strong = TextStyle( + color: Theme.of(context).colorScheme.primary, + fontWeight: FontWeight.w700, + ); + return TextSpan( + children: [ + for (final (index, char) in text.split('').indexed) + TextSpan(text: char, style: marks.contains(index) ? strong : null), + ], + ); + } } diff --git a/app/lib/features/settings/settings_keyboard_shortcuts_section.dart b/app/lib/features/settings/settings_keyboard_shortcuts_section.dart index 4a6466b6..5e2b01b5 100644 --- a/app/lib/features/settings/settings_keyboard_shortcuts_section.dart +++ b/app/lib/features/settings/settings_keyboard_shortcuts_section.dart @@ -1,5 +1,7 @@ import 'package:flutter/material.dart'; +import '../../ui/adaptive/app_popups.dart'; + import 'keyboard_shortcuts_help.dart'; import 'settings_keys.dart'; import 'settings_row.dart'; @@ -14,6 +16,10 @@ class SettingsKeyboardShortcutsSection extends StatelessWidget { title: const Text(keyboardShortcutsLabel), subtitle: const Text('See the shortcuts available on this platform.'), chevron: true, - onTap: () => showKeyboardShortcutsHelp(context), + // On a phone, focusing the filter would cover the list with the keyboard. + onTap: () => showKeyboardShortcutsHelp( + context, + focusSearch: usesDesktopPopups(context), + ), ); } diff --git a/app/lib/shell/shell_cheatsheet.dart b/app/lib/shell/shell_cheatsheet.dart index d9169ed3..3616c147 100644 --- a/app/lib/shell/shell_cheatsheet.dart +++ b/app/lib/shell/shell_cheatsheet.dart @@ -22,7 +22,7 @@ class ShellCheatsheet { void open(BuildContext context) { if (isOpen) return; final token = _token = Object(); - showKeyboardShortcutsHelp(context).whenComplete(() { + showKeyboardShortcutsHelp(context, focusSearch: true).whenComplete(() { if (identical(_token, token)) _token = null; }); } diff --git a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart index a2d24090..54510f69 100644 --- a/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_cheatsheet_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/keyboard_shortcut_keys.dart'; import 'package:pipelines_app/features/settings/keyboard_shortcuts_help.dart'; import 'package:pipelines_app/features/settings/keyboard_shortcuts_registry.dart'; @@ -118,47 +119,14 @@ void main() { expect(actions, isNot(contains('Move between terminal tabs'))); }); - testWidgets('wide help splits groups into two columns', (tester) async { + testWidgets('groups stack in one column with their keys right-aligned', ( + tester, + ) async { const registry = KeyboardShortcutRegistry( platform: TargetPlatform.windows, web: false, ); - tester.view.physicalSize = const Size(900, 1400); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); - await tester.pumpWidget( - const MaterialApp( - home: Scaffold( - // The desktop dialog scrolls its content; mirror that here. - body: SingleChildScrollView( - child: Center( - child: SizedBox( - width: 640, - child: KeyboardShortcutsHelp(registry: registry), - ), - ), - ), - ), - ), - ); - - final navigation = tester.getTopLeft(find.text('Navigation')); - final chat = tester.getTopLeft(find.text('Chat')); - final windows = tester.getTopLeft(find.text('Windows')); - final lists = tester.getTopLeft(find.text('Lists')); - expect(chat.dx, greaterThan(navigation.dx)); - expect(lists.dx, greaterThan(navigation.dx)); - expect(windows.dx, navigation.dx); - expect(windows.dy, greaterThan(navigation.dy)); - }); - - testWidgets('narrow help stacks groups in one column', (tester) async { - const registry = KeyboardShortcutRegistry( - platform: TargetPlatform.iOS, - web: false, - ); - tester.view.physicalSize = const Size(360, 720); + tester.view.physicalSize = const Size(720, 2400); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); @@ -172,5 +140,13 @@ void main() { final chat = tester.getTopLeft(find.text('Chat')); expect(chat.dx, navigation.dx); expect(chat.dy, greaterThan(navigation.dy)); + // Every row's keys end at the same trailing edge. + final ends = { + for (final keys in tester.widgetList( + find.byType(ShortcutKeys), + )) + tester.getTopRight(find.byWidget(keys)).dx, + }; + expect(ends, hasLength(1)); }); } diff --git a/app/test/features/settings/keyboard_shortcuts_filter_test.dart b/app/test/features/settings/keyboard_shortcuts_filter_test.dart new file mode 100644 index 00000000..586beb33 --- /dev/null +++ b/app/test/features/settings/keyboard_shortcuts_filter_test.dart @@ -0,0 +1,62 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/keyboard_shortcut_keys.dart'; +import 'package:pipelines_app/features/settings/keyboard_shortcuts_filter.dart'; +import 'package:pipelines_app/features/settings/keyboard_shortcuts_registry.dart'; + +void main() { + const registry = KeyboardShortcutRegistry( + platform: TargetPlatform.linux, + web: false, + ); + List actions(String query) => [ + for (final match in filterShortcuts(registry.entries, query)) + match.entry.action, + ]; + + test('an empty query keeps every entry in registry order', () { + expect(actions(' '), [for (final e in registry.entries) e.action]); + }); + + test('a subsequence of the action matches and ranks first', () { + final found = actions('flt'); + expect(found.first, contains('floating')); + }); + + test('scattered letters in a long note do not match', () { + // `float` occurs only as scattered letters in other entries' notes. + expect(actions('float'), everyElement(contains('floating'))); + }); + + test('keys are searchable with or without the plus', () { + expect(actions('ctrl k'), contains('Open Chat')); + expect(actions('ctrlk'), contains('Open Chat')); + }); + + test('every word must match', () { + expect(actions('terminal paste'), ['Paste into the terminal']); + expect(actions('terminal zzqx'), isEmpty); + }); + + test('the action positions matched are reported for highlighting', () { + final match = filterShortcuts( + registry.entries, + 'open chat', + ).firstWhere((m) => m.entry.action == 'Open Chat'); + expect(match.actionMatches, containsAll([0, 1, 2, 3, 5, 6, 7, 8])); + }); + + test('chords split on commas and keys on plus signs', () { + expect(shortcutChords('Alt+K, Ctrl+K'), [ + ['Alt', 'K'], + ['Ctrl', 'K'], + ]); + expect(shortcutChords('Esc, Esc'), [ + ['Esc'], + ['Esc'], + ]); + expect(shortcutChords('Ctrl+1…9'), [ + ['Ctrl', '1…9'], + ]); + }); +} diff --git a/app/test/features/settings/keyboard_shortcuts_help_test.dart b/app/test/features/settings/keyboard_shortcuts_help_test.dart index 1d6bd78a..4cfc6412 100644 --- a/app/test/features/settings/keyboard_shortcuts_help_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_help_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/keyboard_shortcut_keys.dart'; import 'package:pipelines_app/features/settings/keyboard_shortcuts_help.dart'; import 'package:pipelines_app/features/settings/keyboard_shortcuts_registry.dart'; @@ -76,20 +77,45 @@ void main() { ); }); - testWidgets('help is readable and keyboard traversable', (tester) async { + Future pumpHelp( + WidgetTester tester, { + bool focusSearch = false, + Size size = const Size(720, 900), + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); await tester.pumpWidget( MaterialApp( home: Scaffold( - body: SingleChildScrollView( - child: KeyboardShortcutsHelp(registry: registry), + body: KeyboardShortcutsHelp( + registry: registry, + focusSearch: focusSearch, ), ), ), ); + await tester.pump(); + } + + Finder search() => find.byKey(const Key('keyboard-shortcuts-search')); + + testWidgets('help is readable and keyboard traversable', (tester) async { + // Tall enough that the lazily built list lays out every group. + await pumpHelp(tester, size: const Size(720, 4000)); expect(find.text('Keyboard shortcuts'), findsOneWidget); expect(find.text('Show or hide floating chats'), findsOneWidget); - expect(find.text('Option+Y, Ctrl+Y, Cmd+Y'), findsOneWidget); + // Keys are drawn as keycaps, one per key of each chord. + expect(find.text('Option'), findsWidgets); + expect(find.byType(ShortcutKeycap), findsWidgets); + expect( + find.bySemanticsLabel( + RegExp(r'^Show or hide floating chats: Option\+Y, Ctrl\+Y, Cmd\+Y'), + ), + findsOneWidget, + ); expect( tester.getSemantics(find.bySemanticsLabel('Keyboard shortcuts help')), matchesSemantics( @@ -103,20 +129,61 @@ void main() { expect(find.byTooltip('Close keyboard shortcuts'), findsOneWidget); }); - testWidgets('narrow help content scrolls', (tester) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData( - size: Size(400, 640), - textScaler: TextScaler.linear(2), - ), - child: MaterialApp( - home: Scaffold(body: KeyboardShortcutsHelp(registry: registry)), - ), - ), - ); + testWidgets('the search field is not focused unless asked', (tester) async { + await pumpHelp(tester); + expect(tester.widget(search()).focusNode!.hasFocus, isFalse); + }); - expect(find.byType(SingleChildScrollView), findsOneWidget); - expect(find.text('Keyboard shortcuts'), findsOneWidget); + testWidgets('the search field starts focused when asked', (tester) async { + await pumpHelp(tester, focusSearch: true); + await tester.pump(); + expect(tester.widget(search()).focusNode!.hasFocus, isTrue); + }); + + testWidgets('typing filters fuzzily and highlights the action', ( + tester, + ) async { + await pumpHelp(tester, focusSearch: true); + await tester.enterText(search(), 'flt'); + await tester.pump(); + + expect(find.textContaining('floating', findRichText: true), findsWidgets); + expect(find.text('Open Search'), findsNothing); + expect(find.text('Leave Search'), findsNothing); + // Only the groups that still have a match are shown. + expect(find.text('Windows'), findsOneWidget); + expect(find.text('Navigation'), findsNothing); + }); + + testWidgets('keys can be searched as written', (tester) async { + await pumpHelp(tester); + await tester.enterText(search(), 'option k'); + await tester.pump(); + expect(find.text('Open Chat'), findsOneWidget); + expect(find.text('Leave Search'), findsNothing); + }); + + testWidgets('no match says so and Clear restores the list', (tester) async { + await pumpHelp(tester); + await tester.enterText(search(), 'zzqx'); + await tester.pump(); + expect(find.text('No shortcuts match “zzqx”'), findsOneWidget); + + await tester.tap(find.byTooltip('Clear search')); + await tester.pump(); + expect(find.text('Navigation'), findsOneWidget); + expect(find.textContaining('No shortcuts match'), findsNothing); + }); + + testWidgets('phone-sized help scrolls its list under a fixed header', ( + tester, + ) async { + await pumpHelp(tester, size: const Size(400, 640)); + final list = find.byKey(const Key('keyboard-shortcuts-list')); + expect(list, findsOneWidget); + final before = tester.getTopLeft(search()).dy; + await tester.drag(list, const Offset(0, -400)); + await tester.pump(); + expect(tester.getTopLeft(search()).dy, before); }); }