diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index e89e7371..20371241 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -313,84 +313,99 @@ mixin _ChatScreenWorkspace on State { Widget _workspaceView() => SafeArea( top: false, - child: ChatWorkspace( - key: _workspaceKey, - controller: _workspace, - onVisibleSessionIdsChanged: _workspaceVisibilityChanged, - shortcutsEnabled: _workspaceVisible, - floatFrame: _floatFrame, - singlePane: !showsListBesideDetail(context), - mobilePeeks: true, - paneTitle: (pane) => - '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', - onFocusPane: (pane) => _composerFocus.request(pane.sessionId), - paneBuilder: (context, pane, active) { - final scope = ChatWorkspacePaneScope.maybeOf(context); - final topShared = scope?.topEdgeShared ?? false; - final bottomShared = scope?.bottomEdgeShared ?? false; - final leftShared = scope?.leftEdgeShared ?? false; - final rightShared = scope?.rightEdgeShared ?? false; - final activeColor = _workspace.paneCount > 1 && active - ? chatColorShade( - context, - chatSessionColor(_rowFor(pane.sessionId)), - ) ?? - (chatControlsStyleOf(context) == ChatControlsStyle.cupertino - ? CupertinoTheme.of(context).primaryColor - : Theme.of(context).colorScheme.primary) - : Colors.transparent; - return Semantics( - selected: active, - child: AnimatedContainer( - duration: showsListBesideDetail(context) - ? Motion.of(context, Motion.standard) - : Duration.zero, - curve: Motion.curve, - foregroundDecoration: BoxDecoration( - border: showsListBesideDetail(context) - ? Border( - top: bottomShared && !topShared - ? BorderSide(color: activeColor) - : BorderSide.none, - bottom: BorderSide( - color: bottomShared ? Colors.transparent : activeColor, + child: ChatCenterStageKeys( + controller: ChatCenterStageController.instance, + enabled: () => + _workspaceVisible && + _workspace.paneCount > 0 && + showsListBesideDetail(context) && + _chatOwnsKeyboard(), + child: ChatWorkspace( + key: _workspaceKey, + centerStage: ChatCenterStageController.instance, + paneColor: (pane) => + chatColorShade(context, chatSessionColor(_rowFor(pane.sessionId))), + controller: _workspace, + onVisibleSessionIdsChanged: _workspaceVisibilityChanged, + shortcutsEnabled: _workspaceVisible, + floatFrame: _floatFrame, + singlePane: !showsListBesideDetail(context), + mobilePeeks: true, + paneTitle: (pane) => + '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', + onFocusPane: (pane) => _composerFocus.request(pane.sessionId), + paneBuilder: (context, pane, active) { + final scope = ChatWorkspacePaneScope.maybeOf(context); + final topShared = scope?.topEdgeShared ?? false; + final bottomShared = scope?.bottomEdgeShared ?? false; + final leftShared = scope?.leftEdgeShared ?? false; + final rightShared = scope?.rightEdgeShared ?? false; + final activeColor = _workspace.paneCount > 1 && active + ? chatColorShade( + context, + chatSessionColor(_rowFor(pane.sessionId)), + ) ?? + (chatControlsStyleOf(context) == ChatControlsStyle.cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary) + : Colors.transparent; + return Semantics( + selected: active, + child: AnimatedContainer( + duration: showsListBesideDetail(context) + ? Motion.of(context, Motion.standard) + : Duration.zero, + curve: Motion.curve, + foregroundDecoration: BoxDecoration( + border: showsListBesideDetail(context) + ? Border( + top: bottomShared && !topShared + ? BorderSide(color: activeColor) + : BorderSide.none, + bottom: BorderSide( + color: bottomShared + ? Colors.transparent + : activeColor, + ), + left: bottomShared && topShared && !leftShared + ? BorderSide(color: activeColor) + : BorderSide.none, + right: + bottomShared && + topShared && + leftShared && + !rightShared + ? BorderSide(color: activeColor) + : BorderSide.none, + ) + : Border( + bottom: BorderSide( + color: bottomShared + ? Colors.transparent + : activeColor, + ), ), - left: bottomShared && topShared && !leftShared - ? BorderSide(color: activeColor) - : BorderSide.none, - right: - bottomShared && - topShared && - leftShared && - !rightShared - ? BorderSide(color: activeColor) - : BorderSide.none, - ) - : Border( - bottom: BorderSide( - color: bottomShared ? Colors.transparent : activeColor, - ), - ), - ), - // Every pane's bar carries its own chat's colour; beside the - // active pane the others fade theirs. - child: ChatPaneActivity( - inactive: _workspace.paneCount > 1 && !active, - child: DetailPane( - key: ValueKey('chat-pane-detail-${pane.id}'), - destination: AppDestination.chat, - implyBack: false, - builder: (context) => _thread( - pane.sessionId, - _back, - pane: pane, - paneContext: context, + ), + // Every pane's bar carries its own chat's colour; beside the + // active pane the others fade theirs. + child: ChatPaneActivity( + inactive: _workspace.paneCount > 1 && !active, + child: DetailPane( + key: ValueKey('chat-pane-detail-${pane.id}'), + destination: AppDestination.chat, + implyBack: false, + builder: (context) => _thread( + pane.sessionId, + _back, + pane: pane, + paneContext: context, + ), ), ), ), - ), - ); - }, + ); + }, + ), ), ); } diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index e8397dae..eef4bc39 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -34,6 +34,9 @@ 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_center_stage_action.dart'; +import 'workspace/chat_center_stage_controller.dart'; +import 'workspace/chat_center_stage_keys.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_workspace_entrance.dart'; import 'ui/sessions/chat_adaptive.dart'; @@ -526,6 +529,8 @@ class _ChatScreenState extends State materialIcon: Icons.view_quilt_outlined, cupertinoIcon: CupertinoIcons.square_split_2x2, ), + if (_workspace.paneCount > 1 && showsListBesideDetail(context)) + chatCenterStageAction(ChatCenterStageController.instance), ...chatPaneMoveActions( ChatWorkspacePaneScope.maybeOf(paneContext ?? context), onMove: (target) => _movePane(pane.id, target), diff --git a/app/lib/features/chat/workspace/chat_center_stage_action.dart b/app/lib/features/chat/workspace/chat_center_stage_action.dart new file mode 100644 index 00000000..262b3881 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_action.dart @@ -0,0 +1,23 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_center_stage_controller.dart'; + +/// The pane menu's center-stage toggle, naming its keyboard shortcut. +ChatBarAction chatCenterStageAction(ChatCenterStageController controller) { + final shortcut = chatCenterStageShortcutLabel(); + return ChatBarAction( + identifier: 'chat-center-stage-toggle', + label: controller.value + ? 'Leave center stage ($shortcut)' + : 'Center stage ($shortcut)', + onPressed: controller.toggle, + materialIcon: controller.value + ? Icons.view_quilt_outlined + : Icons.center_focus_strong_outlined, + cupertinoIcon: controller.value + ? CupertinoIcons.square_split_2x2 + : CupertinoIcons.viewfinder, + ); +} diff --git a/app/lib/features/chat/workspace/chat_center_stage_controller.dart b/app/lib/features/chat/workspace/chat_center_stage_controller.dart new file mode 100644 index 00000000..0b0c8602 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_controller.dart @@ -0,0 +1,99 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const chatCenterStagePreferenceKey = 'pipelines.next.chatCenterStage.v1'; + +abstract interface class ChatCenterStageStore { + Future load(); + Future save(bool on); +} + +class SharedChatCenterStageStore implements ChatCenterStageStore { + const SharedChatCenterStageStore(); + + @override + Future load() async { + try { + return (await SharedPreferences.getInstance()).getBool( + chatCenterStagePreferenceKey, + ); + } on Object { + return null; + } + } + + @override + Future save(bool on) async { + try { + return await (await SharedPreferences.getInstance()).setBool( + chatCenterStagePreferenceKey, + on, + ); + } on Object { + return false; + } + } +} + +/// Whether the wide chat workspace puts its active chat on center stage. +/// Device-local, like the quick-switch style: a presentation choice, not +/// part of any server's layout. +class ChatCenterStageController extends ValueNotifier { + ChatCenterStageController({ChatCenterStageStore? store}) + : _store = store ?? const SharedChatCenterStageStore(), + super(false); + + static final instance = ChatCenterStageController(); + final ChatCenterStageStore _store; + int _revision = 0; + bool _restored = false; + + /// Reads the saved choice once, unless it was changed meanwhile. + Future restore() async { + if (_restored) return; + _restored = true; + final revision = _revision; + final saved = await _store.load(); + if (saved != null && revision == _revision) super.value = saved; + } + + @override + set value(bool on) { + if (on == value) return; + _revision++; + super.value = on; + unawaited(_store.save(on)); + } + + void toggle() => value = !value; +} + +/// Whether [event] toggles center stage: Cmd+E on Apple platforms (where +/// Ctrl+E stays the text fields' and shell's end of line) and Ctrl+E +/// elsewhere, with no other modifier. Repeats of a held chord match too, so +/// they are swallowed; only the first press toggles. +bool chatCenterStageShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is KeyUpEvent || keyboard.isShiftPressed || keyboard.isAltPressed) { + return false; + } + if (event.logicalKey != LogicalKeyboardKey.keyE) return false; + return chatCenterStageUsesCommand(platform) + ? keyboard.isMetaPressed && !keyboard.isControlPressed + : keyboard.isControlPressed && !keyboard.isMetaPressed; +} + +bool chatCenterStageUsesCommand([TargetPlatform? platform]) { + final target = platform ?? defaultTargetPlatform; + return target == TargetPlatform.macOS || target == TargetPlatform.iOS; +} + +/// The shortcut as this platform shows it, for menus and tooltips. +String chatCenterStageShortcutLabel([TargetPlatform? platform]) => + chatCenterStageUsesCommand(platform) ? 'Cmd+E' : 'Ctrl+E'; diff --git a/app/lib/features/chat/workspace/chat_center_stage_keys.dart b/app/lib/features/chat/workspace/chat_center_stage_keys.dart new file mode 100644 index 00000000..a30a17ed --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_keys.dart @@ -0,0 +1,63 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../../ui/input/keyboard_owner.dart'; +import 'chat_center_stage_controller.dart'; + +/// Answers the center-stage chord before any focused widget sees it, so it +/// works from the composer, the sidebar or a toolbar, and the focused field +/// never types it. Handling the key also stops a browser's own Ctrl+E/Cmd+E +/// (address-bar search, find with selection) in the web build. +/// +/// On Apple platforms the chord is Cmd+E and works in the terminal too. +/// Elsewhere it is Ctrl+E, which the terminal keeps while it has the +/// keyboard: there it is the shell's end of line. +class ChatCenterStageKeys extends StatefulWidget { + const ChatCenterStageKeys({ + super.key, + required this.controller, + required this.enabled, + required this.child, + }); + + final ChatCenterStageController controller; + + /// Whether the chord belongs to this workspace now: wide, shown and with + /// no popup or other destination over it. + final bool Function() enabled; + final Widget child; + + @override + State createState() => _ChatCenterStageKeysState(); +} + +class _ChatCenterStageKeysState extends State { + @override + void initState() { + super.initState(); + FocusManager.instance.addEarlyKeyEventHandler(_key); + unawaited(widget.controller.restore()); + } + + @override + void dispose() { + FocusManager.instance.removeEarlyKeyEventHandler(_key); + super.dispose(); + } + + KeyEventResult _key(KeyEvent event) { + if (!mounted || + !chatCenterStageShortcut(event, HardwareKeyboard.instance) || + !widget.enabled() || + (!chatCenterStageUsesCommand() && primaryFocusIsTypingSurface())) { + return KeyEventResult.ignored; + } + if (event is KeyDownEvent) widget.controller.toggle(); + return KeyEventResult.handled; + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/app/lib/features/chat/workspace/chat_center_stage_layout.dart b/app/lib/features/chat/workspace/chat_center_stage_layout.dart new file mode 100644 index 00000000..64b22d36 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_layout.dart @@ -0,0 +1,78 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import '../conversation/chat_reading_width.dart'; +import 'chat_workspace_geometry.dart'; + +/// How much wider than the transcript's reading column the stage is: enough +/// for the copy gutter and some air on each side, not much more. +const double chatCenterStageWidthFactor = 1.25; + +/// The stage's preferred width: [kChatReadingWidth] plus a modest margin. +const double chatCenterStageWidth = + kChatReadingWidth * chatCenterStageWidthFactor; + +/// The narrowest a pane beside the stage gets; wide enough for its colour +/// and a vertical title. +const double chatCenterStageStripMinimumWidth = 56; + +/// The gap between the stage and each pane beside it. +const double chatCenterStageGap = chatPaneDividerExtent; + +/// Where every pane sits while one chat is on center stage. Panes keep their +/// split-tree order left to right; the stage takes the full height and its +/// preferred width (capped by the workspace), and the others share the rest +/// as columns. A column narrower than a usable pane is shown as a strip. +class ChatCenterStageLayout { + ChatCenterStageLayout._(this.rects, this.strips, this.stageId); + + final Map rects; + + /// Panes too narrow to use, shown as a title strip over their retained view. + final Set strips; + final String stageId; + + /// Null when there is nothing to stage (one pane) or no room for a stage + /// beside every other pane's strip. + static ChatCenterStageLayout? of( + Size size, + List order, + String? activeId, + ) { + if (order.length < 2 || activeId == null || !order.contains(activeId)) { + return null; + } + final others = order.length - 1; + final available = size.width - chatCenterStageGap * others; + final stage = math.min( + chatCenterStageWidth, + available - others * chatCenterStageStripMinimumWidth, + ); + if (stage < chatPaneMinimumWidth) return null; + final column = (available - stage) / others; + final rects = {}; + final strips = {}; + var left = 0.0; + for (final id in order) { + final width = id == activeId ? stage : column; + rects[id] = Rect.fromLTWH(left, 0, width, size.height); + if (id != activeId && width < chatPaneMinimumWidth) strips.add(id); + left += width + chatCenterStageGap; + } + return ChatCenterStageLayout._(rects, strips, activeId); + } + + /// The pane beside [active] in [direction]: columns run left to right, so + /// up and down have none. + String? neighbor(String active, ChatPaneDirection direction) { + final order = rects.keys.toList(); + final index = order.indexOf(active); + if (index < 0) return null; + final next = switch (direction) { + ChatPaneDirection.left => index - 1, + ChatPaneDirection.right => index + 1, + _ => -1, + }; + return next < 0 || next >= order.length ? null : order[next]; + } +} diff --git a/app/lib/features/chat/workspace/chat_center_stage_motion.dart b/app/lib/features/chat/workspace/chat_center_stage_motion.dart new file mode 100644 index 00000000..fad8bfdd --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_motion.dart @@ -0,0 +1,129 @@ +import 'dart:math' as math; +import 'dart:ui' show lerpDouble; + +import 'package:flutter/widgets.dart'; + +import 'chat_center_stage_layout.dart'; +import 'chat_workspace_geometry.dart'; + +/// Moves the retained pane views between the split layout and center stage, +/// and the stage between chats. Only a change of role animates (entering, +/// leaving, a new stage chat); a divider drag or window resize follows at once. +class ChatCenterStageMotion { + ChatCenterStageMotion({required TickerProvider vsync}) + : _controller = AnimationController( + vsync: vsync, + duration: duration, + value: 1, + // Reduced motion already settles in [layout] (the context's + // MediaQuery), so the controller does not shorten itself again. + animationBehavior: AnimationBehavior.preserve, + ); + + /// Short enough to follow a quick switch, long enough to read as a move. + static const Duration duration = Duration(milliseconds: 350); + + /// Material's emphasized easing: most of the travel early, then a long, + /// soft landing. + static const Curve curve = Curves.easeInOutCubicEmphasized; + + final AnimationController _controller; + Listenable get animation => _controller; + bool get isAnimating => _controller.isAnimating; + double get _t => curve.transform(_controller.value); + + String? _role; + Map _from = const {}, _to = const {}; + Set _stripsFrom = const {}, _stripsTo = const {}; + ChatCenterStageLayout? _stage; + + /// The stage the panes rest in (or travel to), null in the split layout. + ChatCenterStageLayout? get stage => _stage; + + /// Whether the split layout's dividers apply: not on stage, nor on the way. + bool get showsDividers => _stage == null && !isAnimating; + + /// Called on each workspace layout. [stage] is null while the split layout + /// applies; [split] is the split layout's geometry. [engaged] false (a phone + /// or collapsed window) releases every pane to the workspace's own layout. + void layout({ + required bool engaged, + required Map split, + required ChatCenterStageLayout? stage, + required bool animate, + }) { + if (!engaged) { + _role = null; + _stage = null; + _from = _to = const {}; + _stripsFrom = _stripsTo = const {}; + _controller.value = 1; + return; + } + // A pane moved beside the stage glides to its new column as well. + final role = stage == null + ? 'split' + : 'stage:${stage.stageId}:${stage.rects.keys.join(',')}'; + final rects = stage?.rects ?? split; + final strips = stage?.strips ?? const {}; + _stage = stage; + if (role == _role) { + // Same arrangement: follow sizes at once, or retarget a running move. + if (!isAnimating) _from = rects; + _to = rects; + if (!isAnimating) _stripsFrom = strips; + _stripsTo = strips; + return; + } + final first = _role == null; + _role = role; + if (first || !animate) { + _from = _to = rects; + _stripsFrom = _stripsTo = strips; + _controller.value = 1; + return; + } + _from = { + for (final id in rects.keys) id: rectFor(id) ?? split[id] ?? rects[id]!, + }; + _stripsFrom = { + for (final id in rects.keys) + if (stripFor(id) > .5) id, + }; + _to = rects; + _stripsTo = strips; + _controller.forward(from: 0); + } + + /// Where [id] paints now, or null when this motion does not place it: at + /// rest in the split layout the workspace's own geometry (and its pane-move + /// glide) applies. + Rect? rectFor(String id) { + if (_stage == null && !isAnimating) return null; + final to = _to[id]; + if (to == null) return null; + if (!isAnimating) return to; + return Rect.lerp(_from[id] ?? to, to, _t); + } + + /// How far [id]'s title strip covers it, from 0 (live chat) to 1. + double stripFor(String id) { + final to = _stripsTo.contains(id) ? 1.0 : 0.0; + if (!isAnimating) return to; + final from = _stripsFrom.contains(id) ? 1.0 : 0.0; + return lerpDouble(from, to, _t)!; + } + + /// The size [id]'s chat is laid out at. A strip keeps its chat at a usable + /// width beneath the title, so the transcript never reflows into a sliver. + /// While moving, each chat is laid out once at its destination size and only + /// its clipped, painted rectangle travels: no transcript relayout per frame. + Size? viewportFor(String id) { + if (_role == null || (_stage == null && !isAnimating)) return null; + final rect = _to[id]; + if (rect == null) return null; + return Size(math.max(rect.width, chatPaneMinimumWidth), rect.height); + } + + void dispose() => _controller.dispose(); +} diff --git a/app/lib/features/chat/workspace/chat_center_stage_strip.dart b/app/lib/features/chat/workspace/chat_center_stage_strip.dart new file mode 100644 index 00000000..7dc576bc --- /dev/null +++ b/app/lib/features/chat/workspace/chat_center_stage_strip.dart @@ -0,0 +1,107 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +/// Covers a chat beside the stage too narrow to use: its colour and title, +/// running down the column. A press brings that chat to center stage. The +/// retained chat underneath keeps its state. +class ChatCenterStageStrip extends StatelessWidget { + const ChatCenterStageStrip({ + super.key, + required this.paneId, + required this.title, + required this.color, + required this.onSelected, + }); + + final String paneId; + final String title; + final Color? color; + final VoidCallback onSelected; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final scheme = Theme.of(context).colorScheme; + final accent = + color ?? + (cupertino ? CupertinoTheme.of(context).primaryColor : scheme.primary); + final background = Color.alphaBlend( + accent.withValues(alpha: .12), + cupertino + ? CupertinoColors.secondarySystemBackground.resolveFrom(context) + : scheme.surfaceContainer, + ); + final style = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.titleSmall; + final label = Padding( + padding: const EdgeInsets.symmetric(vertical: 16), + child: Column( + children: [ + Icon(Icons.circle, color: accent, size: style?.fontSize), + const SizedBox(height: 12), + Expanded( + child: RotatedBox( + quarterTurns: 1, + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: style, + ), + ), + ), + ], + ), + ); + return Semantics( + identifier: 'chat-center-stage-strip-$paneId', + button: true, + label: 'Show $title on center stage', + excludeSemantics: true, + onTap: onSelected, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + color: background, + borderRadius: BorderRadius.zero, + onPressed: onSelected, + child: SizedBox.expand(child: label), + ) + : Tooltip( + message: title, + excludeFromSemantics: true, + child: Material( + color: background, + child: InkWell( + onTap: onSelected, + child: SizedBox.expand(child: label), + ), + ), + ), + ); + } +} + +/// One pane's painted layer: its retained [view], with its strip fading in +/// over it while the pane sits (or travels to sit) beside the stage. The +/// structure never changes, so moving in or out of center stage keeps the +/// view's state; a covered view is out of focus traversal. +Widget chatCenterStageLayer({ + required double strip, + required bool covered, + required Widget view, + required Widget Function()? buildStrip, +}) => Stack( + fit: StackFit.expand, + children: [ + ExcludeFocus(excluding: covered, child: view), + if (strip > 0 && buildStrip != null) + IgnorePointer( + ignoring: !covered, + child: Opacity(opacity: strip.clamp(0, 1), child: buildStrip()), + ), + ], +); diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart index 68e2e0e2..bd7579d4 100644 --- a/app/lib/features/chat/workspace/chat_workspace.dart +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -5,6 +5,9 @@ import 'package:flutter/services.dart'; import '../../../ui/motion/motion.dart'; import '../../../ui/motion/quick_switch_animation.dart'; +import 'chat_center_stage_layout.dart'; +import 'chat_center_stage_motion.dart'; +import 'chat_center_stage_strip.dart'; import 'chat_float_binding.dart'; import 'chat_float_host.dart'; import 'chat_workspace_controller.dart'; @@ -39,6 +42,8 @@ class ChatWorkspace extends StatefulWidget { this.animationStyle, this.paneTitle, this.onVisibleSessionIdsChanged, + this.centerStage, + this.paneColor, this.floatFrame, }); final ChatWorkspaceController controller; @@ -52,6 +57,13 @@ class ChatWorkspace extends StatefulWidget { final String Function(ChatWorkspacePane)? paneTitle; final ValueChanged>? onVisibleSessionIdsChanged; + /// While true on a wide window, the active chat takes center stage and the + /// others line up beside it (see [ChatCenterStageLayout]). + final ValueListenable? centerStage; + + /// A pane's chat colour, for its strip beside the stage. + final Color? Function(ChatWorkspacePane)? paneColor; + /// Offers the floating chat (see [ChatFloatHost]) in this frame; null for a /// workspace without one. It shows only while the panes are not collapsed. final ChatFloatFrame? floatFrame; @@ -73,6 +85,7 @@ class _ChatWorkspaceState extends State /// floating window. final Map _views = {}; late final ChatPaneSwitchMotion _motion; + late final ChatCenterStageMotion _stage = ChatCenterStageMotion(vsync: this); late final ChatPaneMoveMotion _move = ChatPaneMoveMotion(vsync: this); int _moveSerial = 0; bool _tiled = false; @@ -126,12 +139,22 @@ class _ChatWorkspaceState extends State 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); + final stage = _stage.stage; + final target = id == null + ? null + : stage != null + ? stage.neighbor(id, direction) + : _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); + final stage = _stage.stage; + final target = id == null + ? null + : stage != null + ? stage.neighbor(id, direction) + : _geometry?.neighbor(id, direction); if (target != null) { widget.controller.activate(target); final pane = widget.controller.activePane!; @@ -155,6 +178,7 @@ class _ChatWorkspaceState extends State _backdrop.dispose(); _motion.animation.removeStatusListener(_motionSettled); _motion.dispose(); + _stage.dispose(); _move.dispose(); _focus.dispose(); for (final node in _panes.values) { @@ -170,6 +194,7 @@ class _ChatWorkspaceState extends State listenable: Listenable.merge([ widget.controller, QuickSwitchAnimationController.instance, + ?widget.centerStage, ]), builder: (context, _) => LayoutBuilder( builder: (context, constraints) { @@ -250,6 +275,17 @@ class _ChatWorkspaceState extends State QuickSwitchAnimationController.instance.value, ); } + final engaged = !collapsed && mobile == null; + _stage.layout( + engaged: engaged, + split: geometry.panes, + stage: engaged && widget.centerStage?.value == true + ? ChatCenterStageLayout.of(constraints.biggest, [ + for (final pane in panes) pane.id, + ], activeId) + : null, + animate: !MediaQuery.disableAnimationsOf(context), + ); _reportVisible({ for (final pane in panes) if (mobile != null @@ -296,6 +332,7 @@ class _ChatWorkspaceState extends State for (final edge in const ['top', 'bottom', 'left', 'right']) if (!collapsed && mobile == null && + _stage.stage == null && sharesEdge(entry.value, edge)) edge, }, @@ -304,6 +341,8 @@ class _ChatWorkspaceState extends State context: context, backdrop: _backdrop, motion: _motion, + stage: _stage, + stageStrip: _strip, move: _move, controller: widget.controller, geometry: geometry, @@ -342,6 +381,22 @@ class _ChatWorkspaceState extends State ), ); + Widget _strip(ChatWorkspacePane pane) => ChatCenterStageStrip( + paneId: pane.id, + title: widget.paneTitle?.call(pane) ?? pane.sessionId, + color: widget.paneColor?.call(pane), + onSelected: () { + FocusManager.instance.primaryFocus?.unfocus(); + widget.controller.activate(pane.id); + // Choosing a strip is choosing that chat: its composer takes the + // keyboard once it is on stage. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || widget.controller.activePaneId != pane.id) return; + widget.onFocusPane?.call(pane); + }); + }, + ); + Widget _paneView( ChatWorkspacePane pane, ChatMobilePanes? mobile, diff --git a/app/lib/features/chat/workspace/chat_workspace_surface.dart b/app/lib/features/chat/workspace/chat_workspace_surface.dart index 41f17f16..f8138cb7 100644 --- a/app/lib/features/chat/workspace/chat_workspace_surface.dart +++ b/app/lib/features/chat/workspace/chat_workspace_surface.dart @@ -1,6 +1,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; +import 'chat_center_stage_motion.dart'; +import 'chat_center_stage_strip.dart'; import 'chat_mobile_panes.dart'; import 'chat_mobile_peek_divider.dart'; import 'chat_pane_backdrop.dart'; @@ -19,6 +21,7 @@ Widget chatWorkspaceSurface({ required BuildContext context, required ChatPaneBackdrop backdrop, required ChatPaneSwitchMotion motion, + required ChatCenterStageMotion stage, required ChatPaneMoveMotion move, required ChatWorkspaceController controller, required ChatWorkspaceGeometry geometry, @@ -27,7 +30,13 @@ Widget chatWorkspaceSurface({ required Size size, required List panes, required Widget Function(ChatWorkspacePane) paneView, + Widget Function(ChatWorkspacePane)? stageStrip, }) { + final moving = Listenable.merge([ + motion.animation, + stage.animation, + move.animation, + ]); final ordered = mobile?.paintOrder(panes) ?? panes; final picture = backdrop.image != null && mobile != null && motion.isTape ? AnimatedBuilder( @@ -67,11 +76,12 @@ Widget chatWorkspaceSurface({ // built once per layout; ticks resize its real scroll viewport. AnimatedBuilder( key: ValueKey('chat-workspace-${pane.id}'), - animation: Listenable.merge([motion.animation, move.animation]), + animation: moving, child: paneView(pane), builder: (context, child) => Positioned.fromRect( rect: motion.rectFor(pane.id) ?? + stage.rectFor(pane.id) ?? (collapsed ? Offset.zero & size : move.rectFor(pane.id, geometry.panes[pane.id]!)), @@ -92,11 +102,18 @@ Widget chatWorkspaceSurface({ child: ChatSwitchCard( motion: motion, outgoing: motion.isRetainedOutgoing(pane.id), - child: ChatMotionViewport( - size: mobile != null && motion.isAnimating && !motion.isTape - ? motion.viewportRectFor(pane.id)?.size - : null, - child: child!, + child: chatCenterStageLayer( + strip: stage.stripFor(pane.id), + covered: stage.stage?.strips.contains(pane.id) ?? false, + buildStrip: stageStrip == null + ? null + : () => stageStrip(pane), + view: ChatMotionViewport( + size: mobile != null && motion.isAnimating && !motion.isTape + ? motion.viewportRectFor(pane.id)?.size + : stage.viewportFor(pane.id), + child: child!, + ), ), ), ), @@ -107,7 +124,7 @@ Widget chatWorkspaceSurface({ return ChatPanePicture( key: backdrop.pictureKey, child: AnimatedBuilder( - animation: motion.animation, + animation: moving, builder: (context, _) => Stack( fit: StackFit.expand, clipBehavior: Clip.hardEdge, @@ -139,7 +156,7 @@ Widget chatWorkspaceSurface({ onChanged: controller.resizeMobilePeek, ), ), - if (!collapsed && mobile == null) + if (!collapsed && mobile == null && stage.showsDividers) for (final divider in geometry.dividers) Positioned.fromRect( key: ValueKey('chat-workspace-${divider.split.id}'), diff --git a/app/notes/chat-center-stage.md b/app/notes/chat-center-stage.md new file mode 100644 index 00000000..9c751e96 --- /dev/null +++ b/app/notes/chat-center-stage.md @@ -0,0 +1,85 @@ +# Chat center stage + +A toggle for the wide (browser/desktop) split chat workspace. While it is on, +the active chat takes center stage and the other chats line up beside it; the +stage follows whichever chat becomes active. Phones (the one-chat layout) are +unchanged. + +## Using it + +- Cmd+E on macOS/iOS, Ctrl+E elsewhere, or the pane's More menu: + **Center stage (Cmd+E)** / **Leave center stage (Cmd+E)** (shown with two or + more panes on a wide window). +- The choice is device-local (`pipelines.next.chatCenterStage.v1` in shared + preferences) and survives reloads. It is not part of the server-scoped + workspace snapshot. +- Any activation moves the stage: clicking or tapping a strip (which also + focuses that chat's composer), Ctrl/Cmd+Shift+Left/Right, Ctrl+Tab, opening an + already-open chat from the list, quick switch, or the Open chats picker. + Opening a new chat from the list replaces the staged chat, as in the split + layout. +- Ctrl/Cmd+Alt+Shift+Left/Right (pane moves) moves the staged chat along the + strip order. Up/down have no neighbours on stage. +- The floating chat (Ctrl/Cmd+Y) is not tiled, so it is never staged or + stripped; a chat docked back into the tiling becomes active and takes the + stage. + +## Checks + +- `tool/memwatch/full.sh 'test/features/chat test/shell'`: 1356 passed, 1 + failed (the new float/dock test's own wrong expectation, fixed after). Then + `test/features/chat/workspace`: 85 passed, 0 failed. `tool/analyze.sh`: clean. +- Captures (`chats=3&rich=1&colors=1`, 1440x900, three panes, headless Chrome, + macOS platform, so Cmd+E): normal split, center stage on, stage moved to + api refactor, and back to the same split sizes, plus filmed toggle-on, switch + and toggle-off. Headless Chrome delivered only a few frames per transition. + +## Layout (`chat_center_stage_layout.dart`) + +- Stage width = `kChatReadingWidth` (760, the transcript's reading column) x + 1.25 = 950, capped so every other pane keeps at least a 56 px strip. Stage + and strips take the full height and are separated by the 12 px divider gap. +- Panes keep their split-tree order left to right. The others share the + remaining width. A column narrower than `chatPaneMinimumWidth` (240) is + covered by a strip (`ChatCenterStageStrip`: the chat colour, a dot and the + title running down the column, Material InkWell / CupertinoButton). Wider + columns, on very wide screens, stay as live, usable chats. +- If there is not room for a 240 px stage plus every strip, or there is only + one pane, the split layout stays. +- The split tree, ratios and dividers are never touched, so leaving center + stage restores the exact split sizes. Dividers are hidden on stage. + +## Motion (`chat_center_stage_motion.dart`) + +- 350 ms, `Curves.easeInOutCubicEmphasized`, for entering, leaving and the + stage moving between chats. Divider drags and window resizes follow at once. + Durations are scaled by the animation-speed setting through the global clock; + reduced motion (MediaQuery) settles instantly. +- Every chat view stays one retained sibling (no reparenting, no remount): the + painted, clipped rectangle travels while each chat is laid out once at its + destination size, so drafts, scroll positions and running turns are kept + and transcripts do not relayout per frame. A covered strip lays its chat out + at 240 px underneath and excludes it from focus traversal. + +## Keyboard and browser + +`ChatCenterStageKeys` is a FocusManager early key handler (like the terminal's +toggle), so the chord works while a composer, the sidebar or a toolbar has +focus and is never typed. A plain `e` and the other platform's chord pass +through: on a Mac, Ctrl+E stays the text fields' end-of-line. Elsewhere Ctrl+E +is left to the terminal while it has focus (the shell's end-of-line); on a Mac +Cmd+E works in the terminal too. Handling the key makes the Flutter web engine +call `preventDefault`, so Chrome's Ctrl+E (address bar search on +Windows/Linux) and Cmd+E (use selection for Find on macOS) do not fire while +the app has the keyboard. Neither is a browser-reserved shortcut. Only +CDP-injected keys were used in captures, so the physical browser default was +not observed directly. + +## Files + +New: `lib/features/chat/workspace/chat_center_stage_{layout,motion,controller,keys,strip,action}.dart`, +`test/features/chat/workspace/chat_center_stage_test.dart`. +Small edits: `chat_workspace.dart` (centerStage/paneColor parameters, motion, +stage-aware neighbours), `chat_workspace_surface.dart` (stage rects, viewport, +strip layer, dividers), `chat_screen_workspace.dart` (keys wrapper, colours), +`screen.dart` (menu action). diff --git a/app/test/features/chat/workspace/chat_center_stage_test.dart b/app/test/features/chat/workspace/chat_center_stage_test.dart new file mode 100644 index 00000000..2948e6f9 --- /dev/null +++ b/app/test/features/chat/workspace/chat_center_stage_test.dart @@ -0,0 +1,345 @@ +import 'package:flutter/foundation.dart'; +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_center_stage_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_center_stage_keys.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_center_stage_layout.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_center_stage_strip.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_motion_viewport.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_geometry.dart'; + +class _MemoryStore implements ChatCenterStageStore { + _MemoryStore(); + bool? saved; + @override + Future load() async => saved; + @override + Future save(bool on) async { + saved = on; + return true; + } +} + +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 workspace, + ChatCenterStageController stage, { + double width = 1368, + bool singlePane = false, + bool reduceMotion = false, + List? fieldKeys, +}) => MaterialApp( + home: MediaQuery( + data: MediaQueryData(disableAnimations: reduceMotion), + child: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: width, + height: 800, + child: ChatCenterStageKeys( + controller: stage, + enabled: () => !singlePane, + child: ChatWorkspace( + controller: workspace, + centerStage: stage, + singlePane: singlePane, + paneTitle: (pane) => pane.sessionId, + paneBuilder: (_, pane, active) => Focus( + onKeyEvent: (_, event) { + fieldKeys?.add(event); + return KeyEventResult.ignored; + }, + child: _Draft( + key: ValueKey(pane.sessionId), + name: pane.sessionId, + ), + ), + ), + ), + ), + ), + ), + ), +); + +ChatWorkspaceController threePanes() => ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal) + ..splitActive('three', ChatSplitAxis.horizontal); + +void wide(WidgetTester tester) { + tester.view + ..physicalSize = const Size(1600, 1000) + ..devicePixelRatio = 1; + addTearDown(tester.view.reset); +} + +double widthOf(WidgetTester tester, String session) => + tester.getSize(find.byKey(ValueKey('input-$session'))).width; + +void main() { + group('layout', () { + test( + 'stage is the reading width plus a quarter, others share the rest', + () { + final layout = ChatCenterStageLayout.of(const Size(1368, 800), [ + 'a', + 'b', + 'c', + ], 'b')!; + expect(chatCenterStageWidth, 950); + expect(layout.rects['b'], const Rect.fromLTWH(209, 0, 950, 800)); + expect(layout.rects['a'], const Rect.fromLTWH(0, 0, 197, 800)); + expect(layout.rects['c']!.right, 1368); + expect(layout.strips, {'a', 'c'}); + expect(layout.neighbor('b', ChatPaneDirection.left), 'a'); + expect(layout.neighbor('b', ChatPaneDirection.right), 'c'); + expect(layout.neighbor('b', ChatPaneDirection.up), isNull); + }, + ); + + test('a narrow workspace caps the stage to leave every strip', () { + final layout = ChatCenterStageLayout.of(const Size(700, 800), [ + 'a', + 'b', + 'c', + ], 'a')!; + expect(layout.rects['a']!.width, 700 - 24 - 2 * 56); + expect(layout.rects['c']!.right, 700); + expect( + ChatCenterStageLayout.of(const Size(300, 800), ['a', 'b'], 'a'), + isNull, + ); + }); + + test('a very wide workspace keeps the stage and shows live columns', () { + final layout = ChatCenterStageLayout.of(const Size(2560, 800), [ + 'a', + 'b', + ], 'a')!; + expect(layout.rects['a']!.width, 950); + expect(layout.strips, isEmpty); + expect( + ChatCenterStageLayout.of(const Size(2560, 800), ['a'], 'a'), + isNull, + ); + }); + }); + + testWidgets('toggling stages the active chat, keeps drafts and split sizes', ( + tester, + ) async { + wide(tester); + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()); + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + final split = (workspace.root! as ChatWorkspaceSplit).id; + workspace.resize(split, .3); + await tester.pumpWidget(host(workspace, stage)); + await tester.enterText(find.byKey(const ValueKey('input-three')), 'draft'); + final before = { + for (final id in ['one', 'two', 'three']) id: widthOf(tester, id), + }; + + stage.value = true; + await tester.pump(); + await tester.pump(const Duration(milliseconds: 40)); + // Mid-flight the stage's painted rectangle is on its way, while its chat + // is laid out once, at its destination width. + final painted = tester + .getSize( + find.ancestor( + of: find.byKey(const ValueKey('input-three')), + matching: find.byType(ChatMotionViewport), + ), + ) + .width; + expect(painted, inExclusiveRange(before['three']!, 950)); + expect(widthOf(tester, 'three'), 950); + await tester.pumpAndSettle(); + expect(widthOf(tester, 'three'), 950); + expect(find.byType(ChatCenterStageStrip), findsNWidgets(2)); + expect(find.text('draft'), findsOneWidget); + + stage.value = false; + await tester.pumpAndSettle(); + for (final id in before.keys) { + expect(widthOf(tester, id), before[id]); + } + expect((workspace.root! as ChatWorkspaceSplit).ratio, .3); + expect(find.byType(ChatCenterStageStrip), findsNothing); + expect(find.text('draft'), findsOneWidget); + }); + + testWidgets('the stage follows the active chat and strip presses', ( + tester, + ) async { + wide(tester); + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()) + ..value = true; + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + await tester.pumpWidget(host(workspace, stage)); + await tester.enterText(find.byKey(const ValueKey('input-three')), 'kept'); + expect(widthOf(tester, 'three'), 950); + + workspace.activate(workspace.panes.first.id); + await tester.pumpAndSettle(); + expect(widthOf(tester, 'one'), 950); + expect(widthOf(tester, 'three'), chatPaneMinimumWidth); + + await tester.tap(find.bySemanticsLabel('Show two on center stage')); + await tester.pumpAndSettle(); + expect(workspace.activePane?.sessionId, 'two'); + expect(widthOf(tester, 'two'), 950); + expect(find.text('kept'), findsOneWidget); + }); + + testWidgets( + 'the floating chat is not staged; a docked chat takes the stage', + (tester) async { + wide(tester); + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()) + ..value = true; + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + await tester.pumpWidget(host(workspace, stage)); + workspace.float(workspace.panes.first.id); + await tester.pumpAndSettle(); + expect(workspace.activePane?.sessionId, 'three'); + expect(widthOf(tester, 'three'), 950); + // One chat beside the stage has room to stay a live column. + expect(widthOf(tester, 'two'), 1368 - 12 - 950); + expect(find.byType(ChatCenterStageStrip), findsNothing); + + workspace.dock(); + await tester.pumpAndSettle(); + expect(workspace.activePane?.sessionId, 'one'); + expect(widthOf(tester, 'one'), 950); + expect(find.byType(ChatCenterStageStrip), findsNWidgets(2)); + }, + ); + + testWidgets('reduced motion stages at once', (tester) async { + wide(tester); + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()); + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + await tester.pumpWidget(host(workspace, stage, reduceMotion: true)); + stage.value = true; + await tester.pump(); + expect(widthOf(tester, 'three'), 950); + }); + + testWidgets('phones keep their one-chat layout', (tester) async { + final workspace = threePanes(); + final stage = ChatCenterStageController(store: _MemoryStore()) + ..value = true; + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + await tester.pumpWidget( + host(workspace, stage, width: 400, singlePane: true), + ); + expect(widthOf(tester, 'three'), 400); + expect(find.byType(ChatCenterStageStrip), findsNothing); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyE); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + expect(stage.value, isTrue); + }); + + for (final mac in [false, true]) { + testWidgets( + '${mac ? 'Cmd' : 'Ctrl'}+E toggles; a plain e reaches the field', + (tester) async { + wide(tester); + debugDefaultTargetPlatformOverride = mac + ? TargetPlatform.macOS + : TargetPlatform.linux; + final workspace = threePanes(); + final store = _MemoryStore(); + final stage = ChatCenterStageController(store: store); + addTearDown(workspace.dispose); + addTearDown(stage.dispose); + final keys = []; + await tester.pumpWidget(host(workspace, stage, fieldKeys: keys)); + await tester.tap(find.byKey(const ValueKey('input-three'))); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.keyE); + expect(stage.value, isFalse); + expect(keys.whereType(), hasLength(1)); + + final modifier = mac + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.controlLeft; + final other = mac + ? LogicalKeyboardKey.controlLeft + : LogicalKeyboardKey.metaLeft; + keys.clear(); + await tester.sendKeyDownEvent(modifier); + await tester.sendKeyEvent(LogicalKeyboardKey.keyE); + await tester.sendKeyUpEvent(modifier); + expect(stage.value, isTrue); + expect(store.saved, isTrue); + expect( + keys.whereType().map((e) => e.logicalKey), + isNot(contains(LogicalKeyboardKey.keyE)), + ); + await tester.pumpAndSettle(); + expect(widthOf(tester, 'three'), 950); + + // The other platform's chord stays with the field (Ctrl+E on a Mac is + // its end of line). + await tester.sendKeyDownEvent(other); + await tester.sendKeyEvent(LogicalKeyboardKey.keyE); + await tester.sendKeyUpEvent(other); + expect(stage.value, isTrue); + debugDefaultTargetPlatformOverride = null; + }, + ); + } + + test('the choice is remembered', () async { + final store = _MemoryStore(); + final first = ChatCenterStageController(store: store)..toggle(); + await Future.delayed(Duration.zero); + expect(store.saved, isTrue); + first.dispose(); + final next = ChatCenterStageController(store: store); + await next.restore(); + expect(next.value, isTrue); + next.dispose(); + }); + + test('labels name the platform chord', () { + expect(chatCenterStageShortcutLabel(TargetPlatform.macOS), 'Cmd+E'); + expect(chatCenterStageShortcutLabel(TargetPlatform.windows), 'Ctrl+E'); + }); +}