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>
This commit is contained in:
2026-12-03 22:18:44 +00:00
parent 130c1e6708
commit efaa0d9fca
30 changed files with 2399 additions and 308 deletions
@@ -0,0 +1,28 @@
/// What the chat stack's groups ask of the workspace that hosts them; each
/// change syncs with the open-chat set.
class ChatStackGroupActions {
const ChatStackGroupActions({
required this.join,
required this.leave,
required this.rename,
required this.ungroup,
required this.closeAll,
});
/// Puts [sessionIds] in [group] (making it when new); the open chats then
/// take [order].
final void Function(List<String> sessionIds, String group, List<String> order)
join;
/// Takes [sessionIds] out of their group; the open chats take [order].
final void Function(List<String> sessionIds, List<String> order) leave;
/// Renames a group (a name in use merges the two).
final void Function(String from, String to) rename;
/// Dissolves a group, its chats staying open, with Undo.
final void Function(String group) ungroup;
/// Closes every chat in a group, with Undo.
final void Function(String group) closeAll;
}
@@ -1,31 +1,41 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import 'chat_stack_actions.dart';
import 'chat_stack_close_target.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_group_dialogs.dart';
import 'chat_stack_group_ops.dart';
import 'chat_stack_group_pile.dart';
import 'chat_stack_motion.dart';
import 'chat_stack_close_target.dart';
import 'chat_stack_node.dart';
part 'chat_stack_column_groups.dart';
/// The chat stack fanned out: a scrim over the screen and the open chats in
/// a column rising from the stack's own slot, each avatar with its name in a
/// small pill beside it, and Add chat at the top.
///
/// The stack's own slot turns into a close button ([ChatStackCloseTarget]);
/// item 0 sits a pitch above it, nearest the thumb. The chats
/// keep the open-chat order (the order the server syncs), so a chat keeps
/// its place in the column from one visit to the next; the chat on screen
/// wears a ring in its colour. Add chat is last, at the top: the reachable
/// bottom slots go to the frequent action (switching), and the rarer one
/// ends the list where the operator reads "and more".
/// item 0 sits a pitch above it, nearest the thumb. The items keep the
/// open-chat order (the order the server syncs), so a chat keeps its place
/// from one visit to the next; the chat on screen wears a ring in its
/// colour. A group shows as one item, its chats piled; a tap opens it: the
/// top level fades and the group's chats rise from its pile, under a
/// header that leads back. Add chat is last, at the top: the reachable
/// bottom slots go to the frequent action (switching).
///
/// 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 close button (armed as a remove target while dragging)
/// it leaves them. Add chat
/// stays put. The same moves are semantic actions on each chat.
/// A short hold lifts an item ([ChatStackDrag]): dragged up or down it
/// reorders; dropped on the middle of another it groups them (or joins the
/// group); dropped on the close button (armed as a remove target while
/// dragging) a chat leaves the open chats and a group is ungrouped. In an
/// open group a chat dropped on the header leaves the group. Add chat stays
/// put. The same moves are semantic actions.
///
/// Nothing here rebuilds per frame: every item moves through
/// `ChatStackPoseTransition` and `ChatStackDragShift` and fades through
@@ -36,21 +46,25 @@ class ChatStackColumn extends StatefulWidget {
super.key,
required this.motion,
required this.anchor,
required this.entries,
required this.nodes,
required this.depths,
required this.interactive,
required this.onOpen,
required this.onAdd,
required this.onDismiss,
required this.group,
this.onRemove,
this.onReorder,
this.groups,
});
final ChatStackMotion motion;
/// The collapsed stack's slot in this overlay's coordinates.
final Rect anchor;
final List<ChatStackEntry> entries;
/// The top level: chats and groups in the open-chat order.
final List<ChatStackNode> nodes;
/// Each item's layer in the collapsed pile (null when it is not drawn
/// there); the add item last.
@@ -62,25 +76,34 @@ class ChatStackColumn extends StatefulWidget {
final VoidCallback onAdd;
final VoidCallback onDismiss;
/// Removes a chat from the open chats (dropped on the "×"); null when it
/// cannot (the only open chat).
/// The open group's name, or null on the top level; Back sets it null.
final ValueNotifier<String?> group;
/// Removes a chat from the open chats; 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;
/// Puts the open chats in this order (session ids); null when they cannot
/// be reordered.
final ValueChanged<List<String>>? onReorder;
/// Grouping; null when the host keeps no groups.
final ChatStackGroupActions? groups;
static const removeLabel = 'Remove from open chats';
static const moveUpLabel = 'Move up';
static const moveDownLabel = 'Move down';
static const addLabel = 'Add chat';
static const moveToGroupLabel = 'Move to group…';
static const leaveGroupLabel = 'Remove from group';
static const addLabel = ChatStackAddTail.label;
@override
State<ChatStackColumn> createState() => _ChatStackColumnState();
}
class _ChatStackColumnState extends State<ChatStackColumn>
with TickerProviderStateMixin {
with TickerProviderStateMixin, _ChatStackColumnGroups {
@override
late final ChatStackDrag _drag = ChatStackDrag(
vsync: this,
pitch: kChatStackPitch,
@@ -89,14 +112,11 @@ class _ChatStackColumnState extends State<ChatStackColumn>
/// 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 initState() {
super.initState();
_initGroups();
}
@override
void didChangeDependencies() {
@@ -107,17 +127,19 @@ class _ChatStackColumnState extends State<ChatStackColumn>
@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.
// Folding, or the items changing under the finger (another device),
// puts the dragged item back.
if (!widget.interactive ||
(_drag.dragging && !listEquals(_ids, _drag.order))) {
(_drag.dragging && !listEquals(_dragOrder(), _drag.order))) {
_drag.cancel();
}
_groupsUpdated(oldWidget);
}
@override
void dispose() {
_drag.dispose();
_disposeGroups();
super.dispose();
}
@@ -125,10 +147,7 @@ class _ChatStackColumnState extends State<ChatStackColumn>
if (mounted) setState(() {});
}
void _start(ChatStackEntry entry) {
if (_draggable) _drag.start(entry.paneId, _ids);
}
@override
void _move(LongPressMoveUpdateDetails details) {
if (!_drag.dragging) return;
final box = context.findRenderObject() as RenderBox?;
@@ -142,19 +161,20 @@ class _ChatStackColumnState extends State<ChatStackColumn>
_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() {
if (_drag.dragging) {
_drag.cancel();
} else if (widget.group.value != null) {
widget.group.value = null;
} else {
widget.onDismiss();
}
}
void _escape() => _drag.dragging ? _drag.cancel() : widget.onDismiss();
/// A tap on the scrim: out of an open group first, then folded.
void _scrim() => widget.group.value != null
? widget.group.value = null
: widget.onDismiss();
@override
Widget build(BuildContext context) {
@@ -163,29 +183,24 @@ class _ChatStackColumnState extends State<ChatStackColumn>
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 = widget.motion.count;
final open = _openGroupMotion(rtl);
final count = open == null || open.count < widget.motion.count
? widget.motion.count
: open.count;
// The stack's own slot (the close button) and the items above it.
final height = count * kChatStackPitch + kChatStackSlot;
final top = media.padding.top + 8;
final available = anchor.bottom - top;
final fits = height <= available;
final fits = height <= anchor.bottom - top;
// The column's own edge is the stack's; the labels take the rest of
// the row back to a margin at the other side.
final endInset = rtl ? anchor.left : size.width - anchor.right;
const margin = 16.0;
final width = size.width - endInset - margin;
final labelMax = width - kChatStackSlot - kChatStackLabelGap;
// Paint the pile's order while it opens: hidden layers first, the
// top of the pile last; 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 lifted = _entries.indexWhere((e) => e.paneId == _drag.lifted);
if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted)));
// The close button takes the pile's place; while a chat is dragged
// The close button takes the pile's place; while an item is dragged
// it is the remove target.
_removeCenter = anchor.center;
final close = Positioned.fromRect(
@@ -202,20 +217,12 @@ class _ChatStackColumnState extends State<ChatStackColumn>
),
),
);
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,
final layers = Stack(
clipBehavior: Clip.none,
children: [
_topLayer(labelMax, inGroup: _openGroup != null),
if (open != null) _groupLayer(open, labelMax),
],
);
return CallbackShortcuts(
bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape},
@@ -231,12 +238,12 @@ class _ChatStackColumnState extends State<ChatStackColumn>
child: ModalBarrier(
color: scheme.scrim.withValues(alpha: dark ? .5 : .32),
dismissible: true,
onDismiss: widget.onDismiss,
onDismiss: _scrim,
semanticsLabel: 'Dismiss',
),
),
),
// A dragged chat is drawn over the button (it shrinks into
// A dragged item is drawn over the button (it shrinks into
// it); otherwise the button is on top, to take its tap.
if (_drag.lifted != null) close,
PositionedDirectional(
@@ -257,7 +264,7 @@ class _ChatStackColumnState extends State<ChatStackColumn>
container: true,
explicitChildNodes: true,
label: 'Open chats',
child: items,
child: layers,
),
),
),
@@ -272,4 +279,43 @@ class _ChatStackColumnState extends State<ChatStackColumn>
},
);
}
/// The top level: chats, groups and Add chat. Behind an open group it
/// fades out and takes no input.
Widget _topLayer(double labelMax, {required bool inGroup}) {
final nodes = widget.nodes;
final depths = widget.depths;
final order = [for (var i = 0; i <= nodes.length; i++) i]
..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99));
_liftToTop(order, nodes);
final items = ChatStackColumnItems(
key: const ValueKey('chat-stack-top'),
motion: widget.motion,
nodes: nodes,
tail: const ChatStackAddTail(),
order: order,
labelMax: labelMax,
drag: _drag,
draggable: _draggable && !inGroup,
onOpen: _openNode,
onTail: widget.onAdd,
onDragStart: _startTop,
onDragMove: _move,
onDragEnd: _endTop,
actionsFor: _topActions,
);
return IgnorePointer(
ignoring: inGroup,
child: ExcludeSemantics(
excluding: inGroup,
child: FadeTransition(opacity: _topOpacity, child: items),
),
);
}
/// Paints a lifted item above the others.
void _liftToTop(List<int> order, List<ChatStackNode> nodes) {
final lifted = nodes.indexWhere((node) => node.key == _drag.lifted);
if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted)));
}
}
@@ -0,0 +1,400 @@
part of 'chat_stack_column.dart';
/// The open column's groups: opening one, dragging and dropping between
/// items and groups, and the semantic actions that do the same.
mixin _ChatStackColumnGroups
on State<ChatStackColumn>, TickerProviderStateMixin<ChatStackColumn> {
ChatStackDrag get _drag;
void _move(LongPressMoveUpdateDetails details);
/// The group being opened or open; null on the top level.
String? _openGroup;
/// The group drawn (also while it folds back into its pile).
ChatStackGroupNode? _shownGroup;
int _shownSlot = 0;
late final AnimationController _groupOpen = AnimationController(
vsync: this,
duration: chatStackOpenDuration,
reverseDuration: chatStackCloseDuration,
animationBehavior: AnimationBehavior.preserve,
)..addStatusListener(_groupStatus);
late final Animation<double> _topOpacity = ReverseAnimation(
_groupOpen.drive(CurveTween(curve: const Interval(0, .6))),
);
ChatStackMotion? _groupMotion;
Object? _groupMotionKey;
bool get _reduced => _drag.reduced;
List<ChatStackNode> get _nodes => widget.nodes;
ChatStackGroupActions? get _groups => widget.groups;
/// A hold lifts an item when there is something to do with it.
bool get _draggable =>
widget.interactive &&
((widget.onReorder != null && _nodes.length > 1) ||
widget.onRemove != null ||
(_groups != null && _nodes.length > 1));
void _initGroups() {
widget.group.addListener(_groupChanged);
// Folded and opened again: straight back into the open group.
final node = switch (widget.group.value) {
final name? => _groupNamed(name),
null => null,
};
if (node == null) {
widget.group.value = null;
return;
}
_openGroup = node.name;
_shownGroup = node;
_shownSlot = _nodes.indexOf(node) + 1;
_groupOpen.value = 1;
}
void _groupsUpdated(ChatStackColumn oldWidget) {
if (!identical(oldWidget.group, widget.group)) {
oldWidget.group.removeListener(_groupChanged);
widget.group.addListener(_groupChanged);
}
final open = _openGroup;
if (open == null) return;
final node = _groupNamed(open);
if (node != null) {
_shownGroup = node;
} else {
// The group dissolved (or left on another device): back to the top.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && widget.group.value == open) widget.group.value = null;
});
}
}
void _disposeGroups() {
widget.group.removeListener(_groupChanged);
_groupMotion?.dispose();
_groupOpen.dispose();
}
ChatStackGroupNode? _groupNamed(String name) => _nodes
.whereType<ChatStackGroupNode>()
.where((node) => node.name == name)
.firstOrNull;
void _groupChanged() {
final name = widget.group.value;
_drag.cancel();
if (name != null) {
final node = _groupNamed(name);
if (node == null) {
widget.group.value = null;
return;
}
setState(() {
_openGroup = name;
_shownGroup = node;
_shownSlot = _nodes.indexOf(node) + 1;
});
if (_reduced) {
_groupOpen.value = 1;
} else {
_groupOpen.forward();
}
} else {
setState(() => _openGroup = null);
if (_reduced) {
_groupOpen.value = 0;
} else {
_groupOpen.reverse();
}
}
}
void _groupStatus(AnimationStatus status) {
if (status == AnimationStatus.dismissed && _openGroup == null && mounted) {
setState(() => _shownGroup = null);
}
}
/// The open group's motion: its chats rise from its pile to the column.
ChatStackMotion? _openGroupMotion(bool rtl) {
final node = _shownGroup;
if (node == null) return null;
final entries = node.entries;
final current = entries.indexWhere((entry) => entry.current);
final top = current < 0 ? 0 : current;
final n = entries.length;
final depths = <int?>[
for (var i = 0; i < n; i++)
if ((i - top) % n case final depth when depth < chatStackGroupLayers)
depth
else
null,
null,
];
final key = Object.hashAll([_reduced, rtl, _shownSlot, ...depths]);
if (_groupMotion != null && key == _groupMotionKey) return _groupMotion;
_groupMotion?.dispose();
_groupMotionKey = key;
return _groupMotion = ChatStackMotion(
parent: _groupOpen,
depths: depths,
reduced: _reduced,
rtl: rtl,
originSlot: _shownSlot,
pileScale: chatStackGroupPileScale,
);
}
List<ChatStackNode> get _groupItems => [
for (final entry in _shownGroup?.entries ?? const <ChatStackEntry>[])
ChatStackChatNode(entry),
];
Widget _groupLayer(ChatStackMotion motion, double labelMax) {
final group = _shownGroup!;
final items = _groupItems;
final order = [for (var i = 0; i <= items.length; i++) i]
..sort(
// The pile's deeper (smaller) layers first, its top last.
(a, b) => motion.from[a].scale.compareTo(motion.from[b].scale),
);
final lifted = items.indexWhere((node) => node.key == _drag.lifted);
if (lifted >= 0) order.add(order.removeAt(order.indexOf(lifted)));
return IgnorePointer(
ignoring: _openGroup == null,
child: ChatStackColumnItems(
key: ValueKey('chat-stack-group-${group.name}'),
motion: motion,
nodes: items,
tail: ChatStackHeaderTail(
group,
onMenu: _groups == null ? null : (at) => _menu(group.name, at),
),
order: order,
labelMax: labelMax,
drag: _drag,
draggable: widget.interactive && _openGroup != null,
onOpen: (node) => widget.onOpen(node.entries.single),
onTail: () => widget.group.value = null,
onDragStart: _startInGroup,
onDragMove: _move,
onDragEnd: _endInGroup,
actionsFor: _inGroupActions,
tailActions: _groupActions(group.name),
),
);
}
/// The keys of the items a drag moves among, as it started.
List<String> _dragOrder() => _openGroup != null
? [for (final node in _groupItems) node.key, ChatStackHeaderTail.key]
: [for (final node in _nodes) node.key];
void _openNode(ChatStackNode node) => switch (node) {
ChatStackChatNode(:final entry) => widget.onOpen(entry),
ChatStackGroupNode(:final name) => widget.group.value = name,
};
void _startTop(ChatStackNode node) {
if (!_draggable) return;
_drag.start(
node.key,
_dragOrder(),
canDropOnto: _groups == null ? null : (_) => true,
);
}
void _endTop(ChatStackNode dragged) {
if (!_drag.dragging) return;
final nodes = _nodes;
final from = nodes.indexOf(dragged);
switch (_drag.end()) {
case ChatStackDropMove(:final index):
widget.onReorder?.call(chatStackMoved(nodes, from, index));
case ChatStackDropOnto(:final index):
_join(from, index);
case ChatStackDropRemove():
switch (dragged) {
case ChatStackChatNode(:final entry):
widget.onRemove?.call(entry);
case ChatStackGroupNode(:final name):
_groups?.ungroup(name);
}
case ChatStackDropBack():
break;
}
}
void _join(int from, int onto) {
final groups = _groups;
if (groups == null || from < 0) return;
final joined = chatStackJoined(_nodes, from, onto, _nextName);
groups.join(joined.join, joined.group, joined.order);
// A new group asks for its name at once; the default stands if not.
if (joined.created) _rename(joined.group, title: 'Name the group');
}
String _nextName() {
final used = {
for (final node in _nodes)
if (node is ChatStackGroupNode) node.name,
};
for (var n = 1; ; n++) {
if (!used.contains('Group $n')) return 'Group $n';
}
}
void _startInGroup(ChatStackNode node) {
final order = _dragOrder();
_drag.start(
node.key,
order,
canDropOnto: _groups == null ? null : (i) => i == order.length - 1,
lastSlot: order.length - 2,
);
}
void _endInGroup(ChatStackNode dragged) {
if (!_drag.dragging) return;
final group = _shownGroup;
if (group == null) return;
final items = _groupItems;
final from = items.indexWhere((node) => node.key == dragged.key);
final id = dragged.entries.single.sessionId;
switch (_drag.end()) {
case ChatStackDropMove(:final index):
_regroup(group.name, chatStackMoved(items, from, index));
case ChatStackDropOnto():
_leave(group.name, id);
case ChatStackDropRemove():
widget.onRemove?.call(dragged.entries.single);
case ChatStackDropBack():
break;
}
}
void _regroup(String group, List<String> groupOrder) =>
widget.onReorder?.call(chatStackRegrouped(_nodes, group, groupOrder));
void _leave(String group, String sessionId) =>
_groups?.leave([sessionId], chatStackLeft(_nodes, group, sessionId));
Future<void> _rename(String group, {String title = 'Rename group'}) async {
final name = await showChatStackRenameDialog(
context,
current: group,
title: title,
);
if (!mounted || name == null || name == group) return;
_groups?.rename(group, name);
if (widget.group.value == group) widget.group.value = name;
}
Future<void> _menu(String group, Rect at) async {
final action = await showChatStackGroupMenu(context, anchor: at);
if (mounted && action != null) _groupAction(group, action);
}
void _groupAction(String group, ChatStackGroupAction action) {
final groups = _groups;
if (groups == null) return;
switch (action) {
case ChatStackGroupAction.rename:
_rename(group);
case ChatStackGroupAction.ungroup:
widget.group.value = null;
groups.ungroup(group);
case ChatStackGroupAction.closeAll:
widget.group.value = null;
groups.closeAll(group);
}
}
Map<CustomSemanticsAction, VoidCallback> _groupActions(String group) => {
if (_groups != null)
for (final action in ChatStackGroupAction.values)
CustomSemanticsAction(label: action.label): () =>
_groupAction(group, action),
};
/// Up is toward the top of the column: a later place in the order.
Map<CustomSemanticsAction, VoidCallback> _moves(
int index,
int count,
void Function(int to) move,
) => {
if (widget.onReorder != null && index < count - 1)
const CustomSemanticsAction(label: ChatStackColumn.moveUpLabel): () =>
move(index + 1),
if (widget.onReorder != null && index > 0)
const CustomSemanticsAction(label: ChatStackColumn.moveDownLabel): () =>
move(index - 1),
};
Map<CustomSemanticsAction, VoidCallback> _topActions(
ChatStackNode node,
int index,
) {
final nodes = _nodes;
final remove = widget.onRemove;
final groupNodes = nodes.whereType<ChatStackGroupNode>().toList();
return {
..._moves(
index,
nodes.length,
(to) => widget.onReorder?.call(chatStackMoved(nodes, index, to)),
),
if (node case ChatStackChatNode(:final entry)) ...{
if (_groups != null && groupNodes.isNotEmpty)
const CustomSemanticsAction(
label: ChatStackColumn.moveToGroupLabel,
): () =>
_moveToGroup(index, groupNodes),
if (remove != null)
const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () =>
remove(entry),
},
if (node case ChatStackGroupNode(:final name)) ..._groupActions(name),
};
}
Future<void> _moveToGroup(int index, List<ChatStackGroupNode> groups) async {
final name = await showChatStackMoveToGroupDialog(
context,
groups: [for (final group in groups) group.name],
);
if (!mounted || name == null) return;
final onto = _nodes.indexWhere(
(node) => node is ChatStackGroupNode && node.name == name,
);
if (onto >= 0 && index < _nodes.length) _join(index, onto);
}
Map<CustomSemanticsAction, VoidCallback> _inGroupActions(
ChatStackNode node,
int index,
) {
final group = _shownGroup;
if (group == null) return const {};
final items = _groupItems;
final entry = node.entries.single;
final remove = widget.onRemove;
return {
..._moves(
index,
items.length,
(to) => _regroup(group.name, chatStackMoved(items, index, to)),
),
if (_groups != null)
const CustomSemanticsAction(
label: ChatStackColumn.leaveGroupLabel,
): () =>
_leave(group.name, entry.sessionId),
if (remove != null)
const CustomSemanticsAction(label: ChatStackColumn.removeLabel): () =>
remove(entry),
};
}
}
@@ -2,53 +2,81 @@ 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_group_pile.dart';
import 'chat_stack_handles.dart';
import 'chat_stack_motion.dart';
import 'chat_stack_node.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].
/// The item at the top of a column: Add chat on the top level, the group's
/// header (back to the top level) in an open group.
sealed class ChatStackTail {
const ChatStackTail();
}
class ChatStackAddTail extends ChatStackTail {
const ChatStackAddTail();
static const label = 'Add chat';
}
class ChatStackHeaderTail extends ChatStackTail {
const ChatStackHeaderTail(this.group, {this.onMenu});
static const key = 'tail:header';
final ChatStackGroupNode group;
/// Opens the group's menu, anchored to the given global rect.
final ValueChanged<Rect>? onMenu;
}
/// The open column's items (chats and groups) and its tail, 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.nodes,
required this.tail,
required this.order,
required this.labelMax,
required this.drag,
required this.draggable,
required this.onOpen,
required this.onAdd,
required this.onTail,
required this.onDragStart,
required this.onDragMove,
required this.onDragEnd,
this.onRemove,
this.onReorder,
required this.actionsFor,
this.tailActions,
});
final ChatStackMotion motion;
final List<ChatStackEntry> entries;
final List<ChatStackNode> nodes;
final ChatStackTail tail;
/// Item indices in paint order, the last on top.
/// Item indices in paint order, the last on top; [nodes.length] is the
/// tail.
final List<int> order;
final double labelMax;
final ChatStackDrag drag;
/// Whether a hold lifts a chat.
/// Whether a hold lifts an item.
final bool draggable;
final ValueChanged<ChatStackEntry> onOpen;
final VoidCallback onAdd;
final ValueChanged<ChatStackEntry> onDragStart;
final ValueChanged<ChatStackNode> onOpen;
final VoidCallback onTail;
final ValueChanged<ChatStackNode> onDragStart;
final ValueChanged<LongPressMoveUpdateDetails> onDragMove;
final ValueChanged<ChatStackEntry> onDragEnd;
final ValueChanged<ChatStackEntry>? onRemove;
final void Function(ChatStackEntry entry, int index)? onReorder;
final ValueChanged<ChatStackNode> onDragEnd;
final Map<CustomSemanticsAction, VoidCallback> Function(
ChatStackNode node,
int index,
)
actionsFor;
final Map<CustomSemanticsAction, VoidCallback>? tailActions;
@override
Widget build(BuildContext context) => Stack(
@@ -58,34 +86,54 @@ class ChatStackColumnItems extends StatelessWidget {
],
);
ChatStackEntry? _entry(int i) => i < entries.length ? entries[i] : null;
ChatStackNode? _node(int i) => i < nodes.length ? nodes[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),
String _keyOf(ChatStackNode? node) => switch (node) {
ChatStackChatNode(:final entry) => entry.paneId,
ChatStackGroupNode(:final name) => 'group-$name',
null => tail is ChatStackAddTail ? 'add' : 'header',
};
/// The drag key [i] paints with; Add chat never moves.
String? _dragKey(int i) {
final node = _node(i);
if (node != null) return node.key;
return tail is ChatStackHeaderTail ? ChatStackHeaderTail.key : null;
}
Widget _handle(ChatStackNode? node, Widget child) => ChatStackDragHandle(
onStart: node == null || !draggable ? null : () => onDragStart(node),
onMove: onDragMove,
onEnd: entry == null ? null : () => onDragEnd(entry),
onEnd: node == null ? null : () => onDragEnd(node),
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,
);
Widget _shift(int i, Widget child, {bool scales = true}) {
final key = _dragKey(i);
return key == null
? child
: ChatStackDragShift(
item: drag.item(key),
scales: scales,
child: child,
);
}
Animation<double>? _lift(ChatStackEntry? entry) =>
entry != null && entry.paneId == drag.lifted ? drag.lift : null;
/// The lifted look while dragged; the drop-target ring while a dragged
/// item would land on it.
(Animation<double>?, Color?) _lift(BuildContext context, String? key) {
if (key == null) return (null, null);
if (key == drag.lifted) return (drag.lift, null);
if (!drag.dragging) return (null, null);
return (drag.glow(key), Theme.of(context).colorScheme.primary);
}
Widget _item(BuildContext context, int i) {
final entry = _entry(i);
final node = _node(i);
final name = _keyOf(node);
return PositionedDirectional(
key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'),
key: ValueKey('chat-stack-item-$name'),
end: 0,
bottom: 0,
// The transforms are outermost: the boxes under them sit at the
@@ -96,14 +144,16 @@ class ChatStackColumnItems extends StatelessWidget {
from: motion.from[i],
to: motion.target[i],
child: _shift(
entry,
i,
FadeTransition(
opacity: motion.fade[i],
child: KeyedSubtree(
key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'),
child: entry == null
? _addButton(context)
: _chatButton(context, entry, i),
key: ValueKey('chat-stack-button-$name'),
child: switch (node) {
ChatStackChatNode() => _chatButton(context, node, i),
ChatStackGroupNode() => _groupButton(context, node, i),
null => _tailButton(context),
},
),
),
),
@@ -112,9 +162,40 @@ class ChatStackColumnItems extends StatelessWidget {
}
Widget _label(BuildContext context, int i) {
final entry = _entry(i);
final node = _node(i);
final (lift, ring) = _lift(context, _dragKey(i));
final tail = this.tail;
final Widget label = switch (node) {
ChatStackChatNode(:final entry) => ChatStackLabel(
text: entry.title,
color: entry.color(context),
emphasized: entry.current,
lift: lift,
liftRing: ring,
),
ChatStackGroupNode(:final name, :final entries) => ChatStackLabel(
text: name,
detail: '${entries.length}',
emphasized: node.current,
lift: lift,
liftRing: ring,
),
null => switch (tail) {
ChatStackAddTail() => const ChatStackLabel(
text: ChatStackAddTail.label,
),
ChatStackHeaderTail(:final group, :final onMenu) => ChatStackLabel(
text: group.name,
detail: '${group.entries.length}',
emphasized: true,
lift: lift,
liftRing: ring,
trailing: onMenu == null ? null : _MenuButton(onMenu: onMenu),
),
},
};
return PositionedDirectional(
key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'),
key: ValueKey('chat-stack-label-${_keyOf(node)}'),
end: kChatStackSlot + kChatStackLabelGap,
bottom: 0,
height: kChatStackSlot,
@@ -125,7 +206,7 @@ class ChatStackColumnItems extends StatelessWidget {
// The pill moves with its avatar but keeps its size, so the gap
// between them stays even.
child: _shift(
entry,
i,
scales: false,
ExcludeSemantics(
child: FadeTransition(
@@ -136,15 +217,10 @@ class ChatStackColumnItems extends StatelessWidget {
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: labelMax),
child: _handle(
entry,
node,
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),
),
onTap: node == null ? onTail : () => onOpen(node),
child: label,
),
),
),
@@ -156,41 +232,27 @@ class ChatStackColumnItems extends StatelessWidget {
);
}
Widget _chatButton(BuildContext context, ChatStackEntry entry, int index) {
final remove = onRemove;
final reorder = onReorder;
final last = entries.length - 1;
Widget _chatButton(BuildContext context, ChatStackChatNode node, int i) {
final entry = node.entry;
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,
final (lift, liftRing) = _lift(context, node.key);
return _semantics(
node,
i,
label: entry.title,
selected: entry.current,
hint: entry.current ? 'Open now' : null,
onTap: () => onOpen(entry),
customSemanticsActions: actions.isEmpty ? null : actions,
child: _handle(
entry,
node,
ChatStackTappable(
autofocus: entry.current,
onTap: () => onOpen(entry),
onTap: () => onOpen(node),
child: ChatStackDisc(
ring: ring,
lift: _lift(entry),
lift: lift,
liftRing: liftRing,
child: chatStackAvatar(entry),
),
),
@@ -198,20 +260,75 @@ class ChatStackColumnItems extends StatelessWidget {
);
}
Widget _addButton(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final tokens = AppDesignTokens.of(context);
Widget _groupButton(BuildContext context, ChatStackGroupNode node, int i) {
final (lift, liftRing) = _lift(context, node.key);
return _semantics(
node,
i,
label: '${node.name}, group of ${node.entries.length}',
selected: node.current,
hint: 'Open group',
child: _handle(
node,
ChatStackTappable(
onTap: () => onOpen(node),
child: ChatStackGroupPile(
entries: node.entries,
glow: lift,
ring: liftRing,
),
),
),
);
}
Widget _semantics(
ChatStackNode node,
int i, {
required String label,
required bool selected,
required Widget child,
String? hint,
}) {
final actions = actionsFor(node, i);
return Semantics(
container: true,
button: true,
label: ChatStackColumn.addLabel,
onTap: onAdd,
selected: selected,
label: label,
hint: hint,
onTap: () => onOpen(node),
customSemanticsActions: actions.isEmpty ? null : actions,
child: child,
);
}
Widget _tailButton(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final tokens = AppDesignTokens.of(context);
final tail = this.tail;
final header = tail is ChatStackHeaderTail;
final (lift, ring) = _lift(context, _dragKey(nodes.length));
final actions = tailActions;
return Semantics(
container: true,
button: true,
label: switch (tail) {
ChatStackAddTail() => ChatStackAddTail.label,
ChatStackHeaderTail(:final group) => '${group.name}, back to all chats',
},
onTap: onTail,
customSemanticsActions: actions == null || actions.isEmpty
? null
: actions,
child: ChatStackTappable(
onTap: onAdd,
onTap: onTail,
child: ChatStackDisc(
lift: lift,
liftRing: ring,
child: DecoratedBox(
decoration: ShapeDecoration(
color: tokens.flat ? null : scheme.primaryContainer,
color: tokens.flat || header ? null : scheme.primaryContainer,
shape: chatStackShape(tokens).copyWith(
side: tokens.flat
? BorderSide(color: scheme.primary.withValues(alpha: .55))
@@ -219,8 +336,10 @@ class ChatStackColumnItems extends StatelessWidget {
),
),
child: Icon(
Icons.add,
color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer,
header ? Icons.arrow_back : Icons.add,
color: tokens.flat || header
? scheme.primary
: scheme.onPrimaryContainer,
),
),
),
@@ -228,3 +347,25 @@ class ChatStackColumnItems extends StatelessWidget {
);
}
}
/// The group header's menu button, inside its pill.
class _MenuButton extends StatelessWidget {
const _MenuButton({required this.onMenu});
final ValueChanged<Rect> onMenu;
@override
Widget build(BuildContext context) => SizedBox.square(
dimension: 28,
child: IconButton(
key: const Key('chat-stack-group-menu'),
tooltip: 'Group actions',
padding: EdgeInsets.zero,
iconSize: 18,
onPressed: () {
final box = context.findRenderObject() as RenderBox;
onMenu(box.localToGlobal(Offset.zero) & box.size);
},
icon: const Icon(Icons.more_horiz),
),
);
}
@@ -22,7 +22,13 @@ 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, this.lift});
const ChatStackDisc({
super.key,
required this.child,
this.ring,
this.lift,
this.liftRing,
});
final Widget child;
@@ -33,6 +39,9 @@ class ChatStackDisc extends StatelessWidget {
/// design a frame in the primary colour.
final Animation<double>? lift;
/// A drop target's ring colour, worn as [lift] runs.
final Color? liftRing;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
@@ -59,7 +68,7 @@ class ChatStackDisc extends StatelessWidget {
child: chatStackLifted(
lift,
rest,
chatStackRaised(rest, tokens, scheme),
chatStackRaised(rest, tokens, scheme, ring: liftRing),
child: SizedBox.square(
dimension: kChatStackDisc,
child: Center(
@@ -117,17 +126,24 @@ List<BoxShadow> chatStackLiftShadows(ColorScheme scheme) => [
];
/// [rest] as a dragged item wears it: the lifted shadow, or under a flat
/// design (which casts none) a frame in the primary colour.
/// design (which casts none) a frame in the primary colour. With [ring] (a
/// drop target) every design gets a ring in that colour.
ShapeDecoration chatStackRaised(
ShapeDecoration rest,
AppDesignTokens tokens,
ColorScheme scheme,
) {
ColorScheme scheme, {
Color? ring,
}) {
final shape = rest.shape;
final side = ring != null
? BorderSide(color: ring, width: 2)
: tokens.flat
? BorderSide(color: scheme.primary, width: 1.5)
: null;
return ShapeDecoration(
color: rest.color,
shape: tokens.flat && shape is OutlinedBorder
? shape.copyWith(side: BorderSide(color: scheme.primary, width: 1.5))
shape: side != null && shape is OutlinedBorder
? shape.copyWith(side: side)
: shape,
shadows: tokens.flat ? null : chatStackLiftShadows(scheme),
);
@@ -156,9 +172,21 @@ class ChatStackLabel extends StatelessWidget {
this.color,
this.emphasized = false,
this.lift,
this.liftRing,
this.detail,
this.trailing,
});
final String text;
/// A muted note after the text (a group's chat count).
final String? detail;
/// A small control at the end (the group header's menu).
final Widget? trailing;
/// A drop target's ring colour, worn as [lift] runs.
final Color? liftRing;
final Color? color;
final bool emphasized;
@@ -188,15 +216,42 @@ class ChatStackLabel extends StatelessWidget {
return chatStackLifted(
lift,
rest,
chatStackRaised(rest, tokens, scheme),
chatStackRaised(rest, tokens, scheme, ring: liftRing),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
style: style,
padding: EdgeInsetsDirectional.only(
start: 12,
end: trailing == null ? 12 : 2,
top: 6,
bottom: 6,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
style: style,
),
),
if (detail case final detail?) ...[
const SizedBox(width: 6),
Text(
detail,
maxLines: 1,
style: style.copyWith(
color: scheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
if (trailing case final trailing?) ...[
const SizedBox(width: 2),
trailing,
],
],
),
),
);
+119 -110
View File
@@ -4,67 +4,15 @@ 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);
import 'chat_stack_drop_target.dart';
/// The lifted avatar's scale.
const double chatStackLiftScale = 1.1;
part 'chat_stack_drag_types.dart';
/// 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.
/// One drag in the open column: which item is lifted, the slot it would
/// drop into or the item it would drop onto, 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 {
@@ -93,23 +41,26 @@ class ChatStackDrag extends ChangeNotifier {
late final AnimationController lift;
late final AnimationController settle;
/// The remove target's entrance, and its highlight while a chat is over
/// it.
/// The remove target arming, and its highlight while the item is over it.
late final AnimationController removeShown;
late final AnimationController hover;
final Map<String, ChatStackDragItem> _items = {};
final Map<String, AnimationController> _shifts = {};
final Map<String, AnimationController> _glows = {};
/// The chat being dragged or settling; it paints above the others.
/// The item 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.
/// The items' order when the drag started; null when none is dragged.
List<String>? get order => _order;
List<String>? _order;
int _from = 0;
int? _slot;
int? _onto;
bool Function(int index)? _canDropOnto;
int? _lastSlot;
bool _over = false;
Offset _pointer = Offset.zero;
Offset _residual = Offset.zero;
@@ -117,24 +68,47 @@ class ChatStackDrag extends ChangeNotifier {
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);
/// The item the dragged one would drop onto, if any.
String? get ontoKey => _onto == null ? null : _order?[_onto!];
/// Where [key]'s item is painted; created on first use.
ChatStackDragItem item(String key) =>
_items.putIfAbsent(key, ChatStackDragItem.new);
/// 0 at rest, 1 while the dragged item is over [key]'s (to drop onto it).
Animation<double> glow(String key) => _glows.putIfAbsent(key, () {
final glow = AnimationController(
vsync: _vsync,
duration: chatStackHoverDuration,
);
glow.addListener(() => _paint(key));
return glow;
});
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);
/// Lifts [key] out of [order] (the items, without Add chat). A drop on the
/// middle of an item [canDropOnto] accepts lands on it; the gap never
/// goes past [lastSlot] (an item after it is a target only).
void start(
String key,
List<String> order, {
bool Function(int index)? canDropOnto,
int? lastSlot,
}) {
final from = order.indexOf(key);
if (from < 0) return;
if (_lifted != null) _finishSettle();
_order = List.of(order);
_from = from;
_slot = from;
_onto = null;
_canDropOnto = canDropOnto;
_lastSlot = lastSlot;
_over = false;
_pointer = Offset.zero;
_residual = Offset.zero;
_lifted = id;
_lifted = key;
HapticFeedback.mediumImpact();
if (reduced) {
lift.value = 1;
@@ -156,18 +130,31 @@ class ChatStackDrag extends ChangeNotifier {
if (overRemove != _over) {
_over = overRemove;
if (overRemove) HapticFeedback.selectionClick();
if (reduced) {
hover.value = overRemove ? 1 : 0;
} else {
overRemove ? hover.forward() : hover.reverse();
}
_run(hover, overRemove ? 1 : 0);
}
// Far to the side of the column, or over the remove target, there is no
// slot: the gap closes and a drop there puts the item back.
int? slot;
int? onto;
if (!overRemove && fromOrigin.dx.abs() <= pitch * 1.5) {
final target = chatStackDropTarget(
position: _from - fromOrigin.dy / pitch,
from: _from,
count: order.length,
slot: _slot ?? _from,
canDropOnto: _canDropOnto,
lastSlot: _lastSlot,
);
slot = target.slot;
onto = target.onto;
}
if (onto != _onto) {
final before = _onto;
_onto = onto;
if (onto != null) HapticFeedback.selectionClick();
if (before != null) _run(glow(order[before]) as AnimationController, 0);
if (onto != null) _run(glow(order[onto]) as AnimationController, 1);
}
// 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;
@@ -182,33 +169,35 @@ class ChatStackDrag extends ChangeNotifier {
final order = _order;
if (order == null) return const ChatStackDropBack();
final slot = _slot;
final onto = _onto;
final ChatStackDrop drop = _over
? const ChatStackDropRemove()
: onto != null
? ChatStackDropOnto(onto)
: slot != null && slot != _from
? ChatStackDropMove(slot)
: const ChatStackDropBack();
_order = null;
_slot = 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;
// dragged item glides from the finger into its new slot.
_residual = _pointer + Offset(0, (index - _from) * pitch);
_shiftNeighbours(animate: false);
case ChatStackDropRemove():
_slot = null;
case ChatStackDropRemove() || ChatStackDropOnto():
// It joins the target (or leaves): no glide back.
_residual = Offset.zero;
_shiftNeighbours(animate: false);
case ChatStackDropBack():
_slot = null;
_residual = _pointer;
_shiftNeighbours(animate: !reduced);
}
_release();
_release(clearGlowAtOnce: drop is ChatStackDropOnto);
return drop;
}
/// Puts the chat back where it was (Escape, a cancelled pointer, the
/// Puts the item back where it was (Escape, a cancelled pointer, the
/// column folding).
void cancel() {
if (_order == null) return;
@@ -219,10 +208,14 @@ class ChatStackDrag extends ChangeNotifier {
_release();
}
void _release() {
void _release({bool clearGlowAtOnce = false}) {
_pointer = Offset.zero;
if (_over) HapticFeedback.selectionClick();
_over = false;
_onto = null;
for (final glow in _glows.values) {
clearGlowAtOnce ? glow.value = 0 : _run(glow, 0);
}
if (reduced) {
hover.value = 0;
removeShown.value = 0;
@@ -237,51 +230,73 @@ class ChatStackDrag extends ChangeNotifier {
settle.forward(from: 0);
}
void _run(AnimationController controller, double target) {
if (reduced) {
controller.value = target;
} else {
controller.animateTo(target, curve: _curve);
}
}
void _settled(AnimationStatus status) {
if (status == AnimationStatus.completed) _finishSettle();
}
void _finishSettle() {
settle.stop();
final id = _lifted;
final key = _lifted;
_residual = Offset.zero;
if (id != null) item(id)._set(Offset.zero, 1);
if (key != null) item(key)._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 key = _lifted;
if (key == null) return;
// Over the remove target the item 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);
item(key)._set(offset, scale);
}
/// Paints a neighbour: slid by its shift, grown by its glow.
void _paint(String key) {
if (key == _lifted) return;
final shift = _shifts[key]?.value ?? 0;
final glow = _glows[key]?.value ?? 0;
item(
key,
)._set(Offset(0, shift * pitch), lerpDouble(1, chatStackOntoScale, glow)!);
}
/// 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 keys = {...order, ..._shifts.keys};
final slot = _slot;
for (final id in ids) {
if (id == _lifted && _order != null) continue;
final i = order.indexOf(id);
for (final key in keys) {
if (key == _lifted && _order != null) continue;
final i = order.indexOf(key);
var target = 0.0;
if (slot != null && i >= 0) {
// Down (toward the thumb) when the lifted chat goes above it, up
// Down (toward the thumb) when the lifted item 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));
final shift = _shifts.putIfAbsent(key, () {
final shift = AnimationController.unbounded(vsync: _vsync);
shift.addListener(() => _paint(key));
return shift;
});
if (shift.value == target) continue;
if (animate) {
shift.animateTo(
@@ -297,20 +312,14 @@ class ChatStackDrag extends ChangeNotifier {
}
}
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 controller in [..._shifts.values, ..._glows.values]) {
controller.dispose();
}
for (final item in _items.values) {
item.dispose();
@@ -0,0 +1,68 @@
part of 'chat_stack_drag.dart';
/// How long a press is held before a chat lifts for a drag: long enough
/// that a tap still opens it, 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;
/// The scale of an item a dragged one would drop onto (to group).
const double chatStackOntoScale = 1.14;
/// How long the neighbours take to slide aside, and the lifted item 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 arm and to light up, and a drop
/// target to grow.
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
/// another 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 item settles back into its own slot.
class ChatStackDropBack extends ChatStackDrop {
const ChatStackDropBack();
}
/// The item moves to [index] among the items.
class ChatStackDropMove extends ChatStackDrop {
const ChatStackDropMove(this.index);
final int index;
}
/// The item drops onto the item at [index] (to group the two).
class ChatStackDropOnto extends ChatStackDrop {
const ChatStackDropOnto(this.index);
final int index;
}
/// The item drops on the remove target.
class ChatStackDropRemove extends ChatStackDrop {
const ChatStackDropRemove();
}
@@ -0,0 +1,50 @@
/// Where a dragged item of the open column would land.
///
/// [position] is the dragged item's place in slots (its start index, plus
/// the slots it moved up; fractional), [from] its start index, [count] the
/// items, and [slot] the gap it opened so far (never past [lastSlot]). The
/// others are drawn around that gap. The middle half of each one
/// [canDropOnto] accepts is a drop on it; its outer quarters (or all of one
/// that accepts none) move the gap before or after it. The
/// gap itself holds while the item is within half a slot of it, so the
/// answer is stable: an item that slides aside never lands back under the
/// finger.
({int slot, int? onto}) chatStackDropTarget({
required double position,
required int from,
required int count,
required int slot,
bool Function(int index)? canDropOnto,
int? lastSlot,
}) {
final last = lastSlot ?? count - 1;
if (count < 2 || (position - slot).abs() <= .5) {
return (slot: slot, onto: null);
}
// The neighbour drawn nearest the position: its index and drawn place.
var nearest = -1;
var drawn = 0;
var distance = double.infinity;
for (var i = 0; i < count; i++) {
if (i == from) continue;
final rank = i < from ? i : i - 1;
final place = rank < slot ? rank : rank + 1;
final d = (position - place).abs();
if (d < distance) {
distance = d;
nearest = i;
drawn = place;
}
}
if (distance <= .25 && (canDropOnto?.call(nearest) ?? false)) {
return (slot: slot, onto: nearest);
}
final int next;
if (position < drawn) {
// Before it (below, toward the thumb).
next = drawn > slot ? drawn - 1 : drawn;
} else {
next = drawn < slot ? drawn + 1 : drawn;
}
return (slot: next.clamp(0, last), onto: null);
}
@@ -15,6 +15,7 @@ class ChatStackEntry {
required this.paneId,
required this.session,
this.current = false,
this.group,
});
final String paneId;
@@ -23,6 +24,9 @@ class ChatStackEntry {
/// Whether this is the chat on screen.
final bool current;
/// The chat stack group it is in, or null.
final String? group;
String get sessionId => '${session['id'] ?? ''}';
String get title => chatSessionTitle(session);
@@ -3,10 +3,12 @@ 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
@@ -21,6 +23,7 @@ class ChatStackFab extends StatefulWidget {
required this.onAdd,
this.onRemove,
this.onReorder,
this.groups,
});
/// The open chats in their synced order; one is [ChatStackEntry.current].
@@ -31,9 +34,12 @@ 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;
/// 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();
@@ -53,6 +59,9 @@ class ChatStackFabState extends State<ChatStackFab>
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());
@@ -99,6 +108,7 @@ class ChatStackFabState extends State<ChatStackFab>
_motion?.dispose();
_open.dispose();
_focus.dispose();
_group.dispose();
super.dispose();
}
@@ -133,6 +143,7 @@ class ChatStackFabState extends State<ChatStackFab>
/// 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;
@@ -161,6 +172,39 @@ class ChatStackFabState extends State<ChatStackFab>
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() {
@@ -196,15 +240,23 @@ class ChatStackFabState extends State<ChatStackFab>
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(depths, 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) collapse();
if (didPop) return;
// Back leaves an open group first.
if (_group.value != null) {
_group.value = null;
} else {
collapse();
}
},
child: OverlayPortal(
controller: _portal,
@@ -214,14 +266,16 @@ class ChatStackFabState extends State<ChatStackFab>
return ChatStackColumn(
motion: motion,
anchor: anchor,
entries: entries,
depths: depths,
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(
@@ -0,0 +1,109 @@
import 'package:flutter/material.dart';
import 'chat_stack_groups.dart';
/// The group actions a group offers in its menu and as semantic actions.
enum ChatStackGroupAction {
rename('Rename group'),
ungroup('Ungroup'),
closeAll('Close all chats in group');
const ChatStackGroupAction(this.label);
final String label;
}
/// Asks for a group name, starting from [current] (selected, so typing
/// replaces it); null when cancelled or left empty.
Future<String?> showChatStackRenameDialog(
BuildContext context, {
required String current,
String title = 'Rename group',
}) => showDialog<String>(
context: context,
builder: (context) => _RenameDialog(current: current, title: title),
);
class _RenameDialog extends StatefulWidget {
const _RenameDialog({required this.current, required this.title});
final String current;
final String title;
@override
State<_RenameDialog> createState() => _RenameDialogState();
}
class _RenameDialogState extends State<_RenameDialog> {
late final TextEditingController _name =
TextEditingController(text: widget.current)
..selection = TextSelection(
baseOffset: 0,
extentOffset: widget.current.length,
);
@override
void dispose() {
_name.dispose();
super.dispose();
}
void _save() => Navigator.of(context).pop(chatStackGroupName(_name.text));
@override
Widget build(BuildContext context) => AlertDialog(
title: Text(widget.title),
content: TextField(
key: const Key('chat-stack-group-name'),
controller: _name,
autofocus: true,
maxLength: chatStackGroupNameLimit,
decoration: const InputDecoration(labelText: 'Group name'),
textInputAction: TextInputAction.done,
onSubmitted: (_) => _save(),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
FilledButton(onPressed: _save, child: const Text('Save')),
],
);
}
/// Asks which of [groups] a chat moves to; null when cancelled.
Future<String?> showChatStackMoveToGroupDialog(
BuildContext context, {
required List<String> groups,
}) => showDialog<String>(
context: context,
builder: (context) => SimpleDialog(
title: const Text('Move to group'),
children: [
for (final group in groups)
SimpleDialogOption(
onPressed: () => Navigator.of(context).pop(group),
child: Text(group),
),
],
),
);
/// The group's menu (Rename, Ungroup, Close all) at [anchor] (global).
Future<ChatStackGroupAction?> showChatStackGroupMenu(
BuildContext context, {
required Rect anchor,
}) {
final overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
final local = Rect.fromPoints(
overlay.globalToLocal(anchor.topLeft),
overlay.globalToLocal(anchor.bottomRight),
);
return showMenu<ChatStackGroupAction>(
context: context,
position: RelativeRect.fromRect(local, Offset.zero & overlay.size),
items: [
for (final action in ChatStackGroupAction.values)
PopupMenuItem(value: action, child: Text(action.label)),
],
);
}
@@ -0,0 +1,104 @@
import 'chat_stack_entry.dart';
import 'chat_stack_node.dart';
/// The open-chat order after the node at [from] moves to [to].
List<String> chatStackMoved(List<ChatStackNode> nodes, int from, int to) {
final next = List.of(nodes);
next.insert(to.clamp(0, nodes.length - 1), next.removeAt(from));
return chatStackOrder(next);
}
/// What dropping one node onto another does: [join] chats go into [group]
/// (a new group when [created]), and the open chats take [order], the
/// group's chats together where the target was.
typedef ChatStackJoin = ({
List<String> join,
String group,
bool created,
List<String> order,
});
/// Dropping the node at [from] onto the one at [onto]:
/// - a chat onto a chat makes a group of the two ([newName]), the target
/// first;
/// - a chat onto a group joins it, last;
/// - a group onto a chat takes the chat in, last;
/// - a group onto a group merges into the target.
ChatStackJoin chatStackJoined(
List<ChatStackNode> nodes,
int from,
int onto,
String Function() newName,
) {
final dragged = nodes[from];
final target = nodes[onto];
final String group;
final bool created;
final List<ChatStackEntry> joining;
final ChatStackNode host;
switch ((dragged, target)) {
case (ChatStackChatNode(), ChatStackChatNode()):
group = newName();
created = true;
joining = [...target.entries, ...dragged.entries];
host = target;
case (_, ChatStackGroupNode(:final name)):
group = name;
created = false;
joining = dragged.entries;
host = target;
case (ChatStackGroupNode(:final name), ChatStackChatNode()):
group = name;
created = false;
joining = target.entries;
host = dragged;
}
final members = <ChatStackEntry>[
...host.entries,
for (final entry in [...dragged.entries, ...target.entries])
if (!host.entries.contains(entry)) entry,
];
// The merged group stands where its host stood.
final order = <String>[
for (final node in nodes)
if (identical(node, host))
...members.map((entry) => entry.sessionId)
else if (!identical(node, dragged) && !identical(node, target))
...node.entries.map((entry) => entry.sessionId),
];
return (
join: [for (final entry in joining) entry.sessionId],
group: group,
created: created,
order: order,
);
}
/// The open-chat order with [group]'s chats in [groupOrder] (session ids).
List<String> chatStackRegrouped(
List<ChatStackNode> nodes,
String group,
List<String> groupOrder,
) => [
for (final node in nodes)
if (node is ChatStackGroupNode && node.name == group)
...groupOrder
else
...node.entries.map((entry) => entry.sessionId),
];
/// The open-chat order with [sessionId] taken out of [group] and placed
/// right after it (on the top level, beside the group it left).
List<String> chatStackLeft(
List<ChatStackNode> nodes,
String group,
String sessionId,
) => [
for (final node in nodes)
if (node is ChatStackGroupNode && node.name == group) ...[
for (final entry in node.entries)
if (entry.sessionId != sessionId) entry.sessionId,
sessionId,
] else
...node.entries.map((entry) => entry.sessionId),
];
@@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
import '../ui/sessions/chat_awaiting.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_entry.dart';
import 'chat_stack_pose.dart';
/// A group's pile is the collapsed stack's, this much smaller, so it keeps
/// inside its slot.
const double chatStackGroupPileScale = .8;
/// How many of a group's chats its pile draws.
const int chatStackGroupLayers = 3;
/// A group in the open column: its first chats piled as the collapsed stack
/// piles the open ones (smaller, turned), the chat on screen on top when it
/// is in the group, and the waiting bell when any of them waits on the
/// operator. Paint-only poses; nothing animates here.
class ChatStackGroupPile extends StatelessWidget {
const ChatStackGroupPile({
super.key,
required this.entries,
this.glow,
this.ring,
});
final List<ChatStackEntry> entries;
/// The top layer's lifted look (dragged) or drop-target [ring] (0 to 1).
final Animation<double>? glow;
final Color? ring;
@override
Widget build(BuildContext context) {
final current = entries.indexWhere((entry) => entry.current);
final top = current < 0 ? 0 : current;
final shown = [
for (var depth = 0; depth < entries.length; depth++)
entries[(top + depth) % entries.length],
].take(chatStackGroupLayers).toList();
final rtl = Directionality.of(context) == TextDirection.rtl;
final waiting = entries.fold(0, (sum, e) => sum + e.awaitingOperator);
return SizedBox.square(
dimension: kChatStackSlot,
child: Stack(
clipBehavior: Clip.none,
children: [
for (var depth = shown.length - 1; depth >= 0; depth--)
ChatStackPoseTransition(
progress: kAlwaysCompleteAnimation,
from: _pose(depth, rtl),
to: _pose(depth, rtl),
child: ChatStackDisc(
lift: depth == 0 ? glow : null,
liftRing: ring,
child: chatStackAvatar(shown[depth], cues: false),
),
),
if (waiting > 0)
PositionedDirectional(
top: -4,
end: -4,
child: IgnorePointer(child: ChatAwaitingBadge(count: waiting)),
),
],
),
);
}
ChatStackPose _pose(int depth, bool rtl) {
final layer = chatStackLayers[depth];
final pose = ChatStackPose(
offset: layer.offset * chatStackGroupPileScale,
turn: layer.turn,
scale: layer.scale * chatStackGroupPileScale,
);
return rtl ? pose.mirrored() : pose;
}
}
@@ -0,0 +1,94 @@
import 'package:flutter/foundation.dart';
/// The longest group name, in characters (the server's limit).
const int chatStackGroupNameLimit = 80;
/// [raw] as a group name: trimmed, without control characters, at most
/// [chatStackGroupNameLimit] characters; null when nothing is left.
String? chatStackGroupName(String raw) {
final cleaned = raw.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
if (cleaned.isEmpty) return null;
final runes = cleaned.runes.toList();
if (runes.length <= chatStackGroupNameLimit) return cleaned;
return String.fromCharCodes(runes.take(chatStackGroupNameLimit)).trim();
}
/// Which open chats belong to which named group in the chat stack.
///
/// A group is the set of chats sharing a name; its order is the open-chat
/// order. A group always has two chats or more: one left alone leaves its
/// group. The server keeps the names with the open-chat set, so groups sync
/// across devices; [replaceAll] applies the server's.
class ChatStackGroups extends ChangeNotifier {
final Map<String, String> _bySession = {};
/// The group [sessionId] is in, or null.
String? groupOf(String sessionId) => _bySession[sessionId];
/// Every grouped chat and its group.
Map<String, String> get assignments => Map.unmodifiable(_bySession);
/// The group names in use.
Set<String> get names => _bySession.values.toSet();
/// The chats in [group].
List<String> membersOf(String group) => [
for (final MapEntry(:key, :value) in _bySession.entries)
if (value == group) key,
];
/// Takes the server's groups (or a restored set) as they are.
void replaceAll(Map<String, String> assignments) => _change(
() => _bySession
..clear()
..addAll(assignments),
);
/// Puts [sessionIds] in [group] (joining it, or making it).
void assign(Iterable<String> sessionIds, String group) => _change(() {
for (final id in sessionIds) {
_bySession[id] = group;
}
});
/// Takes [sessionIds] out of their groups.
void unassign(Iterable<String> sessionIds) => _change(() {
sessionIds.forEach(_bySession.remove);
});
/// Renames [from] to [to]; a name already in use merges the two groups.
void rename(String from, String to) => _change(() {
for (final entry in _bySession.entries.toList()) {
if (entry.value == from) _bySession[entry.key] = to;
}
});
/// Dissolves [group]: its chats stay open, ungrouped.
void ungroup(String group) =>
_change(() => _bySession.removeWhere((_, value) => value == group));
/// Drops chats that are no longer open.
void retain(Set<String> open) =>
_change(() => _bySession.removeWhere((id, _) => !open.contains(id)));
/// The first "Group N" not in use.
String nextName() {
final used = names;
for (var n = 1; ; n++) {
final name = 'Group $n';
if (!used.contains(name)) return name;
}
}
void _change(VoidCallback change) {
final before = Map.of(_bySession);
change();
// A group of one is no group.
final counts = <String, int>{};
for (final group in _bySession.values) {
counts[group] = (counts[group] ?? 0) + 1;
}
_bySession.removeWhere((_, group) => (counts[group] ?? 0) < 2);
if (!mapEquals(before, _bySession)) notifyListeners();
}
}
@@ -30,6 +30,8 @@ class ChatStackMotion {
required List<int?> depths,
required this.reduced,
required bool rtl,
int originSlot = 0,
double pileScale = 1,
}) : count = depths.length {
scrim = _curve(parent, const Interval(0, .7, curve: Curves.easeOut));
close = reduced ? parent : _curve(parent, const Interval(0, .6));
@@ -52,7 +54,15 @@ class ChatStackMotion {
labelFrom.add(to);
continue;
}
from.add(rtl ? layer.mirrored() : layer);
// From its layer in the pile (a group's smaller pile [originSlot]
// slots up the column).
final pile = ChatStackPose(
offset:
layer.offset * pileScale + Offset(0, -originSlot * kChatStackPitch),
turn: layer.turn,
scale: layer.scale * pileScale,
);
from.add(rtl ? pile.mirrored() : pile);
move.add(
_curve(
parent,
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart';
import 'chat_stack_entry.dart';
/// One item of the open column's top level: a chat, or a group of chats.
@immutable
sealed class ChatStackNode {
const ChatStackNode();
/// Stable across rebuilds and reorders: keys widgets and drag state.
String get key;
/// The chats it stands for, in order.
List<ChatStackEntry> get entries;
/// Whether the chat on screen is in it.
bool get current => entries.any((entry) => entry.current);
/// Unanswered approvals and questions across its chats.
int get awaitingOperator =>
entries.fold(0, (sum, entry) => sum + entry.awaitingOperator);
}
/// A chat on its own.
class ChatStackChatNode extends ChatStackNode {
const ChatStackChatNode(this.entry);
final ChatStackEntry entry;
@override
String get key => 'chat:${entry.paneId}';
@override
List<ChatStackEntry> get entries => [entry];
}
/// A named group of chats.
class ChatStackGroupNode extends ChatStackNode {
const ChatStackGroupNode(this.name, this.entries);
final String name;
@override
final List<ChatStackEntry> entries;
@override
String get key => 'group:$name';
}
/// [entries] (in the open-chat order) as the top level shows them: each
/// group where its first chat is, holding its chats in order, and the
/// ungrouped chats on their own.
List<ChatStackNode> chatStackNodes(List<ChatStackEntry> entries) {
final groups = <String, List<ChatStackEntry>>{};
for (final entry in entries) {
final group = entry.group;
if (group != null) (groups[group] ??= []).add(entry);
}
final nodes = <ChatStackNode>[];
final placed = <String>{};
for (final entry in entries) {
final group = entry.group;
final members = group == null ? null : groups[group];
if (group == null || members == null || members.length < 2) {
nodes.add(ChatStackChatNode(entry));
} else if (placed.add(group)) {
nodes.add(ChatStackGroupNode(group, List.unmodifiable(members)));
}
}
return nodes;
}
/// The open-chat order (session ids) [nodes] stand for, each group's chats
/// together.
List<String> chatStackOrder(Iterable<ChatStackNode> nodes) => [
for (final node in nodes)
for (final entry in node.entries) entry.sessionId,
];