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 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 21:17:51 +00:00
parent f8e4d78466
commit fba3b924f1
20 changed files with 1573 additions and 254 deletions
+154 -189
View File
@@ -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<ChatStackEntry>? 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<ChatStackColumn> createState() => _ChatStackColumnState();
}
class _ChatStackColumnState extends State<ChatStackColumn>
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<ChatStackEntry> get _entries => widget.entries;
List<String> 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,
),
),
),
),
],
);
}
}
@@ -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<ChatStackEntry> entries;
/// Item indices in paint order, the last on top.
final List<int> order;
final double labelMax;
final ChatStackDrag drag;
/// Whether a hold lifts a chat.
final bool draggable;
final ValueChanged<ChatStackEntry> onOpen;
final VoidCallback onAdd;
final ValueChanged<ChatStackEntry> onDragStart;
final ValueChanged<LongPressMoveUpdateDetails> onDragMove;
final ValueChanged<ChatStackEntry> onDragEnd;
final ValueChanged<ChatStackEntry>? 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<double>? _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 = <CustomSemanticsAction, VoidCallback>{
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,
),
),
),
),
);
}
}
@@ -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<double>? 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<BoxShadow> chatStackShadows(ColorScheme scheme) => [
),
];
/// A short, close shadow's lifted form: deeper and softer, as a card
/// picked up off the column.
List<BoxShadow> 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<double>? 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<double>? 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
@@ -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<String, ChatStackDragItem> _items = {};
final Map<String, AnimationController> _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<String>? get order => _order;
List<String>? _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<String> 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 <String>[];
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();
}
}
@@ -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<TransformLayer> _layer = LayerHandle<TransformLayer>();
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());
}
}
@@ -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<BuildContext> onAdd;
final ValueChanged<ChatStackEntry>? 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<ChatStackFab> createState() => ChatStackFabState();
}
@@ -216,6 +221,7 @@ class ChatStackFabState extends State<ChatStackFab>
onAdd: _add,
onDismiss: collapse,
onRemove: canRemove ? _remove : null,
onReorder: widget.onReorder,
);
},
child: AnimatedOpacity(
@@ -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<LongPressMoveUpdateDetails>? 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>(
() => 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,
),
),
),
),
],
);
}
}
@@ -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<double> shown;
/// 0 idle, 1 with a chat over it.
final Animation<double> 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<double>(
begin: 1,
end: chatStackRemoveGrowth,
).chain(CurveTween(curve: Curves.easeOutBack)).animate(hover),
child: target,
);
target = SlideTransition(
position: Tween<Offset>(
begin: const Offset(0, .5),
end: Offset.zero,
).animate(curve),
child: target,
);
}
return IgnorePointer(
child: ExcludeSemantics(
child: FadeTransition(opacity: curve, child: target),
),
);
}
}