Merge branch 'worktree-agent-a027d4a4581416c93'

This commit is contained in:
2026-12-03 23:41:55 +00:00
49 changed files with 4365 additions and 323 deletions
+96 -1
View File
@@ -8,7 +8,8 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
void _bindWindows() {
final windows = widget.windows;
if (windows == null) return;
_workspace.showOutside = windows.show;
_workspace.showOutside = _showOutside;
windows.manager.addListener(_windowsChanged);
windows.tiling = _tiling = ChatTiling(
holds: _workspace.holdsSession,
dock: _dockSession,
@@ -35,9 +36,103 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
if (windows != null && identical(windows.tiling, _tiling)) {
windows.tiling = null;
}
windows?.manager.removeListener(_windowsChanged);
_workspace.showOutside = null;
}
/// A chat out in a window comes to the top on a wide layout. A phone
/// ignores floating: the chat leaves its (hidden) window and opens as a
/// pane, still floating in the server's set.
bool _showOutside(String sessionId) {
final windows = widget.windows;
if (windows == null) return false;
if (!_phoneIgnoresFloat) return windows.show(sessionId);
_holdForPhone(windows, sessionId);
return false;
}
/// Takes [sessionId] out of its window, to be tiled on this phone layout.
void _holdForPhone(ChatWindows windows, String sessionId) {
final window = windows.windows
.where((window) => window.contentId == sessionId)
.firstOrNull;
if (window == null) return;
_phoneDocked.add(sessionId);
windows.manager.close(window.id);
}
/// Whether the last build was a phone's layout, which tiles floating chats.
bool? _builtPhoneFloat;
bool _followingFloat = false;
/// Called from build: a change between a phone and a wide layout moves
/// the floating chats between panes and windows after the frame.
@override
void _trackFloatLayout() {
// A phone-width window, or the Chat stack on a wide phone or tablet
// layout: both navigate one chat at a time and ignore floating.
_phoneLayout = !showsListBesideDetail(context) || _stacked(context);
if (widget.windows == null) return;
final phone = _phoneIgnoresFloat;
if (phone == _builtPhoneFloat) return;
_builtPhoneFloat = phone;
_followFloatLayoutSoon();
}
void _windowsChanged() {
if (_builtPhoneFloat == true &&
(widget.windows?.windows.isNotEmpty ?? false)) {
_followFloatLayoutSoon();
}
}
void _followFloatLayoutSoon() {
if (_followingFloat) return;
_followingFloat = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_followingFloat = false;
if (mounted) _followFloatLayout();
});
}
/// On a phone every floating chat becomes a pane (the chat on screen
/// stays); on a wide layout the chats held that way float again.
void _followFloatLayout() {
final windows = widget.windows;
if (windows == null) return;
final phone = _phoneIgnoresFloat;
final ids = phone
? windows.floatingSessionIds.toList()
: _phoneDocked.toList();
if (ids.isEmpty) return;
// One write for the whole move: the chats stay floating in the set.
_applyingServerWorkspace = true;
try {
if (phone) {
final active = _workspace.activePaneId;
for (final id in ids) {
_holdForPhone(windows, id);
_workspace.dock(id);
}
if (active != null) _workspace.activate(active);
} else {
for (final id in ids) {
final pane = _workspace.panes
.where((pane) => pane.sessionId == id)
.firstOrNull;
if (pane == null) continue;
_workspace.detach(pane.id);
windows.float(id);
}
_phoneDocked.clear();
}
} finally {
_applyingServerWorkspace = false;
}
_syncOpenWorkspace();
if (!phone && _workspace.paneCount == 0) _back();
}
/// Panes float only on a wide layout, beside the chat list.
bool get _floatsHere =>
widget.windows != null && !_pageOpen && showsListBesideDetail(context);
+32 -6
View File
@@ -6,7 +6,14 @@ part of 'screen.dart';
/// workspace's panes, the same open chats the server syncs; choosing one
/// opens it as a tap on its list row does, Add chat is the pane menu's Add
/// chat pane, and removing one closes its pane.
mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
/// Whether this is a phone or tablet (Android or iOS, also a browser on one).
bool chatStackOnMobile() => switch (defaultTargetPlatform) {
TargetPlatform.android || TargetPlatform.iOS => true,
_ => false,
};
mixin _ChatScreenStack
on State<ChatScreen>, _ChatScreenWorkspace, _ChatScreenStackGroups {
final LayerLink _stackLink = LayerLink();
void _openBySelection(JsonMap session);
@@ -15,10 +22,14 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
MobileChatNavigationController get _navigation =>
MobileChatNavigationController.instance;
/// Whether this layout navigates with the stack rather than the peek.
/// Whether this layout navigates with the stack rather than the peek: on
/// a phone-width window, and on a phone or tablet at any width (an
/// unfolded foldable keeps the stack above the active pane). A wide
/// desktop or web window keeps its panes alone.
@override
bool _stacked(BuildContext context) =>
_navigation.stack && !showsListBesideDetail(context);
_navigation.stack &&
(!showsListBesideDetail(context) || chatStackOnMobile());
/// Gives the active pane the stack's spot.
@override
@@ -42,6 +53,7 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
_rowFor(pane.sessionId) ??
{'id': pane.sessionId},
current: pane.id == active,
group: _stackGroups.groupOf(pane.sessionId),
),
];
}
@@ -50,7 +62,11 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
/// screen.
@override
Widget _stackOverlay() => ListenableBuilder(
listenable: Listenable.merge([_workspace, _sessionsForSidebar]),
listenable: Listenable.merge([
_workspace,
_sessionsForSidebar,
_stackGroups,
]),
builder: (context, _) => CompositedTransformFollower(
link: _stackLink,
showWhenUnlinked: false,
@@ -59,6 +75,8 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
onOpen: (entry) => _openBySelection(entry.session),
onAdd: (context) => _addPane(context, title: ChatStackColumn.addLabel),
onRemove: _removeFromStack,
onReorder: _workspace.reorderSessions,
groups: _stackGroupActions(),
),
),
);
@@ -66,6 +84,7 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
void _removeFromStack(ChatStackEntry entry) {
final messenger = ScaffoldMessenger.maybeOf(context);
final wasActive = _workspace.activePaneId;
final index = _workspace.panes.indexWhere((p) => p.id == entry.paneId);
_closePane(entry.paneId);
if (messenger == null) return;
messenger
@@ -75,16 +94,23 @@ mixin _ChatScreenStack on State<ChatScreen>, _ChatScreenWorkspace {
content: Text('Removed ${entry.title} from open chats'),
action: SnackBarAction(
label: 'Undo',
onPressed: () => _restoreToStack(entry, wasActive),
onPressed: () => _restoreToStack(entry, wasActive, index),
),
),
);
}
void _restoreToStack(ChatStackEntry entry, String? wasActive) {
/// Undo: the chat comes back at its old place in the open-chat order.
void _restoreToStack(ChatStackEntry entry, String? wasActive, int index) {
if (!mounted || _workspace.holdsSession(entry.sessionId)) return;
_openedSessions[entry.sessionId] = entry.session;
_workspace.splitActive(entry.sessionId, ChatSplitAxis.horizontal);
final restored = _workspace.panes
.where((pane) => pane.sessionId == entry.sessionId)
.firstOrNull;
if (restored != null && index >= 0) {
_workspace.movePane(restored.id, index);
}
// The chat on screen stays on screen unless it was the one removed.
if (wasActive != null && wasActive != entry.paneId) {
final kept = _workspace.panes
@@ -0,0 +1,83 @@
part of 'screen.dart';
/// The chat stack's groups ([ChatStackGroups]): which open chats belong to
/// which named group. They travel with the open-chat set (each entry's
/// `group`), so they persist and sync across devices like the order.
mixin _ChatScreenStackGroups on State<ChatScreen>, _ChatScreenWorkspace {
ChatStackGroupActions _stackGroupActions() => ChatStackGroupActions(
join: (sessionIds, group, order) {
_workspace.reorderSessions(order);
_stackGroups.assign(sessionIds, group);
},
leave: (sessionIds, order) {
_workspace.reorderSessions(order);
_stackGroups.unassign(sessionIds);
},
rename: _stackGroups.rename,
ungroup: _ungroupStack,
closeAll: _closeStackGroup,
);
void _stackSnack(String message, VoidCallback undo) {
final messenger = ScaffoldMessenger.maybeOf(context);
if (messenger == null) return;
messenger
..hideCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(message),
action: SnackBarAction(label: 'Undo', onPressed: undo),
),
);
}
/// The group goes; its chats stay open. Undo puts the open ones back.
void _ungroupStack(String group) {
final members = _stackGroups.membersOf(group);
if (members.isEmpty) return;
_stackGroups.ungroup(group);
_stackSnack('Ungrouped $group', () {
if (!mounted) return;
_stackGroups.assign(members.where(_workspace.holdsSession), group);
});
}
/// Every chat in the group leaves the open chats. Undo opens them again,
/// in their places and grouped, keeping the chat on screen.
void _closeStackGroup(String group) {
final members = _stackGroups.membersOf(group).toSet();
if (members.isEmpty) return;
final order = [for (final pane in _workspace.panes) pane.sessionId];
final rows = {
for (final id in members) id: _rowFor(id) ?? {'id': id},
};
final active = _workspace.activePane?.sessionId;
for (final pane in _workspace.panes.toList()) {
if (members.contains(pane.sessionId)) _closePane(pane.id);
}
_stackSnack(
'Closed ${members.length} chats in $group',
() => _reopenStackGroup(group, order, rows, active),
);
}
void _reopenStackGroup(
String group,
List<String> order,
Map<String, JsonMap> rows,
String? active,
) {
if (!mounted) return;
for (final MapEntry(key: id, value: row) in rows.entries) {
if (_workspace.holdsSession(id)) continue;
_openedSessions[id] = row;
_workspace.splitActive(id, ChatSplitAxis.horizontal);
}
_workspace.reorderSessions(order);
_stackGroups.assign(rows.keys, group);
final kept = _workspace.panes
.where((pane) => pane.sessionId == active)
.firstOrNull;
if (kept != null) _workspace.activate(kept.id);
}
}
@@ -114,18 +114,38 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
ChatWorkspaceBinding? _workspaceBinding;
String? _workspaceScope;
/// Chats that float in windows on a wide layout, held as ordinary panes
/// while the layout is a phone's (see `_ChatScreenFloat`). They stay
/// floating in the server's set, so a wide layout floats them again.
final Set<String> _phoneDocked = {};
/// The chat stack's groups, sent with the open-chat set.
final ChatStackGroups _stackGroups = ChatStackGroups();
/// Whether the last build laid out for a phone (set in build, so it is
/// safe to read from callbacks and initState).
bool _phoneLayout = false;
/// Whether this layout ignores floating: a phone's, where windows are
/// hidden and the chats are navigated one at a time.
bool get _phoneIgnoresFloat => widget.windows != null && _phoneLayout;
Iterable<ChatOpenWorkspaceEntry> _serverWorkspaceEntries() sync* {
final floating =
widget.windows?.floatingSessionIds.toSet() ?? const <String>{};
final floating = {...?widget.windows?.floatingSessionIds, ..._phoneDocked};
for (final pane in _workspace.panes) {
yield ChatOpenWorkspaceEntry(
pane.sessionId,
floating: floating.contains(pane.sessionId),
group: _stackGroups.groupOf(pane.sessionId),
);
}
for (final sessionId in floating) {
if (!_workspace.holdsSession(sessionId)) {
yield ChatOpenWorkspaceEntry(sessionId, floating: true);
yield ChatOpenWorkspaceEntry(
sessionId,
floating: true,
group: _stackGroups.groupOf(sessionId),
);
}
}
}
@@ -232,9 +252,27 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
]);
}
_applyingServerWorkspace = true;
final phone = _phoneIgnoresFloat;
try {
final windows = widget.windows;
if (windows != null) {
for (final entry in snapshot.entries) {
if (!entry.floating) _phoneDocked.remove(entry.sessionId);
}
_stackGroups.replaceAll({
for (final entry in snapshot.entries) entry.sessionId: ?entry.group,
});
if (windows != null && phone) {
// A phone tiles the floating chats too; they float again when the
// layout is wide.
for (final entry in snapshot.entries.where((e) => e.floating)) {
_phoneDocked.add(entry.sessionId);
final window = windows.windows
.where((window) => window.contentId == entry.sessionId)
.firstOrNull;
if (window != null) windows.manager.close(window.id);
}
}
if (windows != null && !phone) {
final entriesBySession = {
for (final entry in snapshot.entries) entry.sessionId: entry,
};
@@ -260,7 +298,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
}
_workspace.reconcileSessions(
snapshot.entries
.where((entry) => !entry.floating)
.where((entry) => phone || !entry.floating)
.map((entry) => entry.sessionId),
);
if (keepInitial) {
@@ -365,6 +403,11 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
if (_workspaceSignature == signature) return;
_workspaceSignature = signature;
// A phone-held floating chat the operator closed is no longer open.
_phoneDocked.removeWhere((id) => !_workspace.holdsSession(id));
_stackGroups.retain({
for (final entry in _serverWorkspaceEntries()) entry.sessionId,
});
_syncOpenWorkspace();
_touchActiveChat();
void update() {
@@ -486,10 +529,12 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
Widget _stackScope(BuildContext context, bool active, Widget child);
Widget _stackOverlay();
MobileChatNavigationController get _navigation;
void _trackFloatLayout();
Widget _workspaceView() => ListenableBuilder(
listenable: _navigation,
builder: (context, _) {
_trackFloatLayout();
final stacked = _stacked(context);
final workspace = _tiledWorkspace(context, stacked: stacked);
if (!stacked) return workspace;
+8 -1
View File
@@ -14,7 +14,7 @@ import 'dart:async';
import '../../ui/motion/motion.dart';
import '../../ui/motion/container_transform_source.dart';
import 'package:flutter/foundation.dart' show setEquals;
import 'package:flutter/foundation.dart' show defaultTargetPlatform, setEquals;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
@@ -43,10 +43,12 @@ import 'conversation/chat_quick_switch_dialog.dart';
import 'conversation/chat_sidebar_controls.dart';
import 'ui/sessions/chat_compact_sidebar.dart';
import 'workspace/chat_workspace.dart';
import 'stack/chat_stack_actions.dart';
import 'stack/chat_stack_anchor.dart';
import 'stack/chat_stack_column.dart';
import 'stack/chat_stack_entry.dart';
import 'stack/chat_stack_fab.dart';
import 'stack/chat_stack_groups.dart';
import 'stack/mobile_chat_navigation.dart';
import 'workspace/chat_center_stage_action.dart';
import 'workspace/chat_center_stage_controller.dart';
@@ -78,6 +80,7 @@ part 'chat_screen_keys.dart';
part 'chat_screen_list_toggle.dart';
part 'chat_screen_quick_switch.dart';
part 'chat_screen_stack.dart';
part 'chat_screen_stack_groups.dart';
part 'chat_screen_workspace.dart';
/// The Chat destination's list/detail switch.
@@ -144,6 +147,7 @@ class _ChatScreenState extends State<ChatScreen>
_ChatScreenPaneMenu,
_ChatScreenQuickSwitch,
_ChatScreenAttention,
_ChatScreenStackGroups,
_ChatScreenStack,
_ChatScreenListToggle {
/// The chats' shared state: the list, opened rows, accepted models,
@@ -195,6 +199,7 @@ class _ChatScreenState extends State<ChatScreen>
_runtime.recency.touch(initial);
}
_workspace.addListener(_workspaceChanged);
_stackGroups.addListener(_syncOpenWorkspace);
_bindWorkspacePersistence();
HardwareKeyboard.instance.addHandler(_cycleChatKey);
HardwareKeyboard.instance.addHandler(_slashFocusKey);
@@ -493,6 +498,7 @@ class _ChatScreenState extends State<ChatScreen>
_page.dispose();
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
_stackGroups.dispose();
_unbindWindows();
_unbindQuickSwitch();
_unbindAttention();
@@ -570,6 +576,7 @@ class _ChatScreenState extends State<ChatScreen>
(_) => _publishWorkspaceRoute(),
);
}
_trackFloatLayout();
_offeredNext = selected != null && _nextAfter(selected) != null;
// A phone opens a chat as a real Navigator page with stock Back. A wide
// window keeps the destination rail and the chat list beside the open
@@ -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;
}
@@ -0,0 +1,126 @@
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_stack_disc.dart';
/// How near the close button's centre a dragged chat's pointer counts as
/// over it: a little past its rim, as a thumb covers what it drags, and
/// short of the first chat's slot a pitch above.
const double kChatStackRemoveReach = kChatStackSlot * .7;
/// How much the button grows while a dragged chat is over it.
const double chatStackRemoveGrowth = 1.2;
/// The open stack's close button, exactly where the pile was: the pile
/// turns into a "×" as the column rises above it, and a tap folds the
/// column back.
///
/// While a chat is dragged it is also the remove target: its "×" turns the
/// error colour ([armed]), and with the chat over it ([hover]) it grows and
/// fills with the error colour. Dropping there is decided from the
/// pointer's position, not by this widget.
///
/// Everything moves through transitions (fade, turn, scale, decoration), so
/// opening and dragging repaint it without rebuilding.
class ChatStackCloseTarget extends StatelessWidget {
const ChatStackCloseTarget({
super.key,
required this.open,
required this.armed,
required this.hover,
required this.reduced,
required this.onClose,
});
static const label = 'Close chats';
/// 0 folded (the pile shows), 1 open.
final Animation<double> open;
/// 0 at rest, 1 while a chat is dragged.
final Animation<double> armed;
/// 0 idle, 1 with a dragged chat over it.
final Animation<double> hover;
/// Fades only: no turn, no growth.
final bool reduced;
final VoidCallback onClose;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
final scheme = Theme.of(context).colorScheme;
final dark = Theme.of(context).brightness == Brightness.dark;
final shape = chatStackShape(tokens);
final side = tokens.flat
? tokens.frameSide ?? BorderSide(color: scheme.outlineVariant)
: BorderSide.none;
final idle = ShapeDecoration(
color: tokens.panelFill(
scheme,
dark ? scheme.surfaceContainerHighest : scheme.surface,
),
shape: shape.copyWith(side: side),
shadows: tokens.flat ? null : chatStackShadows(scheme),
);
final hot = ShapeDecoration(
color: scheme.error,
shape: shape.copyWith(
side: tokens.flat ? side.copyWith(color: scheme.error) : side,
),
shadows: tokens.flat ? null : chatStackShadows(scheme),
);
Widget icon(Color color, Animation<double> opacity) => FadeTransition(
opacity: opacity,
child: Icon(Icons.close, color: color),
);
Widget button = DecoratedBoxTransition(
decoration: DecorationTween(begin: idle, end: hot).animate(hover),
child: SizedBox.square(
dimension: kChatStackDisc,
child: Stack(
alignment: Alignment.center,
children: [
icon(scheme.onSurfaceVariant, ReverseAnimation(armed)),
icon(scheme.error, armed),
icon(scheme.onError, hover),
],
),
),
);
final shown = open.drive(CurveTween(curve: Curves.easeOutCubic));
if (!reduced) {
button = ScaleTransition(
scale: Tween<double>(
begin: 1,
end: chatStackRemoveGrowth,
).chain(CurveTween(curve: Curves.easeOutBack)).animate(hover),
child: button,
);
// The pile's top avatar turns into the "×" a quarter turn.
button = RotationTransition(
turns: Tween<double>(begin: -.25, end: 0).animate(shown),
child: ScaleTransition(
scale: Tween<double>(begin: .6, end: 1).animate(shown),
child: button,
),
);
}
return Semantics(
container: true,
button: true,
label: label,
onTap: onClose,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
excludeFromSemantics: true,
onTap: onClose,
child: FadeTransition(
opacity: shown,
child: Center(child: button),
),
),
);
}
}
+205 -196
View File
@@ -1,46 +1,70 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_stack_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_pose.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.
///
/// 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".
/// The stack's own slot turns into a close button ([ChatStackCloseTarget]);
/// 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 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 fades through [FadeTransition], both
/// repaint-only.
class ChatStackColumn extends StatelessWidget {
/// `ChatStackPoseTransition` and `ChatStackDragShift` and fades through
/// [FadeTransition], all repaint-only; a drag rebuilds the column only as it
/// starts and ends.
class ChatStackColumn extends StatefulWidget {
const ChatStackColumn({
super.key,
required this.motion,
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.
@@ -52,12 +76,105 @@ class ChatStackColumn extends StatelessWidget {
final VoidCallback onAdd;
final VoidCallback onDismiss;
/// Long press removes a chat from the open chats; null when it cannot
/// (the only open chat).
/// 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;
/// 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 addLabel = 'Add chat';
static const moveUpLabel = 'Move up';
static const moveDownLabel = 'Move down';
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, _ChatStackColumnGroups {
@override
late final ChatStackDrag _drag = ChatStackDrag(
vsync: this,
pitch: kChatStackPitch,
)..addListener(_dragChanged);
/// The remove target's centre in this column's box, from the last layout.
Offset? _removeCenter;
@override
void initState() {
super.initState();
_initGroups();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_drag.reduced = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
}
@override
void didUpdateWidget(covariant ChatStackColumn oldWidget) {
super.didUpdateWidget(oldWidget);
// Folding, or the items changing under the finger (another device),
// puts the dragged item back.
if (!widget.interactive ||
(_drag.dragging && !listEquals(_dragOrder(), _drag.order))) {
_drag.cancel();
}
_groupsUpdated(oldWidget);
}
@override
void dispose() {
_drag.dispose();
_disposeGroups();
super.dispose();
}
void _dragChanged() {
if (mounted) setState(() {});
}
@override
void _move(LongPressMoveUpdateDetails details) {
if (!_drag.dragging) return;
final box = context.findRenderObject() as RenderBox?;
final center = _removeCenter;
final over =
widget.onRemove != null &&
box != null &&
center != null &&
(box.globalToLocal(details.globalPosition) - center).distance <=
kChatStackRemoveReach;
_drag.move(details.offsetFromOrigin, overRemove: over);
}
void _escape() {
if (_drag.dragging) {
_drag.cancel();
} else if (widget.group.value != null) {
widget.group.value = null;
} else {
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) {
@@ -65,55 +182,72 @@ class ChatStackColumn extends StatelessWidget {
final scheme = Theme.of(context).colorScheme;
final dark = Theme.of(context).brightness == Brightness.dark;
final rtl = Directionality.of(context) == TextDirection.rtl;
final anchor = widget.anchor;
return LayoutBuilder(
builder: (context, constraints) {
final size = constraints.biggest;
final count = motion.count;
final height = (count - 1) * kChatStackPitch + kChatStackSlot;
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.
final order = [for (var i = 0; i < count; i++) i]
..sort((a, b) => (depths[b] ?? 99).compareTo(depths[a] ?? 99));
final items = Stack(
// 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(
key: const ValueKey('chat-stack-close'),
rect: anchor,
child: IgnorePointer(
ignoring: _drag.lifted != null,
child: ChatStackCloseTarget(
open: widget.motion.close,
armed: _drag.removeShown,
hover: _drag.hover,
reduced: _drag.reduced,
onClose: widget.onDismiss,
),
),
);
final layers = Stack(
clipBehavior: Clip.none,
children: [
for (final i in order) ...[
_label(context, i, labelMax),
_item(context, i),
],
_topLayer(labelMax, inGroup: _openGroup != null),
if (open != null) _groupLayer(open, labelMax),
],
);
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.escape): onDismiss,
},
bindings: {const SingleActivator(LogicalKeyboardKey.escape): _escape},
child: FocusScope(
autofocus: true,
child: IgnorePointer(
ignoring: !interactive,
ignoring: !widget.interactive,
child: Stack(
children: [
Positioned.fill(
child: FadeTransition(
opacity: motion.scrim,
opacity: widget.motion.scrim,
child: ModalBarrier(
color: scheme.scrim.withValues(alpha: dark ? .5 : .32),
dismissible: true,
onDismiss: onDismiss,
semanticsLabel: 'Close chats',
onDismiss: _scrim,
semanticsLabel: 'Dismiss',
),
),
),
// 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(
key: const ValueKey('chat-stack-column'),
end: endInset,
bottom: size.height - anchor.bottom,
top: top,
@@ -130,12 +264,13 @@ class ChatStackColumn extends StatelessWidget {
container: true,
explicitChildNodes: true,
label: 'Open chats',
child: items,
child: layers,
),
),
),
),
),
if (_drag.lifted == null) close,
],
),
),
@@ -145,168 +280,42 @@ class ChatStackColumn extends StatelessWidget {
);
}
Widget _item(BuildContext context, int i) {
final entry = i < entries.length ? entries[i] : null;
return PositionedDirectional(
key: ValueKey('chat-stack-item-${entry?.paneId ?? 'add'}'),
end: 0,
bottom: 0,
// The transform is outermost: the boxes under it sit at the stack's
// slot, and only a transform passes hits on to where it paints them.
child: ChatStackPoseTransition(
progress: motion.move[i],
from: motion.from[i],
to: motion.target[i],
child: FadeTransition(
opacity: motion.fade[i],
child: KeyedSubtree(
key: ValueKey('chat-stack-button-${entry?.paneId ?? 'add'}'),
child: entry == null ? _addButton(context) : _chatButton(entry),
),
),
/// 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),
),
);
}
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,
),
),
),
),
],
);
/// 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),
};
}
}
@@ -0,0 +1,371 @@
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import '../../../ui/theme/app_design_tokens.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 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.nodes,
required this.tail,
required this.order,
required this.labelMax,
required this.drag,
required this.draggable,
required this.onOpen,
required this.onTail,
required this.onDragStart,
required this.onDragMove,
required this.onDragEnd,
required this.actionsFor,
this.tailActions,
});
final ChatStackMotion motion;
final List<ChatStackNode> nodes;
final ChatStackTail tail;
/// 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 an item.
final bool draggable;
final ValueChanged<ChatStackNode> onOpen;
final VoidCallback onTail;
final ValueChanged<ChatStackNode> onDragStart;
final ValueChanged<LongPressMoveUpdateDetails> onDragMove;
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(
clipBehavior: Clip.none,
children: [
for (final i in order) ...[_label(context, i), _item(context, i)],
],
);
ChatStackNode? _node(int i) => i < nodes.length ? nodes[i] : null;
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: node == null ? null : () => onDragEnd(node),
onCancel: drag.cancel,
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,
);
}
/// 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 node = _node(i);
final name = _keyOf(node);
return PositionedDirectional(
key: ValueKey('chat-stack-item-$name'),
end: 0,
bottom: 0,
// The transforms are outermost: the boxes under them sit at the
// stack's slot, and only a transform passes hits on to where it paints
// them.
child: ChatStackPoseTransition(
progress: motion.move[i],
from: motion.from[i],
to: motion.target[i],
child: _shift(
i,
FadeTransition(
opacity: motion.fade[i],
child: KeyedSubtree(
key: ValueKey('chat-stack-button-$name'),
child: switch (node) {
ChatStackChatNode() => _chatButton(context, node, i),
ChatStackGroupNode() => _groupButton(context, node, i),
null => _tailButton(context),
},
),
),
),
),
);
}
Widget _label(BuildContext context, int 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-${_keyOf(node)}'),
end: kChatStackSlot + kChatStackLabelGap,
bottom: 0,
height: kChatStackSlot,
child: ChatStackPoseTransition(
progress: motion.label[i],
from: motion.labelFrom[i],
to: motion.target[i],
// The pill moves with its avatar but keeps its size, so the gap
// between them stays even.
child: _shift(
i,
scales: false,
ExcludeSemantics(
child: FadeTransition(
opacity: motion.label[i],
child: Align(
alignment: AlignmentDirectional.centerEnd,
widthFactor: 1,
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: labelMax),
child: _handle(
node,
GestureDetector(
onTap: node == null ? onTail : () => onOpen(node),
child: label,
),
),
),
),
),
),
),
),
);
}
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;
final (lift, liftRing) = _lift(context, node.key);
return _semantics(
node,
i,
label: entry.title,
selected: entry.current,
hint: entry.current ? 'Open now' : null,
child: _handle(
node,
ChatStackTappable(
autofocus: entry.current,
onTap: () => onOpen(node),
child: ChatStackDisc(
ring: ring,
lift: lift,
liftRing: liftRing,
child: chatStackAvatar(entry),
),
),
),
);
}
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,
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: onTail,
child: ChatStackDisc(
lift: lift,
liftRing: ring,
child: DecoratedBox(
decoration: ShapeDecoration(
color: tokens.flat || header ? null : scheme.primaryContainer,
shape: chatStackShape(tokens).copyWith(
side: tokens.flat
? BorderSide(color: scheme.primary.withValues(alpha: .55))
: BorderSide.none,
),
),
child: Icon(
header ? Icons.arrow_back : Icons.add,
color: tokens.flat || header
? scheme.primary
: scheme.onPrimaryContainer,
),
),
),
),
);
}
}
/// 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),
),
);
}
+138 -22
View File
@@ -22,13 +22,26 @@ const double kChatStackLabelGap = 10;
/// through each other, and its rim separates them. A raised design drops a
/// short shadow; a flat one casts none, and its avatar frames itself.
class ChatStackDisc extends StatelessWidget {
const ChatStackDisc({super.key, required this.child, this.ring});
const ChatStackDisc({
super.key,
required this.child,
this.ring,
this.lift,
this.liftRing,
});
final Widget child;
/// The rim's colour when it marks the current chat; null for the surface.
final Color? ring;
/// While dragged (0 at rest, 1 lifted): a deeper shadow, or under a flat
/// design a frame in the primary colour.
final Animation<double>? lift;
/// A drop target's ring colour, worn as [lift] runs.
final Color? liftRing;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
@@ -42,16 +55,20 @@ class ChatStackDisc extends StatelessWidget {
);
final ring = this.ring;
final shape = chatStackShape(tokens);
final rest = ShapeDecoration(
color: ring ?? base,
// A flat design's avatar frames itself; the rim stays bare.
shape: shape,
shadows: !tokens.flat ? chatStackShadows(scheme) : null,
);
final lift = this.lift;
return SizedBox.square(
dimension: kChatStackSlot,
child: Center(
child: DecoratedBox(
decoration: ShapeDecoration(
color: ring ?? base,
// A flat design's avatar frames itself; the rim stays bare.
shape: shape,
shadows: !tokens.flat ? chatStackShadows(scheme) : null,
),
child: chatStackLifted(
lift,
rest,
chatStackRaised(rest, tokens, scheme, ring: liftRing),
child: SizedBox.square(
dimension: kChatStackDisc,
child: Center(
@@ -93,6 +110,59 @@ List<BoxShadow> chatStackShadows(ColorScheme scheme) => [
),
];
/// A short, close shadow's lifted form: deeper and softer, as a card
/// picked up off the column.
List<BoxShadow> chatStackLiftShadows(ColorScheme scheme) => [
BoxShadow(
color: scheme.shadow.withValues(alpha: .20),
blurRadius: 8,
offset: const Offset(0, 4),
),
BoxShadow(
color: scheme.shadow.withValues(alpha: .14),
blurRadius: 22,
offset: const Offset(0, 12),
),
];
/// [rest] as a dragged item wears it: the lifted shadow, or under a flat
/// design (which casts none) a frame in the primary colour. With [ring] (a
/// drop target) every design gets a ring in that colour.
ShapeDecoration chatStackRaised(
ShapeDecoration rest,
AppDesignTokens tokens,
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: side != null && shape is OutlinedBorder
? shape.copyWith(side: side)
: shape,
shadows: tokens.flat ? null : chatStackLiftShadows(scheme),
);
}
/// [child] over [rest], or blending to [raised] as [lift] runs: repaints
/// only.
Widget chatStackLifted(
Animation<double>? lift,
ShapeDecoration rest,
ShapeDecoration raised, {
required Widget child,
}) => lift == null
? DecoratedBox(decoration: rest, child: child)
: DecoratedBoxTransition(
decoration: DecorationTween(begin: rest, end: raised).animate(lift),
child: child,
);
/// The name beside an avatar in the open column: a small pill tinted with
/// the chat's colour over an opaque face, one line, ellipsised.
class ChatStackLabel extends StatelessWidget {
@@ -101,12 +171,28 @@ class ChatStackLabel extends StatelessWidget {
required this.text,
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;
/// While dragged, as [ChatStackDisc.lift].
final Animation<double>? lift;
@override
Widget build(BuildContext context) {
final tokens = AppDesignTokens.of(context);
@@ -122,26 +208,56 @@ class ChatStackLabel extends StatelessWidget {
color: scheme.onSurface,
fontWeight: emphasized ? FontWeight.w700 : FontWeight.w500,
);
return DecoratedBox(
decoration: ShapeDecoration(
color: fill,
shape: _labelShape(tokens),
shadows: tokens.flat ? null : chatStackShadows(scheme),
),
final rest = ShapeDecoration(
color: fill,
shape: _labelShape(tokens),
shadows: tokens.flat ? null : chatStackShadows(scheme),
);
return chatStackLifted(
lift,
rest,
chatStackRaised(rest, tokens, scheme, 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,
],
],
),
),
);
}
ShapeBorder _labelShape(AppDesignTokens tokens) {
OutlinedBorder _labelShape(AppDesignTokens tokens) {
final side = tokens.frameSide ?? BorderSide.none;
final r = tokens.radius;
return r == null
@@ -0,0 +1,341 @@
import 'dart:ui' show lerpDouble;
import 'package:flutter/animation.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'chat_stack_drop_target.dart';
part 'chat_stack_drag_types.dart';
/// 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 {
lift = AnimationController(vsync: vsync, duration: chatStackShiftDuration)
..addListener(_paintLifted);
settle =
AnimationController(vsync: vsync, duration: chatStackSettleDuration)
..addListener(_paintLifted)
..addStatusListener(_settled);
removeShown = AnimationController(
vsync: vsync,
duration: chatStackRemoveDuration,
);
hover = AnimationController(vsync: vsync, duration: chatStackHoverDuration)
..addListener(_paintLifted);
_ontoAny = AnimationController(
vsync: vsync,
duration: chatStackHoverDuration,
)..addListener(_paintLifted);
}
/// 1 while the item is over another's middle: it shrinks onto it, so the
/// target's grown ring shows around it.
late final AnimationController _ontoAny;
final TickerProvider _vsync;
/// The distance between neighbouring slots.
final double pitch;
/// Under reduced motion neighbours swap at once and nothing slides.
bool reduced = false;
late final AnimationController lift;
late final AnimationController settle;
/// The remove target 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 item being dragged or settling; it paints above the others.
String? get lifted => _lifted;
String? _lifted;
/// 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;
bool get dragging => _order != null;
bool get overRemove => _over;
/// 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 [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 = key;
HapticFeedback.mediumImpact();
if (reduced) {
lift.value = 1;
removeShown.value = 1;
} else {
lift.forward(from: 0);
removeShown.forward();
}
hover.value = 0;
notifyListeners();
}
/// The pointer moved [fromOrigin] since the press; [overRemove] says
/// whether it is over the remove target.
void move(Offset fromOrigin, {required bool overRemove}) {
final order = _order;
if (order == null) return;
_pointer = fromOrigin;
if (overRemove != _over) {
_over = overRemove;
if (overRemove) HapticFeedback.selectionClick();
_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);
_run(_ontoAny, onto == null ? 0 : 1);
}
if (slot != _slot) {
if (slot != null && _slot != null) HapticFeedback.selectionClick();
_slot = slot;
_shiftNeighbours(animate: !reduced);
}
_paintLifted();
}
/// Ends the drag and says what the drop does; the motion back (or into
/// the new slot) runs from here.
ChatStackDrop end() {
final order = _order;
if (order == null) return const ChatStackDropBack();
final slot = _slot;
final 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 item glides from the finger into its new slot.
_residual = _pointer + Offset(0, (index - _from) * pitch);
_shiftNeighbours(animate: false);
case ChatStackDropRemove() || ChatStackDropOnto():
// It joins the target (or leaves): no glide back.
_residual = Offset.zero;
_shiftNeighbours(animate: false);
case ChatStackDropBack():
_residual = _pointer;
_shiftNeighbours(animate: !reduced);
}
_release(clearGlowAtOnce: drop is ChatStackDropOnto);
return drop;
}
/// Puts the item back where it was (Escape, a cancelled pointer, the
/// column folding).
void cancel() {
if (_order == null) return;
_order = null;
_slot = null;
_residual = _pointer;
_shiftNeighbours(animate: !reduced);
_release();
}
void _release({bool clearGlowAtOnce = false}) {
_pointer = Offset.zero;
if (_over) HapticFeedback.selectionClick();
_over = false;
_onto = null;
clearGlowAtOnce ? _ontoAny.value = 0 : _run(_ontoAny, 0);
for (final glow in _glows.values) {
clearGlowAtOnce ? glow.value = 0 : _run(glow, 0);
}
if (reduced) {
hover.value = 0;
removeShown.value = 0;
lift.value = 0;
_residual = Offset.zero;
_finishSettle();
return;
}
hover.reverse();
removeShown.reverse();
lift.reverse();
settle.forward(from: 0);
}
void _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 key = _lifted;
_residual = Offset.zero;
if (key != null) item(key)._set(Offset.zero, 1);
if (_order != null) return;
_lifted = null;
notifyListeners();
}
void _paintLifted() {
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)! *
lerpDouble(1, chatStackOverRemoveScale, _ontoAny.value)!;
final offset = _order != null
? _pointer
: _residual * (1 - _curve.transform(settle.value));
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 keys = {...order, ..._shifts.keys};
final slot = _slot;
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 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(key, () {
final shift = AnimationController.unbounded(vsync: _vsync);
shift.addListener(() => _paint(key));
return shift;
});
if (shift.value == target) continue;
if (animate) {
shift.animateTo(
target,
duration: chatStackShiftDuration,
curve: _curve,
);
} else {
shift
..stop()
..value = target;
}
}
}
@override
void dispose() {
lift.dispose();
settle.dispose();
removeShown.dispose();
hover.dispose();
_ontoAny.dispose();
for (final controller in [..._shifts.values, ..._glows.values]) {
controller.dispose();
}
for (final item in _items.values) {
item.dispose();
}
super.dispose();
}
}
@@ -0,0 +1,145 @@
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'chat_stack_drag.dart';
/// Paints [child] where [item] says while a chat of the open column is
/// dragged: moved, and scaled about its centre when [scales]. A change only
/// repaints (the matrix and the layer are reused); hit tests follow it. At
/// rest it paints straight through, with no layer.
class ChatStackDragShift extends SingleChildRenderObjectWidget {
const ChatStackDragShift({
super.key,
required this.item,
this.scales = true,
super.child,
});
final ChatStackDragItem item;
final bool scales;
@override
RenderChatStackDragShift createRenderObject(BuildContext context) =>
RenderChatStackDragShift(item: item, scales: scales);
@override
void updateRenderObject(
BuildContext context,
RenderChatStackDragShift renderObject,
) {
renderObject
..item = item
..scales = scales;
}
}
class RenderChatStackDragShift extends RenderProxyBox {
RenderChatStackDragShift({
required ChatStackDragItem item,
required bool scales,
}) {
_item = item;
_scales = scales;
}
late ChatStackDragItem _item;
set item(ChatStackDragItem value) {
if (identical(value, _item)) return;
if (attached) _item.removeListener(_changed);
_item = value;
if (attached) _item.addListener(_changed);
_changed();
}
late bool _scales;
set scales(bool value) {
if (value == _scales) return;
_scales = value;
_changed();
}
final Matrix4 _matrix = Matrix4.identity();
final LayerHandle<TransformLayer> _layer = LayerHandle<TransformLayer>();
bool get _moved =>
_item.offset != Offset.zero || (_scales && _item.scale != 1);
bool _wasMoved = false;
void _changed() {
// Entering or leaving rest adds or drops the transform layer.
final moved = _moved;
if (moved != _wasMoved) {
_wasMoved = moved;
markNeedsCompositingBitsUpdate();
}
markNeedsPaint();
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_wasMoved = _moved;
_item.addListener(_changed);
}
@override
void detach() {
_item.removeListener(_changed);
super.detach();
}
@override
void dispose() {
_layer.layer = null;
super.dispose();
}
@override
bool get alwaysNeedsCompositing => child != null && _moved;
Matrix4 _current() {
final offset = _item.offset;
final scale = _scales ? _item.scale : 1.0;
final cx = size.width / 2;
final cy = size.height / 2;
return _matrix
..setIdentity()
..translateByDouble(offset.dx + cx, offset.dy + cy, 0, 1)
..scaleByDouble(scale, scale, 1, 1)
..translateByDouble(-cx, -cy, 0, 1);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child == null) return;
if (!_moved) {
_layer.layer = null;
super.paint(context, offset);
return;
}
_layer.layer = context.pushTransform(
needsCompositing,
offset,
_current(),
super.paint,
oldLayer: _layer.layer,
);
}
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) {
if (!_moved) return super.hitTestChildren(result, position: position);
return result.addWithPaintTransform(
transform: _current(),
position: position,
hitTest: (result, position) =>
super.hitTestChildren(result, position: position),
);
}
@override
void applyPaintTransform(RenderBox child, Matrix4 transform) {
if (_moved) transform.multiply(_current());
}
}
@@ -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
@@ -20,6 +22,8 @@ class ChatStackFab extends StatefulWidget {
required this.onOpen,
required this.onAdd,
this.onRemove,
this.onReorder,
this.groups,
});
/// The open chats in their synced order; one is [ChatStackEntry.current].
@@ -30,6 +34,13 @@ class ChatStackFab extends StatefulWidget {
final ValueChanged<BuildContext> onAdd;
final ValueChanged<ChatStackEntry>? onRemove;
/// Puts the open chats in this order (session ids): a drag in the open
/// column, or its Move up and Move down actions.
final ValueChanged<List<String>>? onReorder;
/// Grouping the open chats; null when the host keeps no groups.
final ChatStackGroupActions? groups;
@override
State<ChatStackFab> createState() => ChatStackFabState();
}
@@ -48,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());
@@ -94,6 +108,7 @@ class ChatStackFabState extends State<ChatStackFab>
_motion?.dispose();
_open.dispose();
_focus.dispose();
_group.dispose();
super.dispose();
}
@@ -128,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;
@@ -156,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() {
@@ -191,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,
@@ -209,13 +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 = .88;
/// 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();
}
}
@@ -0,0 +1,95 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_stack_disc.dart';
import 'chat_stack_drag.dart';
/// Lifts [child] for a drag after a short hold ([chatStackLiftDelay]); a
/// quicker tap still reaches [child]'s own tap. Null callbacks leave the
/// child alone.
class ChatStackDragHandle extends StatelessWidget {
const ChatStackDragHandle({
super.key,
required this.child,
this.onStart,
this.onMove,
this.onEnd,
this.onCancel,
});
final Widget child;
final VoidCallback? onStart;
final ValueChanged<LongPressMoveUpdateDetails>? onMove;
final VoidCallback? onEnd;
final VoidCallback? onCancel;
@override
Widget build(BuildContext context) {
if (onStart == null) return child;
return RawGestureDetector(
// The items offer moving and removing as semantic actions instead.
excludeFromSemantics: true,
gestures: {
LongPressGestureRecognizer:
GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(
duration: chatStackLiftDelay,
debugOwner: this,
),
(recognizer) {
recognizer
..onLongPressStart = ((_) => onStart?.call())
..onLongPressMoveUpdate = onMove
..onLongPressEnd = ((_) => onEnd?.call())
..onLongPressCancel = onCancel;
},
),
},
child: child,
);
}
}
/// A disc's ink and focus: the splash is drawn over the disc (the disc is
/// opaque, so ink under it would never show), in the design's shape.
class ChatStackTappable extends StatelessWidget {
const ChatStackTappable({
super.key,
required this.child,
required this.onTap,
this.autofocus = false,
});
final Widget child;
final VoidCallback onTap;
final bool autofocus;
@override
Widget build(BuildContext context) {
final shape = chatStackShape(AppDesignTokens.of(context));
return Stack(
children: [
child,
Positioned.fill(
child: Padding(
padding: const EdgeInsets.all(
(kChatStackSlot - kChatStackDisc) / 2,
),
child: Material(
type: MaterialType.transparency,
shape: shape,
clipBehavior: Clip.antiAlias,
child: InkWell(
autofocus: autofocus,
excludeFromSemantics: true,
customBorder: shape,
onTap: onTap,
),
),
),
),
],
);
}
}
@@ -20,24 +20,30 @@ const Curve chatStackRise = Cubic(.22, 1.18, .36, 1);
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.
/// when the items change (never per frame). Item 0 is nearest the thumb, a
/// pitch above the stack's slot (where the close button is); 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,
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));
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);
// The stack's own slot holds the close button; the column starts a
// pitch above it.
final to = chatStackColumnPose(i + 1, kChatStackPitch);
final layer = chatStackLayers[depth ?? chatStackLayers.length - 1];
target.add(to);
if (reduced) {
@@ -48,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,
@@ -75,6 +89,9 @@ class ChatStackMotion {
final int count;
final bool reduced;
late final Animation<double> scrim;
/// The close button taking the pile's place.
late final Animation<double> close;
final List<ChatStackPose> from = [];
final List<ChatStackPose> target = [];
final List<Animation<double>> move = [];
@@ -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,
];
@@ -3,7 +3,8 @@ import 'package:shared_preferences/shared_preferences.dart';
const mobileChatNavigationKey = 'pipelines.mobile-chat-navigation.v1';
/// How a phone-width layout moves between the open chats.
/// How a phone-width layout (and any layout on a phone or tablet, an unfolded
/// foldable too, for the Chat stack) moves between the open chats.
enum MobileChatNavigation {
quickSwitch(
'Quick switch',
@@ -59,7 +60,11 @@ class MobileChatNavigationController extends ChangeNotifier {
static final instance = MobileChatNavigationController();
final MobileChatNavigationStore _store;
MobileChatNavigation _value = MobileChatNavigation.quickSwitch;
/// Without a stored choice, the Chat stack.
static const fallback = MobileChatNavigation.chatStack;
MobileChatNavigation _value = fallback;
int _revision = 0;
bool _disposed = false;
bool saveFailed = false;
@@ -91,6 +96,16 @@ class MobileChatNavigationController extends ChangeNotifier {
notifyListeners();
}
/// Sets [mode] without saving it (a test's starting point).
@visibleForTesting
void debugUse(MobileChatNavigation mode) {
_revision++;
saveFailed = false;
if (mode == _value) return;
_value = mode;
notifyListeners();
}
@override
void dispose() {
_disposed = true;
@@ -1,21 +1,33 @@
import '../../../core/api_gateway.dart';
/// One chat in the server-owned open-chat set: its session and whether it is
/// floating. Geometry stays on the device.
/// One chat in the server-owned open-chat set: its session, whether it is
/// floating, and the chat stack group it belongs to (entries sharing a name
/// form one group; null when ungrouped). Geometry stays on the device.
class ChatOpenWorkspaceEntry {
const ChatOpenWorkspaceEntry(this.sessionId, {this.floating = false});
const ChatOpenWorkspaceEntry(
this.sessionId, {
this.floating = false,
this.group,
});
final String sessionId;
final bool floating;
final String? group;
Map<String, dynamic> toJson() => {
'session_id': sessionId,
if (floating) 'floating': true,
if (group != null) 'group': group,
};
static ChatOpenWorkspaceEntry? fromJson(Object? value) {
if (value is! Map) return null;
final id = '${value['session_id'] ?? ''}'.trim();
final group = '${value['group'] ?? ''}'.trim();
return id.isEmpty
? null
: ChatOpenWorkspaceEntry(id, floating: value['floating'] == true);
: ChatOpenWorkspaceEntry(
id,
floating: value['floating'] == true,
group: group.isEmpty ? null : group,
);
}
}
@@ -37,7 +49,8 @@ class ChatOpenWorkspaceSnapshot {
if (list.length != entries.length) return false;
for (var i = 0; i < list.length; i++) {
if (list[i].sessionId != entries[i].sessionId ||
list[i].floating != entries[i].floating) {
list[i].floating != entries[i].floating ||
list[i].group != entries[i].group) {
return false;
}
}
@@ -163,6 +163,31 @@ class ChatWorkspaceController extends ChangeNotifier {
_changed();
}
/// Moves the pane [paneId] to [index] in the pane order (the open-chat
/// order the server syncs). The panes keep their ids and the splits their
/// geometry; only the leaves change slots. The active pane stays.
void movePane(String paneId, int index) {
final order = panes;
final from = order.indexWhere((pane) => pane.id == paneId);
if (from < 0) return;
final to = index.clamp(0, order.length - 1);
if (from == to) return;
order.insert(to, order.removeAt(from));
reorderSessions([for (final pane in order) pane.sessionId]);
}
/// Puts the panes in the order of [sessionIds], as [movePane] does; open
/// chats it does not name keep their relative order after them.
void reorderSessions(List<String> sessionIds) {
final open = [for (final pane in panes) pane.sessionId];
final named = sessionIds.where(open.contains).toSet();
final order = [...named, ...open.where((id) => !named.contains(id))];
final next = reconcileChatWorkspaceTree(_root, order, _id);
if (identical(next, _root)) return;
_root = next;
_changed();
}
void resize(String splitId, double ratio) {
if (_root == null || !ratio.isFinite) return;
_root = _resize(_root!, splitId, ratio.clamp(.01, .99));
@@ -27,8 +27,9 @@ class SettingsChatNavigationSection extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'Saved on this device. Applies on a phone-width window; a wide '
'window keeps the chat list beside the chats.',
'Saved on this device. Applies on a phone-width window; the '
'Chat stack also stays on a wide phone or tablet layout (an '
'unfolded foldable), beside the chat list.',
),
if (navigation.saveFailed)
Text(
+6 -2
View File
@@ -3,8 +3,12 @@
## Behaviour
The authenticated `/connect` protocol stores one bounded ordered open-chat set
per server scope (`default`). Entries hold only an operator session id and a
floating bit; split ratios, pane ids and window rectangles stay on the device.
per server scope (`default`). Entries hold only an operator session id, a
floating bit and an optional chat stack `group` name (entries sharing a name
form one group; trimmed, printable, at most 80 characters, refused otherwise;
older clients ignore it); split ratios, pane ids and window rectangles stay on
the device. The `group` field needs the server rebuilt and restarted: an
older server drops it.
* `chat_open_workspace` without `chat_open_workspace_request` reads the set.
With a request it replaces the set as a compare-and-swap on `base_revision`:
+97 -12
View File
@@ -2,27 +2,49 @@
## Setting
Settings → Mobile chat navigation: Quick switch (default, the next chat's
peek under the current one) or Chat stack. Per device
(`pipelines.mobile-chat-navigation.v1`, `MobileChatNavigationController`,
restored in `bootstrap.dart`), applied live, and only on a phone-width layout
(`!showsListBesideDetail`). A wide window keeps its panes and shows no stack.
Settings → Mobile chat navigation: Chat stack (the default without a stored
choice) or Quick switch (the next chat's peek under the current one). Per
device (`pipelines.mobile-chat-navigation.v1`, `MobileChatNavigationController`,
restored in `bootstrap.dart`; a stored choice is kept), applied live. It
applies on a phone-width layout (`!showsListBesideDetail`); the Chat stack
also stays on a wide layout on Android or iOS (an unfolded foldable, a
tablet, a browser on one), floating above the active pane beside the list
(`chatStackOnMobile`). A wide desktop or web window keeps its panes alone.
Widget tests run as Android: `test/features/chat/flutter_test_config.dart`
starts each chat test on Quick switch (`debugUse`); the stack's tests pick it.
## Behaviour
- The stack's chats are the workspace's panes: the same open-chat set the
server syncs (`ChatOpenWorkspaceController`). Choosing one opens it as a tap
on its list row does (`_openBySelection`); Add chat is the pane menu's Add
chat pane picker (searchable, the list's own rows) titled "Add chat";
long press removes the chat's pane, with an Undo snack bar that re-adds it
and keeps the chat on screen.
chat pane picker (searchable, the list's own rows) titled "Add chat".
- Drag: in the open column a 300 ms hold (a quicker tap still opens) lifts
a chat with its pill: a medium haptic, 1.1x scale and a deeper shadow
(flat designs: a primary-colour frame instead). Dragged up or down, the
others slide aside (200 ms ease-out) to open its slot, with a selection
tick per slot; dropping commits through `ChatWorkspaceController.movePane`
(the pane order the server syncs as the open-chat order). The close
button at the stack's slot is the remove target while dragging: its "×"
turns the error colour, and over it (a reach of 0.7 slot around its
centre, short of item 0 a pitch above) it grows 1.2x and fills with the
error colour, and the chat shrinks into it. Dropping there removes the pane with the Undo snack bar; Undo re-adds
it at its old index and keeps the chat on screen. A drop far to the side
(more than 1.5 pitches) or Escape or a cancelled pointer puts it back.
Add chat never lifts and is never a slot. Semantics: Move up, Move down,
Remove from open chats as custom actions on each chat. Reduced motion:
neighbours swap at once, the lift and settle are instant, the "×" only
fades and does not grow.
- Collapsed: up to four avatars piled with small offsets and turns, the chat
on screen on top; a count badge when more are open, and a bell when another
open chat waits on the operator. It sits bottom-end in the active chat's
transcript area, just above the composer, so it never covers Send; the
transcript pads its last line and Jump to latest above it. It hides while
the on-screen keyboard is up (the window's view insets).
- Expanded: a scrim, and a column rising from the stack's slot. The chats keep
- Expanded: a scrim; the pile turns into a close button ("×", a quarter
turn and scale in, `ChatStackCloseTarget`) exactly where it was, so a
second tap on the same spot folds the column; the column rises from one
pitch above it. The chats keep
the open-chat order bottom-up (stable positions for muscle memory); the chat
on screen wears a ring in its colour; each avatar keeps its list badges
(waiting, working, background tasks) and has a name pill tinted with its
@@ -31,21 +53,84 @@ restored in `bootstrap.dart`), applied live, and only on a phone-width layout
- Motion: one controller, 280 ms open (staggered, a slight-overshoot ease),
220 ms fold (top first). Items move through `ChatStackPoseTransition`, a
repaint-only transform render object that reuses its matrix and layer; no
per-frame rebuilds, no blur. Reduced motion: a 120 ms plain fade in place.
per-frame rebuilds, no blur. A drag adds `ChatStackDragShift` (same idea,
driven by a per-item notifier, no layer at rest); the column rebuilds only
when a drag starts and ends. Reduced motion: a 120 ms plain fade in place.
- Design tokens: circle discs with a short shadow under Default; the design's
square corners and no shadow under flat designs (Terminal, Paper); label
pills take the design radius and frame.
## Groups
- A group is a named set of open chats (`ChatStackGroups`, sessionId → name);
it travels with the open-chat set as each entry's `group`, so it persists
and syncs across devices like the order. Two chats at least: one left
alone leaves its group. Its chats stay together in the open-chat order.
- Top level: each group is one item where its first chat is, its chats piled
as the collapsed stack piles (0.88 scale, the chat on screen on top), the
pill showing its name and count, the bell aggregated. A tap opens it: the
top level fades out (no input) and the group's chats rise from its pile
(280 ms, the same motion as the stack), under a header (back arrow, the
name, a ⋯ menu). The header, the scrim, Back and Escape return to the top
level; a second tap outside folds the stack. Folding always ends on the
top level.
- Drag: the middle half of another item is a drop onto it (it grows 1.14x
and rings in the primary colour, a selection tick); its outer quarters
move the gap (`chatStackDropTarget`: the gap holds within half a slot, so
an item sliding aside never lands back under the finger). Chat onto chat:
a new group ("Group N", the name dialog opens at once, selected); chat
onto group: joins, last; group onto chat: takes it in; group onto group:
merges. In an open group a chat dropped on the header leaves the group
(placed right after it), and the close button removes it from the open
chats. A group dropped on the close button is ungrouped, with Undo.
- Menu (header ⋯) and semantic actions on a group: Rename group, Ungroup,
Close all chats in group (with Undo, restoring order and group). On a
chat: Move up / Move down (within its level), Move to group… (when groups
exist), Remove from group (in a group), Remove from open chats.
- Server: `internal/protocol/chat_open_workspace.go` (`Group`),
`internal/pipeline/chat_open_workspace.go` (validation, stored in the
entries JSON, compared as part of the entry), `internal/server` (copied
through). Needs a server restart.
## Structure
- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column, FAB,
- `lib/features/chat/stack/`: setting, pose, motion, disc/label, column and
its items, drag (session, shift render object, handles, remove target), FAB,
anchor (a `LayerLink` the active pane's transcript marks; the one stack
above the workspace follows it, so it survives switching chats).
- `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove.
- Groups: `chat_stack_groups.dart` (model), `chat_stack_node.dart` (top-level
items), `chat_stack_group_ops.dart` (orders after a drop),
`chat_stack_drop_target.dart`, `chat_stack_group_pile.dart`,
`chat_stack_group_dialogs.dart`, `chat_stack_column_groups.dart`.
- `lib/features/chat/chat_screen_stack.dart`: entries, open/add/remove;
`chat_screen_stack_groups.dart`: join/leave/rename/ungroup/close all.
- `chat_thread_view.dart`: anchor target, bottom clearance, Jump offset.
- `tool/search_selection_probe_entry.dart`: `?chatNav=stack`.
## Floating chats on a phone
A phone layout (Quick switch or Chat stack) ignores floating: windows are
hidden below `kListDetailMinWidth`, so each floating chat is held as an
ordinary pane (`_phoneDocked` in `chat_screen_workspace.dart`) and the
server's set keeps it `floating`. Widening the window (a foldable opened, a
desktop resized) floats those chats again; closing one on the phone drops
it from the open chats. Tests: `test/features/chat/chat_floating_phone_test.dart`.
## Captures
Drag captures use the kit's mouse `drag` with `press: 700`: with Flutter
web semantics on (the kit turns it on), the engine's click debouncer holds a
press on a tappable node for about 200 ms before the framework sees it, so
a 300 ms hold needs about 500 ms in the browser. Not an issue on a device
without a screen reader.
## Not verified
On-device behaviour (Android keyboard insets, haptics) was not run on a
device; web captures used Chrome's touch emulation at 390x844.
Drag limits: no auto-scroll while dragging; when the column is taller than
the screen it scrolls and clips, so a lifted chat cannot leave the clipped
column to reach the "×" there (Move and Remove remain as semantic actions).
The drag captures used the mouse (CDP), not touch; on-device haptics and the
hold feel are unverified.
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_session.dart';
@@ -29,6 +30,12 @@ Widget host(AppSession session, {String? initialSessionId}) => MaterialApp(
);
void main() {
// These describe the Quick switch layout (the peek of the next chat).
setUp(
() => MobileChatNavigationController.instance.debugUse(
MobileChatNavigation.quickSwitch,
),
);
testWidgets('nothing is requested before the shared socket is ready', (
tester,
) async {
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -296,6 +297,12 @@ Future<void> replyChatHistory(
}
void main() {
// These describe the Quick switch layout (the peek of the next chat).
setUp(
() => MobileChatNavigationController.instance.debugUse(
MobileChatNavigation.quickSwitch,
),
);
testWidgets(
'a wide /chat/s1 deep link shows that thread beside the list and route Back returns to /chat',
(tester) async {
@@ -0,0 +1,287 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
import 'package:pipelines_app/features/chat/windows/chat_windows.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/shell/windows/window_host.dart';
import 'package:pipelines_app/shell/windows/window_kind.dart';
import 'package:pipelines_app/shell/windows/window_manager.dart';
import 'package:pipelines_app/shell/windows/window_store.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'conversation/chat_thread_fixtures.dart';
/// A chat server with an open-chat set whose entries may float.
class _Server extends FakeChatGateway {
_Server(this.open, this.floating);
List<String> open;
Set<String> floating;
int revision = 1;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'c'])
{'id': id, 'title': 'Chat $id', 'directory': '/home/$id'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
if (type == 'chat_open_workspace') {
final request = fields['chat_open_workspace_request'] as Map?;
var rejected = false;
if (request != null && request['seed'] != true) {
if (request['base_revision'] != revision) {
rejected = true;
} else {
final entries = (request['entries'] as List).cast<Map>();
open = [for (final e in entries) '${e['session_id']}'];
floating = {
for (final e in entries)
if (e['floating'] == true) '${e['session_id']}',
};
revision++;
}
}
return Future.value({
'type': 'chat_open_workspace',
'chat_open_workspace': _body(rejected),
});
}
return super.call(type, fields);
}
JsonMap _body([bool rejected = false]) => {
'revision': revision,
'entries': [
for (final id in open)
{'session_id': id, if (floating.contains(id)) 'floating': true},
],
if (rejected) 'rejected': true,
};
void change(List<String> ids, Set<String> floats) {
open = ids;
floating = floats;
revision++;
emitRaw({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _body(),
});
}
}
class _Store implements WindowStore {
String? value;
@override
Future<String?> read() async => value;
@override
Future<bool> write(String record) async {
value = record;
return true;
}
}
const _wide = Size(1800, 1000);
const _phone = Size(390, 844);
class _App {
late final _Server server;
late final ChatRuntime runtime;
late final WindowManager manager;
late final ChatWindows windows;
Future<void> start(WidgetTester tester, {Size size = _wide}) async {
SharedPreferences.setMockInitialValues({});
_resize(tester, size);
addTearDown(tester.view.reset);
server = _Server(['a', 'b'], {'b'})..history = (_) async => chatPage([]);
bindServerIdentity(server, 'server-a');
runtime = ChatRuntime(gateway: server, serverKey: 'server-a');
manager = WindowManager(
kinds: WindowKinds(),
store: _Store(),
server: 'server-a',
);
windows = ChatWindows(
manager: manager,
runtime: runtime,
openInChat: (_) {},
)..start();
await manager.restore();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
ChatScreen(
gateway: server,
persistWorkspace: true,
runtime: runtime,
windows: windows,
),
Positioned.fill(child: WindowHost(manager: manager)),
],
),
),
),
);
await tester.pumpAndSettle();
}
Future<void> stop(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.shrink());
windows.dispose();
runtime.dispose();
manager.dispose();
server.close();
}
List<String> get floatingWindows => [
for (final w in windows.windows) w.contentId,
];
}
void _resize(WidgetTester tester, Size size) {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
}
List<String> _panes(WidgetTester tester) {
final workspace = find.byType(ChatWorkspace, skipOffstage: false);
if (workspace.evaluate().isEmpty) return const [];
return tester
.widget<ChatWorkspace>(workspace)
.controller
.panes
.map((pane) => pane.sessionId)
.toList();
}
Finder _shownThread(String id) => find
.byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == id)
.hitTestable();
void main() {
final navigation = MobileChatNavigationController.instance;
tearDown(() {
unawaited(navigation.setValue(MobileChatNavigation.quickSwitch));
});
testWidgets('a phone tiles a floating chat; a wide layout floats it again', (
tester,
) async {
final app = _App();
await app.start(tester);
expect(app.floatingWindows, ['b']);
_resize(tester, _phone);
await tester.pumpAndSettle();
// No window at phone width: the chat is an open chat like the others,
// and the server still has it floating.
expect(app.floatingWindows, isEmpty);
expect(app.server.floating, {'b'});
// The list opens it full screen.
await tester.tap(find.byKey(const Key('chat-row-b')));
await tester.pumpAndSettle();
expect(_shownThread('b'), findsOneWidget);
expect(_panes(tester), ['a', 'b']);
_resize(tester, _wide);
await tester.pumpAndSettle();
expect(app.floatingWindows, ['b']);
expect(_panes(tester), ['a']);
expect(_shownThread('a'), findsOneWidget);
expect(app.server.floating, {'b'});
expect(app.server.open, ['a', 'b']);
expect(tester.takeException(), isNull);
await app.stop(tester);
});
testWidgets('a floating chat opens from the list on a phone from the start', (
tester,
) async {
final app = _App();
await app.start(tester, size: _phone);
expect(app.floatingWindows, isEmpty);
await tester.tap(find.byKey(const Key('chat-row-b')));
await tester.pumpAndSettle();
expect(_shownThread('b'), findsOneWidget);
expect(_panes(tester), ['a', 'b']);
expect(app.server.floating, {'b'});
await app.stop(tester);
});
testWidgets('quick switch reaches a floating chat on a phone', (
tester,
) async {
final app = _App();
await app.start(tester, size: _phone);
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_shownThread('a'), findsOneWidget);
final controller = tester
.widget<ChatWorkspace>(find.byType(ChatWorkspace))
.controller;
final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b');
await tester.tap(find.byKey(ValueKey('chat-peek-${b.id}')));
await tester.pumpAndSettle();
expect(_shownThread('b'), findsOneWidget);
expect(app.floatingWindows, isEmpty);
await app.stop(tester);
});
testWidgets('the chat stack reaches a floating chat on a phone', (
tester,
) async {
unawaited(navigation.setValue(MobileChatNavigation.chatStack));
final app = _App();
await app.start(tester, size: _phone);
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-stack')));
await tester.pumpAndSettle();
final controller = tester
.widget<ChatWorkspace>(find.byType(ChatWorkspace))
.controller;
final b = controller.panes.firstWhere((pane) => pane.sessionId == 'b');
await tester.tap(find.byKey(ValueKey('chat-stack-button-${b.id}')));
await tester.pumpAndSettle();
expect(_shownThread('b'), findsOneWidget);
await app.stop(tester);
});
testWidgets('a chat another device floats stays tiled on a phone', (
tester,
) async {
final app = _App();
await app.start(tester, size: _phone);
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
app.server.change(['a', 'b', 'c'], {'b', 'c'});
await tester.pumpAndSettle();
expect(app.floatingWindows, isEmpty);
expect(_panes(tester), ['a', 'b', 'c']);
// Removing a held chat on the phone drops it from the open chats.
final controller = tester
.widget<ChatWorkspace>(find.byType(ChatWorkspace, skipOffstage: false))
.controller;
controller.close(controller.panes.last.id);
await tester.pumpAndSettle();
expect(app.server.open, ['a', 'b']);
expect(app.server.floating, {'b'});
await app.stop(tester);
});
}
@@ -1,13 +1,23 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
/// Functional chat tests settle asynchronous state with reduced motion. Tests
/// covering animation explicitly opt back in and pump known frame durations.
///
/// Tests run as Android, where the Chat stack (the default) also shows on a
/// wide layout. Each test starts on Quick switch, the layout most of them
/// describe; the stack's own tests choose it.
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
TestWidgetsFlutterBinding.ensureInitialized()
.platformDispatcher
.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(
disableAnimations: true,
);
setUp(
() => MobileChatNavigationController.instance.debugUse(
MobileChatNavigation.quickSwitch,
),
);
await testMain();
}
@@ -0,0 +1,323 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../conversation/chat_thread_fixtures.dart';
/// A chat server keeping the open-chat set, as the sync test's does.
class _Server extends FakeChatGateway {
List<String> open = ['a', 'b', 'c'];
int revision = 1;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'c', 'd'])
{'id': id, 'title': 'Chat $id', 'directory': '/w'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
if (type == 'chat_open_workspace') {
final request = fields['chat_open_workspace_request'] as Map?;
var rejected = false;
if (request != null && request['seed'] != true) {
if (request['base_revision'] != revision) {
rejected = true;
} else {
open = [
for (final e in (request['entries'] as List).cast<Map>())
'${e['session_id']}',
];
revision++;
}
}
return Future.value({
'type': 'chat_open_workspace',
'chat_open_workspace': {
'revision': revision,
'entries': [
for (final id in open) {'session_id': id},
],
if (rejected) 'rejected': true,
},
});
}
return super.call(type, fields);
}
}
Future<_Server> _pump(WidgetTester tester, {bool reduced = false}) async {
SharedPreferences.setMockInitialValues({});
unawaited(
MobileChatNavigationController.instance.setValue(
MobileChatNavigation.chatStack,
),
);
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final server = _Server()..history = (_) async => chatPage(const []);
bindServerIdentity(server, 'server-stack');
addTearDown(server.close);
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(context).copyWith(disableAnimations: reduced),
child: child!,
),
home: AdaptiveShell(
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) =>
ChatScreen(gateway: server, persistWorkspace: true),
},
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-stack')));
await tester.pumpAndSettle();
return server;
}
ChatWorkspaceController _workspace(WidgetTester tester) =>
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller;
List<String> _order(WidgetTester tester) => [
for (final pane in _workspace(tester).panes) pane.sessionId,
];
/// Chat [id]'s avatar in the open column.
Finder _button(WidgetTester tester, String id) {
final pane = _workspace(
tester,
).panes.firstWhere((pane) => pane.sessionId == id);
return find.byKey(ValueKey('chat-stack-button-${pane.id}'));
}
final _add = find.byKey(const ValueKey('chat-stack-button-add'));
final _target = find.byType(ChatStackCloseTarget);
/// Holds [finder] until it lifts.
Future<TestGesture> _lift(WidgetTester tester, Finder finder) async {
final gesture = await tester.startGesture(tester.getCenter(finder));
await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20));
return gesture;
}
double _shown(WidgetTester tester) =>
tester.widget<ChatStackCloseTarget>(_target).armed.value;
void main() {
final navigation = MobileChatNavigationController.instance;
tearDown(() {
unawaited(navigation.setValue(MobileChatNavigation.quickSwitch));
});
test('movePane moves a pane and keeps the active one', () {
final controller = ChatWorkspaceController()..open('a');
controller
..splitActive('b', ChatSplitAxis.horizontal)
..splitActive('c', ChatSplitAxis.horizontal);
final active = controller.activePaneId;
final a = controller.panes.first.id;
controller.movePane(a, 2);
expect(controller.panes.map((p) => p.sessionId), ['b', 'c', 'a']);
expect(controller.panes.last.id, a);
expect(controller.activePaneId, active);
controller.dispose();
});
testWidgets('hold and drag reorders, and the order reaches the server', (
tester,
) async {
final server = await _pump(tester);
expect(_order(tester), ['a', 'b', 'c']);
final b = tester.getCenter(_button(tester, 'b'));
final gesture = await _lift(tester, _button(tester, 'a'));
// Lifted: the remove target comes in.
await tester.pumpAndSettle();
expect(_shown(tester), 1);
// Up past the middle of c (its middle would group): b and c slide down.
await gesture.moveBy(const Offset(0, -kChatStackPitch * 2.4));
await tester.pumpAndSettle();
expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch);
await gesture.up();
await tester.pumpAndSettle();
expect(_order(tester), ['b', 'c', 'a']);
expect(server.open, ['b', 'c', 'a']);
// Everyone settles in the new slots; the column stays open.
expect(tester.getCenter(_button(tester, 'b')).dy, closeTo(b.dy + 56, .5));
expect(_shown(tester), 0);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('dropping on the × removes; Undo restores the place', (
tester,
) async {
final server = await _pump(tester);
final gesture = await _lift(tester, _button(tester, 'b'));
await tester.pumpAndSettle();
final from = tester.getCenter(_button(tester, 'b'));
await gesture.moveBy(tester.getCenter(_target) - from);
await tester.pumpAndSettle();
final drag = tester.widget<ChatStackCloseTarget>(_target).hover;
expect(drag.value, 1);
await gesture.up();
await tester.pumpAndSettle();
expect(find.text('Removed Chat b from open chats'), findsOneWidget);
expect(_order(tester), ['a', 'c']);
expect(server.open, ['a', 'c']);
await tester.tap(find.text('Undo'));
await tester.pumpAndSettle();
expect(_order(tester), ['a', 'b', 'c']);
expect(server.open, ['a', 'b', 'c']);
// The chat on screen stays on screen.
expect(_workspace(tester).activePane?.sessionId, 'a');
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Escape, or a drop away from the column, puts the chat back', (
tester,
) async {
final server = await _pump(tester);
final home = tester.getCenter(_button(tester, 'a'));
var gesture = await _lift(tester, _button(tester, 'a'));
await gesture.moveBy(const Offset(0, -kChatStackPitch * 2));
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
await gesture.up();
await tester.pumpAndSettle();
expect(_order(tester), ['a', 'b', 'c']);
expect(tester.getCenter(_button(tester, 'a')), home);
// Escape only cancelled the drag: the column is still open.
expect(find.byType(ChatStackColumn), findsOneWidget);
gesture = await _lift(tester, _button(tester, 'a'));
await gesture.moveBy(const Offset(-200, -kChatStackPitch * 3));
await tester.pumpAndSettle();
await gesture.up();
await tester.pumpAndSettle();
expect(_order(tester), ['a', 'b', 'c']);
expect(server.open, ['a', 'b', 'c']);
expect(tester.getCenter(_button(tester, 'a')), home);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('a tap still opens a chat; Add chat does not lift', (
tester,
) async {
await _pump(tester);
final add = tester.getCenter(_add);
final gesture = await _lift(tester, _add);
await tester.pumpAndSettle();
expect(_shown(tester), 0);
await gesture.moveBy(const Offset(0, kChatStackPitch * 2));
await tester.pumpAndSettle();
expect(tester.getCenter(_add), add);
await gesture.up();
await tester.pumpAndSettle();
expect(_order(tester), ['a', 'b', 'c']);
// A drag that moved off "+" is no tap: the column is still open.
expect(find.byType(ChatStackColumn), findsOneWidget);
await tester.tap(_button(tester, 'c'));
await tester.pumpAndSettle();
expect(
find
.byWidgetPredicate((w) => w is ChatThreadView && w.sessionId == 'c')
.hitTestable(),
findsOneWidget,
);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Move up, Move down and Remove are semantic actions', (
tester,
) async {
final semantics = tester.ensureSemantics();
final server = await _pump(tester);
void act(String id, String label) {
final node = tester.getSemantics(_button(tester, id));
final action = node
.getSemanticsData()
.customSemanticsActionIds!
.map(CustomSemanticsAction.getAction)
.firstWhere((action) => action!.label == label)!;
tester.binding.renderViews.first.owner!.semanticsOwner!.performAction(
node.id,
SemanticsAction.customAction,
CustomSemanticsAction.getIdentifier(action),
);
}
// The bottom chat cannot move down; the top one cannot move up.
final bottom = tester.getSemantics(_button(tester, 'a'));
expect(
bottom.getSemanticsData().customSemanticsActionIds!.map(
(id) => CustomSemanticsAction.getAction(id)!.label,
),
unorderedEquals([
ChatStackColumn.moveUpLabel,
ChatStackColumn.removeLabel,
]),
);
act('a', ChatStackColumn.moveUpLabel);
await tester.pumpAndSettle();
expect(server.open, ['b', 'a', 'c']);
act('c', ChatStackColumn.moveDownLabel);
await tester.pumpAndSettle();
expect(server.open, ['b', 'c', 'a']);
act('b', ChatStackColumn.removeLabel);
await tester.pumpAndSettle();
expect(server.open, ['c', 'a']);
expect(find.text('Removed Chat b from open chats'), findsOneWidget);
semantics.dispose();
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('reduced motion: neighbours swap at once, the × only fades', (
tester,
) async {
await _pump(tester, reduced: true);
final b = tester.getCenter(_button(tester, 'b'));
final gesture = await _lift(tester, _button(tester, 'a'));
expect(_shown(tester), 1);
await gesture.moveBy(const Offset(0, -kChatStackPitch * 1.4));
await tester.pump();
expect(tester.getCenter(_button(tester, 'b')).dy, b.dy + kChatStackPitch);
// No turn or growth: the button only fades.
expect(
find.descendant(of: _target, matching: find.byType(RotationTransition)),
findsNothing,
);
await gesture.up();
await tester.pump();
expect(_order(tester), ['b', 'a', 'c']);
expect(_shown(tester), 0);
await tester.pumpAndSettle();
await tester.pumpWidget(const SizedBox.shrink());
});
}
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_fab.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_pose.dart';
@@ -103,7 +105,8 @@ void main() {
expect(find.text('Chat 0'), findsOneWidget);
expect(find.text('Chat 4'), findsOneWidget);
expect(find.text(ChatStackColumn.addLabel), findsOneWidget);
// Item 0 sits on the stack; each further item rises one pitch.
// The stack's slot holds the close button; item 0 sits a pitch above
// it and each further item rises one more.
final first = tester.getCenter(
find.byKey(const ValueKey('chat-stack-button-pane-0')),
);
@@ -114,7 +117,11 @@ void main() {
find.byKey(const ValueKey('chat-stack-button-add')),
);
expect(first.dx, closeTo(slot.center.dx, .5));
expect(first.dy, closeTo(slot.center.dy, .5));
expect(first.dy, closeTo(slot.center.dy - kChatStackPitch, .5));
expect(
tester.getCenter(find.bySemanticsLabel(ChatStackCloseTarget.label)),
slot.center,
);
expect(second.dy, lessThan(first.dy));
expect(add.dy, lessThan(second.dy));
// Outside the column.
@@ -126,6 +133,22 @@ void main() {
expect(harness.opened, isEmpty);
});
testWidgets('the close button where the pile was folds the column', (
tester,
) async {
final harness = await _pump(tester);
final slot = tester.getRect(find.byKey(const Key('chat-stack')));
await tester.tap(find.byKey(const Key('chat-stack')));
await _settle(tester);
await tester.tapAt(slot.center);
await tester.pump();
expect(_state(tester).expanded, isFalse);
await _settle(tester);
expect(find.byType(ChatStackColumn), findsNothing);
expect(harness.opened, isEmpty);
expect(harness.added, 0);
});
testWidgets('tapping a chat opens it and folds the column', (tester) async {
final harness = await _pump(tester);
await tester.tap(find.byKey(const Key('chat-stack')));
@@ -145,17 +168,18 @@ void main() {
expect(harness.opened, ['s3']);
});
testWidgets('add opens the picker; long press removes', (tester) async {
testWidgets('add opens the picker; a hold alone removes nothing', (
tester,
) async {
final harness = await _pump(tester);
await tester.tap(find.byKey(const Key('chat-stack')));
await _settle(tester);
// A hold lifts the chat for a drag; let go in place, it settles back.
await tester.longPress(find.text('Chat 2'));
await _settle(tester);
expect(harness.removed, ['s2']);
// Removing folds the column, so a snack bar's Undo is in reach.
expect(find.byType(ChatStackColumn), findsNothing);
await tester.tap(find.byKey(const Key('chat-stack')));
await _settle(tester);
expect(harness.removed, isEmpty);
expect(harness.opened, isEmpty);
expect(find.byType(ChatStackColumn), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('chat-stack-button-add')));
await _settle(tester);
expect(harness.added, 1);
@@ -0,0 +1,371 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_close_target.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_column.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_disc.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_drag.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_group_dialogs.dart';
import 'package:pipelines_app/features/chat/stack/mobile_chat_navigation.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../conversation/chat_thread_fixtures.dart';
/// A chat server keeping the open-chat set with each entry's group.
class _Server extends FakeChatGateway {
List<String> open = ['a', 'b', 'c'];
Map<String, String> groups = {};
int revision = 1;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final id in ['a', 'b', 'c', 'd'])
{'id': id, 'title': 'Chat $id', 'directory': '/w'},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
if (type == 'chat_open_workspace') {
final request = fields['chat_open_workspace_request'] as Map?;
var rejected = false;
if (request != null && request['seed'] != true) {
if (request['base_revision'] != revision) {
rejected = true;
} else {
final entries = (request['entries'] as List).cast<Map>();
open = [for (final e in entries) '${e['session_id']}'];
groups = {
for (final e in entries)
if (e['group'] != null) '${e['session_id']}': '${e['group']}',
};
revision++;
}
}
return Future.value({
'type': 'chat_open_workspace',
'chat_open_workspace': _body(rejected),
});
}
return super.call(type, fields);
}
JsonMap _body([bool rejected = false]) => {
'revision': revision,
'entries': [
for (final id in open)
{'session_id': id, if (groups[id] != null) 'group': groups[id]},
],
if (rejected) 'rejected': true,
};
/// Another device changed the set.
void change(List<String> ids, Map<String, String> byGroup) {
open = ids;
groups = byGroup;
revision++;
emitRaw({
'type': 'chat_open_workspace_changed',
'chat_open_workspace': _body(),
});
}
}
Future<_Server> _pump(WidgetTester tester) async {
SharedPreferences.setMockInitialValues({});
MobileChatNavigationController.instance.debugUse(
MobileChatNavigation.chatStack,
);
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final server = _Server()..history = (_) async => chatPage(const []);
bindServerIdentity(server, 'server-groups');
addTearDown(server.close);
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) =>
ChatScreen(gateway: server, persistWorkspace: true),
},
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
await _expand(tester);
return server;
}
Future<void> _expand(WidgetTester tester) async {
await tester.tap(find.byKey(const Key('chat-stack')));
await tester.pumpAndSettle();
}
ChatWorkspaceController _workspace(WidgetTester tester) =>
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller;
Finder _chat(WidgetTester tester, String id) {
final pane = _workspace(
tester,
).panes.firstWhere((pane) => pane.sessionId == id);
return find.byKey(ValueKey('chat-stack-button-${pane.id}'));
}
Finder _group(String name) =>
find.byKey(ValueKey('chat-stack-button-group-$name'));
final _header = find.byKey(const ValueKey('chat-stack-button-header'));
/// Holds [item] until it lifts, moves it by [by], lets go.
Future<void> _drag(WidgetTester tester, Finder item, Offset by) async {
final gesture = await tester.startGesture(tester.getCenter(item));
await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20));
await gesture.moveBy(by);
await tester.pumpAndSettle();
await gesture.up();
await tester.pumpAndSettle();
}
const _up = Offset(0, -kChatStackPitch);
/// Makes group "Work" of b and a (a dropped onto b), naming it.
Future<void> _makeWork(WidgetTester tester) async {
await _drag(tester, _chat(tester, 'a'), _up);
expect(find.text('Name the group'), findsOneWidget);
await tester.enterText(
find.byKey(const Key('chat-stack-group-name')),
'Work',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
}
void _act(WidgetTester tester, Finder target, String label) {
final node = tester.getSemantics(target);
final action = node
.getSemanticsData()
.customSemanticsActionIds!
.map(CustomSemanticsAction.getAction)
.firstWhere((action) => action!.label == label)!;
tester.binding.renderViews.first.owner!.semanticsOwner!.performAction(
node.id,
SemanticsAction.customAction,
CustomSemanticsAction.getIdentifier(action),
);
}
void main() {
tearDown(
() => MobileChatNavigationController.instance.debugUse(
MobileChatNavigation.quickSwitch,
),
);
testWidgets('a chat dropped onto a chat makes a named group that syncs', (
tester,
) async {
final server = await _pump(tester);
// Mid-drag over b's middle: b grows (the drop target).
final gesture = await tester.startGesture(
tester.getCenter(_chat(tester, 'a')),
);
await tester.pump(chatStackLiftDelay + const Duration(milliseconds: 20));
final b = tester.getSize(_chat(tester, 'b'));
await gesture.moveBy(_up);
await tester.pumpAndSettle();
expect(
tester.getRect(_chat(tester, 'b')).width,
closeTo(b.width * chatStackOntoScale, .5),
);
// The dragged chat shrinks onto it, so the target's ring shows around.
expect(
tester.getRect(_chat(tester, 'a')).width,
closeTo(b.width * chatStackLiftScale * chatStackOverRemoveScale, .5),
);
await gesture.up();
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-stack-group-name')),
'Work',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(server.open, ['b', 'a', 'c']);
expect(server.groups, {'b': 'Work', 'a': 'Work'});
expect(_group('Work'), findsOneWidget);
expect(find.text('Work'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('a group opens in place; header, Back and outside return', (
tester,
) async {
await _pump(tester);
await _makeWork(tester);
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
expect(_chat(tester, 'a').hitTestable(), findsOneWidget);
expect(_chat(tester, 'b').hitTestable(), findsOneWidget);
expect(_header.hitTestable(), findsOneWidget);
// The top level's chat c is behind: no input.
expect(_chat(tester, 'c').hitTestable(), findsNothing);
await tester.tap(_header);
await tester.pumpAndSettle();
expect(_group('Work').hitTestable(), findsOneWidget);
// Outside: out of the group first, then folded.
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
await tester.tapAt(const Offset(40, 120));
await tester.pumpAndSettle();
expect(_group('Work').hitTestable(), findsOneWidget);
await tester.tapAt(const Offset(40, 120));
await tester.pumpAndSettle();
expect(find.byType(ChatStackColumn), findsNothing);
// Back leaves the group, then folds.
await _expand(tester);
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(_group('Work').hitTestable(), findsOneWidget);
// A chat in a group opens as any other.
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
await tester.tap(_chat(tester, 'b'));
await tester.pumpAndSettle();
expect(_workspace(tester).activePane?.sessionId, 'b');
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('a chat joins a group; a group takes a chat in', (tester) async {
final server = await _pump(tester);
await _makeWork(tester);
// Top level: Work (b, a) at the bottom, c above it. c down onto it.
await _drag(tester, _chat(tester, 'c'), -_up);
expect(server.groups, {'b': 'Work', 'a': 'Work', 'c': 'Work'});
expect(server.open, ['b', 'a', 'c']);
// Leaving from inside the group: drop on its header.
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
await _drag(tester, _chat(tester, 'c'), _up);
expect(server.groups, {'b': 'Work', 'a': 'Work'});
expect(server.open, ['b', 'a', 'c']);
// Back on the top level: drag the group onto c.
await tester.tap(_header);
await tester.pumpAndSettle();
await _drag(tester, _group('Work'), _up);
expect(server.groups, {'b': 'Work', 'a': 'Work', 'c': 'Work'});
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('the last chat left alone dissolves the group', (tester) async {
final server = await _pump(tester);
await _makeWork(tester);
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
// a is second in the group: one slot up is the header.
await _drag(tester, _chat(tester, 'a'), _up);
expect(server.groups, isEmpty);
// The group is gone: back on the top level.
expect(_header, findsNothing);
expect(_chat(tester, 'a').hitTestable(), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Rename, Ungroup and Close all; each syncs, Undo restores', (
tester,
) async {
final semantics = tester.ensureSemantics();
final server = await _pump(tester);
await _makeWork(tester);
_act(tester, _group('Work'), ChatStackGroupAction.rename.label);
await tester.pumpAndSettle();
await tester.enterText(
find.byKey(const Key('chat-stack-group-name')),
'Personal',
);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(server.groups, {'b': 'Personal', 'a': 'Personal'});
_act(tester, _group('Personal'), ChatStackGroupAction.ungroup.label);
await tester.pumpAndSettle();
expect(server.groups, isEmpty);
expect(find.text('Ungrouped Personal'), findsOneWidget);
await tester.tap(find.text('Undo'));
await tester.pumpAndSettle();
expect(server.groups, {'b': 'Personal', 'a': 'Personal'});
await _expand(tester);
_act(tester, _group('Personal'), ChatStackGroupAction.closeAll.label);
await tester.pumpAndSettle();
expect(server.open, ['c']);
await tester.tap(find.text('Undo'));
await tester.pumpAndSettle();
expect(server.open, ['b', 'a', 'c']);
expect(server.groups, {'b': 'Personal', 'a': 'Personal'});
semantics.dispose();
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Move to group and Remove from group as semantic actions', (
tester,
) async {
final semantics = tester.ensureSemantics();
final server = await _pump(tester);
await _makeWork(tester);
_act(tester, _chat(tester, 'c'), ChatStackColumn.moveToGroupLabel);
await tester.pumpAndSettle();
await tester.tap(find.text('Work').last);
await tester.pumpAndSettle();
expect(server.groups['c'], 'Work');
await tester.tap(_group('Work'));
await tester.pumpAndSettle();
_act(tester, _chat(tester, 'b'), ChatStackColumn.leaveGroupLabel);
await tester.pumpAndSettle();
expect(server.groups, {'a': 'Work', 'c': 'Work'});
expect(server.open, ['a', 'c', 'b']);
semantics.dispose();
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('a group dropped on the close button is ungrouped', (
tester,
) async {
final server = await _pump(tester);
await _makeWork(tester);
final group = tester.getCenter(_group('Work'));
final close = tester.getCenter(
find.bySemanticsLabel(ChatStackCloseTarget.label),
);
await _drag(tester, _group('Work'), close - group);
expect(server.groups, isEmpty);
expect(server.open, ['b', 'a', 'c']);
expect(find.text('Ungrouped Work'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('groups from another device appear', (tester) async {
final server = await _pump(tester);
server.change(['a', 'b', 'c'], {'a': 'Home', 'c': 'Home'});
await tester.pumpAndSettle();
expect(_group('Home'), findsOneWidget);
expect(find.text('Home'), findsOneWidget);
// The group's pill counts its chats.
expect(find.text('2'), findsWidgets);
await tester.pumpWidget(const SizedBox.shrink());
});
}
@@ -0,0 +1,168 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_drop_target.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_entry.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_group_ops.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_groups.dart';
import 'package:pipelines_app/features/chat/stack/chat_stack_node.dart';
import 'package:pipelines_app/features/chat/workspace/chat_open_workspace_gateway.dart';
ChatStackEntry _entry(String id, [String? group]) =>
ChatStackEntry(paneId: 'p$id', session: {'id': id}, group: group);
void main() {
group('ChatStackGroups', () {
test('assigns, merges on rename, dissolves a group of one', () {
final groups = ChatStackGroups();
var changes = 0;
groups.addListener(() => changes++);
// One chat is no group.
groups.assign(['a'], 'Work');
expect(groups.assignments, isEmpty);
expect(changes, 0);
groups.assign(['a', 'b'], 'Work');
groups.assign(['c', 'd'], 'Home');
expect(groups.membersOf('Work'), ['a', 'b']);
expect(groups.nextName(), 'Group 1');
groups.rename('Home', 'Work');
expect(groups.membersOf('Work'), ['a', 'b', 'c', 'd']);
groups.unassign(['a', 'b', 'c']);
expect(groups.assignments, isEmpty);
groups.assign(['a', 'b', 'c'], 'Group 1');
expect(groups.nextName(), 'Group 2');
groups.retain({'a', 'x'});
expect(groups.assignments, isEmpty);
expect(changes, greaterThan(0));
groups.dispose();
});
test('names are trimmed, bounded and never empty', () {
expect(chatStackGroupName(' Work \n'), 'Work');
expect(chatStackGroupName(' '), isNull);
expect(chatStackGroupName('a\tb'), 'a b');
expect(chatStackGroupName('x' * 100)!.length, chatStackGroupNameLimit);
});
});
group('nodes and drops', () {
final entries = [
_entry('a'),
_entry('b', 'Work'),
_entry('c'),
_entry('d', 'Work'),
];
final nodes = chatStackNodes(entries);
test('a group stands where its first chat is', () {
expect(nodes.map((node) => node.key), [
'chat:pa',
'group:Work',
'chat:pc',
]);
expect(chatStackOrder(nodes), ['a', 'b', 'd', 'c']);
// A lone member shows as a chat.
expect(
chatStackNodes([_entry('x', 'Solo')]).single,
isA<ChatStackChatNode>(),
);
});
test('dropping onto a chat or a group joins as expected', () {
final made = chatStackJoined(nodes, 2, 0, () => 'Group 1');
expect(made.created, isTrue);
expect(made.join, ['a', 'c']);
expect(made.order, ['a', 'c', 'b', 'd']);
final joined = chatStackJoined(nodes, 0, 1, () => 'unused');
expect((joined.group, joined.created), ('Work', false));
expect(joined.join, ['a']);
expect(joined.order, ['b', 'd', 'a', 'c']);
final took = chatStackJoined(nodes, 1, 2, () => 'unused');
expect(took.join, ['c']);
expect(took.order, ['a', 'b', 'd', 'c']);
expect(chatStackLeft(nodes, 'Work', 'b'), ['a', 'd', 'b', 'c']);
expect(chatStackRegrouped(nodes, 'Work', ['d', 'b']), [
'a',
'd',
'b',
'c',
]);
expect(chatStackMoved(nodes, 0, 2), ['b', 'd', 'c', 'a']);
});
test('the middle of an item groups, its edges reorder, stably', () {
bool all(int _) => true;
// From slot 0, one slot up: the middle of item 1.
expect(
chatStackDropTarget(
position: 1,
from: 0,
count: 3,
slot: 0,
canDropOnto: all,
),
(slot: 0, onto: 1),
);
// Past its middle: the gap moves above it...
expect(
chatStackDropTarget(
position: 1.4,
from: 0,
count: 3,
slot: 0,
canDropOnto: all,
),
(slot: 1, onto: null),
);
// ...and holds there while item 1 slides below it.
expect(
chatStackDropTarget(
position: 1.3,
from: 0,
count: 3,
slot: 1,
canDropOnto: all,
),
(slot: 1, onto: null),
);
// Below its middle the gap stays below it.
expect(
chatStackDropTarget(
position: .7,
from: 0,
count: 3,
slot: 0,
canDropOnto: all,
),
(slot: 0, onto: null),
);
// Without grouping the middle reorders too; the gap never passes
// lastSlot.
expect(
chatStackDropTarget(
position: 2.3,
from: 0,
count: 3,
slot: 1,
lastSlot: 1,
),
(slot: 1, onto: null),
);
});
});
test('an entry carries its group over the wire', () {
final entry = ChatOpenWorkspaceEntry.fromJson({
'session_id': 'a',
'group': ' Work ',
})!;
expect(entry.group, 'Work');
expect(entry.toJson(), {'session_id': 'a', 'group': 'Work'});
expect(ChatOpenWorkspaceEntry.fromJson({'session_id': 'b'})!.group, isNull);
const snapshot = ChatOpenWorkspaceSnapshot(1, [
ChatOpenWorkspaceEntry('a'),
]);
expect(
snapshot.sameEntries([const ChatOpenWorkspaceEntry('a', group: 'W')]),
isFalse,
);
});
}
@@ -34,6 +34,15 @@ class _Gateway extends FakeChatGateway {
}
}
class _Store implements MobileChatNavigationStore {
_Store(this.value);
final String? value;
@override
Future<String?> load() async => value;
@override
Future<bool> save(String value) async => true;
}
Future<void> _pump(WidgetTester tester, Size size) async {
SharedPreferences.setMockInitialValues({});
unawaited(
@@ -114,39 +123,53 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('long press removes a chat, Undo restores it', (tester) async {
await _pump(tester, const Size(390, 844));
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
await tester.tap(_stack);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('chat-stack-button-add')));
await tester.pumpAndSettle();
await tester.tap(find.text('Gamma').last);
await tester.pumpAndSettle();
expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget);
await tester.tap(_stack);
await tester.pumpAndSettle();
await tester.longPress(find.text('Alpha').last);
await tester.pumpAndSettle();
expect(find.text('Removed Alpha from open chats'), findsOneWidget);
expect(find.bySemanticsLabel(chatStackLabel(1)), findsOneWidget);
await tester.tap(find.text('Undo'));
await tester.pumpAndSettle();
// Gamma stays on screen; Alpha is back in the stack.
expect(_thread('c').hitTestable(), findsOneWidget);
expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets(
'a wide desktop window keeps its panes and shows no stack',
variant: TargetPlatformVariant.desktop(),
(tester) async {
await _pump(tester, const Size(1280, 800));
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_thread('a'), findsOneWidget);
expect(_stack, findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets('a wide window keeps its panes and shows no stack', (
tester,
) async {
await _pump(tester, const Size(1280, 800));
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_thread('a'), findsOneWidget);
expect(_stack, findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
testWidgets(
'a wide phone or tablet layout (an unfolded foldable) keeps the stack',
variant: TargetPlatformVariant({
TargetPlatform.android,
TargetPlatform.iOS,
}),
(tester) async {
await _pump(tester, const Size(1280, 800));
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_thread('a'), findsOneWidget);
// The list stays beside the chat, the stack floats over the pane.
expect(find.byKey(const Key('chat-row-b')), findsOneWidget);
expect(_stack.hitTestable(), findsOneWidget);
await tester.tap(_stack);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('chat-stack-button-add')));
await tester.pumpAndSettle();
await tester.tap(find.text('Beta').last);
await tester.pumpAndSettle();
expect(find.bySemanticsLabel(chatStackLabel(2)), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
},
);
test('Chat stack is the default without a stored choice', () async {
final controller = MobileChatNavigationController(store: _Store(null));
expect(controller.value, MobileChatNavigation.chatStack);
await controller.restore();
expect(controller.value, MobileChatNavigation.chatStack);
final chosen = MobileChatNavigationController(store: _Store('quickSwitch'));
await chosen.restore();
expect(chosen.value, MobileChatNavigation.quickSwitch);
controller.dispose();
chosen.dispose();
});
}
@@ -32,19 +32,20 @@ void main() {
),
);
expect(find.text(SettingsChatNavigationSection.title), findsOneWidget);
expect(controller.value, MobileChatNavigation.quickSwitch);
// Without a stored choice: the Chat stack.
expect(controller.value, MobileChatNavigation.chatStack);
expect(
find.text(MobileChatNavigation.quickSwitch.description),
find.text(MobileChatNavigation.chatStack.description),
findsOneWidget,
);
await tester.tap(
find.byKey(const ValueKey('settings-chat-navigation-chatStack')),
find.byKey(const ValueKey('settings-chat-navigation-quickSwitch')),
);
await tester.pumpAndSettle();
expect(controller.value, MobileChatNavigation.chatStack);
expect(store.saved, 'chatStack');
expect(controller.value, MobileChatNavigation.quickSwitch);
expect(store.saved, 'quickSwitch');
expect(
find.text(MobileChatNavigation.chatStack.description),
find.text(MobileChatNavigation.quickSwitch.description),
findsOneWidget,
);
@@ -52,11 +53,11 @@ void main() {
final next = MobileChatNavigationController(store: store);
addTearDown(next.dispose);
await next.restore();
expect(next.value, MobileChatNavigation.chatStack);
expect(next.value, MobileChatNavigation.quickSwitch);
store.success = false;
await tester.tap(
find.byKey(const ValueKey('settings-chat-navigation-quickSwitch')),
find.byKey(const ValueKey('settings-chat-navigation-chatStack')),
);
await tester.pumpAndSettle();
expect(find.text('Could not save; applies until reload.'), findsOneWidget);
+1 -1
View File
@@ -85,7 +85,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
| `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) |
| `clipboard=read[:label]` / `clipboard=write:<text>` | read or write the browser's clipboard from a scratch page on the loopback origin (a secure context), then bring the page back; JSON `expect` fails the run unless the read text matches. Works for an `--insecure` page, which has no `navigator.clipboard` |
| `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker |
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) |
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on); JSON `press` holds the finger down that many ms first (a long press), `hold: true` leaves it down for a capture, and the next swipe moves it on from there |
| `pinch=<target>>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) |
| `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab |
| `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) |
+5 -1
View File
@@ -34,7 +34,9 @@ steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target
page on the loopback origin, so it works for an --insecure page)
rightclick=<target> (secondary button: context menus)
drag=<target>><dx>,<dy> (JSON: drag, dx, dy, steps, gap, hold)
swipe=<target>><dx>,<dy> pinch=<target>><scale> (with --touch true)
swipe=<target>><dx>,<dy> pinch=<target>><scale> (with --touch true;
JSON swipe: press ms held before moving, hold keeps the finger down
for the next swipe)
target: <label> | label:<label> | key:<semantics identifier> | x,y`;
const opts = { wait: '1000', 'film-ms': '900' };
@@ -209,6 +211,7 @@ try {
const moved = await page.drag(target, {
dx: Number(step.dx ?? bx ?? 0) || 0, dy: Number(step.dy ?? by2 ?? 0) || 0,
steps: Number(step.steps ?? 12), gap: Number(step.gap ?? 16), hold: Boolean(step.hold),
press: Number(step.press ?? 0),
});
log(` dragged ${Math.round(moved.from.x)},${Math.round(moved.from.y)} -> ${Math.round(moved.to.x)},${Math.round(moved.to.y)}`);
await delay(step.wait ?? settle);
@@ -220,6 +223,7 @@ try {
const moved = await page.swipe(target, {
dx: Number(step.dx ?? bx ?? 0) || 0, dy: Number(step.dy ?? by2 ?? 0) || 0,
steps: Number(step.steps ?? 12), gap: Number(step.gap ?? 16),
press: Number(step.press ?? 0), hold: Boolean(step.hold),
});
log(` swiped ${Math.round(moved.from.x)},${Math.round(moved.from.y)} -> ${Math.round(moved.to.x)},${Math.round(moved.to.y)}`);
await delay(step.wait ?? settle);
+4 -2
View File
@@ -219,13 +219,15 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use
/**
* Presses the mouse on [target], moves it by dx/dy in [steps] moves [gap] ms
* apart, and releases it unless [hold] (to capture mid-drag; the next
* mouse step or the end of the run releases it).
* mouse step or the end of the run releases it). [press] ms held before
* moving makes it a long-press drag.
*/
async drag(target, { dx = 0, dy = 0, steps = 12, gap = 16, hold = false } = {}) {
async drag(target, { dx = 0, dy = 0, steps = 12, gap = 16, hold = false, press = 0 } = {}) {
const at = await locate(target);
const mouse = (type, x, y, extra = {}) => send('Input.dispatchMouseEvent', { type, x, y, button: 'left', ...extra });
await mouse('mouseMoved', at.x, at.y, { button: 'none' });
await mouse('mousePressed', at.x, at.y, { buttons: 1, clickCount: 1 });
if (press > 0) await delay(press);
for (let i = 1; i <= steps; i++) {
await delay(gap);
await mouse('mouseMoved', at.x + (dx * i) / steps, at.y + (dy * i) / steps, { buttons: 1 });
+21 -6
View File
@@ -10,18 +10,33 @@ export async function enableTouch(send, { width, height }) {
await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
}
/** One finger down at [at], moved by dx/dy in [steps] moves [gap] ms apart, lifted. */
export async function swipe(send, at, { dx = 0, dy = 0, steps = 12, gap = 16 } = {}) {
/** The finger a held swipe left down, if any: the next swipe moves it on. */
let held = null;
/**
* One finger down at [at], held [press] ms (a long press), moved by dx/dy in
* [steps] moves [gap] ms apart, lifted unless [hold] (to capture mid-drag;
* the next swipe continues from where it stopped instead of touching down).
*/
export async function swipe(send, at, { dx = 0, dy = 0, steps = 12, gap = 16, press = 0, hold = false } = {}) {
const touch = (type, x, y) => send('Input.dispatchTouchEvent', {
type, touchPoints: type === 'touchEnd' ? [] : [{ x, y, id: 1 }],
});
await touch('touchStart', at.x, at.y);
const from = held ?? at;
if (!held) await touch('touchStart', from.x, from.y);
if (press > 0) await delay(press);
for (let i = 1; i <= steps; i++) {
await delay(gap);
await touch('touchMove', at.x + (dx * i) / steps, at.y + (dy * i) / steps);
await touch('touchMove', from.x + (dx * i) / steps, from.y + (dy * i) / steps);
}
await touch('touchEnd');
return { from: at, to: { x: at.x + dx, y: at.y + dy } };
const to = { x: from.x + dx, y: from.y + dy };
if (hold) {
held = to;
} else {
held = null;
await touch('touchEnd');
}
return { from, to };
}
/** Two fingers spread (scale > 1) or closed (< 1) around [at]. */
+22
View File
@@ -7,6 +7,8 @@ import (
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -35,11 +37,31 @@ func validateOpenWorkspace(entries []protocol.ChatOpenWorkspaceEntry) error {
if _, ok := seen[id]; ok {
return fmt.Errorf("duplicate open chat session id %q", id)
}
if !validOpenWorkspaceGroup(entry.Group) {
return fmt.Errorf("invalid open chat group name")
}
seen[id] = struct{}{}
}
return nil
}
// validOpenWorkspaceGroup accepts an empty name (no group) or a trimmed,
// printable one of at most ChatOpenWorkspaceGroupLimit characters.
func validOpenWorkspaceGroup(name string) bool {
if name == "" {
return true
}
if strings.TrimSpace(name) != name || !utf8.ValidString(name) || utf8.RuneCountInString(name) > protocol.ChatOpenWorkspaceGroupLimit {
return false
}
for _, r := range name {
if unicode.IsControl(r) {
return false
}
}
return true
}
func decodeOpenWorkspace(raw string) ([]protocol.ChatOpenWorkspaceEntry, error) {
var entries []protocol.ChatOpenWorkspaceEntry
if err := json.Unmarshal([]byte(raw), &entries); err != nil {
@@ -3,6 +3,7 @@ package pipeline
import (
"context"
"fmt"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
@@ -127,3 +128,46 @@ func TestChatOpenWorkspaceReplacesARestartedChatInPlace(t *testing.T) {
t.Fatalf("replace onto an open chat = %+v changed=%v err=%v", merged, changed, err)
}
}
// TestChatOpenWorkspaceKeepsGroups pins that chat groups (a name on each
// grouped entry) are stored, compared and restored with the entries, that a
// group-only change stores a new revision, that a restarted chat keeps its
// group, and that malformed names are refused.
func TestChatOpenWorkspaceKeepsGroups(t *testing.T) {
path := t.TempDir() + "/workspace.db"
ctx := context.Background()
store := openWorkspaceStore(t, path)
entries := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Group: "Work"}, {SessionID: "ses_b", Group: "Work"}, {SessionID: "ses_c"}}
snapshot, changed, err := store.SaveChatOpenWorkspace(ctx, "default", entries, false, 0)
if err != nil || !changed || snapshot.Entries[1].Group != "Work" {
t.Fatalf("save: %+v changed=%v err=%v", snapshot, changed, err)
}
renamed := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Group: "Personal"}, {SessionID: "ses_b", Group: "Personal"}, {SessionID: "ses_c"}}
snapshot, changed, err = store.SaveChatOpenWorkspace(ctx, "default", renamed, false, 1)
if err != nil || !changed || snapshot.Revision != 2 {
t.Fatalf("a group-only change was not stored: %+v changed=%v err=%v", snapshot, changed, err)
}
if _, changed, err = store.SaveChatOpenWorkspace(ctx, "default", renamed, false, 2); err != nil || changed {
t.Fatalf("an identical write stored a revision: changed=%v err=%v", changed, err)
}
moved, _, err := store.ReplaceChatOpenWorkspaceSession(ctx, "default", "ses_b", "ses_new")
if err != nil || moved.Entries[1].SessionID != "ses_new" || moved.Entries[1].Group != "Personal" {
t.Fatalf("restarted chat lost its group: %+v err=%v", moved, err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
store = openWorkspaceStore(t, path)
defer store.Close()
loaded, err := store.ChatOpenWorkspace(ctx, "default")
if err != nil || loaded.Entries[0].Group != "Personal" || loaded.Entries[2].Group != "" {
t.Fatalf("groups did not survive restart: %+v err=%v", loaded, err)
}
long := strings.Repeat("g", protocol.ChatOpenWorkspaceGroupLimit+1)
for _, name := range []string{" Work", "Work\n", long} {
bad := []protocol.ChatOpenWorkspaceEntry{{SessionID: "ses_a", Group: name}}
if _, _, err := store.SaveChatOpenWorkspace(ctx, "default", bad, false, loaded.Revision); err == nil {
t.Fatalf("group name %q was accepted", name)
}
}
}
+7
View File
@@ -5,8 +5,15 @@ package protocol
type ChatOpenWorkspaceEntry struct {
SessionID string `json:"session_id"`
Floating bool `json:"floating,omitempty"`
// Group names the chat group this chat belongs to in the phone's chat
// stack; entries sharing a name form one group, ordered as the entries
// are. Empty for an ungrouped chat. Older clients ignore it.
Group string `json:"group,omitempty"`
}
// ChatOpenWorkspaceGroupLimit bounds a group name, in characters.
const ChatOpenWorkspaceGroupLimit = 80
// ChatOpenWorkspaceRequest replaces the open-chat set. A chat_open_workspace
// without a request only reads the current snapshot.
type ChatOpenWorkspaceRequest struct {
+1 -1
View File
@@ -140,7 +140,7 @@ func validChatWorkspaceEntries(ctx context.Context, request protocol.ChatOpenWor
return nil, err
}
if open {
valid = append(valid, protocol.ChatOpenWorkspaceEntry{SessionID: id, Floating: entry.Floating})
valid = append(valid, protocol.ChatOpenWorkspaceEntry{SessionID: id, Floating: entry.Floating, Group: entry.Group})
}
}
return valid, nil
@@ -193,3 +193,39 @@ func TestChatOpenWorkspaceFollowsARestartedChat(t *testing.T) {
t.Fatalf("stored workspace after /new = %+v", read)
}
}
// TestChatOpenWorkspaceSyncsGroups pins that a chat's group travels with its
// entry: stored on a write, pushed to the other connection and read back.
func TestChatOpenWorkspaceSyncsGroups(t *testing.T) {
store := newOperatorStore(t)
ctx, _, conns := dialChatConns(t, Options{Chat: scriptedChat(), OperatorRegistry: store}, 2)
for _, id := range []string{"ses_a", "ses_b", "ses_c"} {
if err := store.RecordOperatorSession(ctx, id, "/work", id, protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
}
writeChat(t, ctx, conns[0], workspaceWrite("w1", 0,
protocol.ChatOpenWorkspaceEntry{SessionID: "ses_a", Group: "Work"},
protocol.ChatOpenWorkspaceEntry{SessionID: "ses_b", Group: "Work"},
protocol.ChatOpenWorkspaceEntry{SessionID: "ses_c"}))
if reply := readUntil(t, ctx, conns[0], protocol.ChatOpenWorkspace).ChatOpenWorkspace; reply.Revision != 1 || reply.Entries[1].Group != "Work" {
t.Fatalf("grouped write reply = %+v", reply)
}
push := readWorkspacePush(t, ctx, conns[1], 1)
if push.Entries[0].Group != "Work" || push.Entries[1].Group != "Work" || push.Entries[2].Group != "" {
t.Fatalf("grouped push = %+v", push)
}
writeChat(t, ctx, conns[1], workspaceWrite("w2", 1, protocol.ChatOpenWorkspaceEntry{SessionID: "ses_a", Group: " bad"}))
for {
var message protocol.Message
if err := readTestFrame(ctx, conns[1], &message); err != nil {
t.Fatalf("read: %v", err)
}
if message.Type == protocol.ChatOpenWorkspace {
t.Fatalf("a malformed group name was accepted: %+v", message.ChatOpenWorkspace)
}
if message.Type == protocol.Error && message.ID == "w2" {
break
}
}
}