From fd62df3815cea874370f87dba5f63508ed8b9b59 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:07:00 +0000 Subject: [PATCH 1/8] Chat stack: a floating pile of the open chats as phone chat navigation (WIP) --- app/lib/application/bootstrap.dart | 3 + app/lib/features/chat/chat_screen_stack.dart | 96 +++++ .../features/chat/chat_screen_workspace.dart | 120 +++--- .../chat/conversation/chat_thread_view.dart | 18 +- app/lib/features/chat/screen.dart | 8 +- .../chat/stack/chat_stack_anchor.dart | 43 ++ .../chat/stack/chat_stack_column.dart | 312 +++++++++++++++ .../features/chat/stack/chat_stack_disc.dart | 158 ++++++++ .../features/chat/stack/chat_stack_entry.dart | 56 +++ .../features/chat/stack/chat_stack_fab.dart | 369 ++++++++++++++++++ .../chat/stack/chat_stack_motion.dart | 106 +++++ .../features/chat/stack/chat_stack_pose.dart | 202 ++++++++++ .../chat/stack/mobile_chat_navigation.dart | 99 +++++ .../settings_chat_navigation_section.dart | 82 ++++ .../settings/settings_page_sections.dart | 6 + .../features/settings/settings_screen.dart | 1 + .../chat/stack/chat_stack_fab_test.dart | 219 +++++++++++ .../chat/stack/chat_stack_screen_test.dart | 152 ++++++++ ...settings_chat_navigation_section_test.dart | 64 +++ 19 files changed, 2066 insertions(+), 48 deletions(-) create mode 100644 app/lib/features/chat/chat_screen_stack.dart create mode 100644 app/lib/features/chat/stack/chat_stack_anchor.dart create mode 100644 app/lib/features/chat/stack/chat_stack_column.dart create mode 100644 app/lib/features/chat/stack/chat_stack_disc.dart create mode 100644 app/lib/features/chat/stack/chat_stack_entry.dart create mode 100644 app/lib/features/chat/stack/chat_stack_fab.dart create mode 100644 app/lib/features/chat/stack/chat_stack_motion.dart create mode 100644 app/lib/features/chat/stack/chat_stack_pose.dart create mode 100644 app/lib/features/chat/stack/mobile_chat_navigation.dart create mode 100644 app/lib/features/settings/settings_chat_navigation_section.dart create mode 100644 app/test/features/chat/stack/chat_stack_fab_test.dart create mode 100644 app/test/features/chat/stack/chat_stack_screen_test.dart create mode 100644 app/test/features/settings/settings_chat_navigation_section_test.dart diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart index 880137bd..cc93839c 100644 --- a/app/lib/application/bootstrap.dart +++ b/app/lib/application/bootstrap.dart @@ -1,3 +1,4 @@ +import '../features/chat/stack/mobile_chat_navigation.dart'; import '../features/terminal/terminal_layout.dart'; import '../core/session/server_session.dart'; import '../ui/scale/ui_scale.dart'; @@ -73,6 +74,7 @@ Future runPipelinesApp({ final terminalLayout = TerminalLayout.instance.restore(); final quickSwitchAnimation = QuickSwitchAnimationController.instance .restore(); + final chatNavigation = MobileChatNavigationController.instance.restore(); final font = AppFontController.instance.restore(wait: appFontStartupWait); final design = AppDesignController.instance.restore(); // A phone behind the web login reconnects with its kept session. @@ -83,6 +85,7 @@ Future runPipelinesApp({ await uiScale; await terminalLayout; await quickSwitchAnimation; + await chatNavigation; final server = await resolveLaunchServer( base: base, configured: configured, diff --git a/app/lib/features/chat/chat_screen_stack.dart b/app/lib/features/chat/chat_screen_stack.dart new file mode 100644 index 00000000..765b8c77 --- /dev/null +++ b/app/lib/features/chat/chat_screen_stack.dart @@ -0,0 +1,96 @@ +part of 'screen.dart'; + +/// The phone's chat stack (Settings → Chat navigation → Chat stack): one +/// floating pile of the open chats above the workspace, following the spot +/// the chat on screen marks above its composer. Its chats are the +/// workspace's panes, the same open chats the server syncs; choosing one +/// opens it as a tap on its list row does, Add chat is the pane menu's Add +/// chat pane, and removing one closes its pane. +mixin _ChatScreenStack on State, _ChatScreenWorkspace { + final LayerLink _stackLink = LayerLink(); + + void _openBySelection(JsonMap session); + + @override + MobileChatNavigationController get _navigation => + MobileChatNavigationController.instance; + + /// Whether this layout navigates with the stack rather than the peek. + @override + bool _stacked(BuildContext context) => + _navigation.stack && !showsListBesideDetail(context); + + /// Gives the active pane the stack's spot. + @override + Widget _stackScope(BuildContext context, bool active, Widget child) => + ChatStackAnchorScope( + link: active && _stacked(context) ? _stackLink : null, + child: child, + ); + + List _stackEntries() { + final live = { + for (final row in _sessionsForSidebar.sessions) '${row['id'] ?? ''}': row, + }; + final active = _workspace.activePaneId; + return [ + for (final pane in _workspace.panes) + ChatStackEntry( + paneId: pane.id, + session: + live[pane.sessionId] ?? + _rowFor(pane.sessionId) ?? + {'id': pane.sessionId}, + current: pane.id == active, + ), + ]; + } + + /// The pile over the workspace; it draws only while linked to the chat on + /// screen. + @override + Widget _stackOverlay() => ListenableBuilder( + listenable: Listenable.merge([_workspace, _sessionsForSidebar]), + builder: (context, _) => CompositedTransformFollower( + link: _stackLink, + showWhenUnlinked: false, + child: ChatStackFab( + entries: _stackEntries(), + onOpen: (entry) => _openBySelection(entry.session), + onAdd: _addPane, + onRemove: _removeFromStack, + ), + ), + ); + + void _removeFromStack(ChatStackEntry entry) { + final messenger = ScaffoldMessenger.maybeOf(context); + final wasActive = _workspace.activePaneId; + _closePane(entry.paneId); + if (messenger == null) return; + messenger + ..hideCurrentSnackBar() + ..showSnackBar( + SnackBar( + content: Text('Removed ${entry.title} from open chats'), + action: SnackBarAction( + label: 'Undo', + onPressed: () => _restoreToStack(entry, wasActive), + ), + ), + ); + } + + void _restoreToStack(ChatStackEntry entry, String? wasActive) { + if (!mounted || _workspace.holdsSession(entry.sessionId)) return; + _openedSessions[entry.sessionId] = entry.session; + _workspace.splitActive(entry.sessionId, ChatSplitAxis.horizontal); + // The chat on screen stays on screen unless it was the one removed. + if (wasActive != null && wasActive != entry.paneId) { + final kept = _workspace.panes + .where((pane) => pane.id == wasActive) + .firstOrNull; + if (kept != null) _workspace.activate(kept.id); + } + } +} diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index ea8d4415..3b22551f 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -479,7 +479,32 @@ mixin _ChatScreenWorkspace on State { }); } - Widget _workspaceView() => SafeArea( + /// See [_ChatScreenStack]. + bool _stacked(BuildContext context); + Widget _stackScope(BuildContext context, bool active, Widget child); + Widget _stackOverlay(); + MobileChatNavigationController get _navigation; + + Widget _workspaceView() => ListenableBuilder( + listenable: _navigation, + builder: (context, _) { + final stacked = _stacked(context); + final workspace = _tiledWorkspace(context, stacked: stacked); + if (!stacked) return workspace; + return Stack( + fit: StackFit.expand, + children: [ + workspace, + Positioned(left: 0, top: 0, child: _stackOverlay()), + ], + ); + }, + ); + + Widget _tiledWorkspace( + BuildContext context, { + required bool stacked, + }) => SafeArea( top: false, child: ChatCenterStageKeys( controller: ChatCenterStageController.instance, @@ -502,7 +527,8 @@ mixin _ChatScreenWorkspace on State { onMoveTargetsChanged: _paneMoveTargetsChanged, shortcutsEnabled: _workspaceVisible, singlePane: !showsListBesideDetail(context), - mobilePeeks: true, + // The chat stack replaces the peek of the next chat. + mobilePeeks: !stacked, paneTitle: (pane) => '${_rowFor(pane.sessionId)?['title'] ?? pane.sessionId}', onFocusPane: (pane) => _composerFocus.request(pane.sessionId), @@ -520,50 +546,54 @@ mixin _ChatScreenWorkspace on State { ) ?? 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, + return _stackScope( + context, + active, + 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: KeyedSubtree( - key: ValueKey('chat-pane-detail-${pane.id}'), - child: _thread(pane), + ), + // 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: KeyedSubtree( + key: ValueKey('chat-pane-detail-${pane.id}'), + child: _thread(pane), + ), ), ), ), diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 0500deb3..c7d69d59 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -99,6 +99,7 @@ import 'chat_permission_group.dart'; import 'chat_question_group.dart'; import 'chat_transcript_card.dart'; import '../workspace/chat_workspace_pane_scope.dart'; +import '../stack/chat_stack_anchor.dart'; /// One read-only conversation: the controller's transcript in the order the /// server reports it, rendered by the existing [ChatMessageView]. @@ -1368,6 +1369,13 @@ class _ChatThreadViewState extends State with ChatFindHost { reading, ); final media = MediaQuery.paddingOf(context); + // The phone's chat stack floats bottom-end above the + // composer while this chat holds it: the last line and + // Jump to latest stay clear of it. + final stackLink = ChatStackAnchorScope.of(context); + final stackClearance = stackLink == null + ? 0.0 + : kChatStackClearance; // The date shows once per calendar day, above that day's // first row; each row itself shows only its time. final days = chatDayDividers(rows); @@ -1444,7 +1452,7 @@ class _ChatThreadViewState extends State with ChatFindHost { side - gutter, media.top + 8, side, - 8, + 8 + stackClearance, ), children: chatCopyGutterInset(gutter, transcript, [ if (initialLoad) @@ -1538,10 +1546,16 @@ class _ChatThreadViewState extends State with ChatFindHost { ), ), ?findBar(top: media.top + 8, end: side + 8), + if (stackLink != null) + PositionedDirectional( + end: side + 12, + bottom: 8, + child: ChatStackAnchorTarget(link: stackLink), + ), if (showJump) PositionedDirectional( end: side + 16, - bottom: 16, + bottom: 16 + stackClearance, child: _ChatJumpToLatest( key: const Key('chat-jump-to-latest'), label: chatJumpToLatestLabel(newMessages), diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index ce9df7e3..a1f43b19 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -41,6 +41,10 @@ import 'conversation/chat_quick_switch_dialog.dart'; import 'conversation/chat_sidebar_controls.dart'; import 'ui/sessions/chat_compact_sidebar.dart'; import 'workspace/chat_workspace.dart'; +import 'stack/chat_stack_anchor.dart'; +import 'stack/chat_stack_entry.dart'; +import 'stack/chat_stack_fab.dart'; +import 'stack/mobile_chat_navigation.dart'; import 'workspace/chat_center_stage_action.dart'; import 'workspace/chat_center_stage_controller.dart'; import 'workspace/chat_center_stage_keys.dart'; @@ -67,6 +71,7 @@ part 'chat_screen_float.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; part 'chat_screen_quick_switch.dart'; +part 'chat_screen_stack.dart'; part 'chat_screen_workspace.dart'; /// The Chat destination's list/detail switch. @@ -126,7 +131,8 @@ class _ChatScreenState extends State _ChatScreenFloat, _ChatScreenPaneMenu, _ChatScreenQuickSwitch, - _ChatScreenAttention { + _ChatScreenAttention, + _ChatScreenStack { /// The chats' shared state: the list, opened rows, accepted models, /// transcript positions and caches (see [ChatRuntime]). @override diff --git a/app/lib/features/chat/stack/chat_stack_anchor.dart b/app/lib/features/chat/stack/chat_stack_anchor.dart new file mode 100644 index 00000000..b5260cc0 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_anchor.dart @@ -0,0 +1,43 @@ +import 'package:flutter/widgets.dart'; + +import 'chat_stack_disc.dart'; + +/// Where the chat stack sits in the chat on screen. The stack itself lives +/// once above all the panes, so it keeps its state (and finishes folding) +/// while the chat under it changes; the active chat marks its spot with a +/// [ChatStackAnchorTarget] that the stack follows. +class ChatStackAnchorScope extends InheritedWidget { + const ChatStackAnchorScope({ + super.key, + required this.link, + required super.child, + }); + + /// The stack's link while this pane holds it; null for every other pane. + final LayerLink? link; + + static LayerLink? of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.link; + + @override + bool updateShouldNotify(ChatStackAnchorScope oldWidget) => + !identical(link, oldWidget.link); +} + +/// The room the stack takes above a chat's composer: the transcript keeps +/// its last line and its own floating controls clear of it. +const double kChatStackClearance = kChatStackSlot + 12; + +/// The stack's slot in a chat's transcript area, bottom-end above the +/// composer. +class ChatStackAnchorTarget extends StatelessWidget { + const ChatStackAnchorTarget({super.key, required this.link}); + + final LayerLink link; + + @override + Widget build(BuildContext context) => CompositedTransformTarget( + link: link, + child: const SizedBox.square(dimension: kChatStackSlot), + ); +} diff --git a/app/lib/features/chat/stack/chat_stack_column.dart b/app/lib/features/chat/stack/chat_stack_column.dart new file mode 100644 index 00000000..908c9eb9 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_column.dart @@ -0,0 +1,312 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_entry.dart'; +import 'chat_stack_motion.dart'; +import 'chat_stack_pose.dart'; + +/// The chat stack fanned out: a scrim over the screen and the open chats in +/// a column rising from the stack's own slot, each avatar with its name in a +/// small pill beside it, and Add chat at the top. +/// +/// Item 0 sits exactly on the collapsed stack, nearest the thumb. The chats +/// keep the open-chat order (the order the server syncs), so a chat keeps +/// its place in the column from one visit to the next; the chat on screen +/// wears a ring in its colour. Add chat is last, at the top: the reachable +/// bottom slots go to the frequent action (switching), and the rarer one +/// ends the list where the operator reads "and more". +/// +/// Nothing here rebuilds per frame: every item moves through +/// [ChatStackPoseTransition] and fades through [FadeTransition], both +/// repaint-only. +class ChatStackColumn extends StatelessWidget { + const ChatStackColumn({ + super.key, + required this.motion, + required this.anchor, + required this.entries, + required this.depths, + required this.interactive, + required this.onOpen, + required this.onAdd, + required this.onDismiss, + this.onRemove, + }); + + final ChatStackMotion motion; + + /// The collapsed stack's slot in this overlay's coordinates. + final Rect anchor; + final List entries; + + /// Each item's layer in the collapsed pile (null when it is not drawn + /// there); the add item last. + final List depths; + + /// False while folding back: taps fall through to nothing. + final bool interactive; + final ValueChanged onOpen; + final VoidCallback onAdd; + final VoidCallback onDismiss; + + /// Long press removes a chat from the open chats; null when it cannot + /// (the only open chat). + final ValueChanged? onRemove; + + static const removeLabel = 'Remove from open chats'; + static const addLabel = 'Add chat'; + + @override + Widget build(BuildContext context) { + final media = MediaQuery.of(context); + final scheme = Theme.of(context).colorScheme; + final dark = Theme.of(context).brightness == Brightness.dark; + final rtl = Directionality.of(context) == TextDirection.rtl; + return LayoutBuilder( + builder: (context, constraints) { + final size = constraints.biggest; + final count = motion.count; + final height = (count - 1) * kChatStackPitch + kChatStackSlot; + final top = media.padding.top + 8; + final available = anchor.bottom - top; + final fits = height <= available; + // The column's own edge is the stack's; the labels take the rest of + // the row back to a margin at the other side. + final endInset = rtl ? anchor.left : size.width - anchor.right; + const margin = 16.0; + final width = size.width - endInset - margin; + final labelMax = width - kChatStackSlot - kChatStackLabelGap; + // Paint the pile's order while it opens: hidden layers first, the + // top of the pile last. + final order = [for (var i = 0; i < count; i++) i] + ..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99)); + final items = Stack( + clipBehavior: Clip.none, + children: [ + for (final i in order) ...[ + _label(context, i, labelMax), + _item(context, i), + ], + ], + ); + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.escape): onDismiss, + }, + child: FocusScope( + autofocus: true, + child: IgnorePointer( + ignoring: !interactive, + child: Stack( + children: [ + Positioned.fill( + child: FadeTransition( + opacity: motion.scrim, + child: ModalBarrier( + color: scheme.scrim.withValues(alpha: dark ? .5 : .32), + dismissible: true, + onDismiss: onDismiss, + semanticsLabel: 'Close chats', + ), + ), + ), + PositionedDirectional( + end: endInset, + bottom: size.height - anchor.bottom, + top: top, + width: width, + child: Align( + alignment: AlignmentDirectional.bottomEnd, + child: SingleChildScrollView( + reverse: true, + clipBehavior: fits ? Clip.none : Clip.hardEdge, + child: SizedBox( + width: width, + height: height, + child: Semantics( + container: true, + explicitChildNodes: true, + label: 'Open chats', + child: items, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + Widget _item(BuildContext context, int i) { + final entry = i < entries.length ? entries[i] : null; + return PositionedDirectional( + key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'), + end: 0, + bottom: 0, + // The transform is outermost: the boxes under it sit at the stack's + // slot, and only a transform passes hits on to where it paints them. + child: ChatStackPoseTransition( + progress: motion.move[i], + from: motion.from[i], + to: motion.target[i], + child: FadeTransition( + opacity: motion.fade[i], + child: KeyedSubtree( + key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'), + child: entry == null ? _addButton(context) : _chatButton(entry), + ), + ), + ), + ); + } + + Widget _label(BuildContext context, int i, double maxWidth) { + final entry = i < entries.length ? entries[i] : null; + return PositionedDirectional( + key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'), + end: kChatStackSlot + kChatStackLabelGap, + bottom: 0, + height: kChatStackSlot, + child: ChatStackPoseTransition( + progress: motion.label[i], + from: motion.labelFrom[i], + to: motion.target[i], + child: ExcludeSemantics( + child: FadeTransition( + opacity: motion.label[i], + child: Align( + alignment: AlignmentDirectional.centerEnd, + widthFactor: 1, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: GestureDetector( + onTap: entry == null ? onAdd : () => onOpen(entry), + onLongPress: entry == null || onRemove == null + ? null + : () => onRemove!(entry), + child: ChatStackLabel( + text: entry?.title ?? addLabel, + color: entry?.color(context), + emphasized: entry?.current ?? false, + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _chatButton(ChatStackEntry entry) => Builder( + builder: (context) { + final remove = onRemove; + final ring = entry.current + ? entry.color(context) ?? Theme.of(context).colorScheme.primary + : null; + return Semantics( + container: true, + button: true, + selected: entry.current, + label: entry.title, + hint: entry.current ? 'Open now' : null, + onTap: () => onOpen(entry), + customSemanticsActions: remove == null + ? null + : { + const CustomSemanticsAction(label: removeLabel): () => + remove(entry), + }, + child: _Tappable( + autofocus: entry.current, + onTap: () => onOpen(entry), + onLongPress: remove == null ? null : () => remove(entry), + child: ChatStackDisc(ring: ring, child: chatStackAvatar(entry)), + ), + ); + }, + ); + + Widget _addButton(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final tokens = AppDesignTokens.of(context); + return Semantics( + container: true, + button: true, + label: addLabel, + onTap: onAdd, + child: _Tappable( + onTap: onAdd, + child: ChatStackDisc( + child: DecoratedBox( + decoration: ShapeDecoration( + color: tokens.flat ? null : scheme.primaryContainer, + shape: chatStackShape(tokens).copyWith( + side: tokens.flat + ? BorderSide(color: scheme.primary.withValues(alpha: .55)) + : BorderSide.none, + ), + ), + child: Icon( + Icons.add, + color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer, + ), + ), + ), + ), + ); + } +} + +/// A disc's ink and focus: the splash is drawn over the disc (the disc is +/// opaque, so ink under it would never show), in the design's shape. +class _Tappable extends StatelessWidget { + const _Tappable({ + required this.child, + required this.onTap, + this.onLongPress, + this.autofocus = false, + }); + + final Widget child; + final VoidCallback onTap; + final VoidCallback? onLongPress; + final bool autofocus; + + @override + Widget build(BuildContext context) { + final shape = chatStackShape(AppDesignTokens.of(context)); + return Stack( + children: [ + child, + Positioned.fill( + child: Padding( + padding: const EdgeInsets.all( + (kChatStackSlot - kChatStackDisc) / 2, + ), + child: Material( + type: MaterialType.transparency, + shape: shape, + clipBehavior: Clip.antiAlias, + child: InkWell( + autofocus: autofocus, + excludeFromSemantics: true, + customBorder: shape, + onTap: onTap, + onLongPress: onLongPress, + ), + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_disc.dart b/app/lib/features/chat/stack/chat_stack_disc.dart new file mode 100644 index 00000000..5795d1ac --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_disc.dart @@ -0,0 +1,158 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/layout/app_list_avatar.dart'; +import '../../../ui/theme/app_design_tokens.dart'; + +/// The square every stack item occupies: a touch target at least as large as +/// the platform's minimum. +const double kChatStackSlot = 48; + +/// The disc behind an avatar: the avatar plus a rim on each side. +const double kChatStackDisc = kChatStackSlot - 4; + +/// The vertical distance between neighbouring items of the open column. +const double kChatStackPitch = kChatStackSlot + 8; + +/// The gap between an item's name label and its avatar. +const double kChatStackLabelGap = 10; + +/// An opaque disc in the design's shape (a circle, or a framed square under a +/// flat design) that carries one avatar of the stack. The list avatar's fill +/// is translucent; the disc keeps stacked avatars from showing through each +/// other, and its rim separates them. A raised design drops a short shadow; +/// a flat one keeps its hairline frame instead. +class ChatStackDisc extends StatelessWidget { + const ChatStackDisc({ + super.key, + required this.child, + this.ring, + this.shadow = true, + }); + + final Widget child; + + /// The rim's colour when it marks the current chat; null for the surface. + final Color? ring; + + /// Whether this disc may cast a shadow (a layer under another does not). + final bool shadow; + + @override + Widget build(BuildContext context) { + final tokens = AppDesignTokens.of(context); + final scheme = Theme.of(context).colorScheme; + final base = tokens.panelFill(scheme, scheme.surface); + final ring = this.ring; + final shape = chatStackShape(tokens); + final frame = tokens.frameSide; + return SizedBox.square( + dimension: kChatStackSlot, + child: Center( + child: DecoratedBox( + decoration: ShapeDecoration( + color: ring ?? base, + shape: shape.copyWith( + side: ring == null && frame != null ? frame : BorderSide.none, + ), + shadows: shadow && !tokens.flat ? chatStackShadows(scheme) : null, + ), + child: SizedBox.square( + dimension: kChatStackDisc, + child: Center( + child: DecoratedBox( + // The avatar's own tint lands on an opaque face, so the + // colour reads the same as in the list. + decoration: ShapeDecoration(color: base, shape: shape), + child: SizedBox.square( + dimension: kAppListAvatarSize, + child: child, + ), + ), + ), + ), + ), + ), + ); + } +} + +/// A circle, or the design's rounded square when it is flat (as the list's +/// avatar draws itself). +OutlinedBorder chatStackShape(AppDesignTokens tokens) => tokens.flat + ? RoundedRectangleBorder(borderRadius: tokens.corners(BorderRadius.zero)) + : const CircleBorder(); + +/// A short, close shadow: enough to lift a layer off the one below without a +/// halo over the transcript. +List chatStackShadows(ColorScheme scheme) => [ + BoxShadow( + color: scheme.shadow.withValues(alpha: .18), + blurRadius: 4, + offset: const Offset(0, 1), + ), + BoxShadow( + color: scheme.shadow.withValues(alpha: .10), + blurRadius: 10, + offset: const Offset(0, 4), + ), +]; + +/// The name beside an avatar in the open column: a small pill tinted with +/// the chat's colour over an opaque face, one line, ellipsised. +class ChatStackLabel extends StatelessWidget { + const ChatStackLabel({ + super.key, + required this.text, + this.color, + this.emphasized = false, + }); + + final String text; + final Color? color; + final bool emphasized; + + @override + Widget build(BuildContext context) { + final tokens = AppDesignTokens.of(context); + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final base = tokens.panelFill(scheme, scheme.surfaceContainerHigh); + final color = this.color; + final dark = theme.brightness == Brightness.dark; + final fill = color == null + ? base + : Color.alphaBlend(color.withValues(alpha: dark ? .22 : .14), base); + final style = (theme.textTheme.labelLarge ?? const TextStyle()).copyWith( + color: scheme.onSurface, + fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500, + ); + return DecoratedBox( + decoration: ShapeDecoration( + color: fill, + shape: _labelShape(tokens), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: Text( + text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + softWrap: false, + style: style, + ), + ), + ); + } + + ShapeBorder _labelShape(AppDesignTokens tokens) { + final side = tokens.frameSide ?? BorderSide.none; + final r = tokens.radius; + return r == null + ? StadiumBorder(side: side) + : RoundedRectangleBorder( + borderRadius: BorderRadius.circular(r), + side: side, + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_entry.dart b/app/lib/features/chat/stack/chat_stack_entry.dart new file mode 100644 index 00000000..8133c6a3 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_entry.dart @@ -0,0 +1,56 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_colors.dart'; +import '../domain/chat_list_activity.dart'; +import '../domain/chat_sessions.dart'; +import '../ui/sessions/chat_color_palette.dart'; +import '../ui/sessions/session_row_content.dart'; + +/// One open chat as the chat stack shows it: the pane that holds it and the +/// chat's latest list row (its title, colour, harness and live state). +@immutable +class ChatStackEntry { + const ChatStackEntry({ + required this.paneId, + required this.session, + this.current = false, + }); + + final String paneId; + final JsonMap session; + + /// Whether this is the chat on screen. + final bool current; + + String get sessionId => '${session['id'] ?? ''}'; + String get title => chatSessionTitle(session); + + bool get _closed => session['closed_at'] != null || session['closed'] == true; + + /// Unanswered approvals and questions: the agent is blocked on the + /// operator. + int get awaitingOperator => + _closed ? 0 : chatSessionAwaitingOperator(session); + bool get running => session['running'] == true; + + /// The chat's colour as the list draws it, or null for none. + Color? color(BuildContext context) => + chatColorShade(context, chatSessionColor(session)); +} + +/// [entry]'s list avatar; with [cues] it keeps the list's corner badge +/// (waiting on the operator, working, background tasks). +Widget chatStackAvatar(ChatStackEntry entry, {bool cues = true}) => + ChatSessionAvatar( + session: entry.session, + awaitingOperator: cues ? entry.awaitingOperator : 0, + running: cues && entry.running, + backgroundTasks: cues && !entry.running + ? chatSessionBackgroundTasks(entry.session) + : 0, + selected: entry.current, + ); + +/// The collapsed stack's spoken name: "Chats, 5 open". +String chatStackLabel(int count) => 'Chats, $count open'; diff --git a/app/lib/features/chat/stack/chat_stack_fab.dart b/app/lib/features/chat/stack/chat_stack_fab.dart new file mode 100644 index 00000000..eafa67bb --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_fab.dart @@ -0,0 +1,369 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/motion/motion.dart'; +import '../../../ui/theme/app_design_tokens.dart'; +import '../ui/sessions/chat_awaiting.dart'; +import 'chat_stack_column.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_entry.dart'; +import 'chat_stack_motion.dart'; +import 'chat_stack_pose.dart'; + +/// The phone's chat stack: the open chats' avatars piled up, the chat on +/// screen on top, a floating button above the composer. A tap fans them out +/// into a column ([ChatStackColumn]); a tap outside, Back or Escape folds +/// them back. It steps aside while the on-screen keyboard is up. +class ChatStackFab extends StatefulWidget { + const ChatStackFab({ + super.key, + required this.entries, + required this.onOpen, + required this.onAdd, + this.onRemove, + }); + + /// The open chats in their synced order; one is [ChatStackEntry.current]. + final List entries; + final ValueChanged onOpen; + + /// Add chat, given the stack's own context to anchor a picker to. + final ValueChanged onAdd; + final ValueChanged? onRemove; + + @override + State createState() => ChatStackFabState(); +} + +class ChatStackFabState extends State + with SingleTickerProviderStateMixin, WidgetsBindingObserver { + late final AnimationController _open = AnimationController( + vsync: this, + duration: chatStackOpenDuration, + reverseDuration: chatStackCloseDuration, + // Reduced motion is handled here (a short plain fade), not by the + // platform's near-instant fallback. + animationBehavior: AnimationBehavior.preserve, + )..addStatusListener(_status); + final _portal = OverlayPortalController(debugLabel: 'Chat stack'); + final _slot = GlobalKey(debugLabel: 'Chat stack slot'); + final _focus = FocusNode(debugLabel: 'Chat stack'); + + /// The pile hides the moment the column starts to move; under reduced + /// motion the two cross-fade in place instead. + late final Animation _hiddenWhileOpen = _open.drive(_ShownAtRest()); + late final Animation _fadedWhileOpen = ReverseAnimation(_open); + ChatStackMotion? _motion; + Object? _motionKey; + Rect? _anchor; + bool _expanded = false; + bool _keyboard = false; + bool _reduced = false; + + bool get expanded => _expanded; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + _keyboard = _keyboardUp(); + } + + /// The window's own inset: a scaffold above may already have taken it out + /// of this subtree's [MediaQuery]. + bool _keyboardUp() => View.of(context).viewInsets.bottom > 0; + + @override + void didChangeMetrics() { + if (!mounted) return; + final up = _keyboardUp(); + // A rotation or a resize moves the slot: fold rather than point at a + // stale place. + if (_expanded) collapse(immediate: up); + if (up != _keyboard) setState(() => _keyboard = up); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _motion?.dispose(); + _open.dispose(); + _focus.dispose(); + super.dispose(); + } + + void _status(AnimationStatus status) { + if (status == AnimationStatus.dismissed && !_expanded && mounted) { + _portal.hide(); + setState(() {}); + } + } + + /// Fans the stack out into its column. + void expand() { + if (_expanded || _keyboard || widget.entries.isEmpty) return; + final box = _slot.currentContext?.findRenderObject() as RenderBox?; + final overlay = + Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?; + if (box == null || overlay == null || !box.hasSize) return; + final origin = box.localToGlobal(Offset.zero, ancestor: overlay); + _open + ..duration = _reduced ? chatStackFadeDuration : chatStackOpenDuration + ..reverseDuration = _reduced + ? chatStackFadeDuration + : chatStackCloseDuration; + setState(() { + _anchor = origin & box.size; + _expanded = true; + }); + _portal.show(); + _open.forward(); + } + + /// Folds the column back into the stack; [immediate] skips the motion. + void collapse({bool immediate = false}) { + if (!_expanded) return; + setState(() => _expanded = false); + if (immediate) { + _open.value = 0; + _portal.hide(); + } else { + _open.reverse(); + } + if (FocusManager.instance.highlightMode == FocusHighlightMode.traditional) { + _focus.requestFocus(); + } + } + + void _choose(ChatStackEntry entry) { + collapse(); + if (!entry.current) widget.onOpen(entry); + } + + /// Removing folds the column, so the snack bar's Undo is in reach. + void _remove(ChatStackEntry entry) { + collapse(); + widget.onRemove?.call(entry); + } + + void _add() { + collapse(); + widget.onAdd(context); + } + + /// Each item's layer in the pile: the chat on screen on top, then the + /// chats after it in order, wrapping; the add item is never in the pile. + List _depths() { + final entries = widget.entries; + final n = entries.length; + final current = entries.indexWhere((entry) => entry.current); + final top = current < 0 ? 0 : current; + return [ + for (var i = 0; i < n; i++) + if ((i - top) % n case final depth when depth < chatStackVisibleLayers) + depth + else + null, + null, + ]; + } + + ChatStackMotion _motionFor(List depths, bool rtl) { + final key = Object.hashAll([_reduced, rtl, ...depths]); + final motion = _motion; + if (motion != null && key == _motionKey) return motion; + motion?.dispose(); + _motionKey = key; + return _motion = ChatStackMotion( + parent: _open, + depths: depths, + reduced: _reduced, + rtl: rtl, + ); + } + + @override + Widget build(BuildContext context) { + final entries = widget.entries; + final depths = _depths(); + final rtl = Directionality.of(context) == TextDirection.rtl; + final motion = _motionFor(depths, rtl); + final hidden = _keyboard || entries.isEmpty; + final remove = widget.onRemove; + final canRemove = remove != null && entries.length > 1; + return PopScope( + canPop: !_expanded, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) collapse(); + }, + child: OverlayPortal( + controller: _portal, + overlayChildBuilder: (context) { + final anchor = _anchor; + if (anchor == null) return const SizedBox.shrink(); + return ChatStackColumn( + motion: motion, + anchor: anchor, + entries: entries, + depths: depths, + interactive: _expanded, + onOpen: _choose, + onAdd: _add, + onDismiss: collapse, + onRemove: canRemove ? _remove : null, + ); + }, + child: AnimatedOpacity( + opacity: hidden ? 0 : 1, + duration: Motion.of(context, Motion.quick), + child: IgnorePointer( + ignoring: hidden, + child: ExcludeFocus( + excluding: hidden, + child: ExcludeSemantics( + excluding: hidden, + child: FadeTransition( + opacity: _reduced ? _fadedWhileOpen : _hiddenWhileOpen, + child: RepaintBoundary( + key: _slot, + child: _pile(context, depths), + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _pile(BuildContext context, List depths) { + final entries = widget.entries; + final rtl = Directionality.of(context) == TextDirection.rtl; + final layers = []; + for (var depth = chatStackVisibleLayers - 1; depth >= 0; depth--) { + final index = depths.indexOf(depth); + if (index < 0 || index >= entries.length) continue; + final pose = rtl + ? chatStackLayers[depth].mirrored() + : chatStackLayers[depth]; + layers.add( + ChatStackPoseTransition( + progress: kAlwaysCompleteAnimation, + from: pose, + to: pose, + child: ChatStackDisc( + child: chatStackAvatar(entries[index], cues: false), + ), + ), + ); + } + final waiting = [ + for (final entry in entries) + if (!entry.current) entry.awaitingOperator, + ].fold(0, (sum, count) => sum + count); + final more = entries.length > chatStackVisibleLayers; + final shape = chatStackShape(AppDesignTokens.of(context)); + return Semantics( + button: true, + expanded: false, + label: chatStackLabel(entries.length), + hint: waiting > 0 ? chatAwaitingLabel(waiting) : null, + onTap: expand, + child: ExcludeSemantics( + child: SizedBox.square( + dimension: kChatStackSlot, + child: Stack( + clipBehavior: Clip.none, + children: [ + ...layers, + Positioned.fill( + child: Padding( + padding: const EdgeInsets.all( + (kChatStackSlot - kChatStackDisc) / 2, + ), + child: Material( + type: MaterialType.transparency, + shape: shape, + clipBehavior: Clip.antiAlias, + child: InkWell( + key: const Key('chat-stack'), + focusNode: _focus, + customBorder: shape, + onTap: expand, + ), + ), + ), + ), + if (waiting > 0) + PositionedDirectional( + top: -6, + end: -6, + child: IgnorePointer( + child: ChatAwaitingBadge(count: waiting), + ), + ), + if (more) + PositionedDirectional( + bottom: -2, + start: -4, + child: IgnorePointer( + child: _CountBadge(count: entries.length), + ), + ), + ], + ), + ), + ), + ); + } +} + +/// Visible only at rest: the open column takes over the pile's place the +/// moment it starts to move. +class _ShownAtRest extends Animatable { + @override + double transform(double t) => t == 0 ? 1 : 0; +} + +/// How many chats the pile holds, once it holds more than it draws. +class _CountBadge extends StatelessWidget { + const _CountBadge({required this.count}); + + final int count; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final tokens = AppDesignTokens.of(context); + final r = tokens.radius; + return DecoratedBox( + decoration: ShapeDecoration( + color: scheme.inverseSurface, + shape: r == null + ? StadiumBorder(side: BorderSide(color: scheme.surface, width: 1.5)) + : RoundedRectangleBorder( + borderRadius: BorderRadius.circular(r), + side: BorderSide(color: scheme.surface, width: 1.5), + ), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1), + child: Text( + '$count', + style: (theme.textTheme.labelSmall ?? const TextStyle()).copyWith( + color: scheme.onInverseSurface, + fontWeight: FontWeight.w700, + height: 1.2, + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_motion.dart b/app/lib/features/chat/stack/chat_stack_motion.dart new file mode 100644 index 00000000..25653705 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_motion.dart @@ -0,0 +1,106 @@ +import 'dart:math' as math; + +import 'package:flutter/animation.dart'; + +import 'chat_stack_disc.dart'; +import 'chat_stack_pose.dart'; + +/// How long the stack takes to fan out into its column and to fold back. +const Duration chatStackOpenDuration = Duration(milliseconds: 280); +const Duration chatStackCloseDuration = Duration(milliseconds: 220); + +/// Under reduced motion the column only fades in and out, in place. +const Duration chatStackFadeDuration = Duration(milliseconds: 120); + +/// A short spring-like ease: a touch of overshoot on arrival, no bounce back. +const Curve chatStackRise = Cubic(.22, 1.18, .36, 1); + +/// Folding plays the controller backwards: an ease-in in forward time leaves +/// the column briskly and settles gently into the pile. +const Curve chatStackFold = Curves.easeInCubic; + +/// Every animation the open column reads, derived once from one controller +/// when the items change (never per frame). Item 0 is nearest the thumb; the +/// column rises from there, each item starting a little after the one below +/// it, and folds back top first. +class ChatStackMotion { + ChatStackMotion({ + required Animation parent, + required List depths, + required this.reduced, + required bool rtl, + }) : count = depths.length { + scrim = _curve(parent, const Interval(0, .7, curve: Curves.easeOut)); + final span = count <= 1 ? 1.0 : .62; + final step = count <= 1 ? 0.0 : (1 - span) / (count - 1); + for (var i = 0; i < count; i++) { + final start = i * step; + final end = math.min(1.0, start + span); + final depth = depths[i]; + final to = chatStackColumnPose(i, kChatStackPitch); + final layer = chatStackLayers[depth ?? chatStackLayers.length - 1]; + target.add(to); + if (reduced) { + from.add(to); + move.add(parent); + fade.add(parent); + label.add(parent); + labelFrom.add(to); + continue; + } + from.add(rtl ? layer.mirrored() : layer); + move.add( + _curve( + parent, + Interval(start, end, curve: chatStackRise), + Interval(start, end, curve: chatStackFold), + ), + ); + // A chat that was not drawn in the pile appears as it leaves it. + fade.add( + depth != null + ? kAlwaysCompleteAnimation + : _curve(parent, Interval(start, math.min(1, start + span * .5))), + ); + final labelStart = start + span * .45; + label.add( + _curve(parent, Interval(labelStart, end, curve: Curves.easeOut)), + ); + labelFrom.add( + ChatStackPose(offset: Offset(rtl ? -8 : 8, to.offset.dy), scale: .96), + ); + } + } + + final int count; + final bool reduced; + late final Animation scrim; + final List from = []; + final List target = []; + final List> move = []; + final List> fade = []; + final List> label = []; + final List labelFrom = []; + final List _owned = []; + + Animation _curve( + Animation parent, + Curve curve, [ + Curve? reverse, + ]) { + final curved = CurvedAnimation( + parent: parent, + curve: curve, + reverseCurve: reverse, + ); + _owned.add(curved); + return curved; + } + + void dispose() { + for (final curved in _owned) { + curved.dispose(); + } + _owned.clear(); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_pose.dart b/app/lib/features/chat/stack/chat_stack_pose.dart new file mode 100644 index 00000000..04b6a5f1 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_pose.dart @@ -0,0 +1,202 @@ +import 'dart:math' as math; +import 'dart:ui' show lerpDouble; + +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Where one avatar of the chat stack sits relative to the stack's slot: a +/// paint-only offset, a turn about its centre and a scale. +@immutable +class ChatStackPose { + const ChatStackPose({ + this.offset = Offset.zero, + this.turn = 0, + this.scale = 1, + }); + + static const rest = ChatStackPose(); + + final Offset offset; + + /// Radians, clockwise. + final double turn; + final double scale; + + /// The same pose for a right-to-left layout: offsets and turns mirror. + ChatStackPose mirrored() => ChatStackPose( + offset: Offset(-offset.dx, offset.dy), + turn: -turn, + scale: scale, + ); + + @override + bool operator ==(Object other) => + other is ChatStackPose && + other.offset == offset && + other.turn == turn && + other.scale == scale; + + @override + int get hashCode => Object.hash(offset, turn, scale); +} + +/// The collapsed stack's layers, top first: each further layer peeks out a +/// little higher, turned a few degrees the other way and slightly smaller, +/// so the pile reads as cards rather than one disc. +const List chatStackLayers = [ + ChatStackPose(), + ChatStackPose(offset: Offset(-4, -6), turn: -7 * math.pi / 180, scale: .94), + ChatStackPose(offset: Offset(4, -11), turn: 6 * math.pi / 180, scale: .88), + ChatStackPose(offset: Offset(-1, -15), turn: -4 * math.pi / 180, scale: .82), +]; + +/// How many avatars the collapsed stack draws. +int get chatStackVisibleLayers => chatStackLayers.length; + +/// The pose of the column's item [index] (0 nearest the thumb), [pitch] +/// apart. +ChatStackPose chatStackColumnPose(int index, double pitch) => + ChatStackPose(offset: Offset(0, -index * pitch)); + +/// Paints [child] moved from [from] to [to] as [progress] runs, without +/// rebuilding or relaying out: each frame only repaints the transform, and +/// hit tests follow it. The matrix and the layer are reused across frames. +class ChatStackPoseTransition extends SingleChildRenderObjectWidget { + const ChatStackPoseTransition({ + super.key, + required this.progress, + required this.from, + required this.to, + super.child, + }); + + final Animation progress; + final ChatStackPose from; + final ChatStackPose to; + + @override + RenderChatStackPose createRenderObject(BuildContext context) => + RenderChatStackPose(progress: progress, from: from, to: to); + + @override + void updateRenderObject( + BuildContext context, + RenderChatStackPose renderObject, + ) { + renderObject + ..progress = progress + ..from = from + ..to = to; + } +} + +class RenderChatStackPose extends RenderProxyBox { + RenderChatStackPose({ + required Animation progress, + required ChatStackPose from, + required ChatStackPose to, + }) { + _progress = progress; + _from = from; + _to = to; + } + + late Animation _progress; + set progress(Animation value) { + if (identical(value, _progress)) return; + if (attached) _progress.removeListener(markNeedsPaint); + _progress = value; + if (attached) _progress.addListener(markNeedsPaint); + markNeedsPaint(); + } + + late ChatStackPose _from; + set from(ChatStackPose value) { + if (value == _from) return; + _from = value; + markNeedsPaint(); + } + + late ChatStackPose _to; + set to(ChatStackPose value) { + if (value == _to) return; + _to = value; + markNeedsPaint(); + } + + final Matrix4 _matrix = Matrix4.identity(); + final LayerHandle _layer = LayerHandle(); + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _progress.addListener(markNeedsPaint); + } + + @override + void detach() { + _progress.removeListener(markNeedsPaint); + super.detach(); + } + + @override + void dispose() { + _layer.layer = null; + super.dispose(); + } + + @override + bool get alwaysNeedsCompositing => child != null; + + /// Fills the reused matrix for the current progress, about the centre. + Matrix4 _current() { + final t = _progress.value; + final dx = lerpDouble(_from.offset.dx, _to.offset.dx, t)!; + final dy = lerpDouble(_from.offset.dy, _to.offset.dy, t)!; + final turn = lerpDouble(_from.turn, _to.turn, t)!; + final scale = lerpDouble(_from.scale, _to.scale, t)!; + final cx = size.width / 2; + final cy = size.height / 2; + return _matrix + ..setIdentity() + ..translateByDouble(dx + cx, dy + cy, 0, 1) + ..rotateZ(turn) + ..scaleByDouble(scale, scale, 1, 1) + ..translateByDouble(-cx, -cy, 0, 1); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child == null) return; + _layer.layer = context.pushTransform( + needsCompositing, + offset, + _current(), + super.paint, + oldLayer: _layer.layer, + ); + } + + @override + bool hitTest(BoxHitTestResult result, {required Offset position}) => + hitTestChildren(result, position: position); + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + final child = this.child; + if (child == null) return false; + return result.addWithPaintTransform( + transform: _current(), + position: position, + hitTest: (result, position) { + if (!child.size.contains(position)) return false; + return child.hitTest(result, position: position); + }, + ); + } + + @override + void applyPaintTransform(RenderBox child, Matrix4 transform) { + transform.multiply(_current()); + } +} diff --git a/app/lib/features/chat/stack/mobile_chat_navigation.dart b/app/lib/features/chat/stack/mobile_chat_navigation.dart new file mode 100644 index 00000000..b8802dc1 --- /dev/null +++ b/app/lib/features/chat/stack/mobile_chat_navigation.dart @@ -0,0 +1,99 @@ +import 'package:flutter/foundation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const mobileChatNavigationKey = 'pipelines.mobile-chat-navigation.v1'; + +/// How a phone-width layout moves between the open chats. +enum MobileChatNavigation { + quickSwitch( + 'Quick switch', + 'The next open chat peeks below the current one; tap it to swap.', + ), + chatStack( + 'Chat stack', + 'A stack of the open chats floats above the composer; tap it to pick one.', + ); + + const MobileChatNavigation(this.label, this.description); + final String label; + final String description; +} + +abstract interface class MobileChatNavigationStore { + Future load(); + Future save(String value); +} + +class SharedMobileChatNavigationStore implements MobileChatNavigationStore { + const SharedMobileChatNavigationStore(); + + @override + Future load() async { + try { + return (await SharedPreferences.getInstance()).getString( + mobileChatNavigationKey, + ); + } catch (_) { + return null; + } + } + + @override + Future save(String value) async { + try { + return await (await SharedPreferences.getInstance()).setString( + mobileChatNavigationKey, + value, + ); + } catch (_) { + return false; + } + } +} + +/// This device's choice of phone chat navigation, applied live. +class MobileChatNavigationController extends ChangeNotifier { + MobileChatNavigationController({MobileChatNavigationStore? store}) + : _store = store ?? const SharedMobileChatNavigationStore(); + + static final instance = MobileChatNavigationController(); + + final MobileChatNavigationStore _store; + MobileChatNavigation _value = MobileChatNavigation.quickSwitch; + int _revision = 0; + bool _disposed = false; + bool saveFailed = false; + + MobileChatNavigation get value => _value; + bool get stack => _value == MobileChatNavigation.chatStack; + + Future restore() async { + final revision = _revision; + final saved = await _store.load(); + if (_disposed || revision != _revision) return; + for (final mode in MobileChatNavigation.values) { + if (mode.name == saved && mode != _value) { + _value = mode; + notifyListeners(); + } + } + } + + Future setValue(MobileChatNavigation mode) async { + if (_disposed) return; + final revision = ++_revision; + _value = mode; + saveFailed = false; + notifyListeners(); + final saved = await _store.save(mode.name); + if (_disposed || revision != _revision) return; + saveFailed = !saved; + notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + super.dispose(); + } +} diff --git a/app/lib/features/settings/settings_chat_navigation_section.dart b/app/lib/features/settings/settings_chat_navigation_section.dart new file mode 100644 index 00000000..81e611de --- /dev/null +++ b/app/lib/features/settings/settings_chat_navigation_section.dart @@ -0,0 +1,82 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../chat/stack/mobile_chat_navigation.dart'; +import 'settings_group.dart'; +import 'settings_theme.dart'; + +/// Chat navigation: how a phone-width window moves between the open chats, +/// with the next chat's peek (Quick switch) or a floating stack of them +/// (Chat stack). Saved on this device and applied at once. +class SettingsChatNavigationSection extends StatelessWidget { + const SettingsChatNavigationSection({super.key, this.controller}); + + final MobileChatNavigationController? controller; + + static const title = 'Mobile chat navigation'; + + @override + Widget build(BuildContext context) { + final navigation = controller ?? MobileChatNavigationController.instance; + return ListenableBuilder( + listenable: navigation, + builder: (context, _) => SettingsGroup( + title: title, + footer: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text( + 'Saved on this device. Applies on a phone-width window; a wide ' + 'window keeps the chat list beside the chats.', + ), + if (navigation.saveFailed) + Text( + 'Could not save; applies until reload.', + style: TextStyle(color: settingsErrorColor(context)), + ), + ], + ), + children: [ + SettingsGroupItem( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Semantics( + label: title, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: SegmentedButton( + segments: [ + for (final mode in MobileChatNavigation.values) + ButtonSegment( + value: mode, + label: Text( + mode.label, + key: ValueKey( + 'settings-chat-navigation-${mode.name}', + ), + ), + icon: Icon( + mode == MobileChatNavigation.quickSwitch + ? Icons.splitscreen_outlined + : Icons.layers_outlined, + ), + ), + ], + selected: {navigation.value}, + onSelectionChanged: (modes) => + unawaited(navigation.setValue(modes.first)), + ), + ), + ), + const SizedBox(height: 8), + Text(navigation.value.description), + ], + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/features/settings/settings_page_sections.dart b/app/lib/features/settings/settings_page_sections.dart index 06b7a697..55e36fe9 100644 --- a/app/lib/features/settings/settings_page_sections.dart +++ b/app/lib/features/settings/settings_page_sections.dart @@ -28,6 +28,12 @@ extension _SettingsPageSections on _SettingsScreenState { widget.animationSpeed ?? AnimationSpeedController.instance, ), ), + SettingsSection( + id: 'chat-navigation', + title: SettingsChatNavigationSection.title, + keywords: 'mobile phone chat navigation quick switch stack floating', + builder: (_) => const SettingsChatNavigationSection(), + ), SettingsSection( id: 'design', title: designSectionTitle, diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 2f77c045..3e7f86b5 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -14,6 +14,7 @@ import 'settings_controller.dart'; import 'settings_design_section.dart'; import 'settings_font_section.dart'; import 'settings_animation_section.dart'; +import 'settings_chat_navigation_section.dart'; import 'settings_scale_section.dart'; import '../../ui/motion/animation_speed.dart'; import '../../ui/theme/app_design_controller.dart'; diff --git a/app/test/features/chat/stack/chat_stack_fab_test.dart b/app/test/features/chat/stack/chat_stack_fab_test.dart new file mode 100644 index 00000000..6804eb4a --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_fab_test.dart @@ -0,0 +1,219 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_fab.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_pose.dart'; + +List _entries(int count, {int current = 0}) => [ + for (var i = 0; i < count; i++) + ChatStackEntry( + paneId: 'pane-$i', + session: { + 'id': 's$i', + 'title': 'Chat $i', + if (i == 1) 'color': 'teal', + if (i == 2) 'running': true, + if (i == 3) 'awaiting_operator': 1, + }, + current: i == current, + ), +]; + +class _Harness { + final opened = []; + final removed = []; + var added = 0; +} + +Future<_Harness> _pump( + WidgetTester tester, { + int count = 5, + bool reduced = false, +}) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final harness = _Harness(); + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: Scaffold( + body: Stack( + children: [ + const Center(child: Text('Transcript')), + Positioned( + right: 16, + bottom: 96, + child: ChatStackFab( + entries: _entries(count), + onOpen: (entry) => harness.opened.add(entry.sessionId), + onAdd: (_) => harness.added++, + onRemove: (entry) => harness.removed.add(entry.sessionId), + ), + ), + ], + ), + ), + ), + ), + ), + ); + return harness; +} + +/// The working and waiting badges animate for as long as they show. +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 150)); + } +} + +ChatStackFabState _state(WidgetTester tester) => + tester.state(find.byType(ChatStackFab)); + +void main() { + testWidgets('collapsed: a labelled pile of at most four layers', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await _pump(tester, count: 6); + expect(find.bySemanticsLabel(chatStackLabel(6)), findsOneWidget); + expect(find.byType(ChatStackPoseTransition), findsNWidgets(4)); + // More chats than layers: the count shows. + expect(find.text('6'), findsOneWidget); + expect(find.byType(ChatStackColumn), findsNothing); + semantics.dispose(); + }); + + testWidgets('tap fans out a column; tap outside folds it back', ( + tester, + ) async { + final harness = await _pump(tester); + final slot = tester.getRect(find.byKey(const Key('chat-stack'))); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pump(); + expect(_state(tester).expanded, isTrue); + // Mid-way the column is still rising. + await tester.pump(const Duration(milliseconds: 100)); + await _settle(tester); + expect(find.text('Chat 0'), findsOneWidget); + expect(find.text('Chat 4'), findsOneWidget); + expect(find.text(ChatStackColumn.addLabel), findsOneWidget); + // Item 0 sits on the stack; each further item rises one pitch. + final first = tester.getCenter( + find.byKey(const ValueKey('chat-stack-button-pane-0')), + ); + final second = tester.getCenter( + find.byKey(const ValueKey('chat-stack-button-pane-1')), + ); + final add = tester.getCenter( + find.byKey(const ValueKey('chat-stack-button-add')), + ); + expect(first.dx, closeTo(slot.center.dx, .5)); + expect(first.dy, closeTo(slot.center.dy, .5)); + expect(second.dy, lessThan(first.dy)); + expect(add.dy, lessThan(second.dy)); + // Outside the column. + await tester.tapAt(const Offset(40, 120)); + await tester.pump(); + expect(_state(tester).expanded, isFalse); + await _settle(tester); + expect(find.byType(ChatStackColumn), findsNothing); + expect(harness.opened, isEmpty); + }); + + testWidgets('tapping a chat opens it and folds the column', (tester) async { + final harness = await _pump(tester); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.tap(find.text('Chat 3')); + await _settle(tester); + expect(harness.opened, ['s3']); + expect(find.byType(ChatStackColumn), findsNothing); + // The chat on screen only folds the column. + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.tap( + find.byKey(const ValueKey('chat-stack-button-pane-0')), + warnIfMissed: false, + ); + await _settle(tester); + expect(harness.opened, ['s3']); + }); + + testWidgets('add opens the picker; long press removes', (tester) async { + final harness = await _pump(tester); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.longPress(find.text('Chat 2')); + await _settle(tester); + expect(harness.removed, ['s2']); + // Removing folds the column, so a snack bar's Undo is in reach. + expect(find.byType(ChatStackColumn), findsNothing); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); + await _settle(tester); + expect(harness.added, 1); + expect(find.byType(ChatStackColumn), findsNothing); + }); + + testWidgets('Back and Escape fold the column', (tester) async { + await _pump(tester); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await _settle(tester); + expect(find.byType(ChatStackColumn), findsNothing); + await tester.tap(find.byKey(const Key('chat-stack'))); + await _settle(tester); + final handled = await tester.binding.handlePopRoute(); + await _settle(tester); + expect(handled, isTrue); + expect(find.byType(ChatStackColumn), findsNothing); + expect(find.byType(ChatStackFab), findsOneWidget); + }); + + testWidgets('reduced motion only fades, in place', (tester) async { + await _pump(tester, reduced: true); + final slot = tester.getRect(find.byKey(const Key('chat-stack'))); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 40)); + // Already at its final place while fading in. + final second = tester.getCenter( + find.byKey(const ValueKey('chat-stack-button-pane-1')), + ); + expect(second.dy, lessThan(slot.center.dy - 40)); + final fades = tester.widgetList( + find.ancestor( + of: find.byKey(const ValueKey('chat-stack-button-pane-1')), + matching: find.byType(FadeTransition), + ), + ); + expect( + fades.map((fade) => fade.opacity.value), + contains(inExclusiveRange(0, 1)), + ); + await _settle(tester); + expect(find.text('Chat 1'), findsOneWidget); + }); + + testWidgets('the on-screen keyboard hides the stack', (tester) async { + await _pump(tester); + expect(find.byKey(const Key('chat-stack')).hitTestable(), findsOneWidget); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await _settle(tester); + expect(find.byKey(const Key('chat-stack')).hitTestable(), findsNothing); + await tester.tap(find.byKey(const Key('chat-stack')), warnIfMissed: false); + await tester.pump(); + expect(_state(tester).expanded, isFalse); + tester.view.resetViewInsets(); + await _settle(tester); + expect(find.byKey(const Key('chat-stack')).hitTestable(), findsOneWidget); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_screen_test.dart b/app/test/features/chat/stack/chat_stack_screen_test.dart new file mode 100644 index 00000000..0e970e7a --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_screen_test.dart @@ -0,0 +1,152 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_peek_header.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +const _rows = [ + {'id': 'a', 'title': 'Alpha', 'directory': '/w', 'color': 'teal'}, + {'id': 'b', 'title': 'Beta', 'directory': '/w'}, + {'id': 'c', 'title': 'Gamma', 'directory': '/v'}, +]; + +class _Gateway extends FakeChatGateway { + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final row in _rows) {...row}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +Future _pump(WidgetTester tester, Size size) async { + SharedPreferences.setMockInitialValues({}); + unawaited( + MobileChatNavigationController.instance.setValue( + MobileChatNavigation.chatStack, + ), + ); + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + final route = ValueNotifier(null); + addTearDown(route.dispose); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => ValueListenableBuilder( + valueListenable: route, + builder: (context, id, _) => ChatScreen( + gateway: gateway, + initialSessionId: id, + onSessionSelected: (next) => route.value = next, + onBack: () => route.value = null, + ), + ), + }, + ), + ), + ); + await tester.pumpAndSettle(); +} + +Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id')); +final _stack = find.byKey(const Key('chat-stack')); + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + testWidgets('the setting swaps the peek for the stack, live', (tester) async { + await _pump(tester, const Size(390, 844)); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_thread('a'), findsOneWidget); + expect(_stack.hitTestable(), findsOneWidget); + expect(find.bySemanticsLabel(chatStackLabel(1)), findsOneWidget); + + // Add chat picks a chat that is not open and opens it. + await tester.tap(_stack); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Beta').last); + await tester.pumpAndSettle(); + expect(_thread('b').hitTestable(), findsOneWidget); + expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); + // The stack replaces the peek. + expect(find.byType(ChatPeekHeader), findsNothing); + + // A chat in the column opens as its list row would. + await tester.tap(_stack); + await tester.pumpAndSettle(); + await tester.tap(find.text('Alpha').last); + await tester.pumpAndSettle(); + expect(_thread('a').hitTestable(), findsOneWidget); + expect(_stack.hitTestable(), findsOneWidget); + + // Back to Quick switch: the peek returns, the stack leaves. + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + await tester.pumpAndSettle(); + expect(_stack, findsNothing); + expect(find.byType(ChatPeekHeader), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('long press removes a chat, Undo restores it', (tester) async { + await _pump(tester, const Size(390, 844)); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(_stack); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Gamma').last); + await tester.pumpAndSettle(); + expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); + await tester.tap(_stack); + await tester.pumpAndSettle(); + await tester.longPress(find.text('Alpha').last); + await tester.pumpAndSettle(); + expect(find.text('Removed Alpha from open chats'), findsOneWidget); + expect(find.bySemanticsLabel(chatStackLabel(1)), findsOneWidget); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + // Gamma stays on screen; Alpha is back in the stack. + expect(_thread('c').hitTestable(), findsOneWidget); + expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a wide window keeps its panes and shows no stack', ( + tester, + ) async { + await _pump(tester, const Size(1280, 800)); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + expect(_thread('a'), findsOneWidget); + expect(_stack, findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/settings/settings_chat_navigation_section_test.dart b/app/test/features/settings/settings_chat_navigation_section_test.dart new file mode 100644 index 00000000..994de1ac --- /dev/null +++ b/app/test/features/settings/settings_chat_navigation_section_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; +import 'package:pipelines_app/features/settings/settings_chat_navigation_section.dart'; + +class _Store implements MobileChatNavigationStore { + String? saved; + bool success = true; + @override + Future load() async => saved; + @override + Future save(String value) async { + saved = value; + return success; + } +} + +void main() { + testWidgets('chooses, saves and restores the phone chat navigation', ( + tester, + ) async { + final store = _Store(); + final controller = MobileChatNavigationController(store: store); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SettingsChatNavigationSection(controller: controller), + ), + ), + ), + ); + expect(find.text(SettingsChatNavigationSection.title), findsOneWidget); + expect(controller.value, MobileChatNavigation.quickSwitch); + expect( + find.text(MobileChatNavigation.quickSwitch.description), + findsOneWidget, + ); + await tester.tap( + find.byKey(const ValueKey('settings-chat-navigation-chatStack')), + ); + await tester.pumpAndSettle(); + expect(controller.value, MobileChatNavigation.chatStack); + expect(store.saved, 'chatStack'); + expect( + find.text(MobileChatNavigation.chatStack.description), + findsOneWidget, + ); + + // A new controller (the next launch) restores the saved choice. + final next = MobileChatNavigationController(store: store); + addTearDown(next.dispose); + await next.restore(); + expect(next.value, MobileChatNavigation.chatStack); + + store.success = false; + await tester.tap( + find.byKey(const ValueKey('settings-chat-navigation-quickSwitch')), + ); + await tester.pumpAndSettle(); + expect(find.text('Could not save; applies until reload.'), findsOneWidget); + }); +} From e629d552c2162da0974c65a8ecb1ea7fde271433 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:18:14 +0000 Subject: [PATCH 2/8] Chat stack: polish pile layers, dark tone, Add chat picker title, probe param --- app/lib/features/chat/chat_screen_stack.dart | 2 +- .../features/chat/chat_screen_workspace.dart | 3 +- .../conversation/chat_add_pane_picker.dart | 6 +++- app/lib/features/chat/screen.dart | 1 + .../features/chat/stack/chat_stack_disc.dart | 36 +++++++++---------- .../features/chat/stack/chat_stack_pose.dart | 6 ++-- app/tool/search_selection_probe_entry.dart | 11 ++++++ 7 files changed, 39 insertions(+), 26 deletions(-) diff --git a/app/lib/features/chat/chat_screen_stack.dart b/app/lib/features/chat/chat_screen_stack.dart index 765b8c77..37b067cd 100644 --- a/app/lib/features/chat/chat_screen_stack.dart +++ b/app/lib/features/chat/chat_screen_stack.dart @@ -57,7 +57,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { child: ChatStackFab( entries: _stackEntries(), onOpen: (entry) => _openBySelection(entry.session), - onAdd: _addPane, + onAdd: (context) => _addPane(context, title: ChatStackColumn.addLabel), onRemove: _removeFromStack, ), ), diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 3b22551f..16cbbc7a 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -450,7 +450,7 @@ mixin _ChatScreenWorkspace on State { }, ); - void _addPane(BuildContext context) { + void _addPane(BuildContext context, {String title = 'Add chat pane'}) { // The action normally lives in the pane's More menu. Let that menu finish // closing before pushing the picker, otherwise its root-overlay teardown // can hide the newly opened anchored menu. @@ -461,6 +461,7 @@ mixin _ChatScreenWorkspace on State { context, controller: _sessionsForSidebar, sidebarFolds: _foldsForSidebar, + title: title, excludedSessionIds: _workspace.panes .map((pane) => pane.sessionId) .toSet(), diff --git a/app/lib/features/chat/conversation/chat_add_pane_picker.dart b/app/lib/features/chat/conversation/chat_add_pane_picker.dart index 71ae52bd..08303347 100644 --- a/app/lib/features/chat/conversation/chat_add_pane_picker.dart +++ b/app/lib/features/chat/conversation/chat_add_pane_picker.dart @@ -15,6 +15,7 @@ Future showAddChatPanePicker( required ChatSectionFolds sidebarFolds, required Set excludedSessionIds, required ValueChanged onSelected, + String title = 'Add chat pane', }) async { final selected = await showAppChoiceMenu( context, @@ -27,6 +28,7 @@ Future showAddChatPanePicker( builder: (context, constraints) => SizedBox( height: constraints.maxHeight, child: _AddChatPanePicker( + title: title, controller: controller, sidebarFolds: sidebarFolds, excludedSessionIds: excludedSessionIds, @@ -53,10 +55,12 @@ Future showAddChatPanePicker( class _AddChatPanePicker extends StatefulWidget { const _AddChatPanePicker({ + required this.title, required this.controller, required this.sidebarFolds, required this.excludedSessionIds, }); + final String title; final ChatSessionsController controller; final ChatSectionFolds sidebarFolds; final Set excludedSessionIds; @@ -89,7 +93,7 @@ class _AddChatPanePickerState extends State<_AddChatPanePicker> { Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 16, 24, 0), child: Text( - 'Add chat pane', + widget.title, style: Theme.of(context).textTheme.titleLarge, ), ), diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index a1f43b19..b41c0cee 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -42,6 +42,7 @@ import 'conversation/chat_sidebar_controls.dart'; import 'ui/sessions/chat_compact_sidebar.dart'; import 'workspace/chat_workspace.dart'; import 'stack/chat_stack_anchor.dart'; +import 'stack/chat_stack_column.dart'; import 'stack/chat_stack_entry.dart'; import 'stack/chat_stack_fab.dart'; import 'stack/mobile_chat_navigation.dart'; diff --git a/app/lib/features/chat/stack/chat_stack_disc.dart b/app/lib/features/chat/stack/chat_stack_disc.dart index 5795d1ac..7f317378 100644 --- a/app/lib/features/chat/stack/chat_stack_disc.dart +++ b/app/lib/features/chat/stack/chat_stack_disc.dart @@ -16,45 +16,41 @@ const double kChatStackPitch = kChatStackSlot + 8; /// The gap between an item's name label and its avatar. const double kChatStackLabelGap = 10; -/// An opaque disc in the design's shape (a circle, or a framed square under a -/// flat design) that carries one avatar of the stack. The list avatar's fill -/// is translucent; the disc keeps stacked avatars from showing through each -/// other, and its rim separates them. A raised design drops a short shadow; -/// a flat one keeps its hairline frame instead. +/// An opaque disc in the design's shape (a circle, or the design's square +/// under a flat design) that carries one avatar of the stack. The list +/// avatar's fill is translucent; the disc keeps stacked avatars from showing +/// through each other, and its rim separates them. A raised design drops a +/// short shadow; a flat one casts none, and its avatar frames itself. class ChatStackDisc extends StatelessWidget { - const ChatStackDisc({ - super.key, - required this.child, - this.ring, - this.shadow = true, - }); + const ChatStackDisc({super.key, required this.child, this.ring}); final Widget child; /// The rim's colour when it marks the current chat; null for the surface. final Color? ring; - /// Whether this disc may cast a shadow (a layer under another does not). - final bool shadow; - @override Widget build(BuildContext context) { final tokens = AppDesignTokens.of(context); final scheme = Theme.of(context).colorScheme; - final base = tokens.panelFill(scheme, scheme.surface); + // A raised dark design lifts the disc a tone, as Material's dark + // elevation does, so the pile's layers read where a shadow cannot. + final dark = Theme.of(context).brightness == Brightness.dark; + final base = tokens.panelFill( + scheme, + dark ? scheme.surfaceContainerHighest : scheme.surface, + ); final ring = this.ring; final shape = chatStackShape(tokens); - final frame = tokens.frameSide; return SizedBox.square( dimension: kChatStackSlot, child: Center( child: DecoratedBox( decoration: ShapeDecoration( color: ring ?? base, - shape: shape.copyWith( - side: ring == null && frame != null ? frame : BorderSide.none, - ), - shadows: shadow && !tokens.flat ? chatStackShadows(scheme) : null, + // A flat design's avatar frames itself; the rim stays bare. + shape: shape, + shadows: !tokens.flat ? chatStackShadows(scheme) : null, ), child: SizedBox.square( dimension: kChatStackDisc, diff --git a/app/lib/features/chat/stack/chat_stack_pose.dart b/app/lib/features/chat/stack/chat_stack_pose.dart index 04b6a5f1..b77bccbf 100644 --- a/app/lib/features/chat/stack/chat_stack_pose.dart +++ b/app/lib/features/chat/stack/chat_stack_pose.dart @@ -45,9 +45,9 @@ class ChatStackPose { /// so the pile reads as cards rather than one disc. const List chatStackLayers = [ ChatStackPose(), - ChatStackPose(offset: Offset(-4, -6), turn: -7 * math.pi / 180, scale: .94), - ChatStackPose(offset: Offset(4, -11), turn: 6 * math.pi / 180, scale: .88), - ChatStackPose(offset: Offset(-1, -15), turn: -4 * math.pi / 180, scale: .82), + ChatStackPose(offset: Offset(-7, -7), turn: -8 * math.pi / 180, scale: .94), + ChatStackPose(offset: Offset(4, -13), turn: 7 * math.pi / 180, scale: .88), + ChatStackPose(offset: Offset(-4, -18), turn: -4 * math.pi / 180, scale: .82), ]; /// How many avatars the collapsed stack draws. diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index b1485f7c..a4c3f429 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -1,3 +1,4 @@ +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart'; import 'package:pipelines_app/application/pipelines_binding.dart'; import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart'; import 'package:pipelines_app/core/servers/machine_access.dart'; @@ -988,6 +989,7 @@ class _FixtureSink implements WebSocketSink { /// `?speech=fake` reads replies aloud with a scripted engine, one word per /// `?speechStep=` ms (tool/probe_speech_fixture.dart); /// `?design=terminal` chooses that app design (Settings → Design); +/// `?chatNav=stack` navigates a phone's open chats with the Chat stack; /// `?poolDelay=` (with `?federated=1`) connects each machine that /// much later, as a real server does (a detached chat window's first list); /// `?theme=dark` / `?theme=light` pins the platform brightness the app's @@ -1032,6 +1034,15 @@ Future main() async { ? AppDesignController.instance.restore() : AppDesignController.instance.select(AppDesign.fromId(design)), ); + // `?chatNav=stack` chooses the phone's Chat stack as Settings would; + // otherwise the stored choice. + unawaited( + params['chatNav'] == 'stack' + ? MobileChatNavigationController.instance.setValue( + MobileChatNavigation.chatStack, + ) + : MobileChatNavigationController.instance.restore(), + ); _fillerRunCount = int.tryParse(params['runs'] ?? '') ?? 0; _fillerStepCount = int.tryParse(params['steps'] ?? '') ?? 0; if (params['running'] == '1') { From 8e19459d6fe46642ffb3d551ad23589510b91b23 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:22:55 +0000 Subject: [PATCH 3/8] Chat stack: notes Co-Authored-By: Claude Opus 5.5 --- app/notes/chat-stack.md | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 app/notes/chat-stack.md diff --git a/app/notes/chat-stack.md b/app/notes/chat-stack.md new file mode 100644 index 00000000..2bb27641 --- /dev/null +++ b/app/notes/chat-stack.md @@ -0,0 +1,51 @@ +# Chat stack (phone chat navigation) + +## Setting + +Settings → Mobile chat navigation: Quick switch (default, the next chat's +peek under the current one) or Chat stack. Per device +(`pipelines.mobile-chat-navigation.v1`, `MobileChatNavigationController`, +restored in `bootstrap.dart`), applied live, and only on a phone-width layout +(`!showsListBesideDetail`). A wide window keeps its panes and shows no stack. + +## Behaviour + +- The stack's chats are the workspace's panes: the same open-chat set the + server syncs (`ChatOpenWorkspaceController`). Choosing one opens it as a tap + on its list row does (`_openBySelection`); Add chat is the pane menu's Add + chat pane picker (searchable, the list's own rows) titled "Add chat"; + long press removes the chat's pane, with an Undo snack bar that re-adds it + and keeps the chat on screen. +- Collapsed: up to four avatars piled with small offsets and turns, the chat + on screen on top; a count badge when more are open, and a bell when another + open chat waits on the operator. It sits bottom-end in the active chat's + transcript area, just above the composer, so it never covers Send; the + transcript pads its last line and Jump to latest above it. It hides while + the on-screen keyboard is up (the window's view insets). +- Expanded: a scrim, and a column rising from the stack's slot. The chats keep + the open-chat order bottom-up (stable positions for muscle memory); the chat + on screen wears a ring in its colour; each avatar keeps its list badges + (waiting, working, background tasks) and has a name pill tinted with its + colour. Add chat is the last item, at the top: the reachable bottom slots + go to switching, the frequent action. Tap outside, Back or Escape folds it. +- Motion: one controller, 280 ms open (staggered, a slight-overshoot ease), + 220 ms fold (top first). Items move through `ChatStackPoseTransition`, a + repaint-only transform render object that reuses its matrix and layer; no + per-frame rebuilds, no blur. Reduced motion: a 120 ms plain fade in place. +- Design tokens: circle discs with a short shadow under Default; the design's + square corners and no shadow under flat designs (Terminal, Paper); label + pills take the design radius and frame. + +## Structure + +- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column, FAB, + anchor (a `LayerLink` the active pane's transcript marks; the one stack + above the workspace follows it, so it survives switching chats). +- `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove. +- `chat_thread_view.dart`: anchor target, bottom clearance, Jump offset. +- `tool/search_selection_probe_entry.dart`: `?chatNav=stack`. + +## Not verified + +On-device behaviour (Android keyboard insets, haptics) was not run on a +device; web captures used Chrome's touch emulation at 390x844. From 8c224fecf8ff9bf27f3bc1cc0e62252ca4dd3720 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:19:55 +0000 Subject: [PATCH 4/8] Anchored menus: bound by system insets instead of shifting by them The anchored choice menu route wrapped its layout in a SafeArea while the anchor rect is in overlay coordinates, so on Android (edge to edge, a status bar inset) every top bar menu opened an inset below its control. The insets and a half-opened hinge now only bound the panel. Co-Authored-By: Claude Opus 5.5 --- app/lib/ui/adaptive/anchored_menu_layout.dart | 126 +++++++++++ app/lib/ui/adaptive/app_popups.dart | 95 ++------ .../ui/adaptive/app_popups_foldable_test.dart | 208 ++++++++++++++++++ 3 files changed, 355 insertions(+), 74 deletions(-) create mode 100644 app/lib/ui/adaptive/anchored_menu_layout.dart create mode 100644 app/test/ui/adaptive/app_popups_foldable_test.dart diff --git a/app/lib/ui/adaptive/anchored_menu_layout.dart b/app/lib/ui/adaptive/anchored_menu_layout.dart new file mode 100644 index 00000000..d1db58d9 --- /dev/null +++ b/app/lib/ui/adaptive/anchored_menu_layout.dart @@ -0,0 +1,126 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +/// Places an anchored menu panel below its anchor, aligned to the anchor's +/// leading edge, or above it when it fits better there, and always inside +/// the app's safe area. +/// +/// [anchor] and the layout share one coordinate space: the overlay the menu +/// route fills. The system insets ([insets]: a status bar, a cutout, a +/// gesture bar) are therefore only bounds the panel stays inside, never an +/// offset. Wrapping the layout in a `SafeArea` shifted the panel down by the +/// top inset while the anchor stayed put, which on an unfolded foldable +/// opened a top bar's menus far below the bar. A hinge that splits the +/// screen ([avoid]) confines the panel to the anchor's side. +class AnchoredMenuLayout extends SingleChildLayoutDelegate { + AnchoredMenuLayout({ + required this.anchor, + required this.width, + this.insets = EdgeInsets.zero, + this.avoid = const [], + }); + + final Rect anchor; + final double width; + final EdgeInsets insets; + final List avoid; + + static const double margin = 8; + static const double gap = 4; + + /// Less room than this on both sides means the anchor is not a button but + /// a region (a pane's bar, a whole pane): the panel then opens over it, + /// from its top. + static const double minRoom = 200; + + /// Where the panel may go in an overlay of [size]. + Rect bounds(Size size) { + var screen = Offset.zero & size; + if (avoid.isNotEmpty) { + Rect? closest; + var best = double.infinity; + for (final candidate in DisplayFeatureSubScreen.subScreensInBounds( + screen, + avoid, + )) { + final distance = _distance(anchor.center, candidate); + if (distance < best) { + best = distance; + closest = candidate; + } + } + screen = closest ?? screen; + } + final inner = insets.deflateRect(screen).deflate(margin); + // An area too small for the insets and margins collapses, never inverts. + return Rect.fromLTRB( + inner.left, + inner.top, + math.max(inner.left, inner.right), + math.max(inner.top, inner.bottom), + ); + } + + static double _distance(Offset point, Rect rect) { + final dx = math.max( + 0.0, + math.max(rect.left - point.dx, point.dx - rect.right), + ); + final dy = math.max( + 0.0, + math.max(rect.top - point.dy, point.dy - rect.bottom), + ); + return math.sqrt(dx * dx + dy * dy); + } + + double _below(Rect area) => area.bottom - anchor.bottom - gap; + double _above(Rect area) => anchor.top - gap - area.top; + bool _over(Rect area) => _below(area) < minRoom && _above(area) < minRoom; + + @override + BoxConstraints getConstraintsForChild(BoxConstraints constraints) { + final area = bounds(constraints.biggest); + final below = _below(area); + final above = _above(area); + final double room; + if (_over(area)) { + room = area.bottom - anchor.top.clamp(area.top, area.bottom); + } else { + room = below >= minRoom || below >= above ? below : above; + } + final panelWidth = width.clamp(0.0, area.width); + return BoxConstraints( + minWidth: panelWidth, + maxWidth: panelWidth, + maxHeight: room.clamp(0.0, area.height), + ); + } + + @override + Offset getPositionForChild(Size size, Size childSize) { + final area = bounds(size); + final double top; + if (_over(area)) { + top = anchor.top + gap; + } else if (childSize.height <= _below(area)) { + top = anchor.bottom + gap; + } else { + top = anchor.top - gap - childSize.height; + } + final maxTop = math.max(area.top, area.bottom - childSize.height); + final maxLeft = math.max(area.left, area.right - childSize.width); + return Offset( + anchor.left.clamp(area.left, maxLeft), + top.clamp(area.top, maxTop), + ); + } + + @override + bool shouldRelayout(AnchoredMenuLayout oldDelegate) => + oldDelegate.anchor != anchor || + oldDelegate.width != width || + oldDelegate.insets != insets || + !listEquals(oldDelegate.avoid, avoid); +} diff --git a/app/lib/ui/adaptive/app_popups.dart b/app/lib/ui/adaptive/app_popups.dart index 95822bab..69705913 100644 --- a/app/lib/ui/adaptive/app_popups.dart +++ b/app/lib/ui/adaptive/app_popups.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import '../motion/motion.dart'; +import 'anchored_menu_layout.dart'; /// The narrowest app that gets desktop popups: the width where a list shows /// beside its open item (`kListDetailMinWidth`). @@ -157,9 +158,26 @@ class _AnchoredMenuRoute extends PopupRoute { Animation secondaryAnimation, ) { final colors = Theme.of(context).colorScheme; - return SafeArea( - child: CustomSingleChildLayout( - delegate: _AnchoredMenuLayout(anchor, width), + final media = MediaQuery.of(context); + // The anchor is in the overlay's coordinates, which this page fills: the + // system insets bound the panel but must not shift it (a SafeArea here + // opened menus an inset below their anchor on Android). The panel itself + // is clear of them, so content that pads itself for a bottom sheet + // (a SafeArea) adds nothing inside it. + return CustomSingleChildLayout( + delegate: AnchoredMenuLayout( + anchor: anchor, + width: width, + insets: + media.padding + EdgeInsets.only(bottom: media.viewInsets.bottom), + avoid: DisplayFeatureSubScreen.avoidBounds(media).toList(), + ), + child: MediaQuery.removePadding( + context: context, + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, child: FadeTransition( opacity: CurvedAnimation(parent: animation, curve: Motion.curve), child: Semantics( @@ -196,74 +214,3 @@ class _AnchoredMenuRoute extends PopupRoute { ); } } - -/// Places the panel below its anchor, aligned to the anchor's leading edge, -/// or above it when it fits better there, and always inside the app. -class _AnchoredMenuLayout extends SingleChildLayoutDelegate { - _AnchoredMenuLayout(this.anchor, this.width); - - final Rect anchor; - final double width; - - static const double margin = 8; - static const double gap = 4; - - /// Less room than this on both sides means the anchor is not a button but - /// a region (a pane's bar, a whole pane): the panel then opens over it, - /// from its top. - static const double minRoom = 200; - - double _below(Size size) => size.height - anchor.bottom - gap - margin; - double _above() => anchor.top - gap - margin; - bool _over(Size size) => _below(size) < minRoom && _above() < minRoom; - - @override - BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - final available = constraints.biggest; - final below = _below(available); - final above = _above(); - final double room; - if (_over(available)) { - room = - available.height - - anchor.top.clamp(margin, available.height) - - margin; - } else { - room = below >= minRoom || below >= above ? below : above; - } - final maxWidth = (available.width - 2 * margin).clamp(0.0, double.infinity); - return BoxConstraints( - minWidth: width.clamp(0.0, maxWidth), - maxWidth: width.clamp(0.0, maxWidth), - maxHeight: room.clamp(0.0, available.height - 2 * margin), - ); - } - - @override - Offset getPositionForChild(Size size, Size childSize) { - final double top; - if (_over(size)) { - top = anchor.top + gap; - } else if (childSize.height <= _below(size)) { - top = anchor.bottom + gap; - } else { - top = anchor.top - gap - childSize.height; - } - final maxTop = (size.height - margin - childSize.height).clamp( - margin, - double.infinity, - ); - final maxLeft = (size.width - margin - childSize.width).clamp( - margin, - double.infinity, - ); - return Offset( - anchor.left.clamp(margin, maxLeft), - top.clamp(margin, maxTop), - ); - } - - @override - bool shouldRelayout(_AnchoredMenuLayout oldDelegate) => - oldDelegate.anchor != anchor || oldDelegate.width != width; -} diff --git a/app/test/ui/adaptive/app_popups_foldable_test.dart b/app/test/ui/adaptive/app_popups_foldable_test.dart new file mode 100644 index 00000000..fcca0751 --- /dev/null +++ b/app/test/ui/adaptive/app_popups_foldable_test.dart @@ -0,0 +1,208 @@ +import 'dart:ui'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_header.dart'; +import 'package:pipelines_app/ui/adaptive/app_popups.dart'; +import 'package:pipelines_app/features/chat/ui/sessions/chat_adaptive.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart'; + +/// An unfolded foldable: 884x1104 dp, a status bar and a cutout above the +/// app (Android draws edge to edge), a gesture bar below it, and the fold +/// down the middle. +void _foldable(WidgetTester tester, {bool halfOpened = false}) { + tester.view.physicalSize = const Size(884, 1104); + tester.view.devicePixelRatio = 1; + tester.view.padding = const FakeViewPadding(top: 52, bottom: 24); + tester.view.viewPadding = const FakeViewPadding(top: 52, bottom: 24); + tester.view.displayFeatures = [ + DisplayFeature( + bounds: halfOpened + ? const Rect.fromLTWH(436, 0, 12, 1104) + : const Rect.fromLTWH(442, 0, 0, 1104), + type: halfOpened ? DisplayFeatureType.hinge : DisplayFeatureType.fold, + state: halfOpened + ? DisplayFeatureState.postureHalfOpened + : DisplayFeatureState.postureFlat, + ), + ]; + addTearDown(tester.view.reset); +} + +Widget _choices(BuildContext menu) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final choice in const ['Opus', 'Sonnet', 'Haiku']) + ListTile(title: Text(choice), onTap: () => Navigator.of(menu).pop()), + ], +); + +Widget _menuButton(String label) => Builder( + builder: (anchor) => TextButton( + onPressed: () => showAppChoiceMenu(anchor, builder: _choices), + child: Text(label), + ), +); + +/// A chat pane's top bar the way the app lays it out: the app's own top +/// bar under the status bar, the selectors in the pane header, and the +/// overflow menu at its end. +Widget _app({required double listWidth}) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold( + body: SafeArea( + child: Row( + children: [ + SizedBox(width: listWidth, child: const Placeholder()), + Expanded( + child: Column( + children: [ + ChatThreadHeader( + title: 'Chat', + folder: 'demo', + onInfo: () {}, + controls: [ + _menuButton('Model'), + _menuButton('Permission'), + _menuButton('Thinking'), + ], + moreActions: [ + ChatBarAction( + label: 'Rename chat', + onPressed: () {}, + materialIcon: Icons.edit_outlined, + ), + ], + ), + const Expanded(child: SizedBox.expand()), + ], + ), + ), + ], + ), + ), + ), +); + +final _menu = find.byKey(const ValueKey('app-choice-menu')); + +Future _expectUnder( + WidgetTester tester, + Finder button, + Finder panel, { + double slack = 16, +}) async { + final anchor = tester.getRect(button); + await tester.tap(button); + await tester.pumpAndSettle(); + final menu = tester.getRect(panel); + expect(menu.top, greaterThanOrEqualTo(anchor.bottom - 1)); + expect( + menu.top - anchor.bottom, + lessThan(slack), + reason: 'the menu opens right under its anchor, not an inset lower', + ); + await tester.tapAt(const Offset(200, 900)); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('unfolded foldable, wide pane: every top bar menu opens ' + 'under its control', (tester) async { + _foldable(tester); + await tester.pumpWidget(_app(listWidth: 200)); + await tester.pumpAndSettle(); + for (final label in const ['Model', 'Thinking', 'Permission']) { + final button = find.widgetWithText(TextButton, label); + await _expectUnder(tester, button, _menu); + } + // The overflow menu is a MenuAnchor in the root overlay. + await _expectUnder( + tester, + find.byKey(segmentedMoreKey).first, + find.text('Rename chat').hitTestable(), + // The first item's label, inside the panel's and the item's padding. + slack: 32, + ); + }); + + testWidgets('unfolded foldable, narrow pane: the settings panel opens ' + 'under the bar and each selector menu under its control', (tester) async { + _foldable(tester); + await tester.pumpWidget(_app(listWidth: 360)); + await tester.pumpAndSettle(); + final bar = tester.getRect(find.byType(ChatThreadHeader)); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Chat settings')); + await tester.pumpAndSettle(); + final settings = tester.getRect(_menu); + expect(settings.top - bar.bottom, inInclusiveRange(-1, 16)); + for (final label in const ['Model', 'Thinking', 'Permission']) { + final button = find.widgetWithText(TextButton, label); + final anchor = tester.getRect(button); + await tester.tap(button); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu.last); + expect( + menu.top - anchor.bottom, + inInclusiveRange(-1, 16), + reason: '$label menu right under its control', + ); + await tester.tap(find.text('Opus').last); + await tester.pumpAndSettle(); + } + }); + + testWidgets('a menu stays inside the safe area and above when needed', ( + tester, + ) async { + _foldable(tester); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.bottomRight, + child: _menuButton('Low'), + ), + ), + ), + ); + final anchor = tester.getRect(find.widgetWithText(TextButton, 'Low')); + await tester.tap(find.text('Low')); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu); + // No room below: above the anchor, close to it, inside the app. + expect(menu.bottom, lessThanOrEqualTo(anchor.top)); + expect(anchor.top - menu.bottom, lessThan(16)); + expect(menu.right, lessThanOrEqualTo(884 - 8)); + }); + + testWidgets('a half opened hinge keeps the menu on its anchor side', ( + tester, + ) async { + _foldable(tester, halfOpened: true); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SafeArea( + child: Padding( + padding: const EdgeInsets.only(left: 340), + child: Align( + alignment: Alignment.topLeft, + child: _menuButton('Across'), + ), + ), + ), + ), + ), + ); + final anchor = tester.getRect(find.widgetWithText(TextButton, 'Across')); + await tester.tap(find.text('Across')); + await tester.pumpAndSettle(); + final menu = tester.getRect(_menu); + expect(menu.top - anchor.bottom, inInclusiveRange(-1, 16)); + // The anchor's centre is left of the hinge: the panel stays left of it. + expect(menu.right, lessThanOrEqualTo(436)); + }); +} From 8ed3998dd59978c33442020fb72b7b328694f4d5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:33:05 +0000 Subject: [PATCH 5/8] Design: Terminal is the default when none is stored; Default is now Classic An unset (or unknown) design id resolves to Terminal, in the controller's initial value, AppDesign.fromId and the boot spinner. A stored choice, including Classic's stable 'default' id, is respected. The picker calls the original Material look Classic so no row reads 'Default'. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/pipelines_root.dart | 5 +- app/lib/ui/theme/app_design.dart | 16 ++++-- app/lib/ui/theme/app_design_controller.dart | 2 +- app/lib/ui/theme/app_design_styles.dart | 4 +- app/lib/ui/theme/app_design_tokens.dart | 6 +-- .../application/chat_registration_test.dart | 12 +++++ .../settings_design_section_test.dart | 33 ++++++------ .../ui/theme/app_design_controller_test.dart | 50 +++++++++++++------ app/test/ui/theme/app_design_test.dart | 20 +++++--- app/test/ui/theme/app_font_theme_test.dart | 5 ++ 10 files changed, 101 insertions(+), 52 deletions(-) diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index 8027da11..0694a204 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -18,7 +18,6 @@ import '../features/settings/settings_store.dart'; import '../ui/scale/ui_scale.dart'; import '../ui/theme/app_design_controller.dart'; import '../ui/theme/app_font_controller.dart'; -import '../ui/theme/app_theme.dart'; import 'detached/detached_app.dart'; import 'detached/detached_route.dart'; import 'pipelines_app.dart'; @@ -322,7 +321,9 @@ class _PipelinesRootState extends State { child: Directionality( textDirection: TextDirection.ltr, child: Theme( - data: appLightTheme(), + // The device's design (Terminal until one is chosen), so the + // spinner does not flash another look before the app. + data: AppDesignController.instance.design.light(), child: const Center(child: CircularProgressIndicator()), ), ), diff --git a/app/lib/ui/theme/app_design.dart b/app/lib/ui/theme/app_design.dart index e79519a3..99494e51 100644 --- a/app/lib/ui/theme/app_design.dart +++ b/app/lib/ui/theme/app_design.dart @@ -25,13 +25,15 @@ final Map<(AppDesign, Brightness, String?), ThemeData> _themes = {}; /// 3. give the theme an [AppDesignTokens] extension: set only the tokens it /// changes (corners, flat surfaces, frame, panel fill, transcript, /// composer and selected-row styles, reading type); every token defaults -/// to the Default look; +/// to the Classic look; /// 4. give it a [swatch] for the picker and say whether it [usesInterfaceFont]. /// 5. run the design budget (app/tool/perf/README.md) and keep it passing. /// Widgets read the tokens, so most surfaces follow without per-widget code. enum AppDesign { - /// The app's own Material look. - standard('default', 'Default', 'The app’s Material look.'), + /// The app's original Material look. Its stored id stays `default` (the + /// id it had when it was the default); the picker calls it Classic so it + /// does not read as "whatever the app starts with". + standard('default', 'Classic', 'The app’s original Material look.'), /// A terminal-style look: monospace text, near-black pages, thin frames /// and a transcript drawn as prompt and tool lines. @@ -60,12 +62,16 @@ enum AppDesign { /// The picker's one-line summary of the design. final String description; - /// The design stored as [id], or [standard] for an unknown or missing id. + /// The design a device has before it chooses one: Terminal. + static const AppDesign defaultDesign = terminal; + + /// The design stored as [id], or [defaultDesign] for an unknown or missing + /// id. A stored choice (Classic's `default` included) is kept. static AppDesign fromId(String? id) { for (final design in values) { if (design.id == id) return design; } - return standard; + return defaultDesign; } /// The design's light theme. [fontFamily] is the device's interface font; diff --git a/app/lib/ui/theme/app_design_controller.dart b/app/lib/ui/theme/app_design_controller.dart index 96a0eb0a..baf81fe5 100644 --- a/app/lib/ui/theme/app_design_controller.dart +++ b/app/lib/ui/theme/app_design_controller.dart @@ -71,7 +71,7 @@ class AppDesignController extends ChangeNotifier { static final AppDesignController instance = AppDesignController(); final AppDesignStore _store; - AppDesign _design = AppDesign.standard; + AppDesign _design = AppDesign.defaultDesign; int _revision = 0; bool _saveFailed = false; diff --git a/app/lib/ui/theme/app_design_styles.dart b/app/lib/ui/theme/app_design_styles.dart index 19014124..ff36b944 100644 --- a/app/lib/ui/theme/app_design_styles.dart +++ b/app/lib/ui/theme/app_design_styles.dart @@ -5,7 +5,7 @@ import 'package:flutter/painting.dart'; /// transcript widgets branch on it, never on the design itself. enum TranscriptStyle { /// The operator's turns as bubbles on the trailing side, the agent's - /// answers on the page and its activity as a one-line button (Default). + /// answers on the page and its activity as a one-line button (Classic). bubbles, /// A CLI's prompt line, glyph-led tool lines and bracketed injected @@ -32,7 +32,7 @@ enum ComposerStyle { /// How a list (AppListRow) marks the row that is open. Every style keeps /// the leading bar in the row's accent; they differ in the fill and frame. enum SelectedRowStyle { - /// Material's tonal `secondaryContainer` fill (Default). + /// Material's tonal `secondaryContainer` fill (Classic). tonal, /// The accent washed over the page, stronger than a tinted row, inside a diff --git a/app/lib/ui/theme/app_design_tokens.dart b/app/lib/ui/theme/app_design_tokens.dart index f8d5eeab..349fc00b 100644 --- a/app/lib/ui/theme/app_design_tokens.dart +++ b/app/lib/ui/theme/app_design_tokens.dart @@ -6,7 +6,7 @@ import 'app_design_styles.dart'; export 'app_design_styles.dart'; /// The muted ANSI-style accents a design names for status and roles. The -/// Default design leaves them to its colour scheme; Terminal sets them, and +/// Classic design leaves them to its colour scheme; Terminal sets them, and /// Paper sets ink-toned ones. @immutable class AnsiAccents { @@ -46,7 +46,7 @@ class AnsiAccents { /// typography. Every theme an [AppDesign] builds carries one; a theme without /// one (a test's bare `ThemeData`) reads as [standard]. /// -/// Adding a design: every field has a default that keeps the Default look, +/// Adding a design: every field has a default that keeps the Classic look, /// so a new design sets only what it changes. Widgets branch on the named /// styles ([transcript], [composer], [selectedRow]) rather than on [design], /// so two designs can share a behaviour. @@ -67,7 +67,7 @@ class AppDesignTokens extends ThemeExtension { this.chatColorSaturation = 1, }); - /// The Default design: every widget keeps its own shapes. + /// The Classic design: every widget keeps its own shapes. static const AppDesignTokens standard = AppDesignTokens( design: AppDesign.standard, ); diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart index 4a32664e..c51c348e 100644 --- a/app/test/application/chat_registration_test.dart +++ b/app/test/application/chat_registration_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; @@ -18,6 +19,8 @@ import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dar import '../core/transport/pipelines_client_test.dart' show FakeChannel; import '../native_back.dart'; import 'package:pipelines_app/ui/adaptive/segmented_bar.dart'; +import 'package:pipelines_app/ui/theme/app_design.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; ServerEndpoint webServer() => ServerEndpoint.resolve( base: Uri.parse('http://127.0.0.1:8096/'), @@ -300,6 +303,15 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); + // The Classic design's transcript (its activity summary line); the + // app starts on Terminal when no design is stored. + // The choice applies at once; its save need not finish here. + unawaited(AppDesignController.instance.select(AppDesign.standard)); + addTearDown( + () => unawaited( + AppDesignController.instance.select(AppDesign.defaultDesign), + ), + ); final channel = FakeChannel()..readyCompleter.complete(); final client = PipelinesClient( diff --git a/app/test/features/settings/settings_design_section_test.dart b/app/test/features/settings/settings_design_section_test.dart index 6b2185ae..7ca1d5bd 100644 --- a/app/test/features/settings/settings_design_section_test.dart +++ b/app/test/features/settings/settings_design_section_test.dart @@ -29,7 +29,7 @@ AppDesignTokens _tokens(WidgetTester tester) => AppDesignTokens.of(tester.element(find.text(designSectionTitle))); void main() { - testWidgets('every design is a radio row; Default is chosen at first', ( + testWidgets('every design is a radio row; Terminal is chosen at first', ( tester, ) async { final designs = AppDesignController(store: MemoryAppDesignStore()); @@ -43,40 +43,43 @@ void main() { final group = tester.widget>( find.byType(RadioGroup), ); - expect(group.groupValue, AppDesign.standard); - expect(_tokens(tester).terminal, isFalse); + expect(group.groupValue, AppDesign.terminal); + expect(_tokens(tester).terminal, isTrue); + // The Material look is called Classic, so no row reads "Default". + expect(find.text('Classic'), findsOneWidget); + expect(find.text('Default'), findsNothing); }); - testWidgets('choosing Terminal stores it and restyles the page live', ( + testWidgets('choosing Classic stores it and restyles the page live', ( tester, ) async { final store = MemoryAppDesignStore(); final designs = AppDesignController(store: store); await _pump(tester, designs); - await tester.tap(find.text(AppDesign.terminal.label)); - await tester.pumpAndSettle(); - expect(store.id, AppDesign.terminal.id); - expect(designs.design, AppDesign.terminal); - expect(_tokens(tester).terminal, isTrue); - expect(find.text(designSaveFailedText), findsNothing); - await tester.tap(find.text(AppDesign.standard.label)); await tester.pumpAndSettle(); expect(store.id, AppDesign.standard.id); + expect(designs.design, AppDesign.standard); expect(_tokens(tester).terminal, isFalse); + expect(find.text(designSaveFailedText), findsNothing); + + await tester.tap(find.text(AppDesign.terminal.label)); + await tester.pumpAndSettle(); + expect(store.id, AppDesign.terminal.id); + expect(_tokens(tester).terminal, isTrue); }); testWidgets('a stored choice is restored into the picker', (tester) async { final designs = AppDesignController( - store: MemoryAppDesignStore(AppDesign.terminal.id), + store: MemoryAppDesignStore(AppDesign.standard.id), ); await designs.restore(); await _pump(tester, designs); final group = tester.widget>( find.byType(RadioGroup), ); - expect(group.groupValue, AppDesign.terminal); + expect(group.groupValue, AppDesign.standard); }); testWidgets('a failed save says the choice lasts until reload', ( @@ -86,10 +89,10 @@ void main() { store: MemoryAppDesignStore()..failSaves = true, ); await _pump(tester, designs); - await tester.tap(find.text(AppDesign.terminal.label)); + await tester.tap(find.text(AppDesign.paper.label)); await tester.pumpAndSettle(); expect(find.text(designSaveFailedText), findsOneWidget); - expect(designs.design, AppDesign.terminal); + expect(designs.design, AppDesign.paper); }); testWidgets('choosing Paper stores it, restyles the page live and is ' diff --git a/app/test/ui/theme/app_design_controller_test.dart b/app/test/ui/theme/app_design_controller_test.dart index 49d51f23..7b34f241 100644 --- a/app/test/ui/theme/app_design_controller_test.dart +++ b/app/test/ui/theme/app_design_controller_test.dart @@ -4,34 +4,52 @@ import 'package:pipelines_app/ui/theme/app_design_controller.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { - test('restore applies the stored design; unknown ids keep Default', () async { - final stored = AppDesignController(store: MemoryAppDesignStore('terminal')); - var notified = 0; - stored.addListener(() => notified++); - await stored.restore(); - expect(stored.design, AppDesign.terminal); - expect(notified, 1); - - final unknown = AppDesignController(store: MemoryAppDesignStore('neon')); - await unknown.restore(); - expect(unknown.design, AppDesign.standard); + test('an unset device starts on Terminal and keeps it', () async { + final unset = AppDesignController(store: MemoryAppDesignStore()); + expect(unset.design, AppDesign.terminal); + await unset.restore(); + expect(unset.design, AppDesign.terminal); }); + test( + 'restore applies the stored design; unknown ids are the default', + () async { + // An explicit Classic choice, stored as `default` back when Classic was + // the default, is respected. + final stored = AppDesignController( + store: MemoryAppDesignStore('default'), + ); + var notified = 0; + stored.addListener(() => notified++); + await stored.restore(); + expect(stored.design, AppDesign.standard); + expect(notified, 1); + + final paper = AppDesignController(store: MemoryAppDesignStore('paper')); + await paper.restore(); + expect(paper.design, AppDesign.paper); + + final unknown = AppDesignController(store: MemoryAppDesignStore('neon')); + await unknown.restore(); + expect(unknown.design, AppDesign.terminal); + }, + ); + test('select applies at once and stores the id', () async { final store = MemoryAppDesignStore(); final designs = AppDesignController(store: store); - final pending = designs.select(AppDesign.terminal); - expect(designs.design, AppDesign.terminal); + final pending = designs.select(AppDesign.standard); + expect(designs.design, AppDesign.standard); await pending; - expect(store.id, 'terminal'); + expect(store.id, 'default'); expect(designs.saveFailed, isFalse); }); test('a failed save is reported and the choice still applies', () async { final store = MemoryAppDesignStore()..failSaves = true; final designs = AppDesignController(store: store); - await designs.select(AppDesign.terminal); - expect(designs.design, AppDesign.terminal); + await designs.select(AppDesign.paper); + expect(designs.design, AppDesign.paper); expect(designs.saveFailed, isTrue); store.failSaves = false; await designs.select(AppDesign.standard); diff --git a/app/test/ui/theme/app_design_test.dart b/app/test/ui/theme/app_design_test.dart index 97689724..1d0193d3 100644 --- a/app/test/ui/theme/app_design_test.dart +++ b/app/test/ui/theme/app_design_test.dart @@ -11,16 +11,19 @@ import 'package:pipelines_app/ui/theme/app_font_store.dart'; import 'package:pipelines_app/ui/theme/app_theme.dart'; void main() { - test('ids round-trip and an unknown id is the Default design', () { + test('ids round-trip and a missing or unknown id is Terminal', () { for (final design in AppDesign.values) { expect(AppDesign.fromId(design.id), design); } - expect(AppDesign.fromId(null), AppDesign.standard); - expect(AppDesign.fromId('neon'), AppDesign.standard); + expect(AppDesign.defaultDesign, AppDesign.terminal); + expect(AppDesign.fromId(null), AppDesign.terminal); + expect(AppDesign.fromId('neon'), AppDesign.terminal); + // Classic keeps the id it was stored under when it was the default. expect(AppDesign.standard.id, 'default'); + expect(AppDesign.standard.label, 'Classic'); }); - test('the Default design builds exactly the existing themes', () { + test('the Classic design builds exactly the existing themes', () { expect(AppDesign.standard.light(), appLightTheme()); expect(AppDesign.standard.dark(), appDarkTheme()); expect( @@ -97,14 +100,15 @@ void main() { }, ), ); - expect(tokens.terminal, isFalse); - expect(family, isNot(appMonospaceFamily)); - await designs.select(AppDesign.terminal); - await tester.pumpAndSettle(); + // Terminal until the device chooses. expect(tokens.terminal, isTrue); expect(family, appMonospaceFamily); await designs.select(AppDesign.standard); await tester.pumpAndSettle(); expect(tokens.terminal, isFalse); + expect(family, isNot(appMonospaceFamily)); + await designs.select(AppDesign.terminal); + await tester.pumpAndSettle(); + expect(tokens.terminal, isTrue); }); } diff --git a/app/test/ui/theme/app_font_theme_test.dart b/app/test/ui/theme/app_font_theme_test.dart index bacaed08..5918b31e 100644 --- a/app/test/ui/theme/app_font_theme_test.dart +++ b/app/test/ui/theme/app_font_theme_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app.dart'; import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/ui/theme/app_design_controller.dart'; import 'package:pipelines_app/ui/theme/app_font.dart'; import 'package:pipelines_app/ui/theme/app_font_controller.dart'; import 'package:pipelines_app/ui/theme/app_font_store.dart'; @@ -36,10 +37,14 @@ void main() { store: MemoryAppFontStore(), loader: (family, assets) async {}, ); + // Classic follows the interface font (Terminal keeps its monospace). + final designs = AppDesignController(store: MemoryAppDesignStore('default')); + await designs.restore(); String? family; await tester.pumpWidget( MyApp( fonts: fonts, + designs: designs, destination: AppDestination.settings, destinationBodies: { AppDestination.settings: (context) => Builder( From 22ab20077b71c41986098c9d2bf2504d5707b263 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:33:05 +0000 Subject: [PATCH 6/8] Capture fixture: ?inset=top,bottom&fold=1 emulates Android insets and a fold A browser reports no system insets, so inset-dependent layout (anchored menus) could not be captured on web. Co-Authored-By: Claude Opus 5.5 --- app/tool/fixture_host/fixture_host_web.dart | 26 +++++- app/tool/fixture_host/inset_view.dart | 92 +++++++++++++++++++++ 2 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 app/tool/fixture_host/inset_view.dart diff --git a/app/tool/fixture_host/fixture_host_web.dart b/app/tool/fixture_host/fixture_host_web.dart index 780346e3..1a113e57 100644 --- a/app/tool/fixture_host/fixture_host_web.dart +++ b/app/tool/fixture_host/fixture_host_web.dart @@ -6,6 +6,7 @@ import '../perf/backdrop_census.dart'; import '../perf/chat_scroll_probe.dart'; import '../perf/design_probe.dart'; import '../perf/frame_log.dart'; +import 'inset_view.dart'; /// The fixture options: the page URL's query. Map fixtureParams() => Uri.base.queryParameters; @@ -30,5 +31,26 @@ ServerEndpoint fixtureServer(Map params) => /// The browser's location is the route; no provider is needed. RouteInformationProvider? fixtureRouteProvider(String? route) => null; -/// Runs [app] unchanged. -void runFixtureApp(Widget app, Map params) => runApp(app); +/// Runs [app], under an Android phone's system insets (and a fold) when +/// `?inset=,` (and `&fold=1`) ask for them; see [InsetView]. +void runFixtureApp(Widget app, Map params) { + final inset = params['inset']; + if (inset == null && params['fold'] != '1') { + runApp(app); + return; + } + final parts = (inset ?? '').split(','); + final binding = WidgetsFlutterBinding.ensureInitialized(); + final view = binding.platformDispatcher.implicitView!; + runWidget( + View( + view: InsetView( + view, + top: double.tryParse(parts.first) ?? 0, + bottom: parts.length > 1 ? double.tryParse(parts[1]) ?? 0 : 0, + fold: params['fold'] == '1', + ), + child: app, + ), + ); +} diff --git a/app/tool/fixture_host/inset_view.dart b/app/tool/fixture_host/inset_view.dart new file mode 100644 index 00000000..c72f8a71 --- /dev/null +++ b/app/tool/fixture_host/inset_view.dart @@ -0,0 +1,92 @@ +import 'dart:ui' as ui; + +/// The real view with an Android phone's system insets: a status bar +/// [top] and a gesture bar [bottom] logical pixels tall, drawn over the app +/// edge to edge, and with [fold] a vertical fold down the middle, as an +/// unfolded foldable reports it. A browser always reports no insets, so this +/// is how a capture sees inset-dependent layout (anchored menus, bars). +/// +/// `?inset=52,24&fold=1` in the fixture URL. +class InsetView implements ui.FlutterView { + InsetView(this._view, {this.top = 0, this.bottom = 0, this.fold = false}); + + final ui.FlutterView _view; + final double top; + final double bottom; + final bool fold; + + ui.ViewPadding get _insets => _Padding( + top: top * _view.devicePixelRatio, + bottom: bottom * _view.devicePixelRatio, + ); + + @override + ui.Size get physicalSize => _view.physicalSize; + + @override + ui.ViewConstraints get physicalConstraints => _view.physicalConstraints; + + @override + int get viewId => _view.viewId; + + @override + ui.PlatformDispatcher get platformDispatcher => _view.platformDispatcher; + + @override + ui.Display get display => _view.display; + + @override + double get devicePixelRatio => _view.devicePixelRatio; + + @override + ui.ViewPadding get viewInsets => _view.viewInsets; + + @override + ui.ViewPadding get viewPadding => _insets; + + @override + ui.ViewPadding get systemGestureInsets => _view.systemGestureInsets; + + @override + ui.ViewPadding get padding => _insets; + + @override + ui.GestureSettings get gestureSettings => _view.gestureSettings; + + @override + List get displayFeatures { + if (!fold) return _view.displayFeatures; + final size = _view.physicalSize; + return [ + ui.DisplayFeature( + bounds: ui.Rect.fromLTWH(size.width / 2, 0, 0, size.height), + type: ui.DisplayFeatureType.fold, + state: ui.DisplayFeatureState.postureFlat, + ), + ]; + } + + @override + ui.DisplayCornerRadii? get displayCornerRadii => _view.displayCornerRadii; + + @override + void render(ui.Scene scene, {ui.Size? size}) => + _view.render(scene, size: size); + + @override + void updateSemantics(ui.SemanticsUpdate update) => + _view.updateSemantics(update); +} + +class _Padding implements ui.ViewPadding { + const _Padding({required this.top, required this.bottom}); + + @override + final double top; + @override + final double bottom; + @override + double get left => 0; + @override + double get right => 0; +} From 109ea72252385f30d0132328e7eb6d73e4a7aa96 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:33:05 +0000 Subject: [PATCH 7/8] Chat: hide the chat list entirely (Ctrl+B / Cmd+B), per device ListDetailPanes takes listHidden and slides the list to zero width (at once with reduced motion), keeping its expanded or compact mode for when it comes back. A wide chat offers Hide chat list in the list's bar and the pane menu, Ctrl+B (Cmd+B on Apple; a focused terminal keeps Ctrl+B) and, while hidden, a Show chat list button at the start of the top-left pane's bar. The choice is device-local (pipelines.chat.listHidden.v1). Co-Authored-By: Claude Opus 5.5 --- app/lib/features/chat/chat_pane_content.dart | 6 + .../chat/chat_screen_list_toggle.dart | 62 ++++++++ .../features/chat/chat_screen_workspace.dart | 2 + .../chat/conversation/chat_thread_header.dart | 7 +- .../chat/conversation/chat_thread_view.dart | 5 + app/lib/features/chat/screen.dart | 26 +++- .../ui/sessions/chat_sessions_screen.dart | 14 ++ .../workspace/chat_center_stage_keys.dart | 16 ++ .../chat_list_hidden_controller.dart | 121 ++++++++++++++ .../settings/keyboard_shortcuts_registry.dart | 9 ++ app/lib/shell/list_detail.dart | 44 +++++- .../chat_quick_switch_shortcut_test.dart | 28 ++++ .../features/chat/chat_list_hide_test.dart | 147 ++++++++++++++++++ .../chat_list_hidden_controller_test.dart | 82 ++++++++++ app/test/shell/list_detail_hide_test.dart | 73 +++++++++ 15 files changed, 631 insertions(+), 11 deletions(-) create mode 100644 app/lib/features/chat/chat_screen_list_toggle.dart create mode 100644 app/lib/features/chat/workspace/chat_list_hidden_controller.dart create mode 100644 app/test/features/chat/chat_list_hide_test.dart create mode 100644 app/test/features/chat/workspace/chat_list_hidden_controller_test.dart create mode 100644 app/test/shell/list_detail_hide_test.dart diff --git a/app/lib/features/chat/chat_pane_content.dart b/app/lib/features/chat/chat_pane_content.dart index 0982cb43..a5a7a352 100644 --- a/app/lib/features/chat/chat_pane_content.dart +++ b/app/lib/features/chat/chat_pane_content.dart @@ -24,6 +24,7 @@ class ChatPanePlacement { this.pasteTarget = false, this.ownsPasteWhenFocused = false, this.paneControls, + this.leadingControl, this.paneCommands, this.onComposerFocus, this.onNextChat, @@ -54,6 +55,10 @@ class ChatPanePlacement { /// The pane menu's choices, built in the pane's own context. final List Function(BuildContext paneContext)? paneControls; + /// The bar's leading control where it shows no Back, built in the pane's + /// own context; null for none. + final Widget? Function(BuildContext paneContext)? leadingControl; + /// Choices the chat list hands to this chat's conversation to run. final ChatPaneCommands? paneCommands; final VoidCallback? onComposerFocus; @@ -117,6 +122,7 @@ Widget buildChatPaneContent({ 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) => diff --git a/app/lib/features/chat/chat_screen_list_toggle.dart b/app/lib/features/chat/chat_screen_list_toggle.dart new file mode 100644 index 00000000..89489b3d --- /dev/null +++ b/app/lib/features/chat/chat_screen_list_toggle.dart @@ -0,0 +1,62 @@ +part of 'screen.dart'; + +/// Hiding the wide layout's chat list entirely (Ctrl+B, the pane menu, the +/// list's own bar), and the button that brings it back. +mixin _ChatScreenListToggle on State { + ChatComposerFocusRequests get _composerFocus; + ChatWorkspaceController get _workspace; + + late final ChatListHiddenController _listHidden = + widget.listHidden ?? ChatListHiddenController.instance; + + /// Whether the list is hidden beside an open chat. With no chat open the + /// list is the page, so it always shows. + bool _listHiddenBeside(String? selected) => + selected != null && _listHidden.value; + + void _bindListHidden() { + _listHidden.addListener(_listHiddenChanged); + unawaited(_listHidden.restore()); + } + + void _unbindListHidden() => _listHidden.removeListener(_listHiddenChanged); + + void _listHiddenChanged() { + if (mounted) setState(() {}); + } + + /// Shows or hides the list. Hiding gives the keyboard to the active chat, + /// since the list (and anything focused in it) goes away. + void _toggleChatList() { + final hiding = !_listHidden.value; + _listHidden.toggle(); + final active = _workspace.activePane?.sessionId; + if (hiding && active != null) _composerFocus.request(active); + } + + /// The pane menu's toggle, naming its shortcut. + ChatBarAction _chatListToggleAction() => ChatBarAction( + identifier: 'chat-list-toggle', + label: chatListToggleLabel(_listHidden.value), + onPressed: _toggleChatList, + materialIcon: _listHidden.value ? Icons.menu : Icons.menu_open, + ); + + /// The top bar's way back to a hidden list, at the start of the top left + /// pane's bar (the one beside where the list was); null elsewhere. + Widget? _showChatListButton(BuildContext paneContext, String? selected) { + if (!_listHiddenBeside(selected) || !showsListBesideDetail(context)) { + return null; + } + final scope = ChatWorkspacePaneScope.maybeOf(paneContext); + if (scope != null && (scope.leftEdgeShared || scope.topEdgeShared)) { + return null; + } + return IconButton( + key: const Key('chat-show-list'), + tooltip: chatListToggleLabel(true), + onPressed: _toggleChatList, + icon: const Icon(Icons.menu), + ); + } +} diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 16cbbc7a..d68d99fc 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -12,6 +12,7 @@ mixin _ChatScreenWorkspace on State { void _back(); void _openRouted(String id); bool get _pageOpen; + void _toggleChatList(); Widget _thread(ChatWorkspacePane pane); ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; @@ -513,6 +514,7 @@ mixin _ChatScreenWorkspace on State { final id = _workspace.activePane?.sessionId; if (id != null) _paneCommands.request(id, ChatPaneCommand.files); }, + onToggleList: _toggleChatList, enabled: () => _workspaceVisible && _workspace.paneCount > 0 && diff --git a/app/lib/features/chat/conversation/chat_thread_header.dart b/app/lib/features/chat/conversation/chat_thread_header.dart index 8ceeec52..fc6d090f 100644 --- a/app/lib/features/chat/conversation/chat_thread_header.dart +++ b/app/lib/features/chat/conversation/chat_thread_header.dart @@ -50,6 +50,7 @@ class ChatThreadHeader extends StatelessWidget { this.moreActions = const [], this.chatColor, this.identity, + this.leading, }); final String title; @@ -77,6 +78,10 @@ class ChatThreadHeader extends StatelessWidget { /// The chat's identity avatar, shown in the title on a phone. final Widget? identity; + /// A control at the bar's leading edge where there is no Back: the wide + /// layout's Show chat list while the list is hidden. + final Widget? leading; + @override Widget build(BuildContext context) { final tint = chatBarTintOf(context, chatColor); @@ -125,7 +130,7 @@ class ChatThreadHeader extends StatelessWidget { key: const Key('chat-back'), onPressed: onBack, ) - : null, + : leading, title: !showTitle ? '' : (title.isEmpty ? 'Chat' : title), titleLeading: showTitle ? identity : null, subtitle: showTitle ? ServerContext.metadata(context, folder) : null, diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index c7d69d59..fba71e0c 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -141,6 +141,7 @@ class ChatThreadView extends StatefulWidget { this.paneCommands, this.onComposerFocus, this.sidebarControl, + this.leadingControl, this.showBackButton, this.useNativeBack = false, this.pasteTarget = true, @@ -159,6 +160,9 @@ class ChatThreadView extends StatefulWidget { final ChatPaneCommands? paneCommands; final VoidCallback? onComposerFocus; final Widget? sidebarControl; + + /// The header's leading control where it shows no Back (Show chat list). + final Widget? leadingControl; final bool? showBackButton; final bool useNativeBack; final bool pasteTarget; @@ -1682,6 +1686,7 @@ class _ChatThreadViewState extends State with ChatFindHost { ? null : ChatSessionAvatar(session: session, selected: true), onInfo: _openInfo, + leading: widget.leadingControl, showTitle: !inWindow, showBack: canGoBack, // A pushed page keeps the platform's stock Back (pop this route); a diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index b41c0cee..c202e92d 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -49,6 +49,7 @@ import 'stack/mobile_chat_navigation.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_list_hidden_controller.dart'; import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_pane_move_shortcuts.dart'; import 'workspace/chat_workspace_entrance.dart'; @@ -71,6 +72,7 @@ part 'chat_screen_attention.dart'; part 'chat_screen_float.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; +part 'chat_screen_list_toggle.dart'; part 'chat_screen_quick_switch.dart'; part 'chat_screen_stack.dart'; part 'chat_screen_workspace.dart'; @@ -96,6 +98,7 @@ class ChatScreen extends StatefulWidget { this.persistWorkspace = false, this.runtime, this.windows, + this.listHidden, }); final ApiGateway gateway; @@ -109,6 +112,10 @@ class ChatScreen extends StatefulWidget { /// float). final ChatWindows? windows; + /// Whether a wide layout hides its chat list beside an open chat; the + /// device's own choice ([ChatListHiddenController.instance]) when null. + final ChatListHiddenController? listHidden; + /// The chat session the current route names, or null for the list. final String? initialSessionId; @@ -133,7 +140,8 @@ class _ChatScreenState extends State _ChatScreenPaneMenu, _ChatScreenQuickSwitch, _ChatScreenAttention, - _ChatScreenStack { + _ChatScreenStack, + _ChatScreenListToggle { /// The chats' shared state: the list, opened rows, accepted models, /// transcript positions and caches (see [ChatRuntime]). @override @@ -174,6 +182,7 @@ class _ChatScreenState extends State _bindWindows(); _bindQuickSwitch(); _bindAttention(); + _bindListHidden(); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); @@ -481,6 +490,7 @@ class _ChatScreenState extends State _unbindWindows(); _unbindQuickSwitch(); _unbindAttention(); + _unbindListHidden(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); @@ -517,12 +527,16 @@ class _ChatScreenState extends State showBackButton: _page.open || !showsListBesideDetail(context), paneCommands: _paneCommands, onComposerFocus: () => _composerFocus.request(selected), + leadingControl: (paneContext) => + _showChatListButton(paneContext, _selected), paneControls: (paneContext) => [ ChatBarAction( label: 'Add chat pane', onPressed: () => _addPane(paneContext), materialIcon: Icons.add_box_outlined, ), + if (showsListBesideDetail(context) && !_page.open) + _chatListToggleAction(), if (_workspace.paneCount > 1 && showsListBesideDetail(context)) chatCenterStageAction(ChatCenterStageController.instance), ...chatPaneMoveActions( @@ -588,8 +602,10 @@ class _ChatScreenState extends State publishShellBar: (selected == null || !beside || - _sidebarMode == ChatSidebarMode.expanded) && + (_sidebarMode == ChatSidebarMode.expanded && + !_listHiddenBeside(selected))) && (beside || !_usedWorkspace || selected == null), + onHideList: beside && selected != null ? _toggleChatList : null, ); final fullList = ContainerTransformScope( sources: _rowSources, @@ -637,11 +653,15 @@ class _ChatScreenState extends State ); } return ShellBar( - active: selected != null && _sidebarMode != ChatSidebarMode.expanded, + active: + selected != null && + (_sidebarMode != ChatSidebarMode.expanded || + _listHiddenBeside(selected)), barless: true, hideNavigation: true, child: ListDetailPanes( list: list, + listHidden: _listHiddenBeside(selected), compactListWidth: selected == null ? null : ChatCompactSidebar.width, onListCompactChanged: selected == null ? null diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart index 76291a84..7e49ea09 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_screen.dart @@ -25,6 +25,7 @@ import 'create_chat_dialog.dart'; import 'rename_chat_dialog.dart'; import 'session_actions.dart'; import 'session_pane_menu.dart'; +import '../../workspace/chat_list_hidden_controller.dart'; /// Browses server-owned sessions. Opening a row is read-only at this layer. class ChatSessionsScreen extends StatefulWidget { @@ -47,6 +48,7 @@ class ChatSessionsScreen extends StatefulWidget { this.visibleSessionIds = const {}, this.publishShellBar, this.folds, + this.onHideList, }); final ApiGateway gateway; final void Function(JsonMap session) onOpen; @@ -87,6 +89,10 @@ class ChatSessionsScreen extends StatefulWidget { /// ready without pretending its open conversation is unread/inactive. final bool? publishShellBar; + /// Hides the list beside the open chat (the wide layout's Hide chat + /// list); null offers no such action. + final VoidCallback? onHideList; + /// Overrides the device-local hidden/read store in tests. final ChatSessionLocalStore? localStore; @@ -440,6 +446,14 @@ class ChatSessionsScreenState extends State { materialIcon: Icons.refresh, ), ?terminal, + if (widget.onHideList case final hide?) + ChatBarAction( + key: const Key('chat-hide-list'), + identifier: 'chat-hide-list', + label: chatListToggleLabel(false), + onPressed: hide, + materialIcon: Icons.menu_open, + ), ]; } } diff --git a/app/lib/features/chat/workspace/chat_center_stage_keys.dart b/app/lib/features/chat/workspace/chat_center_stage_keys.dart index 2a0b8f4f..2be2e5b7 100644 --- a/app/lib/features/chat/workspace/chat_center_stage_keys.dart +++ b/app/lib/features/chat/workspace/chat_center_stage_keys.dart @@ -6,9 +6,12 @@ import 'package:flutter/widgets.dart'; import '../../../ui/input/keyboard_owner.dart'; import '../windows/chat_window_tabs.dart'; import 'chat_center_stage_controller.dart'; +import 'chat_list_hidden_controller.dart'; void _ignoreFilesShortcut() {} +void _ignoreListShortcut() {} + /// 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 app-owned chords also stops a browser's own @@ -24,6 +27,7 @@ class ChatCenterStageKeys extends StatefulWidget { required this.controller, required this.enabled, this.onToggleFiles = _ignoreFilesShortcut, + this.onToggleList = _ignoreListShortcut, required this.child, }); @@ -33,6 +37,9 @@ class ChatCenterStageKeys extends StatefulWidget { /// no popup or other destination over it. final bool Function() enabled; final VoidCallback onToggleFiles; + + /// Shows or hides the chat list (Ctrl+B, Cmd+B on Apple platforms). + final VoidCallback onToggleList; final Widget child; @override @@ -68,6 +75,15 @@ class _ChatCenterStageKeysState extends State { } return KeyEventResult.handled; } + if (chatListToggleShortcut(event, keyboard)) { + // Ctrl+B stays the terminal's (tmux's prefix, the shell's back a + // character) while it has the keyboard; Cmd+B works there too. + if (!chatCenterStageUsesCommand() && primaryFocusIsTypingSurface()) { + return KeyEventResult.ignored; + } + if (event is KeyDownEvent) widget.onToggleList(); + return KeyEventResult.handled; + } if (!chatCenterStageShortcut(event, keyboard)) { return KeyEventResult.ignored; } diff --git a/app/lib/features/chat/workspace/chat_list_hidden_controller.dart b/app/lib/features/chat/workspace/chat_list_hidden_controller.dart new file mode 100644 index 00000000..d7197937 --- /dev/null +++ b/app/lib/features/chat/workspace/chat_list_hidden_controller.dart @@ -0,0 +1,121 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'chat_center_stage_controller.dart'; + +const chatListHiddenPreferenceKey = 'pipelines.chat.listHidden.v1'; + +abstract interface class ChatListHiddenStore { + Future load(); + Future save(bool hidden); +} + +class SharedChatListHiddenStore implements ChatListHiddenStore { + const SharedChatListHiddenStore(); + + @override + Future load() async { + try { + return (await SharedPreferences.getInstance()).getBool( + chatListHiddenPreferenceKey, + ); + } on Object { + return null; + } + } + + @override + Future save(bool hidden) async { + try { + return await (await SharedPreferences.getInstance()).setBool( + chatListHiddenPreferenceKey, + hidden, + ); + } on Object { + return false; + } + } +} + +/// An in-memory store for tests and fixtures. +class MemoryChatListHiddenStore implements ChatListHiddenStore { + MemoryChatListHiddenStore([this.hidden]); + + bool? hidden; + + @override + Future load() async => hidden; + + @override + Future save(bool hidden) async { + this.hidden = hidden; + return true; + } +} + +/// Whether a wide Chat screen hides its chat list entirely while a chat is +/// open, giving the open chats the whole width. Device-local, like center +/// stage: a presentation choice, not part of any server's layout. The +/// expanded or compact list comes back as it was when shown again. +class ChatListHiddenController extends ValueNotifier { + ChatListHiddenController({ChatListHiddenStore? store}) + : _store = store ?? const SharedChatListHiddenStore(), + super(false); + + static final instance = ChatListHiddenController(); + final ChatListHiddenStore _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; + } + + /// An explicit choice, even of the current value, outranks a restore + /// still reading the stored one. + @override + set value(bool hidden) { + _revision++; + if (hidden == value) return; + super.value = hidden; + unawaited(_store.save(hidden)); + } + + void toggle() => value = !value; +} + +/// Whether [event] shows or hides the chat list: Ctrl+B (Cmd+B on Apple +/// platforms), as an editor's sidebar toggle. Repeats of a held chord match +/// too, so they are swallowed; only the first press toggles. +bool chatListToggleShortcut( + KeyEvent event, + HardwareKeyboard keyboard, { + TargetPlatform? platform, +}) { + if (event is KeyUpEvent || + event.physicalKey != PhysicalKeyboardKey.keyB || + keyboard.isShiftPressed || + keyboard.isAltPressed) { + return false; + } + return chatCenterStageUsesCommand(platform) + ? keyboard.isMetaPressed && !keyboard.isControlPressed + : keyboard.isControlPressed && !keyboard.isMetaPressed; +} + +/// The shortcut as this platform shows it, for menus and tooltips. +String chatListToggleShortcutLabel([TargetPlatform? platform]) => + chatCenterStageUsesCommand(platform) ? 'Cmd+B' : 'Ctrl+B'; + +/// The toggle's label, naming its keyboard shortcut. +String chatListToggleLabel(bool hidden, [TargetPlatform? platform]) => + '${hidden ? 'Show chat list' : 'Hide chat list'} ' + '(${chatListToggleShortcutLabel(platform)})'; diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 592b7c7c..dbbf6a45 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -2,6 +2,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 '../terminal/terminal_shortcuts.dart'; import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_shortcuts.dart'; @@ -162,6 +163,14 @@ class KeyboardShortcutRegistry { action: 'Toggle Files', keys: _apple ? 'Cmd+E' : 'Ctrl+E', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Show or hide the chat list', + keys: chatListToggleShortcutLabel(platform), + caveat: _apple + ? 'Beside an open chat on a wide window.' + : 'Beside an open chat on a wide window. In the terminal Ctrl+B goes to the terminal.', + ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, action: 'Toggle Center Stage', diff --git a/app/lib/shell/list_detail.dart b/app/lib/shell/list_detail.dart index ce992640..0e6f869f 100644 --- a/app/lib/shell/list_detail.dart +++ b/app/lib/shell/list_detail.dart @@ -3,6 +3,7 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import '../ui/adaptive/floating_bar_layout.dart'; +import '../ui/motion/motion.dart'; import 'detail_pane_navigator.dart'; import 'list_detail_policy.dart'; import 'list_pane_divider.dart'; @@ -99,6 +100,7 @@ class ListDetailPanes extends StatefulWidget { this.listWidthOverride, this.compactListWidth, this.onListCompactChanged, + this.listHidden = false, }); final Widget list; @@ -110,6 +112,10 @@ class ListDetailPanes extends StatefulWidget { /// The grab handle remains available at the rail edge to expand it again. final double? compactListWidth; final ValueChanged? onListCompactChanged; + + /// Whether the list is hidden entirely: it slides to zero width (at once + /// with reduced motion) and comes back at the width it had. + final bool listHidden; final Widget detail; /// Which item [detail] shows; selecting another item closes any page the @@ -120,13 +126,32 @@ class ListDetailPanes extends StatefulWidget { State createState() => _ListDetailPanesState(); } -class _ListDetailPanesState extends State { +class _ListDetailPanesState extends State + with SingleTickerProviderStateMixin { // Outside a shell (no [ListPaneWidthsScope]) the divider still drags; the // width lasts as long as the panes. ListPaneWidths? _ownWidths; + /// How far the list has slid away: 0 shown, 1 hidden. + late final AnimationController _hidden = AnimationController( + vsync: this, + value: widget.listHidden ? 1 : 0, + ); + + @override + void didUpdateWidget(ListDetailPanes oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.listHidden == oldWidget.listHidden) return; + _hidden.animateTo( + widget.listHidden ? 1 : 0, + duration: Motion.of(context, Motion.standard), + curve: Motion.curve, + ); + } + @override void dispose() { + _hidden.dispose(); _ownWidths?.dispose(); super.dispose(); } @@ -141,7 +166,7 @@ class _ListDetailPanesState extends State { final split = ShellBar.available(context); return ShellPaneSplit( child: ListenableBuilder( - listenable: widths, + listenable: Listenable.merge([widths, _hidden]), builder: (context, _) => LayoutBuilder( builder: (context, constraints) { final window = ShellRailScope.windowWidth(context); @@ -171,14 +196,19 @@ class _ListDetailPanesState extends State { preferred != null ? preferred.clamp(compactThreshold, normalBounds.max).toDouble() : listDetailListWidth(window, available, preferred); - final listWidth = (widget.listWidthOverride ?? normalWidth) + final shownWidth = (widget.listWidthOverride ?? normalWidth) .clamp(0.0, math.max(0.0, available - kDetailPaneMinWidth)) .toDouble(); + final hidden = _hidden.value; + final listWidth = shownWidth * (1 - hidden); final lineWidth = listWidth > 0 ? 1.0 : 0.0; final bodyWidth = math.max(0.0, available - lineWidth - listWidth); + // The list keeps its width while it slides, so it moves out + // rather than reflowing. final retainedWidth = widget.listWidthOverride == null - ? listWidth + ? shownWidth : math.max(normalWidth, kListPaneMinWidth); + final listGone = listWidth == 0 || widget.listHidden; void resize(double value) { widths.preview(key, value); widget.onListCompactChanged?.call(value < compactThreshold); @@ -225,9 +255,9 @@ class _ListDetailPanesState extends State { minWidth: retainedWidth, maxWidth: retainedWidth, child: ExcludeFocus( - excluding: listWidth == 0, + excluding: listGone, child: ExcludeSemantics( - excluding: listWidth == 0, + excluding: listGone, child: SizedBox.expand( key: const ValueKey('list-detail-list'), child: Semantics( @@ -257,7 +287,7 @@ class _ListDetailPanesState extends State { ), ], ), - if (bounds != null) + if (bounds != null && hidden == 0) PositionedDirectional( start: listWidth + 0.5 - kListPaneDividerGrabWidth / 2, top: 0, diff --git a/app/test/application/chat_quick_switch_shortcut_test.dart b/app/test/application/chat_quick_switch_shortcut_test.dart index 4ef9af04..c7695df6 100644 --- a/app/test/application/chat_quick_switch_shortcut_test.dart +++ b/app/test/application/chat_quick_switch_shortcut_test.dart @@ -6,6 +6,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; import '../core/transport/pipelines_client_test.dart' show FakeChannel; import 'chat_registration_test.dart' @@ -269,4 +270,31 @@ void main() { }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), ); + + testWidgets('with the chat list hidden the switcher still opens and ' + 'switches', (tester) async { + final hidden = ChatListHiddenController.instance; + hidden.value = true; + addTearDown(() => hidden.value = false); + final provider = _provider(); + final channel = await _mountOnChat(tester, provider); + expect(find.byKey(const Key('chat-show-list')), findsOneWidget); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + expect(_field, findsOneWidget); + await tester.enterText(_field, 'second'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s2'); + expect(_composerFocused(tester, 's2'), isTrue); + // Switching leaves the list hidden. + expect(hidden.value, isTrue); + expect(find.byKey(const Key('chat-show-list')), findsOneWidget); + expect(tester.takeException(), isNull); + await _teardown(tester); + }); } diff --git a/app/test/features/chat/chat_list_hide_test.dart b/app/test/features/chat/chat_list_hide_test.dart new file mode 100644 index 00000000..a19ee966 --- /dev/null +++ b/app/test/features/chat/chat_list_hide_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/list_pane_divider.dart'; +import 'package:pipelines_app/ui/adaptive/segmented_bar_overflow.dart'; +import 'package:shared_preferences/shared_preferences.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': [ + {'id': 'a', 'title': 'First chat'}, + {'id': 'b', 'title': 'Second chat'}, + {'id': 'c', 'title': 'Third chat'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + return super.call(type, fields); + } +} + +final _body = find.byKey(const ValueKey('list-detail-body')); +final _show = find.byKey(const Key('chat-show-list')); + +Future _open( + WidgetTester tester, { + bool hidden = false, +}) async { + SharedPreferences.setMockInitialValues({}); + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final listHidden = ChatListHiddenController( + store: MemoryChatListHiddenStore(hidden), + ); + addTearDown(listHidden.dispose); + final gateway = _Gateway()..history = (_) async => chatPage(const []); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: gateway, listHidden: listHidden), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('First chat')); + await tester.pumpAndSettle(); + return listHidden; +} + +Future _chord(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); +} + +double _railRight(WidgetTester tester) => + tester.getRect(find.byType(NavigationRail)).right; + +String? _active(WidgetTester tester) => tester + .widget(find.byType(ChatWorkspace)) + .controller + .activePane + ?.sessionId; + +void main() { + testWidgets('Ctrl+B hides the list entirely and Show chat list brings it ' + 'back', (tester) async { + final listHidden = await _open(tester); + final shown = tester.getRect(_body).left; + expect(shown, greaterThan(_railRight(tester) + 100)); + expect(_show, findsNothing); + // The list's own bar offers hiding too. + expect(find.byKey(const Key('chat-hide-list')), findsOneWidget); + + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isTrue); + // The open chat takes the whole width beside the rail; no divider is + // left to drag. + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + expect(find.byType(ListPaneDivider), findsNothing); + expect(find.text('Second chat').hitTestable(), findsNothing); + // The chat's top bar starts with the way back. + expect(_show, findsOneWidget); + final bar = tester.getRect(find.byKey(const Key('chat-thread-header'))); + expect(tester.getRect(_show).left - bar.left, lessThan(24)); + + await tester.tap(_show); + await tester.pumpAndSettle(); + expect(listHidden.value, isFalse); + expect(tester.getRect(_body).left, closeTo(shown, 1)); + expect(_show, findsNothing); + expect(find.text('Second chat').hitTestable(), findsOneWidget); + + // Ctrl+B again hides, and again shows. + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isTrue); + await _chord(tester, LogicalKeyboardKey.keyB); + expect(listHidden.value, isFalse); + expect(tester.takeException(), isNull); + }); + + testWidgets('the pane menu names the toggle and its shortcut', ( + tester, + ) async { + final listHidden = await _open(tester); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + await tester.tap(find.text('Hide chat list (Ctrl+B)')); + await tester.pumpAndSettle(); + expect(listHidden.value, isTrue); + await tester.tap(find.byKey(segmentedMoreKey).first); + await tester.pumpAndSettle(); + expect(find.text('Show chat list (Ctrl+B)'), findsOneWidget); + }); + + testWidgets('a stored hidden list stays hidden, and Ctrl+Tab still cycles ' + 'the chats', (tester) async { + await _open(tester, hidden: true); + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + expect(_show, findsOneWidget); + expect(_active(tester), 'a'); + await _chord(tester, LogicalKeyboardKey.tab); + expect(_active(tester), 'b'); + await _chord(tester, LogicalKeyboardKey.tab); + expect(_active(tester), 'c'); + // Still hidden. + expect(tester.getRect(_body).left, closeTo(_railRight(tester), 1)); + }); +} diff --git a/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart b/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart new file mode 100644 index 00000000..ecefe087 --- /dev/null +++ b/app/test/features/chat/workspace/chat_list_hidden_controller_test.dart @@ -0,0 +1,82 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_list_hidden_controller.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +KeyDownEvent _b() => const KeyDownEvent( + physicalKey: PhysicalKeyboardKey.keyB, + logicalKey: LogicalKeyboardKey.keyB, + timeStamp: Duration.zero, +); + +void main() { + test('the choice is kept per device and restored', () async { + SharedPreferences.setMockInitialValues({}); + final first = ChatListHiddenController(); + expect(first.value, isFalse); + first.toggle(); + expect(first.value, isTrue); + await Future.delayed(Duration.zero); + expect( + (await SharedPreferences.getInstance()).getBool( + chatListHiddenPreferenceKey, + ), + isTrue, + ); + final next = ChatListHiddenController(); + await next.restore(); + expect(next.value, isTrue); + }); + + test('a choice made while restoring wins', () async { + final store = MemoryChatListHiddenStore(true); + final controller = ChatListHiddenController(store: store); + final restoring = controller.restore(); + controller.value = false; + await restoring; + expect(controller.value, isFalse); + }); + + testWidgets('Ctrl+B elsewhere, Cmd+B on Apple; no other chord', ( + tester, + ) async { + final keyboard = HardwareKeyboard.instance; + Future matches( + List modifiers, + TargetPlatform platform, + ) async { + for (final key in modifiers) { + await tester.sendKeyDownEvent(key); + } + final result = chatListToggleShortcut(_b(), keyboard, platform: platform); + for (final key in modifiers.reversed) { + await tester.sendKeyUpEvent(key); + } + return result; + } + + const linux = TargetPlatform.linux; + const mac = TargetPlatform.macOS; + expect(await matches([LogicalKeyboardKey.controlLeft], linux), isTrue); + expect(await matches([LogicalKeyboardKey.metaLeft], mac), isTrue); + expect(await matches([LogicalKeyboardKey.controlLeft], mac), isFalse); + expect(await matches([LogicalKeyboardKey.metaLeft], linux), isFalse); + expect( + await matches([ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.shiftLeft, + ], linux), + isFalse, + ); + expect( + await matches([ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.altLeft, + ], linux), + isFalse, + ); + expect(await matches(const [], linux), isFalse); + expect(chatListToggleLabel(true, linux), 'Show chat list (Ctrl+B)'); + expect(chatListToggleLabel(false, mac), 'Hide chat list (Cmd+B)'); + }); +} diff --git a/app/test/shell/list_detail_hide_test.dart b/app/test/shell/list_detail_hide_test.dart new file mode 100644 index 00000000..e6656a25 --- /dev/null +++ b/app/test/shell/list_detail_hide_test.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/list_detail.dart'; +import 'package:pipelines_app/shell/list_pane_divider.dart'; + +final _body = find.byKey(const ValueKey('list-detail-body')); + +Widget _panes({required bool hidden, bool reduceMotion = false}) => MaterialApp( + home: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion), + child: Scaffold( + body: ListDetailPanes( + listHidden: hidden, + list: const Focus( + autofocus: true, + child: Text('The list', key: Key('list-text')), + ), + detail: const SizedBox.expand(), + ), + ), + ), + ), +); + +void _size(WidgetTester tester) { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); +} + +void main() { + testWidgets('a hidden list slides to zero width and comes back as it was', ( + tester, + ) async { + _size(tester); + await tester.pumpWidget(_panes(hidden: false)); + await tester.pumpAndSettle(); + final shown = tester.getRect(_body).left; + expect(shown, greaterThan(200)); + expect(find.byType(ListPaneDivider), findsOneWidget); + + await tester.pumpWidget(_panes(hidden: true)); + await tester.pump(const Duration(milliseconds: 60)); + final sliding = tester.getRect(_body).left; + expect(sliding, inExclusiveRange(0, shown), reason: 'animates'); + // The handle is not offered while the list slides or is hidden. + expect(find.byType(ListPaneDivider), findsNothing); + await tester.pumpAndSettle(); + expect(tester.getRect(_body).left, 0); + expect(tester.getRect(_body).width, 1200); + // Nothing in the hidden list keeps the keyboard. + final listFocus = Focus.of( + tester.element(find.byKey(const Key('list-text'))), + ); + expect(listFocus.hasFocus, isFalse); + + await tester.pumpWidget(_panes(hidden: false)); + await tester.pumpAndSettle(); + expect(tester.getRect(_body).left, shown); + expect(find.byType(ListPaneDivider), findsOneWidget); + }); + + testWidgets('with reduced motion the list hides at once', (tester) async { + _size(tester); + await tester.pumpWidget(_panes(hidden: false, reduceMotion: true)); + await tester.pumpAndSettle(); + await tester.pumpWidget(_panes(hidden: true, reduceMotion: true)); + await tester.pump(); + await tester.pump(); + expect(tester.getRect(_body).left, 0); + }); +} From 81c73275c074119e8cfff13a1d815653aff432a6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:38:30 +0000 Subject: [PATCH 8/8] Notes: foldable menu offset, hidden chat list, Terminal default Co-Authored-By: Claude Opus 5.5 --- .../fold-menus-hide-list-terminal-default.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 app/notes/fold-menus-hide-list-terminal-default.md diff --git a/app/notes/fold-menus-hide-list-terminal-default.md b/app/notes/fold-menus-hide-list-terminal-default.md new file mode 100644 index 00000000..1bc27b24 --- /dev/null +++ b/app/notes/fold-menus-hide-list-terminal-default.md @@ -0,0 +1,44 @@ +# Foldable menus, hidden chat list, Terminal by default + +## Top bar menus far below the bar on an unfolded foldable + +Cause: `showAppChoiceMenu` (model, mode/permission, thinking, the narrow +bar's Chat settings panel, Add chat pane, Claude account) measured its anchor +in the root overlay's coordinates, then laid the panel out inside a +`SafeArea`. On Android the app draws edge to edge, so the overlay's +`MediaQuery.padding.top` is the status bar (and cutout): the `SafeArea` +moved the layout's origin down by that inset while the anchor rect stayed in +overlay coordinates, so every panel opened one inset (~50 dp) too low. On a +foldable's narrow pane the selectors sit in the Chat settings panel, itself +such a menu, so a selector's menu opened two insets below the bar. Phones +never showed it (they get bottom sheets below 600 dp) and neither did the +web (no insets). Overflow menus (`AppMenuAnchor` / `MenuAnchor`) were right. + +Fix: `AnchoredMenuLayout` (`lib/ui/adaptive/anchored_menu_layout.dart`) lays +out in the overlay's own coordinates and treats the insets (plus the +keyboard) only as bounds; a half-opened hinge confines the panel to the +anchor's side (`DisplayFeatureSubScreen`). The panel's content has the +padding removed, so a sheet's own `SafeArea` adds nothing inside it. +Tests: `test/ui/adaptive/app_popups_foldable_test.dart` (884x1104, 52/24 +insets, a fold; wide and narrow panes; above-anchor; hinge). + +Captures on web: `?inset=52,24&fold=1` (`tool/fixture_host/inset_view.dart`) +gives the fixture app an Android phone's insets and a fold. + +## Hiding the chat list + +Beside an open chat on a wide window the list can be hidden entirely: +Ctrl+B (Cmd+B on Apple; a focused terminal keeps Ctrl+B), Hide chat list in +the list's bar and in the pane's More menu. While hidden the top-left pane's +bar starts with Show chat list. `ListDetailPanes.listHidden` slides the list +to zero width (`Motion.standard`, instant with reduced motion) and brings it +back in its previous expanded or compact mode; the divider is not offered +while hidden. Device-local: `pipelines.chat.listHidden.v1` +(`ChatListHiddenController`). Ctrl/Alt+K and Ctrl+Tab are unaffected. + +## Terminal is the default design + +No stored (or an unknown) design id resolves to Terminal, including the boot +spinner and detached windows (same controller). A stored choice is kept; the +former Default keeps its stored id `default` and is now labelled Classic in +the picker.