diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 804be480..da567cb5 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -249,6 +249,14 @@ mixin _ChatScreenWorkspace on State { _split(session, ChatSplitAxis.horizontal); void _openBelow(JsonMap session) => _split(session, ChatSplitAxis.vertical); + /// The pane's chat trades places with [targetPaneId]'s and keeps focus; the + /// retained view moves, so its scroll, draft and running turn stay. + void _movePane(String paneId, String targetPaneId) { + _workspace.swap(paneId, targetPaneId); + final session = _workspace.activePane?.sessionId; + if (session != null) _composerFocus.request(session); + } + void _closePane(String paneId) { _workspace.close(paneId); if (_workspace.paneCount == 0) _back(); diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 6d8dcbbb..ff3ae4ed 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -31,6 +31,7 @@ import 'conversation/chat_add_pane_picker.dart'; import 'conversation/chat_sidebar_controls.dart'; import 'ui/sessions/chat_compact_sidebar.dart'; import 'workspace/chat_workspace.dart'; +import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_workspace_entrance.dart'; import 'ui/sessions/chat_adaptive.dart'; import 'conversation/chat_row_widgets.dart'; @@ -519,6 +520,10 @@ class _ChatScreenState extends State materialIcon: Icons.view_quilt_outlined, cupertinoIcon: CupertinoIcons.square_split_2x2, ), + ...chatPaneMoveActions( + ChatWorkspacePaneScope.maybeOf(paneContext ?? context), + onMove: (target) => _movePane(pane.id, target), + ), if (_workspace.paneCount > 1) ChatBarAction( label: 'Close pane', diff --git a/app/lib/features/chat/workspace/chat_pane_move_actions.dart b/app/lib/features/chat/workspace/chat_pane_move_actions.dart new file mode 100644 index 00000000..1c50b5d9 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_move_actions.dart @@ -0,0 +1,38 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/segmented_bar_overflow.dart'; +import 'chat_pane_move_shortcuts.dart'; +import 'chat_workspace_geometry.dart'; +import 'chat_workspace_pane_scope.dart'; + +/// "Move up/down/left/right" for a tiled pane's actions (More) menu. A move +/// swaps the pane with the one across that edge. A direction with no pane is +/// disabled in the Material menu (and left out of a Cupertino action sheet). +/// Nothing is offered when the panes are not tiled (one pane, or a phone). +List chatPaneMoveActions( + ChatWorkspacePaneScope? scope, { + required void Function(String targetPaneId) onMove, +}) { + if (scope == null || !scope.movable) return const []; + return [ + for (final (direction, label, icon) in const [ + (ChatPaneDirection.up, 'Move up', Icons.arrow_upward), + (ChatPaneDirection.down, 'Move down', Icons.arrow_downward), + (ChatPaneDirection.left, 'Move left', Icons.arrow_back), + (ChatPaneDirection.right, 'Move right', Icons.arrow_forward), + ]) + SegmentedOverflowAction( + key: ValueKey('chat-pane-move-${direction.name}'), + overflowEntry: SegmentedOverflowEntry( + label: label, + icon: icon, + shortcut: chatPaneMoveActivator(direction), + onPressed: switch (scope.moveTargets[direction]) { + final target? => () => onMove(target), + null => null, + }, + ), + child: const SizedBox.shrink(), + ), + ]; +} diff --git a/app/lib/features/chat/workspace/chat_pane_move_motion.dart b/app/lib/features/chat/workspace/chat_pane_move_motion.dart new file mode 100644 index 00000000..83641a08 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_move_motion.dart @@ -0,0 +1,48 @@ +import 'package:flutter/widgets.dart'; + +import '../../../ui/motion/motion.dart'; + +/// Glides the two panes of a move from their old tiles to their new ones. +/// Only the retained views' positions animate; nothing is rebuilt. Under +/// reduced motion the swap is instant. +class ChatPaneMoveMotion { + ChatPaneMoveMotion({required TickerProvider vsync}) + : _controller = AnimationController( + vsync: vsync, + value: 1, + // Reduced motion is already settled through [Motion.of], so the + // controller does not shorten itself a second time. + animationBehavior: AnimationBehavior.preserve, + ); + + final AnimationController _controller; + late final Animation _curve = CurvedAnimation( + parent: _controller, + curve: Motion.curve, + ); + Map _from = const {}; + + Listenable get animation => _controller; + + /// Starts from each moved pane's previous tile. A zero [duration] (reduced + /// motion) settles at once. + void start(Map from, Duration duration) { + if (duration == Duration.zero || from.isEmpty) { + _from = const {}; + _controller.value = 1; + return; + } + _from = Map.unmodifiable(from); + _controller.duration = duration; + _controller.forward(from: 0); + } + + /// Where pane [id] paints now, on its way to [target]. + Rect rectFor(String id, Rect target) { + final from = _from[id]; + if (from == null || !_controller.isAnimating) return target; + return Rect.lerp(from, target, _curve.value)!; + } + + void dispose() => _controller.dispose(); +} diff --git a/app/lib/features/chat/workspace/chat_pane_move_shortcuts.dart b/app/lib/features/chat/workspace/chat_pane_move_shortcuts.dart new file mode 100644 index 00000000..fff7c4a2 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_pane_move_shortcuts.dart @@ -0,0 +1,56 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import 'chat_workspace_geometry.dart'; + +/// Pane chords share one family: Ctrl+Shift+Arrow focuses the neighbouring +/// pane, and adding Alt moves the active pane there instead. On macOS the +/// Command key stands in for Ctrl, as it does for focusing. +enum ChatPaneChord { focus, move } + +/// The pane chord [event] makes, with its direction, or null. +(ChatPaneChord, ChatPaneDirection)? chatPaneChord( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is! KeyDownEvent || !keyboard.isShiftPressed) return null; + final mac = (platform ?? defaultTargetPlatform) == TargetPlatform.macOS; + final modifier = + keyboard.isControlPressed && !keyboard.isMetaPressed || + mac && keyboard.isMetaPressed && !keyboard.isControlPressed; + if (!modifier) return null; + final direction = switch (event.logicalKey) { + LogicalKeyboardKey.arrowLeft => ChatPaneDirection.left, + LogicalKeyboardKey.arrowRight => ChatPaneDirection.right, + LogicalKeyboardKey.arrowUp => ChatPaneDirection.up, + LogicalKeyboardKey.arrowDown => ChatPaneDirection.down, + _ => null, + }; + if (direction == null) return null; + return ( + keyboard.isAltPressed ? ChatPaneChord.move : ChatPaneChord.focus, + direction, + ); +} + +/// The move chord as a menu shows it: Command on macOS, Ctrl elsewhere. +SingleActivator chatPaneMoveActivator( + ChatPaneDirection direction, { + TargetPlatform? platform, +}) { + final mac = (platform ?? defaultTargetPlatform) == TargetPlatform.macOS; + return SingleActivator( + switch (direction) { + ChatPaneDirection.left => LogicalKeyboardKey.arrowLeft, + ChatPaneDirection.right => LogicalKeyboardKey.arrowRight, + ChatPaneDirection.up => LogicalKeyboardKey.arrowUp, + ChatPaneDirection.down => LogicalKeyboardKey.arrowDown, + }, + control: !mac, + meta: mac, + alt: true, + shift: true, + ); +} diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index a30794af..791b48cb 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -3,48 +3,26 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../../../ui/motion/motion.dart'; import '../../../ui/motion/quick_switch_animation.dart'; import 'chat_workspace_controller.dart'; import 'chat_workspace_geometry.dart'; import 'chat_mobile_panes.dart'; +import 'chat_pane_move_motion.dart'; +import 'chat_pane_move_shortcuts.dart'; import 'chat_pane_switch_motion.dart'; import 'chat_pane_backdrop.dart'; +import 'chat_workspace_pane_scope.dart'; import 'chat_workspace_surface.dart'; import '../../../ui/input/keyboard_owner.dart'; export 'chat_workspace_controller.dart'; export 'chat_workspace_geometry.dart' show ChatPaneDirection; +export 'chat_workspace_pane_scope.dart'; typedef ChatWorkspacePaneBuilder = Widget Function(BuildContext context, ChatWorkspacePane pane, bool active); -/// Describes the edge ownership of the pane currently being built. -class ChatWorkspacePaneScope extends InheritedWidget { - const ChatWorkspacePaneScope({ - super.key, - required this.topEdgeShared, - required this.bottomEdgeShared, - required this.leftEdgeShared, - required this.rightEdgeShared, - required super.child, - }); - - final bool topEdgeShared; - final bool bottomEdgeShared; - final bool leftEdgeShared; - final bool rightEdgeShared; - - static ChatWorkspacePaneScope? maybeOf(BuildContext context) => - context.dependOnInheritedWidgetOfExactType(); - - @override - bool updateShouldNotify(ChatWorkspacePaneScope oldWidget) => - topEdgeShared != oldWidget.topEdgeShared || - bottomEdgeShared != oldWidget.bottomEdgeShared || - leftEdgeShared != oldWidget.leftEdgeShared || - rightEdgeShared != oldWidget.rightEdgeShared; -} - /// All chat views are stable siblings, independent of the split tree. Moving a /// divider or adding/removing a neighbouring split never reparents a chat view. class ChatWorkspace extends StatefulWidget { @@ -80,10 +58,13 @@ class ChatWorkspace extends StatefulWidget { } class _ChatWorkspaceState extends State - with SingleTickerProviderStateMixin { + with TickerProviderStateMixin { final _focus = FocusNode(debugLabel: 'Chat workspace'); final Map _panes = {}; late final ChatPaneSwitchMotion _motion; + late final ChatPaneMoveMotion _move = ChatPaneMoveMotion(vsync: this); + int _moveSerial = 0; + bool _tiled = false; ChatWorkspaceGeometry? _geometry; String? _lastActiveId; Set _visibleSessionIds = const {}; @@ -127,24 +108,18 @@ class _ChatWorkspaceState extends State primaryFocusIsTypingSurface()) { return false; } - final keyboard = HardwareKeyboard.instance; - final modifier = - keyboard.isControlPressed && !keyboard.isMetaPressed || - defaultTargetPlatform == TargetPlatform.macOS && - keyboard.isMetaPressed && - !keyboard.isControlPressed; - if (!modifier || !keyboard.isShiftPressed || keyboard.isAltPressed) { - return false; - } - final direction = switch (event.logicalKey) { - LogicalKeyboardKey.arrowLeft => ChatPaneDirection.left, - LogicalKeyboardKey.arrowRight => ChatPaneDirection.right, - LogicalKeyboardKey.arrowUp => ChatPaneDirection.up, - LogicalKeyboardKey.arrowDown => ChatPaneDirection.down, - _ => null, - }; - if (direction == null) return false; + final chord = chatPaneChord(event, HardwareKeyboard.instance); + if (chord == null) return false; + final (kind, direction) = chord; final id = widget.controller.activePaneId; + if (kind == ChatPaneChord.move) { + // Only tiled panes move; the phone's one-at-a-time layout keeps the keys. + if (!_tiled) return false; + final target = id == null ? null : _geometry?.adjacent(id, direction); + if (target != null) widget.controller.swap(id!, target); + // Consumed at an outer edge too, like focusing. + return true; + } final target = id == null ? null : _geometry?.neighbor(id, direction); if (target != null) { widget.controller.activate(target); @@ -169,6 +144,7 @@ class _ChatWorkspaceState extends State _backdrop.dispose(); _motion.animation.removeStatusListener(_motionSettled); _motion.dispose(); + _move.dispose(); _focus.dispose(); for (final node in _panes.values) { node.dispose(); @@ -192,9 +168,33 @@ class _ChatWorkspaceState extends State return const SizedBox.shrink(); } final geometry = ChatWorkspaceGeometry(root, constraints.biggest); + final previous = _geometry; _geometry = geometry; final collapsed = widget.singlePane || geometry.collapsed; final panes = widget.controller.panes; + final tiled = !collapsed && panes.length > 1; + if (_moveSerial != widget.controller.moveSerial) { + _moveSerial = widget.controller.moveSerial; + // Glide the swapped pair from their previous tiles. + _move.start( + tiled && _tiled && previous != null + ? { + for (final id in widget.controller.movedPaneIds) + id: ?previous.panes[id], + } + : const {}, + Motion.of(context, Motion.standard), + ); + } + _tiled = tiled; + final moveTargets = >{ + if (tiled) + for (final pane in panes) + pane.id: { + for (final direction in ChatPaneDirection.values) + direction: ?geometry.adjacent(pane.id, direction), + }, + }; // Finish one joined loop before taking the latest requested role. // Repeated taps/chords never tear the tape or duplicate a live chat. final activeId = @@ -289,14 +289,21 @@ class _ChatWorkspaceState extends State context: context, backdrop: _backdrop, motion: _motion, + move: _move, controller: widget.controller, geometry: geometry, mobile: mobile, collapsed: collapsed, size: constraints.biggest, panes: panes, - paneView: (pane) => - _paneView(pane, mobile, collapsed, activeId, sharedEdges), + paneView: (pane) => _paneView( + pane, + mobile, + collapsed, + activeId, + sharedEdges, + moveTargets[pane.id], + ), ); }, ), @@ -309,6 +316,7 @@ class _ChatWorkspaceState extends State bool collapsed, String? activeId, Map> sharedEdges, + Map? moveTargets, ) { final outgoing = _motion.isRetainedOutgoing(pane.id); final peek = mobile?.peekId == pane.id || outgoing; @@ -358,6 +366,8 @@ class _ChatWorkspaceState extends State sharedEdges[pane.id]?.contains('left') ?? false, rightEdgeShared: sharedEdges[pane.id]?.contains('right') ?? false, + movable: moveTargets != null, + moveTargets: moveTargets ?? const {}, child: Builder( builder: (paneContext) => widget.paneBuilder(paneContext, pane, active), diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index f15c296a..73eb364a 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -132,6 +132,29 @@ class ChatWorkspaceController extends ChangeNotifier { _changed(); } + int _moveSerial = 0; + Set _movedPaneIds = const {}; + + /// Increments with each [swap], so a renderer can animate just that move. + int get moveSerial => _moveSerial; + Set get movedPaneIds => _movedPaneIds; + + /// The two panes trade places in the tree; the split sizes stay. Each pane + /// keeps its id, so its retained chat view moves rather than rebuilding. + /// [paneId] is the pane being moved and stays (or becomes) active. + void swap(String paneId, String otherId) { + if (_root == null || paneId == otherId) return; + final all = panes; + final a = all.where((p) => p.id == paneId).firstOrNull; + final b = all.where((p) => p.id == otherId).firstOrNull; + if (a == null || b == null) return; + _root = swapChatWorkspacePanes(_root!, a, b); + _active = paneId; + _moveSerial++; + _movedPaneIds = {paneId, otherId}; + _changed(); + } + void resize(String splitId, double ratio) { if (_root == null || !ratio.isFinite) return; _root = _resize(_root!, splitId, ratio.clamp(.01, .99)); diff --git a/app/lib/features/chat/workspace/chat_workspace_geometry.dart b/app/lib/features/chat/workspace/chat_workspace_geometry.dart index c1e6ac9d..3900ff44 100644 --- a/app/lib/features/chat/workspace/chat_workspace_geometry.dart +++ b/app/lib/features/chat/workspace/chat_workspace_geometry.dart @@ -118,6 +118,47 @@ class ChatWorkspaceGeometry { ); } + /// The pane across [id]'s edge in [direction] (only a divider between + /// them) that a move swaps with: the one spanning [id]'s centre line, else + /// the one sharing the longest stretch of that edge. Null at an outer edge. + String? adjacent(String id, ChatPaneDirection direction) { + final origin = panes[id]; + if (origin == null) return null; + const slack = .5; + final horizontal = + direction == ChatPaneDirection.left || + direction == ChatPaneDirection.right; + final centre = horizontal ? origin.center.dy : origin.center.dx; + String? best; + var bestCentred = false; + var bestOverlap = 0.0; + for (final MapEntry(key: other, value: rect) in panes.entries) { + if (other == id) continue; + final gap = switch (direction) { + ChatPaneDirection.left => origin.left - rect.right, + ChatPaneDirection.right => rect.left - origin.right, + ChatPaneDirection.up => origin.top - rect.bottom, + ChatPaneDirection.down => rect.top - origin.bottom, + }; + if (gap < -slack || gap > chatPaneDividerExtent + slack) continue; + final overlap = horizontal + ? math.min(origin.bottom, rect.bottom) - math.max(origin.top, rect.top) + : math.min(origin.right, rect.right) - math.max(origin.left, rect.left); + if (overlap <= slack) continue; + final centred = horizontal + ? rect.top <= centre && centre < rect.bottom + : rect.left <= centre && centre < rect.right; + if (best == null || + centred && !bestCentred || + centred == bestCentred && overlap > bestOverlap) { + best = other; + bestCentred = centred; + bestOverlap = overlap; + } + } + return best; + } + String? neighbor(String active, ChatPaneDirection direction) { final origin = panes[active]; if (origin == null) return null; diff --git a/app/lib/features/chat/workspace/chat_workspace_nodes.dart b/app/lib/features/chat/workspace/chat_workspace_nodes.dart index bce7d994..8448c5b5 100644 --- a/app/lib/features/chat/workspace/chat_workspace_nodes.dart +++ b/app/lib/features/chat/workspace/chat_workspace_nodes.dart @@ -22,3 +22,25 @@ class ChatWorkspaceSplit extends ChatWorkspaceNode { final ChatWorkspaceNode first, second; final double ratio; } + +/// [root] with the leaves [a] and [b] trading places. Each leaf keeps its own +/// node (identity and chat); every split keeps its id, axis and ratio. +ChatWorkspaceNode swapChatWorkspacePanes( + ChatWorkspaceNode root, + ChatWorkspacePane a, + ChatWorkspacePane b, +) { + ChatWorkspaceNode visit(ChatWorkspaceNode node) => switch (node) { + ChatWorkspacePane(:final id) when id == a.id => b, + ChatWorkspacePane(:final id) when id == b.id => a, + ChatWorkspacePane() => node, + ChatWorkspaceSplit() => ChatWorkspaceSplit( + node.id, + node.axis, + visit(node.first), + visit(node.second), + ratio: node.ratio, + ), + }; + return visit(root); +} diff --git a/app/lib/features/chat/workspace/chat_workspace_pane_scope.dart b/app/lib/features/chat/workspace/chat_workspace_pane_scope.dart new file mode 100644 index 00000000..66ca8fde --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_pane_scope.dart @@ -0,0 +1,43 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +import 'chat_workspace_geometry.dart'; + +/// Describes the edge ownership of the pane currently being built, and the +/// panes it can trade places with. +class ChatWorkspacePaneScope extends InheritedWidget { + const ChatWorkspacePaneScope({ + super.key, + required this.topEdgeShared, + required this.bottomEdgeShared, + required this.leftEdgeShared, + required this.rightEdgeShared, + this.movable = false, + this.moveTargets = const {}, + required super.child, + }); + + final bool topEdgeShared; + final bool bottomEdgeShared; + final bool leftEdgeShared; + final bool rightEdgeShared; + + /// Whether the panes are tiled on screen, so moving one means something. + /// A single pane, or the phone's one-at-a-time layout, never moves. + final bool movable; + + /// The pane id a move in each direction swaps with; an outer edge has none. + final Map moveTargets; + + static ChatWorkspacePaneScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(ChatWorkspacePaneScope oldWidget) => + topEdgeShared != oldWidget.topEdgeShared || + bottomEdgeShared != oldWidget.bottomEdgeShared || + leftEdgeShared != oldWidget.leftEdgeShared || + rightEdgeShared != oldWidget.rightEdgeShared || + movable != oldWidget.movable || + !mapEquals(moveTargets, oldWidget.moveTargets); +} diff --git a/app/lib/features/chat/workspace/chat_workspace_surface.dart b/app/lib/features/chat/workspace/chat_workspace_surface.dart index 578c20d4..41f17f16 100644 --- a/app/lib/features/chat/workspace/chat_workspace_surface.dart +++ b/app/lib/features/chat/workspace/chat_workspace_surface.dart @@ -4,6 +4,7 @@ import '../../../ui/adaptive/host.dart'; import 'chat_mobile_panes.dart'; import 'chat_mobile_peek_divider.dart'; import 'chat_pane_backdrop.dart'; +import 'chat_pane_move_motion.dart'; import 'chat_pane_switch_motion.dart'; import 'chat_tape_exit.dart'; import 'chat_switch_card.dart'; @@ -18,6 +19,7 @@ Widget chatWorkspaceSurface({ required BuildContext context, required ChatPaneBackdrop backdrop, required ChatPaneSwitchMotion motion, + required ChatPaneMoveMotion move, required ChatWorkspaceController controller, required ChatWorkspaceGeometry geometry, required ChatMobilePanes? mobile, @@ -65,12 +67,14 @@ Widget chatWorkspaceSurface({ // built once per layout; ticks resize its real scroll viewport. AnimatedBuilder( key: ValueKey('chat-workspace-${pane.id}'), - animation: motion.animation, + animation: Listenable.merge([motion.animation, move.animation]), child: paneView(pane), builder: (context, child) => Positioned.fromRect( rect: motion.rectFor(pane.id) ?? - (collapsed ? Offset.zero & size : geometry.panes[pane.id]!), + (collapsed + ? Offset.zero & size + : move.rectFor(pane.id, geometry.panes[pane.id]!)), child: IgnorePointer( ignoring: motion.isRetainedOutgoing(pane.id) || diff --git a/app/lib/ui/adaptive/segmented_bar_overflow.dart b/app/lib/ui/adaptive/segmented_bar_overflow.dart index c444a8fb..f23c5ba8 100644 --- a/app/lib/ui/adaptive/segmented_bar_overflow.dart +++ b/app/lib/ui/adaptive/segmented_bar_overflow.dart @@ -27,6 +27,7 @@ class SegmentedOverflowEntry { required this.icon, this.onPressed, this.choices = const [], + this.shortcut, }); final String label; @@ -37,6 +38,10 @@ class SegmentedOverflowEntry { /// Choices offered under the entry instead of [onPressed]. final List choices; + + /// The keyboard shortcut the Material menu lists beside the entry. It is + /// shown only; the owner handles the keys itself. + final MenuSerializableShortcut? shortcut; } /// A bar action the bar may move into its More menu. An action that is not @@ -100,6 +105,7 @@ class SegmentedMoreButton extends StatelessWidget { MenuItemButton( leadingIcon: Icon(entry.icon), onPressed: entry.onPressed, + shortcut: entry.shortcut, child: Text(entry.label), ) else diff --git a/app/notes/chat-split-workspace.md b/app/notes/chat-split-workspace.md index 0f399f10..0e9f5f17 100644 --- a/app/notes/chat-split-workspace.md +++ b/app/notes/chat-split-workspace.md @@ -9,3 +9,13 @@ Each divider has a 12px grab area, a native theme separator, horizontal/vertical Ctrl+Shift+Arrow navigates spatially between panes. Command+Shift+Arrow also works on macOS. Chords are consumed at edges so they do not alter composer selection. The handler is gated by workspace focus and `shortcutsEnabled`; pointer activation does not request composer focus. The owner supplies `onFocusPane` for keyboard-only composer focus after layout. No sockets, requests or timers are introduced by these primitives. Checks: bounded analysis clean; eight watchdog tests passed, peak663MB,3s (`/tmp/memwatch/out.7uae7k`). Tests assert actual horizontal/vertical dragging and clamping, nested close collapse, leaf State/draft identity, narrow fallback/restoration, keyboard divider resizing/reset, spatial geometry, Ctrl navigation and macOS Command navigation without changing drafts. Commands from app/: `tool/analyze.sh lib/features/chat/workspace test/features/chat/workspace` and `tool/memwatch/full.sh 'test/features/chat/workspace --no-pub'`. Full-app integration and rendered captures are the manager's next check; no production services or chats were touched. + +## Moving panes + +Each tiled pane's More menu has **Move up**, **Move down**, **Move left** and **Move right** (Material lists the chord beside each). A move swaps the pane with the one across that edge: `ChatWorkspaceGeometry.adjacent` takes the pane separated only by a divider, preferring the one spanning the moved pane's centre line, then the longest shared edge, then reading order. A direction with no pane is disabled (Cupertino's action sheet leaves it out). Single panes and the phone's one-at-a-time layout offer nothing. Swapping was chosen over detach-and-reinsert because it keeps every split's id, axis and ratio, so tile sizes never change. + +`ChatWorkspaceController.swap` trades the two leaf nodes in the tree. Pane ids stay with their chats, so the keyed sibling views (scroll, composer draft, running turn) are reused, and the moved chat stays active and focused. The binding persists the swapped tree like any other edit (the federated store writes the same snapshot). `ChatPaneMoveMotion` glides the two retained views between their tiles over `Motion.standard`; reduced motion swaps instantly. + +Keyboard: Ctrl+Alt+Shift+Arrow (Command+Option+Shift+Arrow on macOS, where Ctrl also works) moves the active pane. It extends the Ctrl/Command+Shift+Arrow focus chord, is consumed at outer edges, and does not clash with Ctrl+Tab, Alt/Ctrl+T or Ctrl+1–9. Linux desktops that bind Ctrl+Alt+Shift+Arrow to "move window to workspace" keep that chord for themselves; the menu still works there. + +Checks: analysis clean; `tool/memwatch/full.sh 'test/features/chat test/shell'` 1328 passed (peak 1911 MB). New tests: `test/features/chat/workspace/chat_pane_move_test.dart` (nested adjacency, edges, swap both ways, persistence round trip, chord, mid-glide state/draft, reduced motion) and `test/features/chat/chat_pane_move_test.dart` (menu items enabled/disabled with shortcut, state/draft/stream/focus kept, persisted order, keyboard move, phone shows none). Fixture captures at 1280x800 (`chats=3&rich=1&colors=1`): before, menu open, after Move left, menu after. In headless Chrome the chord glyphs are tofu, and a right-edge menu is sized too narrow, until the symbol fallback font has loaded once. diff --git a/app/test/features/chat/chat_pane_move_test.dart b/app/test/features/chat/chat_pane_move_test.dart new file mode 100644 index 00000000..c5ae8e8a --- /dev/null +++ b/app/test/features/chat/chat_pane_move_test.dart @@ -0,0 +1,222 @@ +import 'dart:convert'; + +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/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/session_actions.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; + +import 'conversation/chat_thread_fixtures.dart'; + +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 ['a', 'b', 'c']) {'id': id, 'title': 'Chat $id'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Finder _thread(String id) => find.byWidgetPredicate( + (widget) => widget is ChatThreadView && widget.sessionId == id, +); +Finder _input(String id) => find.descendant( + of: find.byKey(ValueKey('chat-composer-$id')), + matching: find.byType(EditableText), +); + +Future<_Gateway> _setup(WidgetTester tester, {Size? size}) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = size ?? const Size(1800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatScreen(gateway: gateway, persistWorkspace: true), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat a').first); + await tester.pumpAndSettle(); + return gateway; +} + +Future _split(WidgetTester tester, String id) async { + await tester.tap( + find.byWidgetPredicate( + (widget) => widget is SessionActionsButton && widget.session['id'] == id, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open to the right')); + await tester.pumpAndSettle(); +} + +Future _openMenu(WidgetTester tester, String session) async { + await tester.tap( + find.descendant( + of: find.descendant( + of: _thread(session), + matching: find.byKey(const Key('chat-actions-island')), + ), + matching: find.byTooltip('More actions'), + ), + ); + await tester.pumpAndSettle(); +} + +MenuItemButton _item(WidgetTester tester, String label) => + tester.widget( + find.ancestor(of: find.text(label), matching: find.byType(MenuItemButton)), + ); + +ChatWorkspaceController _controller(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +void main() { + testWidgets( + 'pane menu moves a chat beside its neighbour and keeps its state', + (tester) async { + final gateway = await _setup(tester); + await _split(tester, 'b'); + final state = tester.state(_thread('a')); + await tester.enterText(_input('a'), 'Keep this draft'); + gateway.emitEvent( + chatTextFrame('Streamed to a', session: 'a', messageId: 'live-a'), + ); + await tester.pumpAndSettle(); + expect( + tester.getCenter(_thread('a')).dx, + lessThan(tester.getCenter(_thread('b')).dx), + ); + + await _openMenu(tester, 'a'); + expect(_item(tester, 'Move right').onPressed, isNotNull); + for (final label in ['Move up', 'Move down', 'Move left']) { + expect(_item(tester, label).onPressed, isNull, reason: label); + } + expect( + (_item(tester, 'Move right').shortcut! as SingleActivator) + .debugDescribeKeys(), + 'Control + Alt + Shift + Arrow Right', + ); + await tester.tap(find.text('Move right')); + await tester.pumpAndSettle(); + + expect( + tester.getCenter(_thread('a')).dx, + greaterThan(tester.getCenter(_thread('b')).dx), + ); + expect(tester.state(_thread('a')), same(state)); + expect( + tester.widget(_input('a')).controller.text, + 'Keep this draft', + ); + expect( + find.descendant(of: _thread('a'), matching: find.text('Streamed to a')), + findsOneWidget, + ); + expect(_controller(tester).activePane?.sessionId, 'a'); + expect( + tester.widget(_input('a')).focusNode.hasFocus, + isTrue, + ); + + // The new order is what a reload restores. + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + final preferences = await SharedPreferences.getInstance(); + final saved = preferences + .getKeys() + .where((key) => key.startsWith(chatWorkspacePreferenceKey)) + .map(preferences.getString) + .single!; + final root = jsonDecode(saved)['root'] as Map; + expect((root['first'] as Map)['session_id'], 'b'); + expect((root['second'] as Map)['session_id'], 'a'); + + await _openMenu(tester, 'a'); + expect(_item(tester, 'Move left').onPressed, isNotNull); + expect(_item(tester, 'Move right').onPressed, isNull); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets( + 'Ctrl+Alt+Shift+Arrow moves the focused chat with its draft and focus', + (tester) async { + await _setup(tester); + await _split(tester, 'b'); + final state = tester.state(_thread('b')); + await tester.enterText(_input('b'), 'Typed in b'); + await tester.pumpAndSettle(); + final text = tester.widget(_input('b')).controller; + final selection = text.selection; + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + expect( + tester.getCenter(_thread('b')).dx, + lessThan(tester.getCenter(_thread('a')).dx), + ); + expect(tester.state(_thread('b')), same(state)); + expect(text.text, 'Typed in b'); + expect(text.selection, selection); + expect( + tester.widget(_input('b')).focusNode.hasPrimaryFocus, + isTrue, + ); + expect(_controller(tester).activePane?.sessionId, 'b'); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets('a phone shows no move items for its one-at-a-time panes', ( + tester, + ) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(560, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage([]); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: ChatScreen(gateway: gateway))), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat a').first); + await tester.pumpAndSettle(); + _controller(tester).splitActive('b', ChatSplitAxis.horizontal); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('More actions').hitTestable().first); + await tester.pumpAndSettle(); + expect(find.text('Close pane'), findsOneWidget); + for (final label in ['Move up', 'Move down', 'Move left', 'Move right']) { + expect(find.text(label), findsNothing, reason: label); + } + }); +} diff --git a/app/test/features/chat/workspace/chat_pane_move_test.dart b/app/test/features/chat/workspace/chat_pane_move_test.dart new file mode 100644 index 00000000..4c727b48 --- /dev/null +++ b/app/test/features/chat/workspace/chat_pane_move_test.dart @@ -0,0 +1,236 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_pane_move_shortcuts.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_geometry.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_snapshot.dart'; + +/// a | (b over (c | d)): a on the left, b top right, c and d below b. +ChatWorkspaceController _nested() { + final controller = ChatWorkspaceController()..open('a'); + controller.splitActive('b', ChatSplitAxis.horizontal); + controller.splitActive('c', ChatSplitAxis.vertical); + controller.splitActive('d', ChatSplitAxis.horizontal); + return controller; +} + +String _id(ChatWorkspaceController controller, String session) => + controller.panes.firstWhere((pane) => pane.sessionId == session).id; + +Map _targets( + ChatWorkspaceController controller, + String session, +) { + final geometry = ChatWorkspaceGeometry( + controller.root!, + const Size(1200, 800), + ); + final names = {for (final p in controller.panes) p.id: p.sessionId}; + return { + for (final direction in ChatPaneDirection.values) + direction: names[geometry.adjacent(_id(controller, session), direction)], + }; +} + +class _Draft extends StatefulWidget { + const _Draft({super.key, required this.name}); + final String name; + @override + State<_Draft> createState() => _DraftState(); +} + +class _DraftState extends State<_Draft> { + final text = TextEditingController(); + @override + void dispose() { + text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + TextField(key: ValueKey('input-${widget.name}'), controller: text); +} + +Widget _host(ChatWorkspaceController controller, {bool reduce = false}) => + MaterialApp( + home: MediaQuery( + data: MediaQueryData( + size: const Size(1200, 800), + disableAnimations: reduce, + ), + child: Scaffold( + body: SizedBox( + width: 1200, + height: 800, + child: ChatWorkspace( + controller: controller, + paneBuilder: (_, pane, _) => + _Draft(key: ValueKey(pane.sessionId), name: pane.sessionId), + ), + ), + ), + ), + ); + +Future _chord(WidgetTester tester, LogicalKeyboardKey arrow) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(arrow); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); +} + +void main() { + test('adjacency follows nested splits and stops at outer edges', () { + final controller = _nested(); + addTearDown(controller.dispose); + expect(_targets(controller, 'a'), { + ChatPaneDirection.up: null, + ChatPaneDirection.down: null, + ChatPaneDirection.left: null, + // b and c share a's right edge equally and a's centre line falls in + // their divider: the tie goes to the first in reading order. + ChatPaneDirection.right: 'b', + }); + expect(_targets(controller, 'b'), { + ChatPaneDirection.up: null, + ChatPaneDirection.down: 'c', + ChatPaneDirection.left: 'a', + ChatPaneDirection.right: null, + }); + // Once d is wider it spans b's centre line, so b's move down takes d. + final bottom = + ((controller.root as ChatWorkspaceSplit).second as ChatWorkspaceSplit) + .second + as ChatWorkspaceSplit; + controller.resize(bottom.id, .3); + expect(_targets(controller, 'b')[ChatPaneDirection.down], 'd'); + controller.resize(bottom.id, .5); + expect(_targets(controller, 'c'), { + ChatPaneDirection.up: 'b', + ChatPaneDirection.down: null, + ChatPaneDirection.left: 'a', + ChatPaneDirection.right: 'd', + }); + expect(_targets(controller, 'd')[ChatPaneDirection.left], 'c'); + expect(_targets(controller, 'd')[ChatPaneDirection.up], 'b'); + }); + + test('swap trades places both ways, keeping ids, ratios and focus', () { + final controller = _nested(); + addTearDown(controller.dispose); + final outer = controller.root as ChatWorkspaceSplit; + controller.resize(outer.id, .3); + final ids = {for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s)}; + final serial = controller.moveSerial; + controller.swap(ids['a']!, ids['c']!); + expect(controller.panes.map((p) => p.sessionId), ['c', 'b', 'a', 'd']); + expect({for (final p in controller.panes) p.sessionId: p.id}, ids); + expect(controller.activePaneId, ids['a']); + expect(controller.moveSerial, serial + 1); + expect(controller.movedPaneIds, {ids['a'], ids['c']}); + expect((controller.root as ChatWorkspaceSplit).ratio, .3); + expect((controller.root as ChatWorkspaceSplit).id, outer.id); + controller.swap(ids['a']!, ids['c']!); + expect(controller.panes.map((p) => p.sessionId), ['a', 'b', 'c', 'd']); + controller.swap(ids['a']!, 'missing'); + controller.swap(ids['a']!, ids['a']!); + expect(controller.moveSerial, serial + 2); + }); + + test('a moved layout survives an encode/decode round trip', () { + final controller = _nested(); + addTearDown(controller.dispose); + controller.swap(_id(controller, 'b'), _id(controller, 'd')); + final source = controller.snapshot(sidebarMode: 'compact')!.encode(); + final restored = ChatWorkspaceController(); + addTearDown(restored.dispose); + expect(restored.restoreLayout(ChatWorkspaceSnapshot.decode(source)!), true); + expect(restored.panes.map((p) => p.sessionId), ['a', 'd', 'c', 'b']); + expect(restored.activePane?.sessionId, 'b'); + }); + + test('the move chord adds Alt to the focus chord, Command on macOS', () { + expect( + chatPaneMoveActivator( + ChatPaneDirection.up, + platform: TargetPlatform.macOS, + ).debugDescribeKeys(), + 'Alt + Meta + Shift + Arrow Up', + ); + expect( + chatPaneMoveActivator( + ChatPaneDirection.down, + platform: TargetPlatform.windows, + ).debugDescribeKeys(), + 'Control + Alt + Shift + Arrow Down', + ); + }); + + test('the chord family: Alt turns focusing into moving', () { + // Only real key events reach the handler; the parse is checked through + // the widget tests below. Here, the menu's chord and the handler agree. + final activator = chatPaneMoveActivator( + ChatPaneDirection.left, + platform: TargetPlatform.linux, + ); + expect(activator.trigger, LogicalKeyboardKey.arrowLeft); + expect( + [activator.control, activator.alt, activator.shift, activator.meta], + [true, true, true, false], + ); + }); + + testWidgets( + 'the chord moves the focused pane, keeps its draft, and is inert at edges', + (tester) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(_host(controller)); + final input = find.byKey(const ValueKey('input-one')); + await tester.enterText(input, 'draft one'); + final state = tester.state(find.byKey(const ValueKey('one'))); + final before = tester.getRect(input); + await _chord(tester, LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + // Mid-glide: the retained view is between its old and new tiles. + final middle = tester.getRect(input); + await tester.pumpAndSettle(); + final after = tester.getRect(input); + expect(middle.left, greaterThan(before.left)); + expect(after.left, greaterThan(middle.left)); + expect(tester.state(find.byKey(const ValueKey('one'))), same(state)); + expect(tester.widget(input).controller!.text, 'draft one'); + expect(controller.activePane?.sessionId, 'one'); + expect(controller.panes.map((p) => p.sessionId), ['two', 'one']); + final serial = controller.moveSerial; + await _chord(tester, LogicalKeyboardKey.arrowRight); + await _chord(tester, LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + expect(controller.moveSerial, serial); + expect(tester.widget(input).controller!.text, 'draft one'); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets('reduced motion swaps the panes instantly', (tester) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(_host(controller, reduce: true)); + final input = find.byKey(const ValueKey('input-one')); + final twoBefore = tester.getRect(find.byKey(const ValueKey('input-two'))); + controller.swap(_id(controller, 'one'), _id(controller, 'two')); + await tester.pump(); + expect(tester.getRect(input).left, twoBefore.left); + expect(tester.hasRunningAnimations, isFalse); + }); +}