From fba3b924f1804b4f4c438f6e8bd08cd4091815dd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 21:17:51 +0000 Subject: [PATCH] Chat stack: hold and drag to reorder the open chats, or onto x to remove A 300 ms hold lifts a chat in the open column; dragging opens a gap and dropping commits through ChatWorkspaceController.movePane, the pane order the server syncs. An x comes in at the bottom while dragging; dropping on it removes the chat with Undo, which restores its place. Escape, a cancelled pointer or a drop away from the column put it back. Move up, Move down and Remove are semantic actions. Repaint-only motion; reduced motion swaps at once. Also keep floating-layout tracking out of initState, and let the capture kit hold a press before a drag. Co-Authored-By: Claude Opus 5.5 --- app/lib/features/chat/chat_screen_float.dart | 1 + app/lib/features/chat/chat_screen_stack.dart | 13 +- .../features/chat/chat_screen_workspace.dart | 7 +- .../chat/stack/chat_stack_column.dart | 343 ++++++++---------- .../chat/stack/chat_stack_column_items.dart | 230 ++++++++++++ .../features/chat/stack/chat_stack_disc.dart | 91 ++++- .../features/chat/stack/chat_stack_drag.dart | 320 ++++++++++++++++ .../chat/stack/chat_stack_drag_shift.dart | 145 ++++++++ .../features/chat/stack/chat_stack_fab.dart | 6 + .../chat/stack/chat_stack_handles.dart | 95 +++++ .../chat/stack/chat_stack_remove_target.dart | 106 ++++++ .../workspace/chat_workspace_controller.dart | 18 + app/notes/chat-stack.md | 50 ++- .../chat/stack/chat_stack_drag_test.dart | 323 +++++++++++++++++ .../chat/stack/chat_stack_fab_test.dart | 13 +- .../chat/stack/chat_stack_screen_test.dart | 25 -- app/tool/capture/README.md | 2 +- app/tool/capture/capture.mjs | 6 +- app/tool/capture/page.mjs | 6 +- app/tool/capture/touch.mjs | 27 +- 20 files changed, 1573 insertions(+), 254 deletions(-) create mode 100644 app/lib/features/chat/stack/chat_stack_column_items.dart create mode 100644 app/lib/features/chat/stack/chat_stack_drag.dart create mode 100644 app/lib/features/chat/stack/chat_stack_drag_shift.dart create mode 100644 app/lib/features/chat/stack/chat_stack_handles.dart create mode 100644 app/lib/features/chat/stack/chat_stack_remove_target.dart create mode 100644 app/test/features/chat/stack/chat_stack_drag_test.dart diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index d2ae80a5..ec2102e3 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -68,6 +68,7 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { /// Called from build: a change between a phone and a wide layout moves /// the floating chats between panes and windows after the frame. void _trackFloatLayout() { + _phoneLayout = !showsListBesideDetail(context); if (widget.windows == null) return; final phone = _phoneIgnoresFloat; if (phone == _builtPhoneFloat) return; diff --git a/app/lib/features/chat/chat_screen_stack.dart b/app/lib/features/chat/chat_screen_stack.dart index 37b067cd..9597a65e 100644 --- a/app/lib/features/chat/chat_screen_stack.dart +++ b/app/lib/features/chat/chat_screen_stack.dart @@ -59,6 +59,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { onOpen: (entry) => _openBySelection(entry.session), onAdd: (context) => _addPane(context, title: ChatStackColumn.addLabel), onRemove: _removeFromStack, + onReorder: (entry, index) => _workspace.movePane(entry.paneId, index), ), ), ); @@ -66,6 +67,7 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { void _removeFromStack(ChatStackEntry entry) { final messenger = ScaffoldMessenger.maybeOf(context); final wasActive = _workspace.activePaneId; + final index = _workspace.panes.indexWhere((p) => p.id == entry.paneId); _closePane(entry.paneId); if (messenger == null) return; messenger @@ -75,16 +77,23 @@ mixin _ChatScreenStack on State, _ChatScreenWorkspace { content: Text('Removed ${entry.title} from open chats'), action: SnackBarAction( label: 'Undo', - onPressed: () => _restoreToStack(entry, wasActive), + onPressed: () => _restoreToStack(entry, wasActive, index), ), ), ); } - void _restoreToStack(ChatStackEntry entry, String? wasActive) { + /// Undo: the chat comes back at its old place in the open-chat order. + void _restoreToStack(ChatStackEntry entry, String? wasActive, int index) { if (!mounted || _workspace.holdsSession(entry.sessionId)) return; _openedSessions[entry.sessionId] = entry.session; _workspace.splitActive(entry.sessionId, ChatSplitAxis.horizontal); + final restored = _workspace.panes + .where((pane) => pane.sessionId == entry.sessionId) + .firstOrNull; + if (restored != null && index >= 0) { + _workspace.movePane(restored.id, index); + } // The chat on screen stays on screen unless it was the one removed. if (wasActive != null && wasActive != entry.paneId) { final kept = _workspace.panes diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 6bff87db..5e2646ba 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -118,10 +118,13 @@ mixin _ChatScreenWorkspace on State { /// floating in the server's set, so a wide layout floats them again. final Set _phoneDocked = {}; + /// Whether the last build laid out for a phone (set in build, so it is + /// safe to read from callbacks and initState). + bool _phoneLayout = false; + /// Whether this layout ignores floating: a phone's, where windows are /// hidden and the chats are navigated one at a time. - bool get _phoneIgnoresFloat => - mounted && widget.windows != null && !showsListBesideDetail(context); + bool get _phoneIgnoresFloat => widget.windows != null && _phoneLayout; Iterable _serverWorkspaceEntries() sync* { final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked}; diff --git a/app/lib/features/chat/stack/chat_stack_column.dart b/app/lib/features/chat/stack/chat_stack_column.dart index 908c9eb9..1b70ddf4 100644 --- a/app/lib/features/chat/stack/chat_stack_column.dart +++ b/app/lib/features/chat/stack/chat_stack_column.dart @@ -1,12 +1,15 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; 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_column_items.dart'; import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; import 'chat_stack_entry.dart'; import 'chat_stack_motion.dart'; -import 'chat_stack_pose.dart'; +import 'chat_stack_remove_target.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 @@ -19,10 +22,16 @@ import 'chat_stack_pose.dart'; /// bottom slots go to the frequent action (switching), and the rarer one /// ends the list where the operator reads "and more". /// +/// A short hold lifts a chat ([ChatStackDrag]): dragged up or down it +/// reorders the open chats, the others sliding aside to open its slot; +/// dropped on the "×" that comes in at the bottom it leaves them. Add chat +/// stays put. The same moves are semantic actions on each chat. +/// /// Nothing here rebuilds per frame: every item moves through -/// [ChatStackPoseTransition] and fades through [FadeTransition], both -/// repaint-only. -class ChatStackColumn extends StatelessWidget { +/// `ChatStackPoseTransition` and `ChatStackDragShift` and fades through +/// [FadeTransition], all repaint-only; a drag rebuilds the column only as it +/// starts and ends. +class ChatStackColumn extends StatefulWidget { const ChatStackColumn({ super.key, required this.motion, @@ -34,6 +43,7 @@ class ChatStackColumn extends StatelessWidget { required this.onAdd, required this.onDismiss, this.onRemove, + this.onReorder, }); final ChatStackMotion motion; @@ -52,23 +62,112 @@ class ChatStackColumn extends StatelessWidget { final VoidCallback onAdd; final VoidCallback onDismiss; - /// Long press removes a chat from the open chats; null when it cannot - /// (the only open chat). + /// Removes a chat from the open chats (dropped on the "×"); null when it + /// cannot (the only open chat). final ValueChanged? onRemove; + /// Moves a chat to an index of the open-chat order; null when the chats + /// cannot be reordered. + final void Function(ChatStackEntry entry, int index)? onReorder; + static const removeLabel = 'Remove from open chats'; + static const moveUpLabel = 'Move up'; + static const moveDownLabel = 'Move down'; static const addLabel = 'Add chat'; + @override + State createState() => _ChatStackColumnState(); +} + +class _ChatStackColumnState extends State + with TickerProviderStateMixin { + late final ChatStackDrag _drag = ChatStackDrag( + vsync: this, + pitch: kChatStackPitch, + )..addListener(_dragChanged); + + /// The remove target's centre in this column's box, from the last layout. + Offset? _removeCenter; + + List get _entries => widget.entries; + List get _ids => [for (final entry in _entries) entry.paneId]; + + /// A hold lifts a chat when there is something to do with it. + bool get _draggable => + widget.interactive && + ((widget.onReorder != null && _entries.length > 1) || + widget.onRemove != null); + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _drag.reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false; + } + + @override + void didUpdateWidget(covariant ChatStackColumn oldWidget) { + super.didUpdateWidget(oldWidget); + // Folding, or the open chats changing under the finger (another + // device), puts the dragged chat back. + if (!widget.interactive || + (_drag.dragging && !listEquals(_ids, _drag.order))) { + _drag.cancel(); + } + } + + @override + void dispose() { + _drag.dispose(); + super.dispose(); + } + + void _dragChanged() { + if (mounted) setState(() {}); + } + + void _start(ChatStackEntry entry) { + if (_draggable) _drag.start(entry.paneId, _ids); + } + + void _move(LongPressMoveUpdateDetails details) { + if (!_drag.dragging) return; + final box = context.findRenderObject() as RenderBox?; + final center = _removeCenter; + final over = + widget.onRemove != null && + box != null && + center != null && + (box.globalToLocal(details.globalPosition) - center).distance <= + kChatStackRemoveReach; + _drag.move(details.offsetFromOrigin, overRemove: over); + } + + void _end(ChatStackEntry entry) { + if (!_drag.dragging) return; + switch (_drag.end()) { + case ChatStackDropMove(:final index): + widget.onReorder?.call(entry, index); + case ChatStackDropRemove(): + widget.onRemove?.call(entry); + case ChatStackDropBack(): + break; + } + } + + void _escape() => _drag.dragging ? _drag.cancel() : widget.onDismiss(); + @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; + final anchor = widget.anchor; + final depths = widget.depths; return LayoutBuilder( builder: (context, constraints) { final size = constraints.biggest; - final count = motion.count; + final count = widget.motion.count; final height = (count - 1) * kChatStackPitch + kChatStackSlot; final top = media.padding.top + 8; final available = anchor.bottom - top; @@ -80,39 +179,70 @@ class ChatStackColumn extends StatelessWidget { 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. + // top of the pile last; a lifted chat above them all. 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), - ], - ], + final lifted = _entries.indexWhere((e) => e.paneId == _drag.lifted); + if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted))); + // The remove target: centred in the band below the stack's slot + // (over the composer), clear of the safe area. + const r = kChatStackRemoveSize / 2; + final floor = size.height - media.padding.bottom; + final removeCenter = Offset( + size.width / 2, + math.max( + anchor.bottom + 4, + math.min((anchor.bottom + floor) / 2, floor - r - 8), + ), + ); + _removeCenter = removeCenter; + final items = ChatStackColumnItems( + motion: widget.motion, + entries: _entries, + order: order, + labelMax: labelMax, + drag: _drag, + draggable: _draggable, + onOpen: widget.onOpen, + onAdd: widget.onAdd, + onRemove: widget.onRemove, + onReorder: widget.onReorder, + onDragStart: _start, + onDragMove: _move, + onDragEnd: _end, ); return CallbackShortcuts( - bindings: { - const SingleActivator(LogicalKeyboardKey.escape): onDismiss, - }, + bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape}, child: FocusScope( autofocus: true, child: IgnorePointer( - ignoring: !interactive, + ignoring: !widget.interactive, child: Stack( children: [ Positioned.fill( child: FadeTransition( - opacity: motion.scrim, + opacity: widget.motion.scrim, child: ModalBarrier( color: scheme.scrim.withValues(alpha: dark ? .5 : .32), dismissible: true, - onDismiss: onDismiss, + onDismiss: widget.onDismiss, semanticsLabel: 'Close chats', ), ), ), + // Under the column: a chat dragged onto it is drawn over it. + if (widget.onRemove != null) + Positioned( + left: removeCenter.dx - r, + top: removeCenter.dy - r, + width: kChatStackRemoveSize, + height: kChatStackRemoveSize, + child: ChatStackRemoveTarget( + shown: _drag.removeShown, + hover: _drag.hover, + reduced: _drag.reduced, + ), + ), PositionedDirectional( end: endInset, bottom: size.height - anchor.bottom, @@ -144,169 +274,4 @@ class ChatStackColumn extends StatelessWidget { }, ); } - - 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_column_items.dart b/app/lib/features/chat/stack/chat_stack_column_items.dart new file mode 100644 index 00000000..8389216e --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_column_items.dart @@ -0,0 +1,230 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_column.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; +import 'chat_stack_drag_shift.dart'; +import 'chat_stack_entry.dart'; +import 'chat_stack_handles.dart'; +import 'chat_stack_motion.dart'; +import 'chat_stack_pose.dart'; + +/// The open column's avatars and name pills, each placed at the stack's +/// slot and moved by the open motion ([ChatStackPoseTransition]) and by a +/// drag ([ChatStackDragShift]), painted in [order]. +class ChatStackColumnItems extends StatelessWidget { + const ChatStackColumnItems({ + super.key, + required this.motion, + required this.entries, + required this.order, + required this.labelMax, + required this.drag, + required this.draggable, + required this.onOpen, + required this.onAdd, + required this.onDragStart, + required this.onDragMove, + required this.onDragEnd, + this.onRemove, + this.onReorder, + }); + + final ChatStackMotion motion; + final List entries; + + /// Item indices in paint order, the last on top. + final List order; + final double labelMax; + final ChatStackDrag drag; + + /// Whether a hold lifts a chat. + final bool draggable; + final ValueChanged onOpen; + final VoidCallback onAdd; + final ValueChanged onDragStart; + final ValueChanged onDragMove; + final ValueChanged onDragEnd; + final ValueChanged? onRemove; + final void Function(ChatStackEntry entry, int index)? onReorder; + + @override + Widget build(BuildContext context) => Stack( + clipBehavior: Clip.none, + children: [ + for (final i in order) ...[_label(context, i), _item(context, i)], + ], + ); + + ChatStackEntry? _entry(int i) => i < entries.length ? entries[i] : null; + + /// [child] lifted by a hold when [entry] can be dragged. + Widget _handle(ChatStackEntry? entry, Widget child) => ChatStackDragHandle( + onStart: entry == null || !draggable ? null : () => onDragStart(entry), + onMove: onDragMove, + onEnd: entry == null ? null : () => onDragEnd(entry), + onCancel: drag.cancel, + child: child, + ); + + /// [child] where the drag paints [entry]'s item; Add chat never moves. + Widget _shift(ChatStackEntry? entry, Widget child, {bool scales = true}) => + entry == null + ? child + : ChatStackDragShift( + item: drag.item(entry.paneId), + scales: scales, + child: child, + ); + + Animation? _lift(ChatStackEntry? entry) => + entry != null && entry.paneId == drag.lifted ? drag.lift : null; + + Widget _item(BuildContext context, int i) { + final entry = _entry(i); + return PositionedDirectional( + key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'), + end: 0, + bottom: 0, + // The transforms are outermost: the boxes under them 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: _shift( + entry, + FadeTransition( + opacity: motion.fade[i], + child: KeyedSubtree( + key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'), + child: entry == null + ? _addButton(context) + : _chatButton(context, entry, i), + ), + ), + ), + ), + ); + } + + Widget _label(BuildContext context, int i) { + final entry = _entry(i); + 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], + // The pill moves with its avatar but keeps its size, so the gap + // between them stays even. + child: _shift( + entry, + scales: false, + ExcludeSemantics( + child: FadeTransition( + opacity: motion.label[i], + child: Align( + alignment: AlignmentDirectional.centerEnd, + widthFactor: 1, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: labelMax), + child: _handle( + entry, + GestureDetector( + onTap: entry == null ? onAdd : () => onOpen(entry), + child: ChatStackLabel( + text: entry?.title ?? ChatStackColumn.addLabel, + color: entry?.color(context), + emphasized: entry?.current ?? false, + lift: _lift(entry), + ), + ), + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _chatButton(BuildContext context, ChatStackEntry entry, int index) { + final remove = onRemove; + final reorder = onReorder; + final last = entries.length - 1; + final ring = entry.current + ? entry.color(context) ?? Theme.of(context).colorScheme.primary + : null; + // Up is toward the top of the column: a later place in the order. + final actions = { + if (reorder != null && index < last) + const CustomSemanticsAction(label: ChatStackColumn.moveUpLabel): () => + reorder(entry, index + 1), + if (reorder != null && index > 0) + const CustomSemanticsAction(label: ChatStackColumn.moveDownLabel): () => + reorder(entry, index - 1), + if (remove != null) + const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () => + remove(entry), + }; + return Semantics( + container: true, + button: true, + selected: entry.current, + label: entry.title, + hint: entry.current ? 'Open now' : null, + onTap: () => onOpen(entry), + customSemanticsActions: actions.isEmpty ? null : actions, + child: _handle( + entry, + ChatStackTappable( + autofocus: entry.current, + onTap: () => onOpen(entry), + child: ChatStackDisc( + ring: ring, + lift: _lift(entry), + 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: ChatStackColumn.addLabel, + onTap: onAdd, + child: ChatStackTappable( + 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, + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_disc.dart b/app/lib/features/chat/stack/chat_stack_disc.dart index 7f317378..391a3ac4 100644 --- a/app/lib/features/chat/stack/chat_stack_disc.dart +++ b/app/lib/features/chat/stack/chat_stack_disc.dart @@ -22,13 +22,17 @@ const double kChatStackLabelGap = 10; /// 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}); + const ChatStackDisc({super.key, required this.child, this.ring, this.lift}); final Widget child; /// The rim's colour when it marks the current chat; null for the surface. final Color? ring; + /// While dragged (0 at rest, 1 lifted): a deeper shadow, or under a flat + /// design a frame in the primary colour. + final Animation? lift; + @override Widget build(BuildContext context) { final tokens = AppDesignTokens.of(context); @@ -42,16 +46,20 @@ class ChatStackDisc extends StatelessWidget { ); final ring = this.ring; final shape = chatStackShape(tokens); + final rest = ShapeDecoration( + color: ring ?? base, + // A flat design's avatar frames itself; the rim stays bare. + shape: shape, + shadows: !tokens.flat ? chatStackShadows(scheme) : null, + ); + final lift = this.lift; return SizedBox.square( dimension: kChatStackSlot, child: Center( - child: DecoratedBox( - decoration: ShapeDecoration( - color: ring ?? base, - // A flat design's avatar frames itself; the rim stays bare. - shape: shape, - shadows: !tokens.flat ? chatStackShadows(scheme) : null, - ), + child: chatStackLifted( + lift, + rest, + chatStackRaised(rest, tokens, scheme), child: SizedBox.square( dimension: kChatStackDisc, child: Center( @@ -93,6 +101,52 @@ List chatStackShadows(ColorScheme scheme) => [ ), ]; +/// A short, close shadow's lifted form: deeper and softer, as a card +/// picked up off the column. +List chatStackLiftShadows(ColorScheme scheme) => [ + BoxShadow( + color: scheme.shadow.withValues(alpha: .20), + blurRadius: 8, + offset: const Offset(0, 4), + ), + BoxShadow( + color: scheme.shadow.withValues(alpha: .14), + blurRadius: 22, + offset: const Offset(0, 12), + ), +]; + +/// [rest] as a dragged item wears it: the lifted shadow, or under a flat +/// design (which casts none) a frame in the primary colour. +ShapeDecoration chatStackRaised( + ShapeDecoration rest, + AppDesignTokens tokens, + ColorScheme scheme, +) { + final shape = rest.shape; + return ShapeDecoration( + color: rest.color, + shape: tokens.flat && shape is OutlinedBorder + ? shape.copyWith(side: BorderSide(color: scheme.primary, width: 1.5)) + : shape, + shadows: tokens.flat ? null : chatStackLiftShadows(scheme), + ); +} + +/// [child] over [rest], or blending to [raised] as [lift] runs: repaints +/// only. +Widget chatStackLifted( + Animation? lift, + ShapeDecoration rest, + ShapeDecoration raised, { + required Widget child, +}) => lift == null + ? DecoratedBox(decoration: rest, child: child) + : DecoratedBoxTransition( + decoration: DecorationTween(begin: rest, end: raised).animate(lift), + child: child, + ); + /// 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 { @@ -101,12 +155,16 @@ class ChatStackLabel extends StatelessWidget { required this.text, this.color, this.emphasized = false, + this.lift, }); final String text; final Color? color; final bool emphasized; + /// While dragged, as [ChatStackDisc.lift]. + final Animation? lift; + @override Widget build(BuildContext context) { final tokens = AppDesignTokens.of(context); @@ -122,12 +180,15 @@ class ChatStackLabel extends StatelessWidget { color: scheme.onSurface, fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500, ); - return DecoratedBox( - decoration: ShapeDecoration( - color: fill, - shape: _labelShape(tokens), - shadows: tokens.flat ? null : chatStackShadows(scheme), - ), + final rest = ShapeDecoration( + color: fill, + shape: _labelShape(tokens), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + return chatStackLifted( + lift, + rest, + chatStackRaised(rest, tokens, scheme), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), child: Text( @@ -141,7 +202,7 @@ class ChatStackLabel extends StatelessWidget { ); } - ShapeBorder _labelShape(AppDesignTokens tokens) { + OutlinedBorder _labelShape(AppDesignTokens tokens) { final side = tokens.frameSide ?? BorderSide.none; final r = tokens.radius; return r == null diff --git a/app/lib/features/chat/stack/chat_stack_drag.dart b/app/lib/features/chat/stack/chat_stack_drag.dart new file mode 100644 index 00000000..4c80ee51 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_drag.dart @@ -0,0 +1,320 @@ +import 'dart:ui' show lerpDouble; + +import 'package:flutter/animation.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// How long a press is held before the chat lifts for a drag: long enough +/// that a tap still opens the chat, short enough to feel immediate. +const Duration chatStackLiftDelay = Duration(milliseconds: 300); + +/// The lifted avatar's scale. +const double chatStackLiftScale = 1.1; + +/// The lifted avatar's scale, relative to lifted, over the remove target. +const double chatStackOverRemoveScale = .8; + +/// How long the neighbours take to slide aside, and the lifted chat to +/// settle into its slot (or back) after the drop. +const Duration chatStackShiftDuration = Duration(milliseconds: 200); +const Duration chatStackSettleDuration = Duration(milliseconds: 220); + +/// How long the remove target takes to come in and to light up. +const Duration chatStackRemoveDuration = Duration(milliseconds: 180); +const Duration chatStackHoverDuration = Duration(milliseconds: 140); + +/// Where one item of the open column is painted relative to its slot while +/// a chat is dragged; a render object repaints when it changes. +class ChatStackDragItem extends ChangeNotifier { + Offset _offset = Offset.zero; + double _scale = 1; + + Offset get offset => _offset; + double get scale => _scale; + + void _set(Offset offset, double scale) { + if (offset == _offset && scale == _scale) return; + _offset = offset; + _scale = scale; + notifyListeners(); + } +} + +/// What a drop does. +sealed class ChatStackDrop { + const ChatStackDrop(); +} + +/// Nothing: the chat settles back into its own slot. +class ChatStackDropBack extends ChatStackDrop { + const ChatStackDropBack(); +} + +/// The chat moves to [index] in the open-chat order. +class ChatStackDropMove extends ChatStackDrop { + const ChatStackDropMove(this.index); + final int index; +} + +/// The chat leaves the open chats. +class ChatStackDropRemove extends ChatStackDrop { + const ChatStackDropRemove(); +} + +/// One drag in the open column: which chat is lifted, the slot it would +/// drop into, whether it is over the remove target, and the motion of every +/// item. It notifies only when a drag starts or ends (the column then +/// rebuilds once); each pointer move only repaints the items that move. +class ChatStackDrag extends ChangeNotifier { + ChatStackDrag({required TickerProvider vsync, required this.pitch}) + : _vsync = vsync { + lift = AnimationController(vsync: vsync, duration: chatStackShiftDuration) + ..addListener(_paintLifted); + settle = + AnimationController(vsync: vsync, duration: chatStackSettleDuration) + ..addListener(_paintLifted) + ..addStatusListener(_settled); + removeShown = AnimationController( + vsync: vsync, + duration: chatStackRemoveDuration, + ); + hover = AnimationController(vsync: vsync, duration: chatStackHoverDuration) + ..addListener(_paintLifted); + } + + final TickerProvider _vsync; + + /// The distance between neighbouring slots. + final double pitch; + + /// Under reduced motion neighbours swap at once and nothing slides. + bool reduced = false; + + late final AnimationController lift; + late final AnimationController settle; + + /// The remove target's entrance, and its highlight while a chat is over + /// it. + late final AnimationController removeShown; + late final AnimationController hover; + + final Map _items = {}; + final Map _shifts = {}; + + /// The chat being dragged or settling; it paints above the others. + String? get lifted => _lifted; + String? _lifted; + + /// The chats' order when the drag started; null when none is dragged. + List? get order => _order; + List? _order; + int _from = 0; + int? _slot; + bool _over = false; + Offset _pointer = Offset.zero; + Offset _residual = Offset.zero; + + bool get dragging => _order != null; + bool get overRemove => _over; + + /// Where [id]'s item is painted; created on first use. + ChatStackDragItem item(String id) => + _items.putIfAbsent(id, ChatStackDragItem.new); + + static const _curve = Curves.easeOutCubic; + + /// Lifts [id] out of [order] (the chats, without Add chat). + void start(String id, List order) { + final from = order.indexOf(id); + if (from < 0) return; + if (_lifted != null) _finishSettle(); + _order = List.of(order); + _from = from; + _slot = from; + _over = false; + _pointer = Offset.zero; + _residual = Offset.zero; + _lifted = id; + HapticFeedback.mediumImpact(); + if (reduced) { + lift.value = 1; + removeShown.value = 1; + } else { + lift.forward(from: 0); + removeShown.forward(); + } + hover.value = 0; + notifyListeners(); + } + + /// The pointer moved [fromOrigin] since the press; [overRemove] says + /// whether it is over the remove target. + void move(Offset fromOrigin, {required bool overRemove}) { + final order = _order; + if (order == null) return; + _pointer = fromOrigin; + if (overRemove != _over) { + _over = overRemove; + if (overRemove) HapticFeedback.selectionClick(); + if (reduced) { + hover.value = overRemove ? 1 : 0; + } else { + overRemove ? hover.forward() : hover.reverse(); + } + } + // Far to the side of the column, or over the target, there is no slot: + // the gap closes and a drop there puts the chat back. + final inColumn = !overRemove && fromOrigin.dx.abs() <= pitch * 1.5; + final slot = inColumn + ? (_from - (fromOrigin.dy / pitch).round()).clamp(0, order.length - 1) + : null; + if (slot != _slot) { + if (slot != null && _slot != null) HapticFeedback.selectionClick(); + _slot = slot; + _shiftNeighbours(animate: !reduced); + } + _paintLifted(); + } + + /// Ends the drag and says what the drop does; the motion back (or into + /// the new slot) runs from here. + ChatStackDrop end() { + final order = _order; + if (order == null) return const ChatStackDropBack(); + final slot = _slot; + final ChatStackDrop drop = _over + ? const ChatStackDropRemove() + : slot != null && slot != _from + ? ChatStackDropMove(slot) + : const ChatStackDropBack(); + _order = null; + switch (drop) { + case ChatStackDropMove(:final index): + // The new order puts the neighbours where they are now drawn; the + // dragged chat glides from the finger into its new slot. + _slot = null; + _residual = _pointer + Offset(0, (index - _from) * pitch); + _shiftNeighbours(animate: false); + case ChatStackDropRemove(): + _slot = null; + _residual = Offset.zero; + _shiftNeighbours(animate: false); + case ChatStackDropBack(): + _slot = null; + _residual = _pointer; + _shiftNeighbours(animate: !reduced); + } + _release(); + return drop; + } + + /// Puts the chat back where it was (Escape, a cancelled pointer, the + /// column folding). + void cancel() { + if (_order == null) return; + _order = null; + _slot = null; + _residual = _pointer; + _shiftNeighbours(animate: !reduced); + _release(); + } + + void _release() { + _pointer = Offset.zero; + if (_over) HapticFeedback.selectionClick(); + _over = false; + if (reduced) { + hover.value = 0; + removeShown.value = 0; + lift.value = 0; + _residual = Offset.zero; + _finishSettle(); + return; + } + hover.reverse(); + removeShown.reverse(); + lift.reverse(); + settle.forward(from: 0); + } + + void _settled(AnimationStatus status) { + if (status == AnimationStatus.completed) _finishSettle(); + } + + void _finishSettle() { + settle.stop(); + final id = _lifted; + _residual = Offset.zero; + if (id != null) item(id)._set(Offset.zero, 1); + if (_order != null) return; + _lifted = null; + notifyListeners(); + } + + void _paintLifted() { + final id = _lifted; + if (id == null) return; + // Over the remove target the chat shrinks into it, so the target's + // lit rim shows around it. + final scale = + lerpDouble(1, chatStackLiftScale, _curve.transform(lift.value))! * + lerpDouble(1, chatStackOverRemoveScale, hover.value)!; + final offset = _order != null + ? _pointer + : _residual * (1 - _curve.transform(settle.value)); + item(id)._set(offset, scale); + } + + /// Slides each neighbour aside to open the gap at the current slot, or + /// back home when there is none. + void _shiftNeighbours({required bool animate}) { + final order = _order ?? const []; + final ids = {...order, ..._shifts.keys}; + final slot = _slot; + for (final id in ids) { + if (id == _lifted && _order != null) continue; + final i = order.indexOf(id); + var target = 0.0; + if (slot != null && i >= 0) { + // Down (toward the thumb) when the lifted chat goes above it, up + // when it goes below. + if (_from < slot && i > _from && i <= slot) target = 1; + if (slot < _from && i >= slot && i < _from) target = -1; + } + final shift = _shifts.putIfAbsent(id, () => _shiftFor(id)); + if (shift.value == target) continue; + if (animate) { + shift.animateTo( + target, + duration: chatStackShiftDuration, + curve: _curve, + ); + } else { + shift + ..stop() + ..value = target; + } + } + } + + AnimationController _shiftFor(String id) { + final shift = AnimationController.unbounded(vsync: _vsync); + shift.addListener(() => item(id)._set(Offset(0, shift.value * pitch), 1)); + return shift; + } + + @override + void dispose() { + lift.dispose(); + settle.dispose(); + removeShown.dispose(); + hover.dispose(); + for (final shift in _shifts.values) { + shift.dispose(); + } + for (final item in _items.values) { + item.dispose(); + } + super.dispose(); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_drag_shift.dart b/app/lib/features/chat/stack/chat_stack_drag_shift.dart new file mode 100644 index 00000000..292499a8 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_drag_shift.dart @@ -0,0 +1,145 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +import 'chat_stack_drag.dart'; + +/// Paints [child] where [item] says while a chat of the open column is +/// dragged: moved, and scaled about its centre when [scales]. A change only +/// repaints (the matrix and the layer are reused); hit tests follow it. At +/// rest it paints straight through, with no layer. +class ChatStackDragShift extends SingleChildRenderObjectWidget { + const ChatStackDragShift({ + super.key, + required this.item, + this.scales = true, + super.child, + }); + + final ChatStackDragItem item; + final bool scales; + + @override + RenderChatStackDragShift createRenderObject(BuildContext context) => + RenderChatStackDragShift(item: item, scales: scales); + + @override + void updateRenderObject( + BuildContext context, + RenderChatStackDragShift renderObject, + ) { + renderObject + ..item = item + ..scales = scales; + } +} + +class RenderChatStackDragShift extends RenderProxyBox { + RenderChatStackDragShift({ + required ChatStackDragItem item, + required bool scales, + }) { + _item = item; + _scales = scales; + } + + late ChatStackDragItem _item; + set item(ChatStackDragItem value) { + if (identical(value, _item)) return; + if (attached) _item.removeListener(_changed); + _item = value; + if (attached) _item.addListener(_changed); + _changed(); + } + + late bool _scales; + set scales(bool value) { + if (value == _scales) return; + _scales = value; + _changed(); + } + + final Matrix4 _matrix = Matrix4.identity(); + final LayerHandle _layer = LayerHandle(); + + bool get _moved => + _item.offset != Offset.zero || (_scales && _item.scale != 1); + + bool _wasMoved = false; + + void _changed() { + // Entering or leaving rest adds or drops the transform layer. + final moved = _moved; + if (moved != _wasMoved) { + _wasMoved = moved; + markNeedsCompositingBitsUpdate(); + } + markNeedsPaint(); + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _wasMoved = _moved; + _item.addListener(_changed); + } + + @override + void detach() { + _item.removeListener(_changed); + super.detach(); + } + + @override + void dispose() { + _layer.layer = null; + super.dispose(); + } + + @override + bool get alwaysNeedsCompositing => child != null && _moved; + + Matrix4 _current() { + final offset = _item.offset; + final scale = _scales ? _item.scale : 1.0; + final cx = size.width / 2; + final cy = size.height / 2; + return _matrix + ..setIdentity() + ..translateByDouble(offset.dx + cx, offset.dy + cy, 0, 1) + ..scaleByDouble(scale, scale, 1, 1) + ..translateByDouble(-cx, -cy, 0, 1); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child == null) return; + if (!_moved) { + _layer.layer = null; + super.paint(context, offset); + return; + } + _layer.layer = context.pushTransform( + needsCompositing, + offset, + _current(), + super.paint, + oldLayer: _layer.layer, + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + if (!_moved) return super.hitTestChildren(result, position: position); + return result.addWithPaintTransform( + transform: _current(), + position: position, + hitTest: (result, position) => + super.hitTestChildren(result, position: position), + ); + } + + @override + void applyPaintTransform(RenderBox child, Matrix4 transform) { + if (_moved) transform.multiply(_current()); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_fab.dart b/app/lib/features/chat/stack/chat_stack_fab.dart index eafa67bb..7fb9e419 100644 --- a/app/lib/features/chat/stack/chat_stack_fab.dart +++ b/app/lib/features/chat/stack/chat_stack_fab.dart @@ -20,6 +20,7 @@ class ChatStackFab extends StatefulWidget { required this.onOpen, required this.onAdd, this.onRemove, + this.onReorder, }); /// The open chats in their synced order; one is [ChatStackEntry.current]. @@ -30,6 +31,10 @@ class ChatStackFab extends StatefulWidget { final ValueChanged onAdd; final ValueChanged? onRemove; + /// Moves a chat to an index of the open-chat order (a drag in the open + /// column, or its Move up and Move down actions). + final void Function(ChatStackEntry entry, int index)? onReorder; + @override State createState() => ChatStackFabState(); } @@ -216,6 +221,7 @@ class ChatStackFabState extends State onAdd: _add, onDismiss: collapse, onRemove: canRemove ? _remove : null, + onReorder: widget.onReorder, ); }, child: AnimatedOpacity( diff --git a/app/lib/features/chat/stack/chat_stack_handles.dart b/app/lib/features/chat/stack/chat_stack_handles.dart new file mode 100644 index 00000000..3bb76256 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_handles.dart @@ -0,0 +1,95 @@ +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_disc.dart'; +import 'chat_stack_drag.dart'; + +/// Lifts [child] for a drag after a short hold ([chatStackLiftDelay]); a +/// quicker tap still reaches [child]'s own tap. Null callbacks leave the +/// child alone. +class ChatStackDragHandle extends StatelessWidget { + const ChatStackDragHandle({ + super.key, + required this.child, + this.onStart, + this.onMove, + this.onEnd, + this.onCancel, + }); + + final Widget child; + final VoidCallback? onStart; + final ValueChanged? onMove; + final VoidCallback? onEnd; + final VoidCallback? onCancel; + + @override + Widget build(BuildContext context) { + if (onStart == null) return child; + return RawGestureDetector( + // The items offer moving and removing as semantic actions instead. + excludeFromSemantics: true, + gestures: { + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => LongPressGestureRecognizer( + duration: chatStackLiftDelay, + debugOwner: this, + ), + (recognizer) { + recognizer + ..onLongPressStart = ((_) => onStart?.call()) + ..onLongPressMoveUpdate = onMove + ..onLongPressEnd = ((_) => onEnd?.call()) + ..onLongPressCancel = onCancel; + }, + ), + }, + child: child, + ); + } +} + +/// 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 ChatStackTappable extends StatelessWidget { + const ChatStackTappable({ + super.key, + required this.child, + required this.onTap, + this.autofocus = false, + }); + + final Widget child; + final VoidCallback onTap; + 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, + ), + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/chat/stack/chat_stack_remove_target.dart b/app/lib/features/chat/stack/chat_stack_remove_target.dart new file mode 100644 index 00000000..72123b52 --- /dev/null +++ b/app/lib/features/chat/stack/chat_stack_remove_target.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/theme/app_design_tokens.dart'; +import 'chat_stack_disc.dart'; + +/// The remove target's diameter: a little larger than an item, so it reads +/// as a destination rather than another chat. +const double kChatStackRemoveSize = kChatStackSlot + 8; + +/// How near its centre a finger counts as over the target: past its rim, +/// as a thumb covers what it drags. +const double kChatStackRemoveReach = kChatStackRemoveSize * .8; + +/// How much the target grows while a chat is over it. +const double chatStackRemoveGrowth = 1.2; + +/// The "×" a dragged chat is dropped on to leave the open chats: a circle +/// (the design's square under a flat design) that comes in when a drag +/// starts and fills with the error colour while a chat is over it. It takes +/// no input and says nothing to assistive technology: dropping is decided +/// from the pointer's position, and the column's items offer the same +/// removal as an action. +/// +/// Everything moves through transitions (fade, slide, scale, decoration), +/// so a drag repaints it without rebuilding. +class ChatStackRemoveTarget extends StatelessWidget { + const ChatStackRemoveTarget({ + super.key, + required this.shown, + required this.hover, + required this.reduced, + }); + + /// 0 hidden, 1 in place. + final Animation shown; + + /// 0 idle, 1 with a chat over it. + final Animation hover; + + /// Fades only: no slide in, no growth. + final bool reduced; + + @override + Widget build(BuildContext context) { + final tokens = AppDesignTokens.of(context); + final scheme = Theme.of(context).colorScheme; + final dark = Theme.of(context).brightness == Brightness.dark; + final shape = chatStackShape(tokens); + final side = tokens.flat + ? tokens.frameSide ?? BorderSide(color: scheme.outlineVariant) + : BorderSide.none; + final idle = ShapeDecoration( + color: tokens.panelFill( + scheme, + dark ? scheme.surfaceContainerHighest : scheme.surface, + ), + shape: shape.copyWith(side: side), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + final hot = ShapeDecoration( + color: scheme.error, + shape: shape.copyWith( + side: tokens.flat ? side.copyWith(color: scheme.error) : side, + ), + shadows: tokens.flat ? null : chatStackShadows(scheme), + ); + final curve = shown.drive(CurveTween(curve: Curves.easeOutCubic)); + Widget target = DecoratedBoxTransition( + decoration: DecorationTween(begin: idle, end: hot).animate(hover), + child: SizedBox.square( + dimension: kChatStackRemoveSize, + child: Stack( + alignment: Alignment.center, + children: [ + Icon(Icons.close, color: scheme.onSurfaceVariant), + FadeTransition( + opacity: hover, + child: Icon(Icons.close, color: scheme.onError), + ), + ], + ), + ), + ); + if (!reduced) { + target = ScaleTransition( + scale: Tween( + begin: 1, + end: chatStackRemoveGrowth, + ).chain(CurveTween(curve: Curves.easeOutBack)).animate(hover), + child: target, + ); + target = SlideTransition( + position: Tween( + begin: const Offset(0, .5), + end: Offset.zero, + ).animate(curve), + child: target, + ); + } + return IgnorePointer( + child: ExcludeSemantics( + child: FadeTransition(opacity: curve, child: target), + ), + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart index c6643a71..4a671b28 100644 --- a/app/lib/features/chat/workspace/chat_workspace_controller.dart +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -163,6 +163,24 @@ class ChatWorkspaceController extends ChangeNotifier { _changed(); } + /// Moves the pane [paneId] to [index] in the pane order (the open-chat + /// order the server syncs). The panes keep their ids and the splits their + /// geometry; only the leaves change slots. The active pane stays. + void movePane(String paneId, int index) { + final order = panes; + final from = order.indexWhere((pane) => pane.id == paneId); + if (from < 0) return; + final to = index.clamp(0, order.length - 1); + if (from == to) return; + order.insert(to, order.removeAt(from)); + final next = reconcileChatWorkspaceTree(_root, [ + for (final pane in order) pane.sessionId, + ], _id); + if (identical(next, _root)) return; + _root = next; + _changed(); + } + void resize(String splitId, double ratio) { if (_root == null || !ratio.isFinite) return; _root = _resize(_root!, splitId, ratio.clamp(.01, .99)); diff --git a/app/notes/chat-stack.md b/app/notes/chat-stack.md index 2bb27641..0ffac150 100644 --- a/app/notes/chat-stack.md +++ b/app/notes/chat-stack.md @@ -13,9 +13,23 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout - 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. + chat pane picker (searchable, the list's own rows) titled "Add chat". +- Drag: in the open column a 300 ms hold (a quicker tap still opens) lifts + a chat with its pill: a medium haptic, 1.1x scale and a deeper shadow + (flat designs: a primary-colour frame instead). Dragged up or down, the + others slide aside (200 ms ease-out) to open its slot, with a selection + tick per slot; dropping commits through `ChatWorkspaceController.movePane` + (the pane order the server syncs as the open-chat order). A "×" fades and + slides in, centred in the band below the stack's slot (over the composer, + above the safe area); over it (a reach of 0.8x its size around its centre) + it grows 1.2x and fills with the error colour, and the chat shrinks into + it. Dropping there removes the pane with the Undo snack bar; Undo re-adds + it at its old index and keeps the chat on screen. A drop far to the side + (more than 1.5 pitches) or Escape or a cancelled pointer puts it back. + Add chat never lifts and is never a slot. Semantics: Move up, Move down, + Remove from open chats as custom actions on each chat. Reduced motion: + neighbours swap at once, the lift and settle are instant, the "×" only + fades and does not grow. - 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 @@ -31,21 +45,47 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout - 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. + per-frame rebuilds, no blur. A drag adds `ChatStackDragShift` (same idea, + driven by a per-item notifier, no layer at rest); the column rebuilds only + when a drag starts and ends. 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, +- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column and + its items, drag (session, shift render object, handles, remove target), 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`. +## Floating chats on a phone + +A phone layout (Quick switch or Chat stack) ignores floating: windows are +hidden below `kListDetailMinWidth`, so each floating chat is held as an +ordinary pane (`_phoneDocked` in `chat_screen_workspace.dart`) and the +server's set keeps it `floating`. Widening the window (a foldable opened, a +desktop resized) floats those chats again; closing one on the phone drops +it from the open chats. Tests: `test/features/chat/chat_floating_phone_test.dart`. + +## Captures + +Drag captures use the kit's mouse `drag` with `press: 700`: with Flutter +web semantics on (the kit turns it on), the engine's click debouncer holds a +press on a tappable node for about 200 ms before the framework sees it, so +a 300 ms hold needs about 500 ms in the browser. Not an issue on a device +without a screen reader. + ## Not verified On-device behaviour (Android keyboard insets, haptics) was not run on a device; web captures used Chrome's touch emulation at 390x844. + +Drag limits: no auto-scroll while dragging; when the column is taller than +the screen it scrolls and clips, so a lifted chat cannot leave the clipped +column to reach the "×" there (Move and Remove remain as semantic actions). +The drag captures used the mouse (CDP), not touch; on-device haptics and the +hold feel are unverified. diff --git a/app/test/features/chat/stack/chat_stack_drag_test.dart b/app/test/features/chat/stack/chat_stack_drag_test.dart new file mode 100644 index 00000000..a97afd51 --- /dev/null +++ b/app/test/features/chat/stack/chat_stack_drag_test.dart @@ -0,0 +1,323 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.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/core/servers/server_scope.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/screen.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart'; +import 'package:pipelines_app/features/chat/stack/chat_stack_remove_target.dart'; +import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.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:shared_preferences/shared_preferences.dart'; + +import '../conversation/chat_thread_fixtures.dart'; + +/// A chat server keeping the open-chat set, as the sync test's does. +class _Server extends FakeChatGateway { + List open = ['a', 'b', 'c']; + int revision = 1; + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'chat_sessions') { + return Future.value({ + 'chat_sessions': [ + for (final id in ['a', 'b', 'c', 'd']) + {'id': id, 'title': 'Chat $id', 'directory': '/w'}, + ], + }); + } + if (type == 'chat_shells') return Future.value({'chat_shells': []}); + if (type == 'chat_open_workspace') { + final request = fields['chat_open_workspace_request'] as Map?; + var rejected = false; + if (request != null && request['seed'] != true) { + if (request['base_revision'] != revision) { + rejected = true; + } else { + open = [ + for (final e in (request['entries'] as List).cast()) + '${e['session_id']}', + ]; + revision++; + } + } + return Future.value({ + 'type': 'chat_open_workspace', + 'chat_open_workspace': { + 'revision': revision, + 'entries': [ + for (final id in open) {'session_id': id}, + ], + if (rejected) 'rejected': true, + }, + }); + } + return super.call(type, fields); + } +} + +Future<_Server> _pump(WidgetTester tester, {bool reduced = false}) async { + SharedPreferences.setMockInitialValues({}); + unawaited( + MobileChatNavigationController.instance.setValue( + MobileChatNavigation.chatStack, + ), + ); + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final server = _Server()..history = (_) async => chatPage(const []); + bindServerIdentity(server, 'server-stack'); + addTearDown(server.close); + await tester.pumpWidget( + MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(disableAnimations: reduced), + child: child!, + ), + home: AdaptiveShell( + destination: AppDestination.chat, + destinationBodies: { + AppDestination.chat: (_) => + ChatScreen(gateway: server, persistWorkspace: true), + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-row-a'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-stack'))); + await tester.pumpAndSettle(); + return server; +} + +ChatWorkspaceController _workspace(WidgetTester tester) => + tester.widget(find.byType(ChatWorkspace)).controller; + +List _order(WidgetTester tester) => [ + for (final pane in _workspace(tester).panes) pane.sessionId, +]; + +/// Chat [id]'s avatar in the open column. +Finder _button(WidgetTester tester, String id) { + final pane = _workspace( + tester, + ).panes.firstWhere((pane) => pane.sessionId == id); + return find.byKey(ValueKey('chat-stack-button-${pane.id}')); +} + +final _add = find.byKey(const ValueKey('chat-stack-button-add')); +final _target = find.byType(ChatStackRemoveTarget); + +/// Holds [finder] until it lifts. +Future _lift(WidgetTester tester, Finder finder) async { + final gesture = await tester.startGesture(tester.getCenter(finder)); + await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20)); + return gesture; +} + +double _shown(WidgetTester tester) => + tester.widget(_target).shown.value; + +void main() { + final navigation = MobileChatNavigationController.instance; + tearDown(() { + unawaited(navigation.setValue(MobileChatNavigation.quickSwitch)); + }); + + test('movePane moves a pane and keeps the active one', () { + final controller = ChatWorkspaceController()..open('a'); + controller + ..splitActive('b', ChatSplitAxis.horizontal) + ..splitActive('c', ChatSplitAxis.horizontal); + final active = controller.activePaneId; + final a = controller.panes.first.id; + controller.movePane(a, 2); + expect(controller.panes.map((p) => p.sessionId), ['b', 'c', 'a']); + expect(controller.panes.last.id, a); + expect(controller.activePaneId, active); + controller.dispose(); + }); + + testWidgets('hold and drag reorders, and the order reaches the server', ( + tester, + ) async { + final server = await _pump(tester); + expect(_order(tester), ['a', 'b', 'c']); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + // Lifted: the remove target comes in. + await tester.pumpAndSettle(); + expect(_shown(tester), 1); + // Up two slots: b and c slide down to open the gap. + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['b', 'c', 'a']); + expect(server.open, ['b', 'c', 'a']); + // Everyone settles in the new slots; the column stays open. + expect(tester.getCenter(_button(tester, 'b')).dy, closeTo(b.dy + 56, .5)); + expect(_shown(tester), 0); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('dropping on the × removes; Undo restores the place', ( + tester, + ) async { + final server = await _pump(tester); + final gesture = await _lift(tester, _button(tester, 'b')); + await tester.pumpAndSettle(); + final from = tester.getCenter(_button(tester, 'b')); + await gesture.moveBy(tester.getCenter(_target) - from); + await tester.pumpAndSettle(); + final drag = tester.widget(_target).hover; + expect(drag.value, 1); + await gesture.up(); + await tester.pumpAndSettle(); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + expect(_order(tester), ['a', 'c']); + expect(server.open, ['a', 'c']); + await tester.tap(find.text('Undo')); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + // The chat on screen stays on screen. + expect(_workspace(tester).activePane?.sessionId, 'a'); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Escape, or a drop away from the column, puts the chat back', ( + tester, + ) async { + final server = await _pump(tester); + final home = tester.getCenter(_button(tester, 'a')); + var gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(0, -kChatStackPitch * 2)); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + // Escape only cancelled the drag: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + + gesture = await _lift(tester, _button(tester, 'a')); + await gesture.moveBy(const Offset(-200, -kChatStackPitch * 3)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + expect(server.open, ['a', 'b', 'c']); + expect(tester.getCenter(_button(tester, 'a')), home); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('a tap still opens a chat; Add chat does not lift', ( + tester, + ) async { + await _pump(tester); + final add = tester.getCenter(_add); + final gesture = await _lift(tester, _add); + await tester.pumpAndSettle(); + expect(_shown(tester), 0); + await gesture.moveBy(const Offset(0, kChatStackPitch * 2)); + await tester.pumpAndSettle(); + expect(tester.getCenter(_add), add); + await gesture.up(); + await tester.pumpAndSettle(); + expect(_order(tester), ['a', 'b', 'c']); + + // A drag that moved off "+" is no tap: the column is still open. + expect(find.byType(ChatStackColumn), findsOneWidget); + await tester.tap(_button(tester, 'c')); + await tester.pumpAndSettle(); + expect( + find + .byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == 'c') + .hitTestable(), + findsOneWidget, + ); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('Move up, Move down and Remove are semantic actions', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final server = await _pump(tester); + void act(String id, String label) { + final node = tester.getSemantics(_button(tester, id)); + final action = node + .getSemanticsData() + .customSemanticsActionIds! + .map(CustomSemanticsAction.getAction) + .firstWhere((action) => action!.label == label)!; + tester.binding.renderViews.first.owner!.semanticsOwner!.performAction( + node.id, + SemanticsAction.customAction, + CustomSemanticsAction.getIdentifier(action), + ); + } + + // The bottom chat cannot move down; the top one cannot move up. + final bottom = tester.getSemantics(_button(tester, 'a')); + expect( + bottom.getSemanticsData().customSemanticsActionIds!.map( + (id) => CustomSemanticsAction.getAction(id)!.label, + ), + unorderedEquals([ + ChatStackColumn.moveUpLabel, + ChatStackColumn.removeLabel, + ]), + ); + act('a', ChatStackColumn.moveUpLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'a', 'c']); + act('c', ChatStackColumn.moveDownLabel); + await tester.pumpAndSettle(); + expect(server.open, ['b', 'c', 'a']); + act('b', ChatStackColumn.removeLabel); + await tester.pumpAndSettle(); + expect(server.open, ['c', 'a']); + expect(find.text('Removed Chat b from open chats'), findsOneWidget); + semantics.dispose(); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('reduced motion: neighbours swap at once, the × only fades', ( + tester, + ) async { + await _pump(tester, reduced: true); + final b = tester.getCenter(_button(tester, 'b')); + final gesture = await _lift(tester, _button(tester, 'a')); + expect(_shown(tester), 1); + await gesture.moveBy(const Offset(0, -kChatStackPitch)); + await tester.pump(); + expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch); + // No slide: the target sits in place. + expect( + find.descendant(of: _target, matching: find.byType(SlideTransition)), + findsNothing, + ); + await gesture.up(); + await tester.pump(); + expect(_order(tester), ['b', 'a', 'c']); + expect(_shown(tester), 0); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/features/chat/stack/chat_stack_fab_test.dart b/app/test/features/chat/stack/chat_stack_fab_test.dart index 6804eb4a..6b7339ea 100644 --- a/app/test/features/chat/stack/chat_stack_fab_test.dart +++ b/app/test/features/chat/stack/chat_stack_fab_test.dart @@ -145,17 +145,18 @@ void main() { expect(harness.opened, ['s3']); }); - testWidgets('add opens the picker; long press removes', (tester) async { + testWidgets('add opens the picker; a hold alone removes nothing', ( + tester, + ) async { final harness = await _pump(tester); await tester.tap(find.byKey(const Key('chat-stack'))); await _settle(tester); + // A hold lifts the chat for a drag; let go in place, it settles back. 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); + expect(harness.removed, isEmpty); + expect(harness.opened, isEmpty); + expect(find.byType(ChatStackColumn), findsOneWidget); await tester.tap(find.byKey(const ValueKey('chat-stack-button-add'))); await _settle(tester); expect(harness.added, 1); diff --git a/app/test/features/chat/stack/chat_stack_screen_test.dart b/app/test/features/chat/stack/chat_stack_screen_test.dart index 0e970e7a..789a19a0 100644 --- a/app/test/features/chat/stack/chat_stack_screen_test.dart +++ b/app/test/features/chat/stack/chat_stack_screen_test.dart @@ -114,31 +114,6 @@ void main() { 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 { diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 5e98e76e..ef62148c 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -85,7 +85,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) | | `clipboard=read[:label]` / `clipboard=write:` | read or write the browser's clipboard from a scratch page on the loopback origin (a secure context), then bring the page back; JSON `expect` fails the run unless the read text matches. Works for an `--insecure` page, which has no `navigator.clipboard` | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | -| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | +| `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on); JSON `press` holds the finger down that many ms first (a long press), `hold: true` leaves it down for a capture, and the next swipe moves it on from there | | `pinch=>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) | | `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab | | `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) | diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index c280a9e5..b1facc78 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -34,7 +34,9 @@ steps: open=[@WxH] wait= shot= click= waitfor= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) - swipe=>, pinch=> (with --touch true) + swipe=>, pinch=> (with --touch true; + JSON swipe: press ms held before moving, hold keeps the finger down + for the next swipe) target: