Files
pipelines/app/lib/features/chat/stack/chat_stack_fab.dart
T
alan efaa0d9fca Chat stack: groups of open chats, synced with the open-chat set
A chat dropped onto the middle of another makes a named group (asked at
once, "Group N" by default); onto a group it joins, a group dropped onto
a chat takes it in, groups merge. The top level shows each group as a
small pile with its name and count; a tap opens it in place under a
header that leads back (also the scrim, Back and Escape). In a group,
dropping a chat on the header leaves the group; a group of one
dissolves. The close button ungroups a dropped group with Undo. Rename,
Ungroup, Close all (with Undo), Move to group and Remove from group are
in the group menu and as semantic actions.

Each open-chat entry carries its group name (protocol field "group",
omitted when ungrouped; older clients ignore it), stored and pushed by
the server like the order; names are trimmed, printable, at most 80
characters. Needs a server restart to keep groups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 22:18:44 +00:00

430 lines
13 KiB
Dart

import 'package:flutter/material.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../ui/sessions/chat_awaiting.dart';
import 'chat_stack_actions.dart';
import 'chat_stack_column.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_entry.dart';
import 'chat_stack_motion.dart';
import 'chat_stack_node.dart';
import 'chat_stack_pose.dart';
/// The phone's chat stack: the open chats' avatars piled up, the chat on
/// screen on top, a floating button above the composer. A tap fans them out
/// into a column ([ChatStackColumn]); a tap outside, Back or Escape folds
/// them back. It steps aside while the on-screen keyboard is up.
class ChatStackFab extends StatefulWidget {
const ChatStackFab({
super.key,
required this.entries,
required this.onOpen,
required this.onAdd,
this.onRemove,
this.onReorder,
this.groups,
});
/// The open chats in their synced order; one is [ChatStackEntry.current].
final List<ChatStackEntry> entries;
final ValueChanged<ChatStackEntry> onOpen;
/// Add chat, given the stack's own context to anchor a picker to.
final ValueChanged<BuildContext> onAdd;
final ValueChanged<ChatStackEntry>? onRemove;
/// Puts the open chats in this order (session ids): a drag in the open
/// column, or its Move up and Move down actions.
final ValueChanged<List<String>>? onReorder;
/// Grouping the open chats; null when the host keeps no groups.
final ChatStackGroupActions? groups;
@override
State<ChatStackFab> createState() => ChatStackFabState();
}
class ChatStackFabState extends State<ChatStackFab>
with SingleTickerProviderStateMixin, WidgetsBindingObserver {
late final AnimationController _open = AnimationController(
vsync: this,
duration: chatStackOpenDuration,
reverseDuration: chatStackCloseDuration,
// Reduced motion is handled here (a short plain fade), not by the
// platform's near-instant fallback.
animationBehavior: AnimationBehavior.preserve,
)..addStatusListener(_status);
final _portal = OverlayPortalController(debugLabel: 'Chat stack');
final _slot = GlobalKey(debugLabel: 'Chat stack slot');
final _focus = FocusNode(debugLabel: 'Chat stack');
/// The group open in the column, or null on its top level.
final _group = ValueNotifier<String?>(null);
/// The pile hides the moment the column starts to move; under reduced
/// motion the two cross-fade in place instead.
late final Animation<double> _hiddenWhileOpen = _open.drive(_ShownAtRest());
late final Animation<double> _fadedWhileOpen = ReverseAnimation(_open);
ChatStackMotion? _motion;
Object? _motionKey;
Rect? _anchor;
bool _expanded = false;
bool _keyboard = false;
bool _reduced = false;
bool get expanded => _expanded;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
_keyboard = _keyboardUp();
}
/// The window's own inset: a scaffold above may already have taken it out
/// of this subtree's [MediaQuery].
bool _keyboardUp() => View.of(context).viewInsets.bottom > 0;
@override
void didChangeMetrics() {
if (!mounted) return;
final up = _keyboardUp();
// A rotation or a resize moves the slot: fold rather than point at a
// stale place.
if (_expanded) collapse(immediate: up);
if (up != _keyboard) setState(() => _keyboard = up);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_motion?.dispose();
_open.dispose();
_focus.dispose();
_group.dispose();
super.dispose();
}
void _status(AnimationStatus status) {
if (status == AnimationStatus.dismissed && !_expanded && mounted) {
_portal.hide();
setState(() {});
}
}
/// Fans the stack out into its column.
void expand() {
if (_expanded || _keyboard || widget.entries.isEmpty) return;
final box = _slot.currentContext?.findRenderObject() as RenderBox?;
final overlay =
Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?;
if (box == null || overlay == null || !box.hasSize) return;
final origin = box.localToGlobal(Offset.zero, ancestor: overlay);
_open
..duration = _reduced ? chatStackFadeDuration : chatStackOpenDuration
..reverseDuration = _reduced
? chatStackFadeDuration
: chatStackCloseDuration;
setState(() {
_anchor = origin & box.size;
_expanded = true;
});
_portal.show();
_open.forward();
}
/// Folds the column back into the stack; [immediate] skips the motion.
void collapse({bool immediate = false}) {
if (!_expanded) return;
_group.value = null;
setState(() => _expanded = false);
if (immediate) {
_open.value = 0;
_portal.hide();
} else {
_open.reverse();
}
if (FocusManager.instance.highlightMode == FocusHighlightMode.traditional) {
_focus.requestFocus();
}
}
void _choose(ChatStackEntry entry) {
collapse();
if (!entry.current) widget.onOpen(entry);
}
/// Removing folds the column, so the snack bar's Undo is in reach.
void _remove(ChatStackEntry entry) {
collapse();
widget.onRemove?.call(entry);
}
void _add() {
collapse();
widget.onAdd(context);
}
/// The groups' actions; ungrouping and closing fold the column, so the
/// snack bar's Undo is in reach.
ChatStackGroupActions? _groupActions() {
final groups = widget.groups;
if (groups == null) return null;
return ChatStackGroupActions(
join: groups.join,
leave: groups.leave,
rename: groups.rename,
ungroup: (group) {
collapse();
groups.ungroup(group);
},
closeAll: (group) {
collapse();
groups.closeAll(group);
},
);
}
/// Each top-level item's layer in the pile: a group's is its top chat's.
List<int?> _nodeDepths(List<ChatStackNode> nodes, List<int?> depths) {
final entries = widget.entries;
return [
for (final node in nodes)
node.entries
.map((entry) => depths[entries.indexOf(entry)])
.whereType<int>()
.fold<int?>(null, (a, b) => a == null || b < a ? b : a),
null,
];
}
/// Each item's layer in the pile: the chat on screen on top, then the
/// chats after it in order, wrapping; the add item is never in the pile.
List<int?> _depths() {
final entries = widget.entries;
final n = entries.length;
final current = entries.indexWhere((entry) => entry.current);
final top = current < 0 ? 0 : current;
return [
for (var i = 0; i < n; i++)
if ((i - top) % n case final depth when depth < chatStackVisibleLayers)
depth
else
null,
null,
];
}
ChatStackMotion _motionFor(List<int?> depths, bool rtl) {
final key = Object.hashAll([_reduced, rtl, ...depths]);
final motion = _motion;
if (motion != null && key == _motionKey) return motion;
motion?.dispose();
_motionKey = key;
return _motion = ChatStackMotion(
parent: _open,
depths: depths,
reduced: _reduced,
rtl: rtl,
);
}
@override
Widget build(BuildContext context) {
final entries = widget.entries;
final depths = _depths();
final nodes = chatStackNodes(entries);
final nodeDepths = _nodeDepths(nodes, depths);
final rtl = Directionality.of(context) == TextDirection.rtl;
final motion = _motionFor(nodeDepths, rtl);
final hidden = _keyboard || entries.isEmpty;
final remove = widget.onRemove;
final canRemove = remove != null && entries.length > 1;
return PopScope(
canPop: !_expanded,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
// Back leaves an open group first.
if (_group.value != null) {
_group.value = null;
} else {
collapse();
}
},
child: OverlayPortal(
controller: _portal,
overlayChildBuilder: (context) {
final anchor = _anchor;
if (anchor == null) return const SizedBox.shrink();
return ChatStackColumn(
motion: motion,
anchor: anchor,
nodes: nodes,
depths: nodeDepths,
group: _group,
interactive: _expanded,
onOpen: _choose,
onAdd: _add,
onDismiss: collapse,
onRemove: canRemove ? _remove : null,
onReorder: widget.onReorder,
groups: _groupActions(),
);
},
child: AnimatedOpacity(
opacity: hidden ? 0 : 1,
duration: Motion.of(context, Motion.quick),
child: IgnorePointer(
ignoring: hidden,
child: ExcludeFocus(
excluding: hidden,
child: ExcludeSemantics(
excluding: hidden,
child: FadeTransition(
opacity: _reduced ? _fadedWhileOpen : _hiddenWhileOpen,
child: RepaintBoundary(
key: _slot,
child: _pile(context, depths),
),
),
),
),
),
),
),
);
}
Widget _pile(BuildContext context, List<int?> depths) {
final entries = widget.entries;
final rtl = Directionality.of(context) == TextDirection.rtl;
final layers = <Widget>[];
for (var depth = chatStackVisibleLayers - 1; depth >= 0; depth--) {
final index = depths.indexOf(depth);
if (index < 0 || index >= entries.length) continue;
final pose = rtl
? chatStackLayers[depth].mirrored()
: chatStackLayers[depth];
layers.add(
ChatStackPoseTransition(
progress: kAlwaysCompleteAnimation,
from: pose,
to: pose,
child: ChatStackDisc(
child: chatStackAvatar(entries[index], cues: false),
),
),
);
}
final waiting = [
for (final entry in entries)
if (!entry.current) entry.awaitingOperator,
].fold(0, (sum, count) => sum + count);
final more = entries.length > chatStackVisibleLayers;
final shape = chatStackShape(AppDesignTokens.of(context));
return Semantics(
button: true,
expanded: false,
label: chatStackLabel(entries.length),
hint: waiting > 0 ? chatAwaitingLabel(waiting) : null,
onTap: expand,
child: ExcludeSemantics(
child: SizedBox.square(
dimension: kChatStackSlot,
child: Stack(
clipBehavior: Clip.none,
children: [
...layers,
Positioned.fill(
child: Padding(
padding: const EdgeInsets.all(
(kChatStackSlot - kChatStackDisc) / 2,
),
child: Material(
type: MaterialType.transparency,
shape: shape,
clipBehavior: Clip.antiAlias,
child: InkWell(
key: const Key('chat-stack'),
focusNode: _focus,
customBorder: shape,
onTap: expand,
),
),
),
),
if (waiting > 0)
PositionedDirectional(
top: -6,
end: -6,
child: IgnorePointer(
child: ChatAwaitingBadge(count: waiting),
),
),
if (more)
PositionedDirectional(
bottom: -2,
start: -4,
child: IgnorePointer(
child: _CountBadge(count: entries.length),
),
),
],
),
),
),
);
}
}
/// Visible only at rest: the open column takes over the pile's place the
/// moment it starts to move.
class _ShownAtRest extends Animatable<double> {
@override
double transform(double t) => t == 0 ? 1 : 0;
}
/// How many chats the pile holds, once it holds more than it draws.
class _CountBadge extends StatelessWidget {
const _CountBadge({required this.count});
final int count;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final tokens = AppDesignTokens.of(context);
final r = tokens.radius;
return DecoratedBox(
decoration: ShapeDecoration(
color: scheme.inverseSurface,
shape: r == null
? StadiumBorder(side: BorderSide(color: scheme.surface, width: 1.5))
: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(r),
side: BorderSide(color: scheme.surface, width: 1.5),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
child: Text(
'$count',
style: (theme.textTheme.labelSmall ?? const TextStyle()).copyWith(
color: scheme.onInverseSurface,
fontWeight: FontWeight.w700,
height: 1.2,
),
),
),
);
}
}