diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart index a5a7a352..19022df2 100644 --- a/app/lib/features/chat/chat_pane_content.dart +++ b/app/lib/features/chat/chat_pane_content.dart @@ -8,7 +8,10 @@ import 'chat_runtime.dart'; import 'conversation/chat_seen_interaction.dart'; import 'conversation/chat_thread_view.dart'; import 'conversation/composer_focus_request.dart'; +import 'domain/chat_colors.dart'; +import 'ui/sessions/chat_color_palette.dart'; import 'workspace/chat_pane_commands.dart'; +import 'workspace/chat_pane_focus_flash.dart'; /// Where an open chat is shown and what that place alone decides: its Back, /// its pane menu, whether it takes pastes, and what follows `/new` and @@ -81,54 +84,59 @@ Widget buildChatPaneContent({ builder: (context) { final row = runtime.rowFor(sessionId); final start = runtime.startNotice; - return ChatComposerFocusScope( + return ChatPaneFocusFlash( sessionId: sessionId, - requests: runtime.composerFocus, - child: ServerContext.forServer( - context, - runtime.serverIdFor(sessionId), - ChatSeenInteraction( - sessionId: sessionId, - onInteract: () => runtime.sessions.reportInteraction(sessionId), - child: ChatThreadView( - key: ValueKey('chat-session-$sessionId'), - gateway: runtime.gatewayFor(sessionId), + requests: runtime.paneFlash, + color: chatColorShade(context, chatSessionColor(row)), + child: ChatComposerFocusScope( + sessionId: sessionId, + requests: runtime.composerFocus, + child: ServerContext.forServer( + context, + runtime.serverIdFor(sessionId), + ChatSeenInteraction( sessionId: sessionId, - title: '${row?['title'] ?? ''}'.trim(), - session: row, - initialDraft: runtime.pendingDrafts.remove(sessionId), - syncToken: placement.syncToken, - scrollPositions: runtime.scrollPositions, - transcripts: runtime.transcripts, - initialNotice: start != null && start.id == sessionId - ? start.notice - : null, - onBack: placement.onBack, - onModelChanged: (applied) => - runtime.modelChanged(sessionId, applied), - onModeChanged: (mode, name) => - runtime.acceptMode(sessionId, mode, name), - onEffortChanged: (state) => - runtime.acceptEffort(sessionId, state), - onNewSession: placement.onNewSession, - onSessionRenamed: (title) => - runtime.acceptRename(sessionId, title), - onSessionClosed: placement.onSessionClosed, - onColorSelected: (color) => - runtime.sessions.setColor(sessionId, color), - onNextChat: placement.onNextChat, - useNativeBack: placement.useNativeBack, - pasteTarget: placement.pasteTarget, - ownsPasteWhenFocused: placement.ownsPasteWhenFocused, - showBackButton: placement.showBackButton, - paneControls: placement.paneControls?.call(context) ?? const [], - leadingControl: placement.leadingControl?.call(context), - paneCommands: placement.paneCommands, - onComposerFocus: placement.onComposerFocus, - onComposerReady: (composer) => - runtime.registerComposer(sessionId, composer), - onComposerDisposed: (composer) => - runtime.unregisterComposer(sessionId, composer), + onInteract: () => runtime.sessions.reportInteraction(sessionId), + child: ChatThreadView( + key: ValueKey('chat-session-$sessionId'), + gateway: runtime.gatewayFor(sessionId), + sessionId: sessionId, + title: '${row?['title'] ?? ''}'.trim(), + session: row, + initialDraft: runtime.pendingDrafts.remove(sessionId), + syncToken: placement.syncToken, + scrollPositions: runtime.scrollPositions, + transcripts: runtime.transcripts, + initialNotice: start != null && start.id == sessionId + ? start.notice + : null, + onBack: placement.onBack, + onModelChanged: (applied) => + runtime.modelChanged(sessionId, applied), + onModeChanged: (mode, name) => + runtime.acceptMode(sessionId, mode, name), + onEffortChanged: (state) => + runtime.acceptEffort(sessionId, state), + onNewSession: placement.onNewSession, + onSessionRenamed: (title) => + runtime.acceptRename(sessionId, title), + onSessionClosed: placement.onSessionClosed, + onColorSelected: (color) => + runtime.sessions.setColor(sessionId, color), + onNextChat: placement.onNextChat, + useNativeBack: placement.useNativeBack, + pasteTarget: placement.pasteTarget, + ownsPasteWhenFocused: placement.ownsPasteWhenFocused, + showBackButton: placement.showBackButton, + paneControls: placement.paneControls?.call(context) ?? const [], + leadingControl: placement.leadingControl?.call(context), + paneCommands: placement.paneCommands, + onComposerFocus: placement.onComposerFocus, + onComposerReady: (composer) => + runtime.registerComposer(sessionId, composer), + onComposerDisposed: (composer) => + runtime.unregisterComposer(sessionId, composer), + ), ), ), ), diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart index f828de14..8197badc 100644 --- a/app/lib/features/chat/chat_runtime.dart +++ b/app/lib/features/chat/chat_runtime.dart @@ -17,6 +17,7 @@ import 'data/chat_recency.dart'; import 'data/chat_repository.dart'; import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; +import 'workspace/chat_pane_focus_flash.dart'; /// What open chats share for one server, wherever they are shown (the Chat /// destination's tiling or a floating window): the session list, the rows @@ -134,6 +135,9 @@ class ChatRuntime extends ChangeNotifier { /// Puts the keyboard in an opened chat's composer once it is built. final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests(); + /// Flashes the focus ring of the pane the keyboard just moved to. + final ChatPaneFlashRequests paneFlash = ChatPaneFlashRequests(); + /// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there. final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests(); @@ -296,6 +300,7 @@ class ChatRuntime extends ChangeNotifier { sessions.dispose(); folds.dispose(); composerFocus.dispose(); + paneFlash.dispose(); composers.clear(); _pendingAppends.clear(); super.dispose(); diff --git a/app/lib/features/chat/chat_screen_pane_cycle.dart b/app/lib/features/chat/chat_screen_pane_cycle.dart new file mode 100644 index 00000000..dbb470ad --- /dev/null +++ b/app/lib/features/chat/chat_screen_pane_cycle.dart @@ -0,0 +1,86 @@ +part of 'screen.dart'; + +/// A chat pane the keyboard can move to: a tiled pane or a floating window. +class _PaneCycleTarget { + const _PaneCycleTarget.pane(this.paneId, this.sessionId) : window = null; + _PaneCycleTarget.window(WindowEntry this.window) + : paneId = null, + sessionId = window.contentId; + + final String? paneId; + final WindowEntry? window; + final String sessionId; +} + +/// Alt+] and Alt+[ (also Cmd+] and Cmd+[ on Apple platforms, see +/// [chatPaneCycleShortcut]) move the keyboard to the next or previous chat +/// pane on screen: the tiled panes in their visual order (left to right, +/// then top to bottom, as the split tree lays them out; the center stage's +/// row in order), then the shown floating chat windows in the order they +/// were opened, wrapping around. The pane's composer takes the keyboard and +/// its focus ring flashes in the chat's colour. Nothing opens or closes. +/// +/// It does nothing with one pane on screen, on a phone layout (the chat +/// stack and the quick switcher own moving between chats there), over a +/// popup or another destination, and while a terminal has the keyboard, +/// which keeps its Alt keys. Handled before the focus tree, so it works from +/// a composer and the web build stops the browser's own use of the keys. +mixin _ChatScreenPaneCycle on State, _ChatScreenWorkspace { + ChatRuntime get _runtime; + + bool _paneCycleKey(KeyEvent event) { + final step = chatPaneCycleShortcut(event, HardwareKeyboard.instance); + if (step == null || + !mounted || + primaryFocusIsTypingSurface() || + !_workspaceVisible || + !showsListBesideDetail(context) || + !_chatOwnsKeyboard()) { + return false; + } + final order = _paneCycleOrder(); + final target = chatPaneCycleTarget(order, _paneCycleCurrent(order), step); + if (target == null) return false; + // A held chord is swallowed; only its first press moves. + if (event is KeyDownEvent) _focusPaneCycleTarget(target); + return true; + } + + /// The panes on screen, in cycling order. + List<_PaneCycleTarget> _paneCycleOrder() { + final visible = _visibleSidebarSessions; + return [ + for (final pane in _workspace.panes) + if (visible.contains(pane.sessionId)) + _PaneCycleTarget.pane(pane.id, pane.sessionId), + for (final window + in widget.windows?.shownInOpenOrder() ?? const []) + _PaneCycleTarget.window(window), + ]; + } + + /// Where the keyboard is in [order]: the floating chat window holding it, + /// otherwise the active tiled pane (also while the chat list has it). + int _paneCycleCurrent(List<_PaneCycleTarget> order) { + final window = keyboardWindow()?.entry; + if (window != null && window.kind == chatWindowKind) { + return order.indexWhere((target) => target.window?.id == window.id); + } + final active = _workspace.activePaneId; + return order.indexWhere((target) => target.paneId == active); + } + + void _focusPaneCycleTarget(_PaneCycleTarget target) { + final window = target.window; + final windows = widget.windows; + if (window != null && windows != null) { + windows.manager.raise(window.id); + windows.kind.focusContent(window); + } else if (target.paneId case final paneId?) { + _workspace.activate(paneId); + _composerFocus.request(target.sessionId); + } + _runtime.paneFlash.flash(target.sessionId); + WidgetsBinding.instance.ensureVisualUpdate(); + } +} diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index c202e92d..d7b26d37 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -23,11 +23,13 @@ import '../../core/api_gateway.dart'; import '../../core/servers/server_context.dart'; import '../../core/servers/server_scope.dart'; import '../../shell/detached/detached_window_scope.dart'; +import '../../shell/windows/window_entry.dart'; import '../../shell/windows/window_scope.dart'; import 'shell/chat_shell_dismiss.dart'; import '../terminal/terminal_open_action.dart'; import 'ui/sessions/session_pane_menu.dart'; import 'workspace/chat_pane_commands.dart'; +import 'workspace/chat_pane_cycle.dart'; import 'workspace/chat_float_shortcut.dart'; import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; @@ -70,6 +72,7 @@ import '../../ui/input/keyboard_owner.dart'; part 'chat_screen_attention.dart'; part 'chat_screen_float.dart'; +part 'chat_screen_pane_cycle.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; part 'chat_screen_list_toggle.dart'; @@ -137,6 +140,7 @@ class _ChatScreenState extends State _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat, + _ChatScreenPaneCycle, _ChatScreenPaneMenu, _ChatScreenQuickSwitch, _ChatScreenAttention, @@ -194,6 +198,7 @@ class _ChatScreenState extends State _bindWorkspacePersistence(); HardwareKeyboard.instance.addHandler(_cycleChatKey); HardwareKeyboard.instance.addHandler(_slashFocusKey); + HardwareKeyboard.instance.addHandler(_paneCycleKey); // Seen from now on, so the press that chooses the first chat counts. LastPointerKind.instance; _sessions.addListener(_nextChanged); @@ -484,6 +489,7 @@ class _ChatScreenState extends State _paneCommands.dispose(); HardwareKeyboard.instance.removeHandler(_cycleChatKey); HardwareKeyboard.instance.removeHandler(_slashFocusKey); + HardwareKeyboard.instance.removeHandler(_paneCycleKey); _page.dispose(); _workspaceBinding?.dispose(); _openWorkspace?.dispose(); diff --git a/app/lib/features/chat/workspace/chat_pane_cycle.dart b/app/lib/features/chat/workspace/chat_pane_cycle.dart new file mode 100644 index 00000000..61352bc0 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_cycle.dart @@ -0,0 +1,76 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The step Alt+] (1) or Alt+[ (-1) moves the keyboard between the chat +/// panes on screen, or null for any other key. On Apple platforms Cmd+] and +/// Cmd+[ do the same. +/// +/// Why these keys: +/// - Alt+Tab and Cmd+Tab are the system's window switchers, Ctrl+Tab cycles +/// the open chats (and the browser keeps it), and Alt+` already cycles the +/// floating windows. +/// - Browsers use Alt+Left/Right for back and forward; nothing on GNOME, +/// Hyprland, Windows or a browser binds Alt+[ or Alt+]. +/// - Option+] and Option+[ type quotes on a Mac, so with Alt the key is +/// matched by its position (also catching layouts whose bracket keys type +/// something else). Cmd+] and Cmd+[ are the Mac's own next/previous pair +/// and leave Option free for typing. +/// - AltGr is how several layouts type brackets, so it never matches. +/// +/// Shift never matches: Alt+Shift+[ types braces. A focused terminal keeps +/// these keys (Alt+[ is its escape prefix); the caller checks that. +int? chatPaneCycleShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is KeyUpEvent || + keyboard.isShiftPressed || + keyboard.isControlPressed || + keyboard.isLogicalKeyPressed(LogicalKeyboardKey.altGraph)) { + return null; + } + final alt = keyboard.isAltPressed; + final meta = keyboard.isMetaPressed; + final int? step; + if (alt && !meta) { + step = switch (event.physicalKey) { + PhysicalKeyboardKey.bracketRight => 1, + PhysicalKeyboardKey.bracketLeft => -1, + _ => null, + }; + } else if (meta && !alt && _apple(platform ?? defaultTargetPlatform)) { + step = + event.logicalKey == LogicalKeyboardKey.bracketRight || + event.physicalKey == PhysicalKeyboardKey.bracketRight + ? 1 + : event.logicalKey == LogicalKeyboardKey.bracketLeft || + event.physicalKey == PhysicalKeyboardKey.bracketLeft + ? -1 + : null; + } else { + step = null; + } + return step; +} + +bool _apple(TargetPlatform platform) => + platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; + +/// The forward and backward chords as this platform reads them, for the +/// shortcuts list. +String chatPaneCycleShortcutLabel([TargetPlatform? platform]) => + _apple(platform ?? defaultTargetPlatform) + ? 'Option+], Option+[, Cmd+], Cmd+[' + : 'Alt+], Alt+['; + +/// The entry [step] places from [current] in [order], wrapping around; null +/// when there is no other entry to move to. A [current] outside [order] +/// starts from the first entry going forward and the last going back. +T? chatPaneCycleTarget(List order, int current, int step) { + if (order.length < 2 || step == 0) return null; + if (current < 0 || current >= order.length) { + return step > 0 ? order.first : order.last; + } + return order[(current + step) % order.length]; +} diff --git a/app/lib/features/chat/workspace/chat_pane_focus_flash.dart b/app/lib/features/chat/workspace/chat_pane_focus_flash.dart new file mode 100644 index 00000000..da4ac6c7 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_focus_flash.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; + +/// Asks the chat pane showing a session to flash its focus ring, once the +/// keyboard moved there by the pane-cycling chord (see +/// [chatPaneCycleShortcut]). Shared by the tiling and the floating windows. +class ChatPaneFlashRequests extends ChangeNotifier { + String? _sessionId; + int _serial = 0; + + /// The session last asked to flash. + String? get sessionId => _sessionId; + + /// Advances on every request, so asking the same pane again flashes again. + int get serial => _serial; + + void flash(String sessionId) { + _sessionId = sessionId; + _serial++; + notifyListeners(); + } +} + +/// How long the ring shows before it is gone. +const chatPaneFlashDuration = Duration(milliseconds: 700); + +/// The ring's width, in logical pixels. +const chatPaneFlashWidth = 2.0; + +/// One chat pane's focus cue: a ring in the chat's [color] drawn over the +/// pane, fading out, when [requests] names [sessionId]. Under reduced motion +/// the ring shows for the same time without fading. It also holds a focus +/// node around the pane: when nothing inside the pane took the keyboard +/// (the composer is not there or cannot be focused), the pane itself does. +class ChatPaneFocusFlash extends StatefulWidget { + const ChatPaneFocusFlash({ + super.key, + required this.sessionId, + required this.requests, + required this.color, + required this.child, + }); + + final String sessionId; + final ChatPaneFlashRequests requests; + final Color? color; + final Widget child; + + @override + State createState() => _ChatPaneFocusFlashState(); +} + +class _ChatPaneFocusFlashState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _ring = AnimationController( + vsync: this, + duration: chatPaneFlashDuration, + ); + final FocusNode _pane = FocusNode( + debugLabel: 'Chat pane', + skipTraversal: true, + ); + int _seen = 0; + + @override + void initState() { + super.initState(); + _seen = widget.requests.serial; + widget.requests.addListener(_requested); + } + + @override + void didUpdateWidget(ChatPaneFocusFlash oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.requests != widget.requests) { + oldWidget.requests.removeListener(_requested); + widget.requests.addListener(_requested); + _seen = widget.requests.serial; + } + } + + @override + void dispose() { + widget.requests.removeListener(_requested); + _ring.dispose(); + _pane.dispose(); + super.dispose(); + } + + void _requested() { + final requests = widget.requests; + if (requests.serial == _seen) return; + _seen = requests.serial; + if (requests.sessionId != widget.sessionId) return; + _ring.forward(from: 0); + // The composer takes its request after a frame; look a frame later. + SchedulerBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + SchedulerBinding.instance + ..addPostFrameCallback((_) { + if (mounted && !_pane.hasFocus) _pane.requestFocus(); + }) + ..ensureVisualUpdate(); + }); + } + + @override + Widget build(BuildContext context) { + final color = widget.color ?? Theme.of(context).colorScheme.primary; + final still = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + final radius = AppDesignTokens.of(context).radius ?? 0; + return Focus( + focusNode: _pane, + child: Stack( + fit: StackFit.passthrough, + children: [ + widget.child, + Positioned.fill( + child: IgnorePointer( + child: AnimatedBuilder( + animation: _ring, + builder: (context, _) { + if (!_ring.isAnimating) return const SizedBox.shrink(); + final fade = still + ? 1.0 + : 1 - Curves.easeIn.transform(_ring.value); + return DecoratedBox( + key: const ValueKey('chat-pane-focus-flash'), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(radius), + border: Border.all( + color: color.withValues(alpha: color.a * fade), + width: chatPaneFlashWidth, + ), + ), + ); + }, + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 5161df77..00c3f013 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart'; import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../chat/workspace/chat_list_hidden_controller.dart'; +import '../chat/workspace/chat_pane_cycle.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_shortcuts.dart'; @@ -197,6 +198,13 @@ class KeyboardShortcutRegistry { action: 'Focus the neighbouring chat pane', keys: _apple ? 'Cmd+Shift+Arrows' : 'Ctrl+Shift+Arrows', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Next or previous chat pane on screen', + keys: chatPaneCycleShortcutLabel(platform), + caveat: + 'On a wide window with more than one chat shown: the tiled panes left to right, then top to bottom, then the floating chat windows, wrapping around. The pane\'s message input takes the keyboard and its border flashes. No chat opens or closes. In the terminal the keys go to the terminal.', + ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, action: 'Move the active chat pane', diff --git a/app/notes/chat-pane-cycle.md b/app/notes/chat-pane-cycle.md new file mode 100644 index 00000000..88e660ff --- /dev/null +++ b/app/notes/chat-pane-cycle.md @@ -0,0 +1,53 @@ +# Cycling the chat panes on screen + +Alt+] and Alt+[ move the keyboard to the next or previous chat pane on screen +(wide layouts only). On macOS and iOS, Cmd+] and Cmd+[ do the same. + +## Keys + +- Alt+Tab and Cmd+Tab belong to the OS window switcher. Ctrl+Tab already + cycles the open chats, and Alt+` cycles the floating windows. + Alt+Y, Alt+K, Alt+L, Alt+T and Ctrl+B are also taken. +- Browsers use Alt+Left and Alt+Right for back and forward. GNOME, Hyprland, + Windows and browsers do not bind Alt+[ or Alt+]. The web build handles the + key, so Flutter calls `preventDefault`. The capture's keydown recorder shows + this (`prevented: true`). +- On a Mac, Option+] and Option+[ type quotes. With Alt, the shortcut matches + the key's position, as Option+Y does. Cmd+] and Cmd+[ are the macOS + next/previous pair, so Option stays free for typing. On the web, Cmd+[ is + Back, and the app prevents that default. +- The shortcut never matches with Shift (Alt+Shift+[ types a brace), Ctrl or + AltGr. AltGr is how several layouts type brackets. +- A focused terminal (any `TypingSurface`) keeps the keys. Alt+[ is its + escape prefix. + +## Behaviour + +- Order: the tiled panes in split-tree order, which is visual order (left + before right, top before bottom; the center stage's row in order). Then + come the shown floating chat windows in the order they were opened. The + cycle wraps around. The shortcut never opens, closes, hides or moves a + chat. +- The target's composer takes focus. If nothing in the pane takes focus, a + pane-level focus node takes it. The pane's border flashes in the chat + colour for 700 ms (`ChatPaneFocusFlash`). The flash uses the design's + corner radius. Under reduced motion it shows for the same time without + fading. +- It does nothing in these cases: one pane on screen, a phone layout (the + stack and the quick switcher handle chats there), a popup or another + destination open, or a focused terminal. +- The shortcut is listed in the keyboard shortcuts list (Settings and the + Ctrl+? cheatsheet) as "Next or previous chat pane on screen". + +## Evidence + +- Tests: `test/features/chat/chat_pane_cycle_test.dart` (three tiles plus a + window, forward, backward and wrapping; two tiles plus a window; no-op + with one pane and on a phone; terminal keeps the keys) and + `test/features/chat/workspace/chat_pane_cycle_test.dart` (key matching, + labels, wrap). +- Capture: `tool/capture/examples/chat-pane-cycle.json` with + `CHROME_PATH=/usr/bin/chromium`, at 1600x900. `chat-pane-cycle/before.png` + shows the left pane focused. `chat-pane-cycle/after-alt-bracket.png` was + taken 120 ms after Alt+]: the right pane (api refactor) is active, its + composer has the caret, and its purple ring is fading. diff --git a/app/notes/chat-pane-cycle/after-alt-bracket.png b/app/notes/chat-pane-cycle/after-alt-bracket.png new file mode 100644 index 00000000..43dfef04 Binary files /dev/null and b/app/notes/chat-pane-cycle/after-alt-bracket.png differ diff --git a/app/notes/chat-pane-cycle/before.png b/app/notes/chat-pane-cycle/before.png new file mode 100644 index 00000000..e609026f Binary files /dev/null and b/app/notes/chat-pane-cycle/before.png differ diff --git a/app/test/features/chat/chat_pane_cycle_test.dart b/app/test/features/chat/chat_pane_cycle_test.dart new file mode 100644 index 00000000..e18d5a3d --- /dev/null +++ b/app/test/features/chat/chat_pane_cycle_test.dart @@ -0,0 +1,329 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/chat_runtime.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/windows/chat_windows.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_focus_flash.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; +import 'package:pipelines_app/shell/windows/window_host.dart'; +import 'package:pipelines_app/shell/windows/window_kind.dart'; +import 'package:pipelines_app/shell/windows/window_manager.dart'; +import 'package:pipelines_app/shell/windows/window_store.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +const _ids = ['a', 'b', 'c', 'd']; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in _ids) + {'id': id, 'title': 'Chat $id', 'directory': '/home/$id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +class _Store implements WindowStore { + String? value; + @override + Future read() async => value; + @override + Future write(String record) async { + value = record; + return true; + } +} + +Finder _thread(String id) => find.byWidgetPredicate( + (widget) => widget is ChatThreadView && widget.sessionId == id, + skipOffstage: false, +); +Finder _input(String id) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id'), skipOffstage: false), + matching: find.byType(EditableText, skipOffstage: false), + skipOffstage: false, +); +bool _composerFocused(WidgetTester tester, String id) => + tester.widget(_input(id)).focusNode.hasPrimaryFocus; +ChatWorkspaceController _workspace(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace, skipOffstage: false)) + .controller; + +/// The chats whose focus ring is showing. +List _flashing(WidgetTester tester) => [ + for (final id in _ids) + if (find + .descendant( + of: find.ancestor( + of: _thread(id), + matching: find.byType(ChatPaneFocusFlash), + ), + matching: find.byKey(const ValueKey('chat-pane-focus-flash')), + ) + .evaluate() + .isNotEmpty) + id, +]; + +/// Saves a horizontal layout of [ids], left to right. +void _saved(List ids) { + final layout = ChatWorkspaceController()..open(ids.first); + for (final id in ids.skip(1)) { + layout.splitActive(id, ChatSplitAxis.horizontal); + } + SharedPreferences.setMockInitialValues({ + scopedServerKey(chatWorkspacePreferenceKey, 'server-a'): layout + .snapshot()! + .encode(), + }); +} + +/// The Chat destination with its floating windows over it, and optionally a +/// terminal that takes typing. +class _App { + final gateway = _Gateway()..history = (_) async => chatPage([]); + late final ChatRuntime runtime; + late final WindowManager manager; + late final ChatWindows windows; + final terminalFocus = FocusNode(debugLabel: 'test terminal'); + final terminalTyped = []; + + Future start( + WidgetTester tester, { + Size size = const Size(1800, 1000), + bool terminal = false, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + bindServerIdentity(gateway, 'server-a'); + runtime = ChatRuntime(gateway: gateway, serverKey: 'server-a'); + manager = WindowManager( + kinds: WindowKinds(), + store: _Store(), + server: 'server-a', + ); + windows = ChatWindows( + manager: manager, + runtime: runtime, + openInChat: (_) {}, + )..start(); + await manager.restore(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Stack( + fit: StackFit.expand, + children: [ + ChatScreen( + gateway: gateway, + persistWorkspace: true, + runtime: runtime, + windows: windows, + ), + if (terminal) + Positioned( + left: 0, + top: 0, + width: 10, + height: 10, + child: TypingSurface( + child: Focus( + focusNode: terminalFocus, + onKeyEvent: (node, event) { + if (event is KeyDownEvent) { + terminalTyped.add(event.logicalKey); + } + return KeyEventResult.handled; + }, + child: const SizedBox(), + ), + ), + ), + Positioned.fill(child: WindowHost(manager: manager)), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future stop(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + windows.dispose(); + runtime.dispose(); + manager.dispose(); + terminalFocus.dispose(); + gateway.close(); + } + + List get floating => [for (final w in windows.windows) w.contentId]; +} + +/// Floats [session] from its pane menu. +Future _float(WidgetTester tester, String session) async { + await tester.tap( + find + .descendant( + of: _thread(session), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Float (Alt+Y)').last); + await tester.pumpAndSettle(); +} + +/// Alt+] (or Alt+[ with [back]), leaving the focus ring mid-flash. +Future _cycle(WidgetTester tester, {bool back = false}) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + final physical = back + ? PhysicalKeyboardKey.bracketLeft + : PhysicalKeyboardKey.bracketRight; + final logical = back + ? LogicalKeyboardKey.bracketLeft + : LogicalKeyboardKey.bracketRight; + await tester.sendKeyDownEvent(logical, physicalKey: physical); + await tester.sendKeyUpEvent(logical, physicalKey: physical); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + for (var i = 0; i < 3; i++) { + await tester.pump(); + } +} + +/// Lets the flash finish. +Future _settle(WidgetTester tester) async { + await tester.pump(chatPaneFlashDuration); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('Alt+] and Alt+[ cycle three tiled panes and a floating ' + 'window, wrapping, each composer focused and its ring flashing', ( + tester, + ) async { + _saved(['a', 'b', 'c', 'd']); + final app = _App(); + await app.start(tester); + await _float(tester, 'd'); + final workspace = _workspace(tester); + expect(workspace.panes.map((p) => p.sessionId), ['a', 'b', 'c']); + expect(app.floating, ['d']); + + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + expect(_composerFocused(tester, 'a'), isTrue); + + // Forward: the tiles left to right, then the window, then around. + for (final id in ['b', 'c', 'd', 'a']) { + await _cycle(tester); + expect(_composerFocused(tester, id), isTrue, reason: id); + expect(_flashing(tester), [id]); + if (id != 'd') expect(workspace.activePane?.sessionId, id); + await _settle(tester); + expect(_flashing(tester), isEmpty); + } + + // Back: around to the window, then the tiles right to left. + for (final id in ['d', 'c', 'b', 'a']) { + await _cycle(tester, back: true); + expect(_composerFocused(tester, id), isTrue, reason: id); + expect(_flashing(tester), [id]); + await _settle(tester); + } + + // Nothing opened, closed or moved. + expect(workspace.panes.map((p) => p.sessionId), ['a', 'b', 'c']); + expect(app.floating, ['d']); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('two tiled panes and a floating window cycle in the same order', ( + tester, + ) async { + _saved(['a', 'b', 'c']); + final app = _App(); + await app.start(tester); + await _float(tester, 'c'); + await tester.tapAt(tester.getCenter(_input('b'))); + await tester.pumpAndSettle(); + for (final id in ['c', 'a', 'b']) { + await _cycle(tester); + expect(_composerFocused(tester, id), isTrue, reason: id); + await _settle(tester); + } + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('with one pane on screen the keys do nothing', (tester) async { + _saved(['a']); + final app = _App(); + await app.start(tester); + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + await _cycle(tester); + await _cycle(tester, back: true); + expect(_composerFocused(tester, 'a'), isTrue); + expect(_flashing(tester), isEmpty); + expect(_workspace(tester).paneCount, 1); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('on a phone layout the keys do nothing', (tester) async { + _saved(['a', 'b']); + final app = _App(); + await app.start(tester, size: const Size(400, 800)); + final workspace = _workspace(tester); + final active = workspace.activePane?.sessionId; + await _cycle(tester); + await _cycle(tester); + expect(workspace.activePane?.sessionId, active); + expect(_flashing(tester), isEmpty); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); + + testWidgets('a focused terminal keeps Alt+] and Alt+[', (tester) async { + _saved(['a', 'b']); + final app = _App(); + await app.start(tester, terminal: true); + final workspace = _workspace(tester); + await tester.tapAt(tester.getCenter(_input('a'))); + await tester.pumpAndSettle(); + app.terminalFocus.requestFocus(); + await tester.pumpAndSettle(); + + await _cycle(tester); + await _cycle(tester, back: true); + expect(app.terminalTyped, [ + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.bracketRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.bracketLeft, + ]); + expect(app.terminalFocus.hasPrimaryFocus, isTrue); + expect(workspace.activePane?.sessionId, 'a'); + expect(_flashing(tester), isEmpty); + expect(tester.takeException(), isNull); + await app.stop(tester); + }); +} diff --git a/app/test/features/chat/workspace/chat_pane_cycle_test.dart b/app/test/features/chat/workspace/chat_pane_cycle_test.dart new file mode 100644 index 00000000..ea0caf10 --- /dev/null +++ b/app/test/features/chat/workspace/chat_pane_cycle_test.dart @@ -0,0 +1,122 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_cycle.dart'; + +KeyEvent _down( + PhysicalKeyboardKey physical, + LogicalKeyboardKey logical, { + String? character, +}) => KeyDownEvent( + physicalKey: physical, + logicalKey: logical, + character: character, + timeStamp: Duration.zero, +); + +final _right = _down( + PhysicalKeyboardKey.bracketRight, + LogicalKeyboardKey.bracketRight, +); +final _left = _down( + PhysicalKeyboardKey.bracketLeft, + LogicalKeyboardKey.bracketLeft, +); + +int? _step( + KeyEvent event, + Set held, [ + TargetPlatform platform = TargetPlatform.linux, +]) => chatPaneCycleShortcut(event, _FakeKeyboard(held), platform: platform); + +void main() { + test('Alt+] goes forward and Alt+[ back on every platform', () { + for (final platform in TargetPlatform.values) { + expect(_step(_right, {LogicalKeyboardKey.altLeft}, platform), 1); + expect(_step(_left, {LogicalKeyboardKey.altLeft}, platform), -1); + } + }); + + test('Option+] types a quote on a Mac: it matches by key position', () { + final quote = _down( + PhysicalKeyboardKey.bracketRight, + const LogicalKeyboardKey(0x2018), + character: '‘', + ); + expect(_step(quote, {LogicalKeyboardKey.altLeft}, TargetPlatform.macOS), 1); + }); + + test('Cmd+] and Cmd+[ only on Apple platforms', () { + expect( + _step(_right, {LogicalKeyboardKey.metaLeft}, TargetPlatform.macOS), + 1, + ); + expect(_step(_left, {LogicalKeyboardKey.metaLeft}, TargetPlatform.iOS), -1); + expect(_step(_right, {LogicalKeyboardKey.metaLeft}), isNull); + expect( + _step(_right, {LogicalKeyboardKey.metaLeft}, TargetPlatform.windows), + isNull, + ); + }); + + test('plain brackets type; Shift, Ctrl, AltGr and key-up do not match', () { + expect(_step(_right, {}), isNull); + for (final extra in [ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.altGraph, + ]) { + expect( + _step(_right, {LogicalKeyboardKey.altLeft, extra}), + isNull, + reason: '$extra', + ); + } + expect( + _step( + const KeyUpEvent( + physicalKey: PhysicalKeyboardKey.bracketRight, + logicalKey: LogicalKeyboardKey.bracketRight, + timeStamp: Duration.zero, + ), + {LogicalKeyboardKey.altLeft}, + ), + isNull, + ); + // A key typing "[" elsewhere on the keyboard is not the chord. + expect( + _step(_down(PhysicalKeyboardKey.digit8, LogicalKeyboardKey.bracketLeft), { + LogicalKeyboardKey.altLeft, + }), + isNull, + ); + }); + + test('labels name the chords this platform answers', () { + expect(chatPaneCycleShortcutLabel(TargetPlatform.linux), 'Alt+], Alt+['); + expect(chatPaneCycleShortcutLabel(TargetPlatform.windows), 'Alt+], Alt+['); + expect( + chatPaneCycleShortcutLabel(TargetPlatform.macOS), + 'Option+], Option+[, Cmd+], Cmd+[', + ); + }); + + test('targets wrap both ways; one entry or none has no target', () { + const order = ['a', 'b', 'c']; + expect(chatPaneCycleTarget(order, 0, 1), 'b'); + expect(chatPaneCycleTarget(order, 2, 1), 'a'); + expect(chatPaneCycleTarget(order, 0, -1), 'c'); + expect(chatPaneCycleTarget(order, 1, -1), 'a'); + expect(chatPaneCycleTarget(order, -1, 1), 'a'); + expect(chatPaneCycleTarget(order, -1, -1), 'c'); + expect(chatPaneCycleTarget(['a'], 0, 1), isNull); + expect(chatPaneCycleTarget([], -1, 1), isNull); + }); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/app/test/features/settings/keyboard_shortcuts_filter_test.dart b/app/test/features/settings/keyboard_shortcuts_filter_test.dart index 586beb33..ff94aed7 100644 --- a/app/test/features/settings/keyboard_shortcuts_filter_test.dart +++ b/app/test/features/settings/keyboard_shortcuts_filter_test.dart @@ -24,8 +24,13 @@ void main() { }); 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'))); + // `float` occurs as scattered letters in many entries' notes; only the + // entries that say "floating" match. + final found = [ + for (final match in filterShortcuts(registry.entries, 'float')) + '${match.entry.action} ${match.entry.caveat ?? ''}', + ]; + expect(found, everyElement(contains('floating'))); }); test('keys are searchable with or without the plus', () { diff --git a/app/tool/capture/examples/chat-pane-cycle.json b/app/tool/capture/examples/chat-pane-cycle.json new file mode 100644 index 00000000..899027c3 --- /dev/null +++ b/app/tool/capture/examples/chat-pane-cycle.json @@ -0,0 +1,24 @@ +{ + "size": "1600x900", + "params": "chats=3&colors=1", + "steps": [ + { "open": "/chat/perf-chat-0" }, + { "wait": 1500 }, + { "click": "Chat actions for api refactor" }, + { "click": "Open to the right", "wait": 1500 }, + { "eval": "(window.__k = [], window.addEventListener('keydown', (e) => { if (e.altKey) setTimeout(() => window.__k.push({ code: e.code, prevented: e.defaultPrevented })); }, true), true)", "name": "record" }, + { "click": "xy:800,850", "wait": 800 }, + { "shot": "before" }, + { "keys": [ + { "type": "keyDown", "key": "Alt", "code": "AltLeft", "windowsVirtualKeyCode": 18, "modifiers": 1 }, + { "type": "keyDown", "key": "]", "code": "BracketRight", "windowsVirtualKeyCode": 221, "modifiers": 1 }, + { "type": "keyUp", "key": "]", "code": "BracketRight", "windowsVirtualKeyCode": 221, "modifiers": 1 }, + { "type": "keyUp", "key": "Alt", "code": "AltLeft", "windowsVirtualKeyCode": 18, "modifiers": 0 } + ], "wait": 120 }, + { "shot": "after-alt-bracket" }, + { "eval": "JSON.stringify(window.__k)", "name": "keydown-defaults" }, + { "expect": "window.__k.some((k) => k.code === 'BracketRight' && k.prevented)", "name": "alt-bracket-default-prevented" }, + { "wait": 1200 }, + { "labels": "settled" } + ] +}