Chat stack: a floating pile of the open chats as phone chat navigation (WIP)

This commit is contained in:
2026-12-03 20:07:00 +00:00
parent ab7b0b2c8c
commit fd62df3815
19 changed files with 2066 additions and 48 deletions
@@ -0,0 +1,43 @@
import 'package:flutter/widgets.dart';
import 'chat_stack_disc.dart';
/// Where the chat stack sits in the chat on screen. The stack itself lives
/// once above all the panes, so it keeps its state (and finishes folding)
/// while the chat under it changes; the active chat marks its spot with a
/// [ChatStackAnchorTarget] that the stack follows.
class ChatStackAnchorScope extends InheritedWidget {
const ChatStackAnchorScope({
super.key,
required this.link,
required super.child,
});
/// The stack's link while this pane holds it; null for every other pane.
final LayerLink? link;
static LayerLink? of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<ChatStackAnchorScope>()?.link;
@override
bool updateShouldNotify(ChatStackAnchorScope oldWidget) =>
!identical(link, oldWidget.link);
}
/// The room the stack takes above a chat's composer: the transcript keeps
/// its last line and its own floating controls clear of it.
const double kChatStackClearance = kChatStackSlot + 12;
/// The stack's slot in a chat's transcript area, bottom-end above the
/// composer.
class ChatStackAnchorTarget extends StatelessWidget {
const ChatStackAnchorTarget({super.key, required this.link});
final LayerLink link;
@override
Widget build(BuildContext context) => CompositedTransformTarget(
link: link,
child: const SizedBox.square(dimension: kChatStackSlot),
);
}
@@ -0,0 +1,312 @@
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_entry.dart';
import 'chat_stack_motion.dart';
import 'chat_stack_pose.dart';
/// The chat stack fanned out: a scrim over the screen and the open chats in
/// a column rising from the stack's own slot, each avatar with its name in a
/// small pill beside it, and Add chat at the top.
///
/// Item 0 sits exactly on the collapsed stack, nearest the thumb. The chats
/// keep the open-chat order (the order the server syncs), so a chat keeps
/// its place in the column from one visit to the next; the chat on screen
/// wears a ring in its colour. Add chat is last, at the top: the reachable
/// bottom slots go to the frequent action (switching), and the rarer one
/// ends the list where the operator reads "and more".
///
/// Nothing here rebuilds per frame: every item moves through
/// [ChatStackPoseTransition] and fades through [FadeTransition], both
/// repaint-only.
class ChatStackColumn extends StatelessWidget {
const ChatStackColumn({
super.key,
required this.motion,
required this.anchor,
required this.entries,
required this.depths,
required this.interactive,
required this.onOpen,
required this.onAdd,
required this.onDismiss,
this.onRemove,
});
final ChatStackMotion motion;
/// The collapsed stack's slot in this overlay's coordinates.
final Rect anchor;
final List<ChatStackEntry> entries;
/// Each item's layer in the collapsed pile (null when it is not drawn
/// there); the add item last.
final List<int?> depths;
/// False while folding back: taps fall through to nothing.
final bool interactive;
final ValueChanged<ChatStackEntry> onOpen;
final VoidCallback onAdd;
final VoidCallback onDismiss;
/// Long press removes a chat from the open chats; null when it cannot
/// (the only open chat).
final ValueChanged<ChatStackEntry>? onRemove;
static const removeLabel = 'Remove from open chats';
static const addLabel = 'Add chat';
@override
Widget build(BuildContext context) {
final media = MediaQuery.of(context);
final scheme = Theme.of(context).colorScheme;
final dark = Theme.of(context).brightness == Brightness.dark;
final rtl = Directionality.of(context) == TextDirection.rtl;
return LayoutBuilder(
builder: (context, constraints) {
final size = constraints.biggest;
final count = motion.count;
final height = (count - 1) * kChatStackPitch + kChatStackSlot;
final top = media.padding.top + 8;
final available = anchor.bottom - top;
final fits = height <= available;
// The column's own edge is the stack's; the labels take the rest of
// the row back to a margin at the other side.
final endInset = rtl ? anchor.left : size.width - anchor.right;
const margin = 16.0;
final width = size.width - endInset - margin;
final labelMax = width - kChatStackSlot - kChatStackLabelGap;
// Paint the pile's order while it opens: hidden layers first, the
// top of the pile last.
final order = [for (var i = 0; i < count; i++) i]
..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99));
final items = Stack(
clipBehavior: Clip.none,
children: [
for (final i in order) ...[
_label(context, i, labelMax),
_item(context, i),
],
],
);
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.escape): onDismiss,
},
child: FocusScope(
autofocus: true,
child: IgnorePointer(
ignoring: !interactive,
child: Stack(
children: [
Positioned.fill(
child: FadeTransition(
opacity: motion.scrim,
child: ModalBarrier(
color: scheme.scrim.withValues(alpha: dark ? .5 : .32),
dismissible: true,
onDismiss: onDismiss,
semanticsLabel: 'Close chats',
),
),
),
PositionedDirectional(
end: endInset,
bottom: size.height - anchor.bottom,
top: top,
width: width,
child: Align(
alignment: AlignmentDirectional.bottomEnd,
child: SingleChildScrollView(
reverse: true,
clipBehavior: fits ? Clip.none : Clip.hardEdge,
child: SizedBox(
width: width,
height: height,
child: Semantics(
container: true,
explicitChildNodes: true,
label: 'Open chats',
child: items,
),
),
),
),
),
],
),
),
),
);
},
);
}
Widget _item(BuildContext context, int i) {
final entry = i < entries.length ? entries[i] : null;
return PositionedDirectional(
key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'),
end: 0,
bottom: 0,
// The transform is outermost: the boxes under it sit at the stack's
// slot, and only a transform passes hits on to where it paints them.
child: ChatStackPoseTransition(
progress: motion.move[i],
from: motion.from[i],
to: motion.target[i],
child: FadeTransition(
opacity: motion.fade[i],
child: KeyedSubtree(
key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'),
child: entry == null ? _addButton(context) : _chatButton(entry),
),
),
),
);
}
Widget _label(BuildContext context, int i, double maxWidth) {
final entry = i < entries.length ? entries[i] : null;
return PositionedDirectional(
key: ValueKey('chat-stack-label-${entry?.paneId ?? 'add'}'),
end: kChatStackSlot + kChatStackLabelGap,
bottom: 0,
height: kChatStackSlot,
child: ChatStackPoseTransition(
progress: motion.label[i],
from: motion.labelFrom[i],
to: motion.target[i],
child: ExcludeSemantics(
child: FadeTransition(
opacity: motion.label[i],
child: Align(
alignment: AlignmentDirectional.centerEnd,
widthFactor: 1,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth),
child: GestureDetector(
onTap: entry == null ? onAdd : () => onOpen(entry),
onLongPress: entry == null || onRemove == null
? null
: () => onRemove!(entry),
child: ChatStackLabel(
text: entry?.title ?? addLabel,
color: entry?.color(context),
emphasized: entry?.current ?? false,
),
),
),
),
),
),
),
);
}
Widget _chatButton(ChatStackEntry entry) => Builder(
builder: (context) {
final remove = onRemove;
final ring = entry.current
? entry.color(context) ?? Theme.of(context).colorScheme.primary
: null;
return Semantics(
container: true,
button: true,
selected: entry.current,
label: entry.title,
hint: entry.current ? 'Open now' : null,
onTap: () => onOpen(entry),
customSemanticsActions: remove == null
? null
: {
const CustomSemanticsAction(label: removeLabel): () =>
remove(entry),
},
child: _Tappable(
autofocus: entry.current,
onTap: () => onOpen(entry),
onLongPress: remove == null ? null : () => remove(entry),
child: ChatStackDisc(ring: ring, child: chatStackAvatar(entry)),
),
);
},
);
Widget _addButton(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final tokens = AppDesignTokens.of(context);
return Semantics(
container: true,
button: true,
label: addLabel,
onTap: onAdd,
child: _Tappable(
onTap: onAdd,
child: ChatStackDisc(
child: DecoratedBox(
decoration: ShapeDecoration(
color: tokens.flat ? null : scheme.primaryContainer,
shape: chatStackShape(tokens).copyWith(
side: tokens.flat
? BorderSide(color: scheme.primary.withValues(alpha: .55))
: BorderSide.none,
),
),
child: Icon(
Icons.add,
color: tokens.flat ? scheme.primary : scheme.onPrimaryContainer,
),
),
),
),
);
}
}
/// A disc's ink and focus: the splash is drawn over the disc (the disc is
/// opaque, so ink under it would never show), in the design's shape.
class _Tappable extends StatelessWidget {
const _Tappable({
required this.child,
required this.onTap,
this.onLongPress,
this.autofocus = false,
});
final Widget child;
final VoidCallback onTap;
final VoidCallback? onLongPress;
final bool autofocus;
@override
Widget build(BuildContext context) {
final shape = chatStackShape(AppDesignTokens.of(context));
return Stack(
children: [
child,
Positioned.fill(
child: Padding(
padding: const EdgeInsets.all(
(kChatStackSlot - kChatStackDisc) / 2,
),
child: Material(
type: MaterialType.transparency,
shape: shape,
clipBehavior: Clip.antiAlias,
child: InkWell(
autofocus: autofocus,
excludeFromSemantics: true,
customBorder: shape,
onTap: onTap,
onLongPress: onLongPress,
),
),
),
),
],
);
}
}
@@ -0,0 +1,158 @@
import 'package:flutter/material.dart';
import '../../../ui/layout/app_list_avatar.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The square every stack item occupies: a touch target at least as large as
/// the platform's minimum.
const double kChatStackSlot = 48;
/// The disc behind an avatar: the avatar plus a rim on each side.
const double kChatStackDisc = kChatStackSlot - 4;
/// The vertical distance between neighbouring items of the open column.
const double kChatStackPitch = kChatStackSlot + 8;
/// The gap between an item's name label and its avatar.
const double kChatStackLabelGap = 10;
/// An opaque disc in the design's shape (a circle, or a framed square under a
/// flat design) that carries one avatar of the stack. The list avatar's fill
/// is translucent; the disc keeps stacked avatars from showing through each
/// other, and its rim separates them. A raised design drops a short shadow;
/// a flat one keeps its hairline frame instead.
class ChatStackDisc extends StatelessWidget {
const ChatStackDisc({
super.key,
required this.child,
this.ring,
this.shadow = true,
});
final Widget child;
/// The rim's colour when it marks the current chat; null for the surface.
final Color? ring;
/// Whether this disc may cast a shadow (a layer under another does not).
final bool shadow;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
final scheme = Theme.of(context).colorScheme;
final base = tokens.panelFill(scheme, scheme.surface);
final ring = this.ring;
final shape = chatStackShape(tokens);
final frame = tokens.frameSide;
return SizedBox.square(
dimension: kChatStackSlot,
child: Center(
child: DecoratedBox(
decoration: ShapeDecoration(
color: ring ?? base,
shape: shape.copyWith(
side: ring == null && frame != null ? frame : BorderSide.none,
),
shadows: shadow && !tokens.flat ? chatStackShadows(scheme) : null,
),
child: SizedBox.square(
dimension: kChatStackDisc,
child: Center(
child: DecoratedBox(
// The avatar's own tint lands on an opaque face, so the
// colour reads the same as in the list.
decoration: ShapeDecoration(color: base, shape: shape),
child: SizedBox.square(
dimension: kAppListAvatarSize,
child: child,
),
),
),
),
),
),
);
}
}
/// A circle, or the design's rounded square when it is flat (as the list's
/// avatar draws itself).
OutlinedBorder chatStackShape(AppDesignTokens tokens) => tokens.flat
? RoundedRectangleBorder(borderRadius: tokens.corners(BorderRadius.zero))
: const CircleBorder();
/// A short, close shadow: enough to lift a layer off the one below without a
/// halo over the transcript.
List<BoxShadow> chatStackShadows(ColorScheme scheme) => [
BoxShadow(
color: scheme.shadow.withValues(alpha: .18),
blurRadius: 4,
offset: const Offset(0, 1),
),
BoxShadow(
color: scheme.shadow.withValues(alpha: .10),
blurRadius: 10,
offset: const Offset(0, 4),
),
];
/// The name beside an avatar in the open column: a small pill tinted with
/// the chat's colour over an opaque face, one line, ellipsised.
class ChatStackLabel extends StatelessWidget {
const ChatStackLabel({
super.key,
required this.text,
this.color,
this.emphasized = false,
});
final String text;
final Color? color;
final bool emphasized;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final base = tokens.panelFill(scheme, scheme.surfaceContainerHigh);
final color = this.color;
final dark = theme.brightness == Brightness.dark;
final fill = color == null
? base
: Color.alphaBlend(color.withValues(alpha: dark ? .22 : .14), base);
final style = (theme.textTheme.labelLarge ?? const TextStyle()).copyWith(
color: scheme.onSurface,
fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500,
);
return DecoratedBox(
decoration: ShapeDecoration(
color: fill,
shape: _labelShape(tokens),
shadows: tokens.flat ? null : chatStackShadows(scheme),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
softWrap: false,
style: style,
),
),
);
}
ShapeBorder _labelShape(AppDesignTokens tokens) {
final side = tokens.frameSide ?? BorderSide.none;
final r = tokens.radius;
return r == null
? StadiumBorder(side: side)
: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(r),
side: side,
);
}
}
@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_colors.dart';
import '../domain/chat_list_activity.dart';
import '../domain/chat_sessions.dart';
import '../ui/sessions/chat_color_palette.dart';
import '../ui/sessions/session_row_content.dart';
/// One open chat as the chat stack shows it: the pane that holds it and the
/// chat's latest list row (its title, colour, harness and live state).
@immutable
class ChatStackEntry {
const ChatStackEntry({
required this.paneId,
required this.session,
this.current = false,
});
final String paneId;
final JsonMap session;
/// Whether this is the chat on screen.
final bool current;
String get sessionId => '${session['id'] ?? ''}';
String get title => chatSessionTitle(session);
bool get _closed => session['closed_at'] != null || session['closed'] == true;
/// Unanswered approvals and questions: the agent is blocked on the
/// operator.
int get awaitingOperator =>
_closed ? 0 : chatSessionAwaitingOperator(session);
bool get running => session['running'] == true;
/// The chat's colour as the list draws it, or null for none.
Color? color(BuildContext context) =>
chatColorShade(context, chatSessionColor(session));
}
/// [entry]'s list avatar; with [cues] it keeps the list's corner badge
/// (waiting on the operator, working, background tasks).
Widget chatStackAvatar(ChatStackEntry entry, {bool cues = true}) =>
ChatSessionAvatar(
session: entry.session,
awaitingOperator: cues ? entry.awaitingOperator : 0,
running: cues && entry.running,
backgroundTasks: cues && !entry.running
? chatSessionBackgroundTasks(entry.session)
: 0,
selected: entry.current,
);
/// The collapsed stack's spoken name: "Chats, 5 open".
String chatStackLabel(int count) => 'Chats, $count open';
@@ -0,0 +1,369 @@
import 'package:flutter/material.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../ui/sessions/chat_awaiting.dart';
import 'chat_stack_column.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_entry.dart';
import 'chat_stack_motion.dart';
import 'chat_stack_pose.dart';
/// The phone's chat stack: the open chats' avatars piled up, the chat on
/// screen on top, a floating button above the composer. A tap fans them out
/// into a column ([ChatStackColumn]); a tap outside, Back or Escape folds
/// them back. It steps aside while the on-screen keyboard is up.
class ChatStackFab extends StatefulWidget {
const ChatStackFab({
super.key,
required this.entries,
required this.onOpen,
required this.onAdd,
this.onRemove,
});
/// The open chats in their synced order; one is [ChatStackEntry.current].
final List<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;
@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 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();
super.dispose();
}
void _status(AnimationStatus status) {
if (status == AnimationStatus.dismissed && !_expanded && mounted) {
_portal.hide();
setState(() {});
}
}
/// Fans the stack out into its column.
void expand() {
if (_expanded || _keyboard || widget.entries.isEmpty) return;
final box = _slot.currentContext?.findRenderObject() as RenderBox?;
final overlay =
Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?;
if (box == null || overlay == null || !box.hasSize) return;
final origin = box.localToGlobal(Offset.zero, ancestor: overlay);
_open
..duration = _reduced ? chatStackFadeDuration : chatStackOpenDuration
..reverseDuration = _reduced
? chatStackFadeDuration
: chatStackCloseDuration;
setState(() {
_anchor = origin & box.size;
_expanded = true;
});
_portal.show();
_open.forward();
}
/// Folds the column back into the stack; [immediate] skips the motion.
void collapse({bool immediate = false}) {
if (!_expanded) return;
setState(() => _expanded = false);
if (immediate) {
_open.value = 0;
_portal.hide();
} else {
_open.reverse();
}
if (FocusManager.instance.highlightMode == FocusHighlightMode.traditional) {
_focus.requestFocus();
}
}
void _choose(ChatStackEntry entry) {
collapse();
if (!entry.current) widget.onOpen(entry);
}
/// Removing folds the column, so the snack bar's Undo is in reach.
void _remove(ChatStackEntry entry) {
collapse();
widget.onRemove?.call(entry);
}
void _add() {
collapse();
widget.onAdd(context);
}
/// Each item's layer in the pile: the chat on screen on top, then the
/// chats after it in order, wrapping; the add item is never in the pile.
List<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 rtl = Directionality.of(context) == TextDirection.rtl;
final motion = _motionFor(depths, rtl);
final hidden = _keyboard || entries.isEmpty;
final remove = widget.onRemove;
final canRemove = remove != null && entries.length > 1;
return PopScope(
canPop: !_expanded,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) collapse();
},
child: OverlayPortal(
controller: _portal,
overlayChildBuilder: (context) {
final anchor = _anchor;
if (anchor == null) return const SizedBox.shrink();
return ChatStackColumn(
motion: motion,
anchor: anchor,
entries: entries,
depths: depths,
interactive: _expanded,
onOpen: _choose,
onAdd: _add,
onDismiss: collapse,
onRemove: canRemove ? _remove : null,
);
},
child: AnimatedOpacity(
opacity: hidden ? 0 : 1,
duration: Motion.of(context, Motion.quick),
child: IgnorePointer(
ignoring: hidden,
child: ExcludeFocus(
excluding: hidden,
child: ExcludeSemantics(
excluding: hidden,
child: FadeTransition(
opacity: _reduced ? _fadedWhileOpen : _hiddenWhileOpen,
child: RepaintBoundary(
key: _slot,
child: _pile(context, depths),
),
),
),
),
),
),
),
);
}
Widget _pile(BuildContext context, List<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,
),
),
),
);
}
}
@@ -0,0 +1,106 @@
import 'dart:math' as math;
import 'package:flutter/animation.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_pose.dart';
/// How long the stack takes to fan out into its column and to fold back.
const Duration chatStackOpenDuration = Duration(milliseconds: 280);
const Duration chatStackCloseDuration = Duration(milliseconds: 220);
/// Under reduced motion the column only fades in and out, in place.
const Duration chatStackFadeDuration = Duration(milliseconds: 120);
/// A short spring-like ease: a touch of overshoot on arrival, no bounce back.
const Curve chatStackRise = Cubic(.22, 1.18, .36, 1);
/// Folding plays the controller backwards: an ease-in in forward time leaves
/// the column briskly and settles gently into the pile.
const Curve chatStackFold = Curves.easeInCubic;
/// Every animation the open column reads, derived once from one controller
/// when the items change (never per frame). Item 0 is nearest the thumb; the
/// column rises from there, each item starting a little after the one below
/// it, and folds back top first.
class ChatStackMotion {
ChatStackMotion({
required Animation<double> parent,
required List<int?> depths,
required this.reduced,
required bool rtl,
}) : count = depths.length {
scrim = _curve(parent, const Interval(0, .7, curve: Curves.easeOut));
final span = count <= 1 ? 1.0 : .62;
final step = count <= 1 ? 0.0 : (1 - span) / (count - 1);
for (var i = 0; i < count; i++) {
final start = i * step;
final end = math.min(1.0, start + span);
final depth = depths[i];
final to = chatStackColumnPose(i, kChatStackPitch);
final layer = chatStackLayers[depth ?? chatStackLayers.length - 1];
target.add(to);
if (reduced) {
from.add(to);
move.add(parent);
fade.add(parent);
label.add(parent);
labelFrom.add(to);
continue;
}
from.add(rtl ? layer.mirrored() : layer);
move.add(
_curve(
parent,
Interval(start, end, curve: chatStackRise),
Interval(start, end, curve: chatStackFold),
),
);
// A chat that was not drawn in the pile appears as it leaves it.
fade.add(
depth != null
? kAlwaysCompleteAnimation
: _curve(parent, Interval(start, math.min(1, start + span * .5))),
);
final labelStart = start + span * .45;
label.add(
_curve(parent, Interval(labelStart, end, curve: Curves.easeOut)),
);
labelFrom.add(
ChatStackPose(offset: Offset(rtl ? -8 : 8, to.offset.dy), scale: .96),
);
}
}
final int count;
final bool reduced;
late final Animation<double> scrim;
final List<ChatStackPose> from = [];
final List<ChatStackPose> target = [];
final List<Animation<double>> move = [];
final List<Animation<double>> fade = [];
final List<Animation<double>> label = [];
final List<ChatStackPose> labelFrom = [];
final List<CurvedAnimation> _owned = [];
Animation<double> _curve(
Animation<double> parent,
Curve curve, [
Curve? reverse,
]) {
final curved = CurvedAnimation(
parent: parent,
curve: curve,
reverseCurve: reverse,
);
_owned.add(curved);
return curved;
}
void dispose() {
for (final curved in _owned) {
curved.dispose();
}
_owned.clear();
}
}
@@ -0,0 +1,202 @@
import 'dart:math' as math;
import 'dart:ui' show lerpDouble;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Where one avatar of the chat stack sits relative to the stack's slot: a
/// paint-only offset, a turn about its centre and a scale.
@immutable
class ChatStackPose {
const ChatStackPose({
this.offset = Offset.zero,
this.turn = 0,
this.scale = 1,
});
static const rest = ChatStackPose();
final Offset offset;
/// Radians, clockwise.
final double turn;
final double scale;
/// The same pose for a right-to-left layout: offsets and turns mirror.
ChatStackPose mirrored() => ChatStackPose(
offset: Offset(-offset.dx, offset.dy),
turn: -turn,
scale: scale,
);
@override
bool operator ==(Object other) =>
other is ChatStackPose &&
other.offset == offset &&
other.turn == turn &&
other.scale == scale;
@override
int get hashCode => Object.hash(offset, turn, scale);
}
/// The collapsed stack's layers, top first: each further layer peeks out a
/// little higher, turned a few degrees the other way and slightly smaller,
/// so the pile reads as cards rather than one disc.
const List<ChatStackPose> chatStackLayers = [
ChatStackPose(),
ChatStackPose(offset: Offset(-4, -6), turn: -7 * math.pi / 180, scale: .94),
ChatStackPose(offset: Offset(4, -11), turn: 6 * math.pi / 180, scale: .88),
ChatStackPose(offset: Offset(-1, -15), turn: -4 * math.pi / 180, scale: .82),
];
/// How many avatars the collapsed stack draws.
int get chatStackVisibleLayers => chatStackLayers.length;
/// The pose of the column's item [index] (0 nearest the thumb), [pitch]
/// apart.
ChatStackPose chatStackColumnPose(int index, double pitch) =>
ChatStackPose(offset: Offset(0, -index * pitch));
/// Paints [child] moved from [from] to [to] as [progress] runs, without
/// rebuilding or relaying out: each frame only repaints the transform, and
/// hit tests follow it. The matrix and the layer are reused across frames.
class ChatStackPoseTransition extends SingleChildRenderObjectWidget {
const ChatStackPoseTransition({
super.key,
required this.progress,
required this.from,
required this.to,
super.child,
});
final Animation<double> progress;
final ChatStackPose from;
final ChatStackPose to;
@override
RenderChatStackPose createRenderObject(BuildContext context) =>
RenderChatStackPose(progress: progress, from: from, to: to);
@override
void updateRenderObject(
BuildContext context,
RenderChatStackPose renderObject,
) {
renderObject
..progress = progress
..from = from
..to = to;
}
}
class RenderChatStackPose extends RenderProxyBox {
RenderChatStackPose({
required Animation<double> progress,
required ChatStackPose from,
required ChatStackPose to,
}) {
_progress = progress;
_from = from;
_to = to;
}
late Animation<double> _progress;
set progress(Animation<double> value) {
if (identical(value, _progress)) return;
if (attached) _progress.removeListener(markNeedsPaint);
_progress = value;
if (attached) _progress.addListener(markNeedsPaint);
markNeedsPaint();
}
late ChatStackPose _from;
set from(ChatStackPose value) {
if (value == _from) return;
_from = value;
markNeedsPaint();
}
late ChatStackPose _to;
set to(ChatStackPose value) {
if (value == _to) return;
_to = value;
markNeedsPaint();
}
final Matrix4 _matrix = Matrix4.identity();
final LayerHandle<TransformLayer> _layer = LayerHandle<TransformLayer>();
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_progress.addListener(markNeedsPaint);
}
@override
void detach() {
_progress.removeListener(markNeedsPaint);
super.detach();
}
@override
void dispose() {
_layer.layer = null;
super.dispose();
}
@override
bool get alwaysNeedsCompositing => child != null;
/// Fills the reused matrix for the current progress, about the centre.
Matrix4 _current() {
final t = _progress.value;
final dx = lerpDouble(_from.offset.dx, _to.offset.dx, t)!;
final dy = lerpDouble(_from.offset.dy, _to.offset.dy, t)!;
final turn = lerpDouble(_from.turn, _to.turn, t)!;
final scale = lerpDouble(_from.scale, _to.scale, t)!;
final cx = size.width / 2;
final cy = size.height / 2;
return _matrix
..setIdentity()
..translateByDouble(dx + cx, dy + cy, 0, 1)
..rotateZ(turn)
..scaleByDouble(scale, scale, 1, 1)
..translateByDouble(-cx, -cy, 0, 1);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child == null) return;
_layer.layer = context.pushTransform(
needsCompositing,
offset,
_current(),
super.paint,
oldLayer: _layer.layer,
);
}
@override
bool hitTest(BoxHitTestResult result, {required Offset position}) =>
hitTestChildren(result, position: position);
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
final child = this.child;
if (child == null) return false;
return result.addWithPaintTransform(
transform: _current(),
position: position,
hitTest: (result, position) {
if (!child.size.contains(position)) return false;
return child.hitTest(result, position: position);
},
);
}
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
transform.multiply(_current());
}
}
@@ -0,0 +1,99 @@
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
const mobileChatNavigationKey = 'pipelines.mobile-chat-navigation.v1';
/// How a phone-width layout moves between the open chats.
enum MobileChatNavigation {
quickSwitch(
'Quick switch',
'The next open chat peeks below the current one; tap it to swap.',
),
chatStack(
'Chat stack',
'A stack of the open chats floats above the composer; tap it to pick one.',
);
const MobileChatNavigation(this.label, this.description);
final String label;
final String description;
}
abstract interface class MobileChatNavigationStore {
Future<String?> load();
Future<bool> save(String value);
}
class SharedMobileChatNavigationStore implements MobileChatNavigationStore {
const SharedMobileChatNavigationStore();
@override
Future<String?> load() async {
try {
return (await SharedPreferences.getInstance()).getString(
mobileChatNavigationKey,
);
} catch (_) {
return null;
}
}
@override
Future<bool> save(String value) async {
try {
return await (await SharedPreferences.getInstance()).setString(
mobileChatNavigationKey,
value,
);
} catch (_) {
return false;
}
}
}
/// This device's choice of phone chat navigation, applied live.
class MobileChatNavigationController extends ChangeNotifier {
MobileChatNavigationController({MobileChatNavigationStore? store})
: _store = store ?? const SharedMobileChatNavigationStore();
static final instance = MobileChatNavigationController();
final MobileChatNavigationStore _store;
MobileChatNavigation _value = MobileChatNavigation.quickSwitch;
int _revision = 0;
bool _disposed = false;
bool saveFailed = false;
MobileChatNavigation get value => _value;
bool get stack => _value == MobileChatNavigation.chatStack;
Future<void> restore() async {
final revision = _revision;
final saved = await _store.load();
if (_disposed || revision != _revision) return;
for (final mode in MobileChatNavigation.values) {
if (mode.name == saved && mode != _value) {
_value = mode;
notifyListeners();
}
}
}
Future<void> setValue(MobileChatNavigation mode) async {
if (_disposed) return;
final revision = ++_revision;
_value = mode;
saveFailed = false;
notifyListeners();
final saved = await _store.save(mode.name);
if (_disposed || revision != _revision) return;
saveFailed = !saved;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}