From fd62df3815cea874370f87dba5f63508ed8b9b59 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 20:07:00 +0000 Subject: [PATCH 1/3] 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/3] 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/3] 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.