Merge main: ntfy removed, first-run messages kept

Resolved docs/install.md, internal/cli/app.go, internal/statusview and
scripts/setup-native.py: no ntfy anywhere (connection, status, installer
constants, troubleshooting ports), keeping the first-run next steps, the
unreachable-server and tool/Docker install hints. README drops the C
compiler (ntfy was its only user). The installer summary's password
wording is now per run (a reinstall in the same process no longer says
"you just chose"), and its test checks the URLs then the next steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 23:54:57 +00:00
337 changed files with 14221 additions and 5709 deletions
-4
View File
@@ -1,8 +1,4 @@
# Prefer scripts/configure-compose.py to detect the host timezone automatically.
TZ=Europe/London
# Replace this with your machine's LAN/VPN address, not localhost on the phone.
NTFY_BASE_URL=http://192.168.1.20:8090
# Explicitly expose ntfy on your trusted LAN/VPN; use HTTPS on public networks.
NTFY_BIND_ADDRESS=0.0.0.0
# Avoid collision while an existing host pipeline server still owns port 8080.
PIPELINES_PORT=8081
+1 -1
View File
@@ -4,7 +4,7 @@ Pipelines is a per-user server and CLI for running reusable AI workflows and cha
## Install
You need Go, Node.js 18+, Python 3.9+, git, curl, a C compiler, a running
You need Go, Node.js 18+, Python 3.9+, git, curl, a running
Docker (it builds the web app) and [OpenCode](https://opencode.ai) on your
`PATH`; see [docs/install.md](docs/install.md). From this checkout, run:
+1 -1
View File
@@ -63,7 +63,7 @@
<data android:scheme="pipelines" android:host="chat" />
</intent-filter>
</activity>
<!-- Instant delivery of server notifications without the ntfy app.
<!-- Instant delivery of server notifications while the app is closed.
specialUse: a persistent push connection to a self-hosted server
has no dedicated type, and dataSync is time-limited on Android 15. -->
<service
@@ -10,7 +10,7 @@ data class ServerNotification(
val title: String,
val message: String,
val click: String,
/** ntfy-style priority, clamped to 1..5 (3 is the default). */
/** Priority, clamped to 1..5 (3 is the default). */
val priority: Int,
val tags: List<String>,
val createdAt: String,
@@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit
/**
* Keeps one authenticated websocket to the configured Pipelines server while
* the app is in the background, like ntfy's instant delivery: no Flutter
* the app is in the background, for instant delivery: no Flutter
* engine runs here. It subscribes with the replay cursor, posts each pushed
* notification, mirrors cross-device clears and sends the user's own clears.
*
+5 -3
View File
@@ -1,5 +1,4 @@
import '../ui/adaptive/window_margins.dart';
import '../ui/theme/app_design.dart';
import '../ui/theme/app_design_controller.dart';
import '../ui/theme/app_font_controller.dart';
import '../ui/scale/ui_scale.dart';
@@ -55,11 +54,12 @@ class MyApp extends StatelessWidget {
final designs = this.designs ?? AppDesignController.instance;
return ListenableBuilder(
listenable: Listenable.merge([fonts, designs]),
builder: (context, _) => _host(designs.design, fonts.family),
builder: (context, _) => _host(designs, fonts.family),
);
}
Widget _host(AppDesign design, String? fontFamily) {
Widget _host(AppDesignController designs, String? fontFamily) {
final design = designs.design;
final router = routerConfig;
if (router != null) {
return MaterialApp.router(
@@ -68,6 +68,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
routerConfig: router,
);
@@ -78,6 +79,7 @@ class MyApp extends StatelessWidget {
builder: _scaled,
theme: design.light(fontFamily: fontFamily),
darkTheme: design.dark(fontFamily: fontFamily),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
home: AdaptiveShell(
destinationBodies: destinationBodies,
@@ -27,6 +27,7 @@ import 'detached_route.dart';
import 'detached_terminal.dart';
import 'detached_window_body.dart';
import 'detached_windows.dart';
import '../../features/chat/speech/app_speech.dart';
/// A detached window's whole app: one item ([route]) over its own
/// connection, without the shell (no navigation rail, lists, floating
@@ -119,6 +120,9 @@ class _DetachedWindowAppState extends State<DetachedWindowApp> {
@override
void dispose() {
// A reply read aloud belongs to this app's server: switching servers (a
// fresh app) or closing the window ends it.
unawaited(speechControllerIfCreated?.stop());
_session.removeListener(_connectionChanged);
widget.chatPool?.removeListener(_connectionChanged);
_terminals?.dispose();
@@ -223,6 +227,7 @@ class _DetachedWindowAppState extends State<DetachedWindowApp> {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
themeAnimationDuration: designs.themeAnimationDuration,
themeMode: ThemeMode.system,
// The window's one page is named by its route, so the address bar
// (and a reload) keeps the detached location instead of `/`.
+4
View File
@@ -84,6 +84,7 @@ import 'templates_destination.dart';
import 'tab_locations.dart';
import 'tab_locations_store.dart';
import '../ui/input/keyboard_owner.dart';
import '../features/chat/speech/app_speech.dart';
/// The application's return-to-foreground policy for the shared socket.
///
@@ -643,6 +644,9 @@ class _PipelinesAppState extends State<PipelinesApp>
@override
void dispose() {
// A reply read aloud belongs to this app's server: switching servers (a
// fresh app) or closing the window ends it.
unawaited(speechControllerIfCreated?.stop());
_stopAsking();
_tabLocations.dispose();
WidgetsBinding.instance.removeObserver(this);
+1
View File
@@ -389,6 +389,7 @@ class _PipelinesRootState extends State<PipelinesRoot> {
),
theme: designs.design.light(fontFamily: fonts.family),
darkTheme: designs.design.dark(fontFamily: fonts.family),
themeAnimationDuration: designs.themeAnimationDuration,
debugShowCheckedModeBanner: false,
home: flow,
),
@@ -1,6 +1,6 @@
/// An agent's own notification: the `chat_notify` app notification the server
/// records when a chat's model calls the `notify` tool, as the notification
/// stream carries it (see docs/ntfy.md).
/// stream carries it (see docs/notifications.md).
library;
/// The stream kind of an agent's notify call.
@@ -30,7 +30,7 @@ class AgentNotice {
final String title;
final String message;
/// The ntfy-style priority: 2 low, 3 default, 4 high.
/// The priority, 1-5: 2 low, 3 default, 4 high.
final int priority;
final DateTime? createdAt;
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The find-in-diff field `/` opens: the query, "3 of 12", previous and next
/// match, and close. Enter goes to the next match, Shift+Enter to the
@@ -37,7 +38,9 @@ class DiffSearchBar extends StatelessWidget {
: '$position of $count';
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(28),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(28)),
color: Theme.of(context).colorScheme.surfaceContainerHigh,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 4, 4),
+54 -46
View File
@@ -8,7 +8,10 @@ import 'chat_runtime.dart';
import 'conversation/chat_seen_interaction.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/composer_focus_request.dart';
import 'domain/chat_colors.dart';
import 'ui/sessions/chat_color_palette.dart';
import 'workspace/chat_pane_commands.dart';
import 'workspace/chat_pane_focus_flash.dart';
/// Where an open chat is shown and what that place alone decides: its Back,
/// its pane menu, whether it takes pastes, and what follows `/new` and
@@ -81,54 +84,59 @@ Widget buildChatPaneContent({
builder: (context) {
final row = runtime.rowFor(sessionId);
final start = runtime.startNotice;
return ChatComposerFocusScope(
return ChatPaneFocusFlash(
sessionId: sessionId,
requests: runtime.composerFocus,
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
requests: runtime.paneFlash,
color: chatColorShade(context, chatSessionColor(row)),
child: ChatComposerFocusScope(
sessionId: sessionId,
requests: runtime.composerFocus,
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatSeenInteraction(
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
initialDraft: runtime.pendingDrafts.remove(sessionId),
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
leadingControl: placement.leadingControl?.call(context),
paneCommands: placement.paneCommands,
onComposerFocus: placement.onComposerFocus,
onComposerReady: (composer) =>
runtime.registerComposer(sessionId, composer),
onComposerDisposed: (composer) =>
runtime.unregisterComposer(sessionId, composer),
onInteract: () => runtime.sessions.reportInteraction(sessionId),
child: ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
initialDraft: runtime.pendingDrafts.remove(sessionId),
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) =>
runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) =>
runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
leadingControl: placement.leadingControl?.call(context),
paneCommands: placement.paneCommands,
onComposerFocus: placement.onComposerFocus,
onComposerReady: (composer) =>
runtime.registerComposer(sessionId, composer),
onComposerDisposed: (composer) =>
runtime.unregisterComposer(sessionId, composer),
),
),
),
),
+5
View File
@@ -17,6 +17,7 @@ import 'data/chat_recency.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_body.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'workspace/chat_pane_focus_flash.dart';
/// What open chats share for one server, wherever they are shown (the Chat
/// destination's tiling or a floating window): the session list, the rows
@@ -134,6 +135,9 @@ class ChatRuntime extends ChangeNotifier {
/// Puts the keyboard in an opened chat's composer once it is built.
final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests();
/// Flashes the focus ring of the pane the keyboard just moved to.
final ChatPaneFlashRequests paneFlash = ChatPaneFlashRequests();
/// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there.
final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests();
@@ -296,6 +300,7 @@ class ChatRuntime extends ChangeNotifier {
sessions.dispose();
folds.dispose();
composerFocus.dispose();
paneFlash.dispose();
composers.clear();
_pendingAppends.clear();
super.dispose();
+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);
@@ -0,0 +1,86 @@
part of 'screen.dart';
/// A chat pane the keyboard can move to: a tiled pane or a floating window.
class _PaneCycleTarget {
const _PaneCycleTarget.pane(this.paneId, this.sessionId) : window = null;
_PaneCycleTarget.window(WindowEntry this.window)
: paneId = null,
sessionId = window.contentId;
final String? paneId;
final WindowEntry? window;
final String sessionId;
}
/// Alt+] and Alt+[ (also Cmd+] and Cmd+[ on Apple platforms, see
/// [chatPaneCycleShortcut]) move the keyboard to the next or previous chat
/// pane on screen: the tiled panes in their visual order (left to right,
/// then top to bottom, as the split tree lays them out; the center stage's
/// row in order), then the shown floating chat windows in the order they
/// were opened, wrapping around. The pane's composer takes the keyboard and
/// its focus ring flashes in the chat's colour. Nothing opens or closes.
///
/// It does nothing with one pane on screen, on a phone layout (the chat
/// stack and the quick switcher own moving between chats there), over a
/// popup or another destination, and while a terminal has the keyboard,
/// which keeps its Alt keys. Handled before the focus tree, so it works from
/// a composer and the web build stops the browser's own use of the keys.
mixin _ChatScreenPaneCycle on State<ChatScreen>, _ChatScreenWorkspace {
ChatRuntime get _runtime;
bool _paneCycleKey(KeyEvent event) {
final step = chatPaneCycleShortcut(event, HardwareKeyboard.instance);
if (step == null ||
!mounted ||
primaryFocusIsTypingSurface() ||
!_workspaceVisible ||
!showsListBesideDetail(context) ||
!_chatOwnsKeyboard()) {
return false;
}
final order = _paneCycleOrder();
final target = chatPaneCycleTarget(order, _paneCycleCurrent(order), step);
if (target == null) return false;
// A held chord is swallowed; only its first press moves.
if (event is KeyDownEvent) _focusPaneCycleTarget(target);
return true;
}
/// The panes on screen, in cycling order.
List<_PaneCycleTarget> _paneCycleOrder() {
final visible = _visibleSidebarSessions;
return [
for (final pane in _workspace.panes)
if (visible.contains(pane.sessionId))
_PaneCycleTarget.pane(pane.id, pane.sessionId),
for (final window
in widget.windows?.shownInOpenOrder() ?? const <WindowEntry>[])
_PaneCycleTarget.window(window),
];
}
/// Where the keyboard is in [order]: the floating chat window holding it,
/// otherwise the active tiled pane (also while the chat list has it).
int _paneCycleCurrent(List<_PaneCycleTarget> order) {
final window = keyboardWindow()?.entry;
if (window != null && window.kind == chatWindowKind) {
return order.indexWhere((target) => target.window?.id == window.id);
}
final active = _workspace.activePaneId;
return order.indexWhere((target) => target.paneId == active);
}
void _focusPaneCycleTarget(_PaneCycleTarget target) {
final window = target.window;
final windows = widget.windows;
if (window != null && windows != null) {
windows.manager.raise(window.id);
windows.kind.focusContent(window);
} else if (target.paneId case final paneId?) {
_workspace.activate(paneId);
_composerFocus.request(target.sessionId);
}
_runtime.paneFlash.flash(target.sessionId);
WidgetsBinding.instance.ensureVisualUpdate();
}
}
+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;
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import 'chat_bar_tint.dart';
/// The conversation bar's model and mode controls read as the bar's other
@@ -18,7 +19,13 @@ ButtonStyle chatBarTextButtonStyle(
// The same 12 px each side as an icon button's glyph inside its 48 px
// target, so text sits off its hover/press shape as it does top and bottom.
padding: compact ? null : chatBarButtonPadding,
minimumSize: compact ? null : const Size.square(kMinInteractiveDimension),
minimumSize: compact
? null
: Size.square(
AppDesignTokens.of(context).density.dense
? 32
: kMinInteractiveDimension,
),
);
/// Horizontal padding inside the bar's text buttons (model, mode).
@@ -1,8 +1,11 @@
import 'dart:async';
import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import '../../../core/transport/connection_state.dart';
import '../data/chat_repository.dart';
import '../domain/chat_commands.dart';
import '../speech/app_speech.dart';
/// Shows one local line in the conversation the command ran in.
typedef ChatCommandNoticeCallback = void Function(String text, {bool failed});
@@ -105,6 +108,8 @@ class ChatCommandActions {
if (!await confirmClose()) return;
try {
await repository.close(sessionId);
// Closing the chat ends its reply reading aloud.
unawaited(speechControllerIfCreated?.stopScope(sessionId));
onClosed?.call();
} catch (error) {
showNotice(_reason(error), failed: true);
@@ -1061,7 +1061,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context),
// A dense design's 32px attach centres
// on the 40px send button's line.
if (AppDesignTokens.of(context).density.dense)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: _attach(context),
)
else
_attach(context),
Expanded(
child: Focus(
canRequestFocus: false,
@@ -1329,7 +1337,12 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
// The pill draws the field's surface; the field adds no border.
border: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 12),
// A dense design's slim composer: one line as tall as the 40px send
// button (every design pins it), so the pill is 48px. Its compact
// density takes 4px off each of these 14.
contentPadding: EdgeInsets.symmetric(
vertical: AppDesignTokens.of(context).density.dense ? 14 : 12,
),
),
);
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_find_controller.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The chat's find bar, like the terminal's: the query field, the match
/// count, Match case, the older/newer and close buttons. Matches count from
@@ -68,7 +69,9 @@ class _ChatFindBarState extends State<ChatFindBar> {
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -78,6 +78,7 @@ import '../../../ui/layout/wheel_scroll_forwarding.dart';
import 'chat_reading_width.dart';
import '../ui/transcript/chat_copy_gutter.dart';
import '../speech/speech.dart';
import '../ui/speech/chat_speaking_control.dart';
import 'chat_pane_presentation.dart';
import 'chat_thread_header.dart';
import 'chat_transcript_anchor.dart';
@@ -754,11 +755,10 @@ class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
@override
void didUpdateWidget(covariant ChatThreadView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.sessionId != widget.sessionId ||
oldWidget.gateway != widget.gateway) {
// A pane reused for another conversation stops reading the previous
// one's reply, so neither its audio nor its highlight carries over.
unawaited(speechController.stopScope(oldWidget.sessionId));
// A reply keeps reading when its pane shows another conversation (the
// reader is the app's); a rename relabels the reading.
if (oldWidget.title != widget.title) {
speechControllerIfCreated?.retitle(widget.sessionId, widget.title.trim());
}
if (!identical(oldWidget.paneCommands, widget.paneCommands)) {
oldWidget.paneCommands?.removeListener(_takeCommands);
@@ -862,9 +862,8 @@ class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
@override
void dispose() {
// Leaving or closing the conversation stops its reply reading aloud; a
// reply another pane is reading carries on.
unawaited(speechController.stopScope(widget.sessionId));
// Leaving the conversation keeps its reply reading aloud: the reader is
// the app's, and closing or deleting the chat is what stops it.
_persistPosition();
_saveTranscript(widget.transcripts, widget.sessionId, widget.gateway);
widget.paneCommands?.removeListener(_takeCommands);
@@ -1334,11 +1333,20 @@ class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
pasteTarget: widget.pasteTarget,
ownsPasteWhenFocused: widget.ownsPasteWhenFocused,
runShell: _shellRuns.start,
limitBanner: ChatUsageLimitBanner(
thread: _controller,
composer: _composer,
accounts: _accounts,
autoContinue: widget.autoContinue,
limitBanner: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// The global Stop for a reading reply of any chat, shown
// above the active pane's composer only.
if (widget.pasteTarget) const ChatSpeakingControl(),
ChatUsageLimitBanner(
thread: _controller,
composer: _composer,
accounts: _accounts,
autoContinue: widget.autoContinue,
),
],
),
backgroundTasks: ChatBackgroundTasks(
key: ValueKey('chat-background-tasks-${widget.sessionId}'),
@@ -1604,13 +1612,19 @@ class _ChatThreadViewState extends State<ChatThreadView> with ChatFindHost {
],
)
: column;
if (!inShellBar) return content;
// The conversation draws its own floating bar; the page shows none.
final title = widget.title.trim();
// Read aloud labels a reading with this conversation.
final origin = SpeechOrigin(
scope: widget.sessionId,
title: title,
child: content,
);
if (!inShellBar) return origin;
// The conversation draws its own floating bar; the page shows none.
return ShellBar(
barless: true,
title: title.isEmpty ? null : title,
child: content,
child: origin,
);
},
),
+14 -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';
@@ -23,11 +23,13 @@ import '../../core/api_gateway.dart';
import '../../core/servers/server_context.dart';
import '../../core/servers/server_scope.dart';
import '../../shell/detached/detached_window_scope.dart';
import '../../shell/windows/window_entry.dart';
import '../../shell/windows/window_scope.dart';
import 'shell/chat_shell_dismiss.dart';
import '../terminal/terminal_open_action.dart';
import 'ui/sessions/session_pane_menu.dart';
import 'workspace/chat_pane_commands.dart';
import 'workspace/chat_pane_cycle.dart';
import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart';
@@ -41,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';
@@ -70,11 +74,13 @@ import '../../ui/input/keyboard_owner.dart';
part 'chat_screen_attention.dart';
part 'chat_screen_float.dart';
part 'chat_screen_pane_cycle.dart';
part 'chat_screen_pane_menu.dart';
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.
@@ -137,9 +143,11 @@ class _ChatScreenState extends State<ChatScreen>
_ChatScreenWorkspace,
_ChatScreenKeys,
_ChatScreenFloat,
_ChatScreenPaneCycle,
_ChatScreenPaneMenu,
_ChatScreenQuickSwitch,
_ChatScreenAttention,
_ChatScreenStackGroups,
_ChatScreenStack,
_ChatScreenListToggle {
/// The chats' shared state: the list, opened rows, accepted models,
@@ -191,9 +199,11 @@ class _ChatScreenState extends State<ChatScreen>
_runtime.recency.touch(initial);
}
_workspace.addListener(_workspaceChanged);
_stackGroups.addListener(_syncOpenWorkspace);
_bindWorkspacePersistence();
HardwareKeyboard.instance.addHandler(_cycleChatKey);
HardwareKeyboard.instance.addHandler(_slashFocusKey);
HardwareKeyboard.instance.addHandler(_paneCycleKey);
// Seen from now on, so the press that chooses the first chat counts.
LastPointerKind.instance;
_sessions.addListener(_nextChanged);
@@ -484,9 +494,11 @@ class _ChatScreenState extends State<ChatScreen>
_paneCommands.dispose();
HardwareKeyboard.instance.removeHandler(_cycleChatKey);
HardwareKeyboard.instance.removeHandler(_slashFocusKey);
HardwareKeyboard.instance.removeHandler(_paneCycleKey);
_page.dispose();
_workspaceBinding?.dispose();
_openWorkspace?.dispose();
_stackGroups.dispose();
_unbindWindows();
_unbindQuickSwitch();
_unbindAttention();
@@ -564,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
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'chat_shell_terminal_find.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The terminal's find bar: the query field (Enter finds the next match,
/// Shift+Enter the previous, Esc closes), the match count, Match case and
@@ -69,7 +70,9 @@ class _ChatShellTerminalFindBarState extends State<ChatShellTerminalFindBar> {
child: Material(
elevation: 3,
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
child: ListenableBuilder(
@@ -0,0 +1,50 @@
import 'package:flutter/foundation.dart';
import 'speech_controller.dart';
import 'speech_reading.dart';
/// The app's single reader, owned by the app (this window's engine), never by
/// a conversation view: a reply keeps reading across chat switches, panes and
/// the chat list. Each window (a detached window is its own app) has its own.
SpeechController get speechController =>
_speech ??= _bind<SpeechController>(SpeechController());
/// The app's reader if anything has used it yet. Code that only needs to stop
/// or retitle a reading uses this, so it never creates a platform engine.
SpeechController? get speechControllerIfCreated => _speech;
/// Replaces the app's reader (a fake engine in tests and capture fixtures);
/// null restores the platform one.
set debugSpeechController(SpeechController? controller) =>
_speech = _bind(controller);
/// The conversation the app's reader is reading, for the speaking indicator
/// and the global Stop. It follows the reader [debugSpeechController]
/// installs, and stays null until a reader exists.
ValueListenable<SpeechReading?> get speechReading => _reading;
SpeechController? _speech;
final _reading = _AppSpeechReading();
T _bind<T extends SpeechController?>(T controller) {
_reading.bind(controller);
return controller;
}
class _AppSpeechReading extends ChangeNotifier
implements ValueListenable<SpeechReading?> {
SpeechController? _source;
@override
SpeechReading? get value => _source?.reading.value;
void bind(SpeechController? source) {
final before = value;
_source?.reading.removeListener(notifyListeners);
_source = source;
source?.reading.addListener(notifyListeners);
// The reader is created lazily, often while a reply builds: a fresh one
// reads nothing, so it changes nothing and must not notify mid-build.
if (value != before) notifyListeners();
}
}
+3
View File
@@ -1,4 +1,7 @@
export 'app_speech.dart';
export 'speech_controller.dart';
export 'speech_document.dart';
export 'speech_engine.dart';
export 'speech_origin.dart';
export 'speech_preferences.dart';
export 'speech_reading.dart';
@@ -7,11 +7,18 @@ import 'flutter_tts_speech_engine.dart'
import 'speech_document.dart';
import 'speech_engine.dart';
import 'speech_preferences.dart';
import 'speech_reading.dart';
enum SpeechState { idle, speaking, paused }
/// The app-wide reader: one reply speaks at a time. It notifies on state
/// changes; the spoken word moves on the separate, frequent [word].
///
/// It belongs to the app (see [speechController]), not to the conversation
/// that started it: leaving that chat, switching panes or opening the list
/// keeps the reply reading. It ends when stopped, when it finishes, when
/// another reply starts, when its chat is closed or deleted ([stopScope]),
/// and when the app goes to the background or closes.
class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store})
: engine = engine ?? createSpeechEngine(),
@@ -44,6 +51,10 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
/// The range of the word being spoken in [document]'s text, or null.
final word = ValueNotifier<SpeechRange?>(null);
/// The conversation whose reply is reading (paused included), or null.
/// It changes only when a reading starts, ends or its chat is renamed.
final reading = ValueNotifier<SpeechReading?>(null);
bool get supported => engine.supported;
SpeechState get state => _state;
String? get messageId => _messageId;
@@ -64,12 +75,25 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
}
/// Reads reply [id] made of markdown [parts], stopping any other reading.
Future<void> read(String id, List<String> parts) async {
/// [scope] is the reply's conversation (by default the part of [id] before
/// its first `/`, see [speechMessageId]) and [title] its name, which the
/// speaking indicator and the global Stop show.
Future<void> read(
String id,
List<String> parts, {
String? scope,
String title = '',
}) async {
final document = speechDocumentFor(parts);
await stop();
await restore();
if (document.text.isEmpty) return;
await _speak(id, document, _voice);
await _speak(
id,
document,
_voice,
SpeechReading(scope: scope ?? speechScopeOf(id), title: title),
);
}
/// Speaks a short sample in [voice] (or the chosen one) at the chosen rate.
@@ -80,12 +104,19 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
speechSampleId,
speechDocumentFor(['This is how replies will sound when read aloud.']),
voice ?? _voice,
null,
);
}
Future<void> _speak(String id, SpeechDocument document, SpeechVoice? voice) {
Future<void> _speak(
String id,
SpeechDocument document,
SpeechVoice? voice,
SpeechReading? origin,
) {
_messageId = id;
_document = document;
reading.value = origin;
_awaitingStart = true;
word.value = null;
_set(SpeechState.speaking);
@@ -131,13 +162,24 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
_clear();
}
/// Stops reading when the reply being read has an id under [scope].
/// Stops reading when the reply being read belongs to conversation
/// [scope]: the chat was closed or deleted.
Future<void> stopScope(String scope) async {
if (_messageId?.startsWith(speechScopePrefix(scope)) ?? false) {
if (reading.value?.scope == scope ||
(_messageId?.startsWith(speechScopePrefix(scope)) ?? false)) {
await stop();
}
}
/// Follows a rename of the conversation being read.
void retitle(String scope, String title) {
final current = reading.value;
if (current == null || current.scope != scope || current.title == title) {
return;
}
reading.value = SpeechReading(scope: scope, title: title);
}
/// Sets the rate for the next reading; [save] false previews a slider drag.
Future<void> setRate(double value, {bool save = true}) async {
_rate = value.clamp(minSpeechRate, maxSpeechRate);
@@ -219,6 +261,7 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
_messageId = null;
_document = null;
word.value = null;
reading.value = null;
_state = SpeechState.idle;
notifyListeners();
}
@@ -247,6 +290,7 @@ class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
..onProgress = null;
if (_state != SpeechState.idle) unawaited(engine.stop().catchError((_) {}));
word.dispose();
reading.dispose();
super.dispose();
}
}
@@ -260,13 +304,8 @@ String speechScopePrefix(String scope) => '$scope/';
/// A reply's id for the reader, unique across conversations.
String speechMessageId(String scope, String rowId) => '$scope/$rowId';
SpeechController? _speechController;
/// The app's single reader.
SpeechController get speechController =>
_speechController ??= SpeechController();
/// Replaces the app's reader (a fake engine in tests and capture fixtures);
/// null restores the platform one.
set debugSpeechController(SpeechController? controller) =>
_speechController = controller;
/// The conversation part of a reader id made by [speechMessageId].
String speechScopeOf(String id) {
final slash = id.indexOf('/');
return slash < 0 ? id : id.substring(0, slash);
}
@@ -0,0 +1,22 @@
import 'package:flutter/widgets.dart';
/// Names the conversation a subtree's replies belong to, so Read aloud can
/// label the reading (the speaking indicator and the global Stop show it).
/// Looked up when a reading starts; it rebuilds nothing.
class SpeechOrigin extends InheritedWidget {
const SpeechOrigin({
super.key,
required this.scope,
required this.title,
required super.child,
});
final String scope;
final String title;
static SpeechOrigin? maybeOf(BuildContext context) =>
context.getInheritedWidgetOfExactType<SpeechOrigin>();
@override
bool updateShouldNotify(SpeechOrigin oldWidget) => false;
}
@@ -0,0 +1,18 @@
import 'package:flutter/foundation.dart';
/// The conversation a reading reply belongs to: [scope] is its chat id (the
/// list row's `id`, a federated id in a combined list) and [title] its name.
@immutable
class SpeechReading {
const SpeechReading({required this.scope, this.title = ''});
final String scope;
final String title;
@override
bool operator ==(Object other) =>
other is SpeechReading && other.scope == scope && other.title == title;
@override
int get hashCode => Object.hash(scope, title);
}
@@ -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,6 +1,7 @@
import '../../../../ui/adaptive/segmented_bar_overflow.dart';
import 'package:flutter/material.dart';
import '../../../../ui/status/app_spinner.dart';
import '../../../../ui/theme/app_design_tokens.dart';
class ChatBarAction extends StatelessWidget implements SegmentedOverflowable {
const ChatBarAction({
@@ -220,7 +221,9 @@ class ChatUndoBar extends StatelessWidget {
);
return Material(
elevation: 3,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: content,
);
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import '../../speech/app_speech.dart';
import 'chat_session_state.dart';
import 'session_activity_badge.dart';
@@ -14,7 +15,11 @@ class ChatCompactAvatar extends StatelessWidget {
required this.backgroundTasks,
this.awaitingOperator = 0,
required this.unread,
this.sessionId = '',
});
/// The chat's id; its reply being read aloud shows the speaking badge.
final String sessionId;
final String title;
final Color color;
final bool active, visible, running, unread;
@@ -45,13 +50,21 @@ class ChatCompactAvatar extends StatelessWidget {
),
),
),
if (chatSessionActivityBadge(
running: running,
backgroundTasks: backgroundTasks,
awaitingOperator: awaitingOperator,
)
case final badge?)
PositionedDirectional(bottom: -2, end: -3, child: badge),
PositionedDirectional(
bottom: -2,
end: -3,
child: ValueListenableBuilder(
valueListenable: speechReading,
builder: (context, reading, _) =>
chatSessionActivityBadge(
running: running,
backgroundTasks: backgroundTasks,
awaitingOperator: awaitingOperator,
speaking: sessionId.isNotEmpty && reading?.scope == sessionId,
) ??
const SizedBox.shrink(),
),
),
if (unread)
PositionedDirectional(
top: -2,
@@ -14,6 +14,7 @@ import 'session_row_style.dart';
import '../../domain/chat_list_activity.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import '../../../../ui/theme/app_design_tokens.dart';
/// A small, scrollable device-local rail. Full titles remain accessible.
class ChatCompactSidebar extends StatelessWidget {
@@ -102,6 +103,7 @@ class ChatCompactSidebar extends StatelessWidget {
awaitingOperator: awaitingOperator,
backgroundTasks: backgroundTasks,
unread: unread,
sessionId: id,
),
if (machineName case final name?)
Text(
@@ -147,7 +149,9 @@ class ChatCompactSidebar extends StatelessWidget {
data: row,
feedback: Material(
elevation: 4,
borderRadius: BorderRadius.circular(20),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatCompactAvatar(
title: title,
@@ -158,6 +162,7 @@ class ChatCompactSidebar extends StatelessWidget {
awaitingOperator: awaitingOperator,
backgroundTasks: backgroundTasks,
unread: unread,
sessionId: id,
),
label: Text(title),
),
@@ -12,6 +12,7 @@ import '../../../attention/runtime/attention_ack_sync.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_list_activity.dart';
import '../../domain/chat_sessions.dart';
import '../../speech/app_speech.dart';
import 'chat_seen_focus.dart';
import 'chat_session_local.dart';
import 'session_attention.dart';
@@ -425,6 +426,7 @@ class ChatSessionsController extends ChangeNotifier {
];
_seedLocal();
_loading = false;
_stopEndedReading(dropped: held.keys.toSet());
_notify();
} catch (error) {
if (generation != _generation) return;
@@ -646,7 +648,22 @@ class ChatSessionsController extends ChangeNotifier {
}
void _notify() {
if (!_disposed) notifyListeners();
if (_disposed) return;
_stopEndedReading();
notifyListeners();
}
/// A reply read aloud ends with its chat: closed here or on another device
/// (a refreshed row), or gone from a list that was read successfully
/// ([dropped]: deleted, or its machine removed).
void _stopEndedReading({Set<String> dropped = const {}}) {
final scope = speechReading.value?.scope;
if (scope == null) return;
final row = _sessions.where((row) => '${row['id'] ?? ''}' == scope);
final ended = row.isEmpty
? dropped.contains(scope)
: row.first['closed_at'] != null || row.first['closed'] == true;
if (ended) unawaited(speechControllerIfCreated?.stopScope(scope));
}
@override
@@ -1,16 +1,27 @@
import 'package:flutter/material.dart';
import '../../../../ui/status/app_spinner.dart';
import '../speech/chat_speaking_glyph.dart';
import 'chat_awaiting.dart';
/// The corner badge a chat's avatar wears for its live activity: the
/// platform's activity indicator while a turn runs; otherwise, while
/// background tasks still run, a quiet muted glyph (never a second spinner).
/// Null when the chat is idle.
/// Null when the chat is idle. While one of the chat's replies is read aloud
/// ([speaking]) the badge is the speaking glyph instead, above everything
/// else: it is the only place that says which chat is talking.
Widget? chatSessionActivityBadge({
required bool running,
required int backgroundTasks,
int awaitingOperator = 0,
bool speaking = false,
}) {
if (speaking) {
return Semantics(
key: const Key('chat-row-speaking'),
label: 'Reading aloud',
child: const _BadgeDisc(child: ChatSpeakingGlyph()),
);
}
// Waiting on the operator outranks everything: the agent is blocked.
if (awaitingOperator > 0) return ChatAwaitingBadge(count: awaitingOperator);
if (running) {
@@ -13,11 +13,13 @@ import 'chat_color_palette.dart';
import 'chat_visibility_marker.dart';
import 'chat_session_state.dart';
import 'session_actions.dart';
import '../../speech/app_speech.dart';
import 'session_activity_badge.dart';
import 'session_harness_icon.dart';
import 'session_pane_menu.dart';
import 'session_row_style.dart';
import 'chat_awaiting.dart';
import '../../../../ui/theme/app_design_tokens.dart';
/// One chat in the list, in the app's shared row on both hosts: the harness
/// avatar, the title with its recency, one muted line, and the actions menu.
@@ -90,7 +92,9 @@ class ChatSessionRow extends StatelessWidget {
data: session,
feedback: Material(
elevation: 4,
borderRadius: BorderRadius.circular(20),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(20)),
child: Chip(
avatar: ChatSessionAvatar(session: session),
label: Text(chatSessionTitle(session)),
@@ -275,15 +279,24 @@ class ChatSessionAvatar extends StatelessWidget {
: scheme.surfaceContainerHighest;
mark = selected ? scheme.onPrimaryContainer : scheme.onSurfaceVariant;
}
return AppListAvatar(
foreground: mark,
background: fill,
badge: chatSessionActivityBadge(
running: running,
backgroundTasks: backgroundTasks,
awaitingOperator: awaitingOperator,
final id = '${session['id'] ?? ''}';
final icon = SessionHarnessIcon(session: session, color: mark);
// The badge follows the app's reader: the chat whose reply is being read
// aloud shows the speaking glyph, wherever its avatar is drawn.
return ValueListenableBuilder(
valueListenable: speechReading,
child: icon,
builder: (context, reading, icon) => AppListAvatar(
foreground: mark,
background: fill,
badge: chatSessionActivityBadge(
running: running,
backgroundTasks: backgroundTasks,
awaitingOperator: awaitingOperator,
speaking: id.isNotEmpty && reading?.scope == id,
),
child: icon!,
),
child: SessionHarnessIcon(session: session, color: mark),
);
}
}
@@ -0,0 +1,85 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../../../ui/theme/app_design_tokens.dart';
import '../../speech/speech.dart';
const chatSpeakingStopLabel = 'Stop speaking';
/// "Speaking · Chat name" and Stop for the reply the app is reading, from any
/// chat: the reader is the app's, so a reply keeps reading after its chat is
/// left, and this is the one place to stop it without going back. Nothing
/// while no reply reads (the Settings voice sample included).
class ChatSpeakingControl extends StatelessWidget {
const ChatSpeakingControl({super.key});
@override
Widget build(BuildContext context) => ValueListenableBuilder(
valueListenable: speechReading,
builder: (context, reading, _) {
final speech = speechControllerIfCreated;
if (reading == null || speech == null) return const SizedBox.shrink();
return ListenableBuilder(
listenable: speech,
builder: (context, _) => _pill(context, speech, reading),
);
},
);
Widget _pill(
BuildContext context,
SpeechController speech,
SpeechReading reading,
) {
final scheme = Theme.of(context).colorScheme;
final tokens = AppDesignTokens.of(context);
final state = speech.state == SpeechState.paused ? 'Paused' : 'Speaking';
final title = reading.title.isEmpty ? 'a chat' : reading.title;
final label = '$state · $title';
final text = Theme.of(context).textTheme.labelMedium;
return Padding(
padding: const EdgeInsetsDirectional.only(bottom: 8),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Material(
key: const Key('chat-speaking-control'),
color: tokens.panelFill(scheme, scheme.surfaceContainerHigh),
shape: tokens
.shape(const StadiumBorder())
.copyWith(side: tokens.frameSide),
clipBehavior: Clip.antiAlias,
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.graphic_eq, size: 16, color: scheme.primary),
const SizedBox(width: 8),
Flexible(
child: Semantics(
liveRegion: true,
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: text?.copyWith(color: scheme.onSurfaceVariant),
),
),
),
IconButton(
key: const Key('chat-speaking-stop'),
tooltip: chatSpeakingStopLabel,
visualDensity: VisualDensity.compact,
iconSize: 18,
onPressed: () => unawaited(speech.stop()),
icon: const Icon(Icons.stop),
),
],
),
),
),
),
);
}
}
@@ -0,0 +1,95 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
/// A chat's "speaking" mark: three sound-wave bars that rise and fall while
/// one of its replies is read aloud. Under reduced motion it is a still
/// speaker icon.
class ChatSpeakingGlyph extends StatefulWidget {
const ChatSpeakingGlyph({super.key, this.size = 12, this.color});
final double size;
/// Null takes the theme's primary colour.
final Color? color;
@override
State<ChatSpeakingGlyph> createState() => _ChatSpeakingGlyphState();
}
class _ChatSpeakingGlyphState extends State<ChatSpeakingGlyph>
with SingleTickerProviderStateMixin {
late final AnimationController _wave = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 900),
);
bool get _still => MediaQuery.maybeDisableAnimationsOf(context) ?? false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_still) {
_wave.stop();
} else if (!_wave.isAnimating) {
_wave.repeat();
}
}
@override
void dispose() {
_wave.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final color = widget.color ?? Theme.of(context).colorScheme.primary;
if (_still) {
return Icon(
Icons.volume_up,
key: const Key('chat-speaking-still'),
size: widget.size,
color: color,
);
}
// Its own layer: the bars repaint every frame without the row.
return RepaintBoundary(
child: CustomPaint(
key: const Key('chat-speaking-wave'),
size: Size.square(widget.size),
painter: _WavePainter(_wave, color),
),
);
}
}
class _WavePainter extends CustomPainter {
_WavePainter(this.wave, this.color) : super(repaint: wave);
final Animation<double> wave;
final Color color;
@override
void paint(Canvas canvas, Size size) {
const bars = 3;
final gap = size.width / (bars * 2 + 1);
final paint = Paint()
..color = color
..strokeWidth = gap * 1.4
..strokeCap = StrokeCap.round;
for (var bar = 0; bar < bars; bar++) {
final phase = (wave.value + bar / bars) * 2 * math.pi;
// Each bar swings between a third and the full height, out of step.
final height = size.height * (0.35 + 0.3 * (1 + math.sin(phase)));
final x = gap * (bar * 2 + 1.5);
final top = (size.height - height) / 2 + paint.strokeWidth / 2;
final bottom = (size.height + height) / 2 - paint.strokeWidth / 2;
canvas.drawLine(Offset(x, top), Offset(x, math.max(top, bottom)), paint);
}
}
@override
bool shouldRepaint(_WavePainter oldDelegate) =>
oldDelegate.color != color || oldDelegate.wave != wave;
}
@@ -69,7 +69,9 @@ class ChatAutomatedPromptCard extends StatelessWidget {
],
),
);
final transcript = AppDesignTokens.of(context).transcript;
final tokens = AppDesignTokens.of(context);
final density = tokens.density;
final transcript = tokens.transcript;
final card = transcript == TranscriptStyle.manuscript
? PaperEditorialNote(
label: label,
@@ -84,11 +86,18 @@ class ChatAutomatedPromptCard extends StatelessWidget {
color: scheme.surfaceContainerLow,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(16)),
borderRadius: tokens.corners(
const BorderRadius.all(Radius.circular(16)),
),
side: BorderSide(color: scheme.outlineVariant),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 8, 14, 10),
padding: EdgeInsets.fromLTRB(
density.inset(14),
density.space(8),
density.inset(14),
density.space(10),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
@@ -166,7 +166,11 @@ class ChatCodeCopyRegion extends StatelessWidget {
key: const Key('chat-code-header'),
color: headerFill(context),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12, end: 4),
// Its label starts at the code's own inset (tighter when dense).
padding: EdgeInsetsDirectional.only(
start: AppDesignTokens.of(context).density.space(12),
end: 4,
),
child: Row(
children: [
Expanded(child: label),
@@ -272,7 +272,9 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
code: code,
label: Text(markdownCodeLabel(language), style: labelStyle),
child: Padding(
padding: const EdgeInsets.all(12),
padding: EdgeInsets.all(
AppDesignTokens.of(context).density.space(12),
),
child: ChatTranscriptHorizontalScrollView(
label: 'code block',
child: Text.rich(
@@ -570,9 +572,15 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
/// a tighter line, as a technical book does.
TextStyle _codeStyle(BuildContext context) {
const mono = TextStyle(fontFamily: appMonospaceFamily);
final reading = AppDesignTokens.of(context).reading;
if (reading.family == null) return mono;
final tokens = AppDesignTokens.of(context);
final reading = tokens.reading;
final size = DefaultTextStyle.of(context).style.fontSize ?? 16;
// A dense design sets code at its body size (13 beside 14px prose): the
// monospace runs wider than the prose face.
if (reading.family == null && tokens.density.dense) {
return mono.copyWith(fontSize: size * 13 / 14, height: 1.4);
}
if (reading.family == null) return mono;
return mono.copyWith(
fontSize: size * 0.82,
height: 1.45,
@@ -55,15 +55,26 @@ class ChatUserBubble extends StatelessWidget {
break;
}
// A Material surface (not a bare DecoratedBox) so a disclosure ListTile
// inside the bubble keeps its ink and background.
// inside the bubble keeps its ink and background. A dense design draws
// a tighter bubble in its own corners.
final tokens = AppDesignTokens.of(context);
final density = tokens.density;
return Material(
color: chatBubbleFill(
context,
Theme.of(context).colorScheme.surfaceContainerHighest,
),
clipBehavior: Clip.antiAlias,
shape: const RoundedRectangleBorder(borderRadius: _radius),
child: Padding(padding: _padding, child: child),
shape: RoundedRectangleBorder(borderRadius: tokens.corners(_radius)),
child: Padding(
padding: density.dense
? EdgeInsets.symmetric(
horizontal: density.inset(_padding.left),
vertical: density.space(_padding.top),
)
: _padding,
child: child,
),
);
}
}
@@ -89,8 +100,10 @@ TextStyle? chatMessageTextStyle(BuildContext context) => AppDesignTokens.of(
/// The empty-line gap between two paragraphs of a reply: about one line of
/// body text at [fontSize] (else the ambient text size), scaled by the
/// operator's text scaling, so chunks read as separate paragraphs.
/// operator's text scaling, so chunks read as separate paragraphs. A design
/// may set a tighter gap ([ReadingType.paragraphGap]).
double chatParagraphGap(BuildContext context, [double? fontSize]) {
final size = fontSize ?? DefaultTextStyle.of(context).style.fontSize ?? 14;
return MediaQuery.textScalerOf(context).scale(size) * 0.9;
return MediaQuery.textScalerOf(context).scale(size) *
AppDesignTokens.of(context).reading.paragraphGap;
}
@@ -22,7 +22,7 @@ import 'paper/paper_quote.dart';
import 'terminal/terminal_glyphs.dart';
import 'chat_message_timestamp.dart';
import 'chat_read_aloud_button.dart';
import '../../speech/speech_controller.dart';
import '../../speech/speech.dart';
/// Builds an assistant text part; the default keeps the server's text exactly.
typedef ChatMessageTextBuilder = Widget Function(BuildContext, String);
@@ -83,7 +83,8 @@ class ChatMessageView extends StatelessWidget {
// A terminal or manuscript transcript reads top to bottom: the
// operator's prompt line or block quote starts at the same edge as the
// answer and spans its column.
final transcript = AppDesignTokens.of(context).transcript;
final tokens = AppDesignTokens.of(context);
final transcript = tokens.transcript;
final trailingUser =
user && !automated && transcript == TranscriptStyle.bubbles;
// No visible role label: side and surface say who spoke and the row's
@@ -104,9 +105,12 @@ class ChatMessageView extends StatelessWidget {
label: '$role message',
child: Padding(
// A manuscript leaves a little more air between turns, as a page
// spaces its paragraphs, since no bubble sets them apart.
// spaces its paragraphs, since no bubble sets them apart; a dense
// design a little less.
padding: EdgeInsets.symmetric(
vertical: transcript == TranscriptStyle.manuscript ? 12 : 6,
vertical: transcript == TranscriptStyle.manuscript
? 12
: tokens.density.space(6),
),
child: LayoutBuilder(
builder: (context, constraints) => Align(
@@ -13,6 +13,8 @@ const chatStopReadingLabel = 'Stop reading';
/// Read aloud for one reply, styled like its Copy button. While this reply
/// reads it becomes Pause (or Resume) and Stop, laid out along [direction]
/// (a column in the narrow copy gutter). Absent where speech is unsupported.
/// The reader is the app's, so a reply still reading after its chat was left
/// shows Pause and Stop again when the chat is reopened.
class ChatReadAloudButton extends StatelessWidget {
const ChatReadAloudButton({
super.key,
@@ -40,7 +42,19 @@ class ChatReadAloudButton extends StatelessWidget {
key: const Key('chat-message-read-aloud'),
style: style,
tooltip: chatReadAloudLabel,
onPressed: () => unawaited(speech.read(messageId, parts)),
onPressed: () {
// The conversation's name labels the reading wherever it is
// shown (the avatar's indicator, the global Stop).
final origin = SpeechOrigin.maybeOf(context);
unawaited(
speech.read(
messageId,
parts,
scope: origin?.scope,
title: origin?.title ?? '',
),
);
},
icon: const Icon(Icons.volume_up_outlined),
);
}
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
@@ -123,7 +124,8 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
: DateTime.now().difference(started);
final seconds = duration.inSeconds.clamp(0, 2147483647);
final label = '${data.label}${widget.streaming ? ' ${seconds}s' : ''}';
switch (AppDesignTokens.of(context).transcript) {
final tokens = AppDesignTokens.of(context);
switch (tokens.transcript) {
case TranscriptStyle.prompt:
return TerminalActivityRows(
data: data,
@@ -145,8 +147,12 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
}
// Desktop hover hugs the label; phones keep the full-width touch row.
final compact = prefersCompactHitTargets(context);
// A dense design draws the line slimmer on a pointer device; a touch
// device keeps a 40px target.
final density = tokens.density;
final dense = density.dense;
final content = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 32),
constraints: BoxConstraints(minHeight: dense ? 20 : 32),
child: Row(
mainAxisSize: compact ? MainAxisSize.min : MainAxisSize.max,
children: [
@@ -157,7 +163,7 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
child: const ChatResponsePending(),
),
),
const SizedBox(width: 8),
SizedBox(width: density.space(8)),
],
Flexible(
child: Text(
@@ -179,8 +185,13 @@ class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
final button = TextButton(
key: const Key('chat-turn-activity'),
style: TextButton.styleFrom(
minimumSize: const Size(0, 48),
padding: const EdgeInsets.all(chatAgentContentInset),
minimumSize: Size(0, dense ? math.max(28, density.minTouchRow) : 48),
padding: dense
? const EdgeInsets.symmetric(
horizontal: chatAgentContentInset,
vertical: 4,
)
: const EdgeInsets.all(chatAgentContentInset),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: AlignmentDirectional.centerStart,
),
@@ -109,9 +109,9 @@ class _ChatTurnChipState extends State<ChatTurnChip> {
).corners(BorderRadius.circular(8)),
onTap: _show,
child: Padding(
padding: const EdgeInsets.symmetric(
padding: EdgeInsets.symmetric(
horizontal: chatAgentContentInset,
vertical: 6,
vertical: AppDesignTokens.of(context).density.space(6),
),
child: content,
),
@@ -4,8 +4,9 @@ import '../../../../../core/api_gateway.dart';
import 'chat_shown_surface.dart';
/// What a `notify` entry says: where the notification went (the server's
/// `channels`: the operator's signed-in Pipelines `apps` and/or their `phone`),
/// or why it was not sent.
/// `channels`: the operator's signed-in Pipelines `apps`; `phone` appears only
/// in entries recorded before the server stopped publishing to a phone push
/// service), or why it was not sent.
String chatShownNotifyText(JsonMap item) {
final title = chatShownTitle(item, 'notification');
if (item['delivered'] == true) return '${_notifiedWhere(item)}: $title';
@@ -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;
}
}
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// The step Alt+] (1) or Alt+[ (-1) moves the keyboard between the chat
/// panes on screen, or null for any other key. On Apple platforms Cmd+] and
/// Cmd+[ do the same.
///
/// Why these keys:
/// - Alt+Tab and Cmd+Tab are the system's window switchers, Ctrl+Tab cycles
/// the open chats (and the browser keeps it), and Alt+` already cycles the
/// floating windows.
/// - Browsers use Alt+Left/Right for back and forward; nothing on GNOME,
/// Hyprland, Windows or a browser binds Alt+[ or Alt+].
/// - Option+] and Option+[ type quotes on a Mac, so with Alt the key is
/// matched by its position (also catching layouts whose bracket keys type
/// something else). Cmd+] and Cmd+[ are the Mac's own next/previous pair
/// and leave Option free for typing.
/// - AltGr is how several layouts type brackets, so it never matches.
///
/// Shift never matches: Alt+Shift+[ types braces. A focused terminal keeps
/// these keys (Alt+[ is its escape prefix); the caller checks that.
int? chatPaneCycleShortcut(
KeyEvent event,
HardwareKeyboard keyboard, {
TargetPlatform? platform,
}) {
if (event is KeyUpEvent ||
keyboard.isShiftPressed ||
keyboard.isControlPressed ||
keyboard.isLogicalKeyPressed(LogicalKeyboardKey.altGraph)) {
return null;
}
final alt = keyboard.isAltPressed;
final meta = keyboard.isMetaPressed;
final int? step;
if (alt && !meta) {
step = switch (event.physicalKey) {
PhysicalKeyboardKey.bracketRight => 1,
PhysicalKeyboardKey.bracketLeft => -1,
_ => null,
};
} else if (meta && !alt && _apple(platform ?? defaultTargetPlatform)) {
step =
event.logicalKey == LogicalKeyboardKey.bracketRight ||
event.physicalKey == PhysicalKeyboardKey.bracketRight
? 1
: event.logicalKey == LogicalKeyboardKey.bracketLeft ||
event.physicalKey == PhysicalKeyboardKey.bracketLeft
? -1
: null;
} else {
step = null;
}
return step;
}
bool _apple(TargetPlatform platform) =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The forward and backward chords as this platform reads them, for the
/// shortcuts list.
String chatPaneCycleShortcutLabel([TargetPlatform? platform]) =>
_apple(platform ?? defaultTargetPlatform)
? 'Option+], Option+[, Cmd+], Cmd+['
: 'Alt+], Alt+[';
/// The entry [step] places from [current] in [order], wrapping around; null
/// when there is no other entry to move to. A [current] outside [order]
/// starts from the first entry going forward and the last going back.
T? chatPaneCycleTarget<T>(List<T> order, int current, int step) {
if (order.length < 2 || step == 0) return null;
if (current < 0 || current >= order.length) {
return step > 0 ? order.first : order.last;
}
return order[(current + step) % order.length];
}
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// Asks the chat pane showing a session to flash its focus ring, once the
/// keyboard moved there by the pane-cycling chord (see
/// [chatPaneCycleShortcut]). Shared by the tiling and the floating windows.
class ChatPaneFlashRequests extends ChangeNotifier {
String? _sessionId;
int _serial = 0;
/// The session last asked to flash.
String? get sessionId => _sessionId;
/// Advances on every request, so asking the same pane again flashes again.
int get serial => _serial;
void flash(String sessionId) {
_sessionId = sessionId;
_serial++;
notifyListeners();
}
}
/// How long the ring shows before it is gone.
const chatPaneFlashDuration = Duration(milliseconds: 700);
/// The ring's width, in logical pixels.
const chatPaneFlashWidth = 2.0;
/// One chat pane's focus cue: a ring in the chat's [color] drawn over the
/// pane, fading out, when [requests] names [sessionId]. Under reduced motion
/// the ring shows for the same time without fading. It also holds a focus
/// node around the pane: when nothing inside the pane took the keyboard
/// (the composer is not there or cannot be focused), the pane itself does.
class ChatPaneFocusFlash extends StatefulWidget {
const ChatPaneFocusFlash({
super.key,
required this.sessionId,
required this.requests,
required this.color,
required this.child,
});
final String sessionId;
final ChatPaneFlashRequests requests;
final Color? color;
final Widget child;
@override
State<ChatPaneFocusFlash> createState() => _ChatPaneFocusFlashState();
}
class _ChatPaneFocusFlashState extends State<ChatPaneFocusFlash>
with SingleTickerProviderStateMixin {
late final AnimationController _ring = AnimationController(
vsync: this,
duration: chatPaneFlashDuration,
);
final FocusNode _pane = FocusNode(
debugLabel: 'Chat pane',
skipTraversal: true,
);
int _seen = 0;
@override
void initState() {
super.initState();
_seen = widget.requests.serial;
widget.requests.addListener(_requested);
}
@override
void didUpdateWidget(ChatPaneFocusFlash oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.requests != widget.requests) {
oldWidget.requests.removeListener(_requested);
widget.requests.addListener(_requested);
_seen = widget.requests.serial;
}
}
@override
void dispose() {
widget.requests.removeListener(_requested);
_ring.dispose();
_pane.dispose();
super.dispose();
}
void _requested() {
final requests = widget.requests;
if (requests.serial == _seen) return;
_seen = requests.serial;
if (requests.sessionId != widget.sessionId) return;
_ring.forward(from: 0);
// The composer takes its request after a frame; look a frame later.
SchedulerBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
SchedulerBinding.instance
..addPostFrameCallback((_) {
if (mounted && !_pane.hasFocus) _pane.requestFocus();
})
..ensureVisualUpdate();
});
}
@override
Widget build(BuildContext context) {
final color = widget.color ?? Theme.of(context).colorScheme.primary;
final still = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
final radius = AppDesignTokens.of(context).radius ?? 0;
return Focus(
focusNode: _pane,
child: Stack(
fit: StackFit.passthrough,
children: [
widget.child,
Positioned.fill(
child: IgnorePointer(
child: AnimatedBuilder(
animation: _ring,
builder: (context, _) {
if (!_ring.isAnimating) return const SizedBox.shrink();
final fade = still
? 1.0
: 1 - Curves.easeIn.transform(_ring.value);
return DecoratedBox(
key: const ValueKey('chat-pane-focus-flash'),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(radius),
border: Border.all(
color: color.withValues(alpha: color.a * fade),
width: chatPaneFlashWidth,
),
),
);
},
),
),
),
],
),
);
}
}
@@ -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));
@@ -0,0 +1,115 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart';
import '../../runs/domain/run_tokens.dart';
import 'stage_visits.dart';
/// What one run recorded for one stage, for the graph's stage popover.
///
/// Read from the run detail's own steps only: a stage the run never visited
/// has [visits] 0 and nothing else, and nothing is estimated.
class StageRunFacts {
const StageRunFacts({
required this.visits,
this.status,
this.duration,
this.usage,
this.verdict,
this.handoff,
this.failure,
});
/// How many recorded visits the stage has.
final int visits;
/// The latest visit's recorded status word.
final String? status;
/// The latest visit's duration, when both timestamps were recorded.
final String? duration;
/// Reported tokens and cost summed over every visit (`12.4k tok · $0.31`).
final String? usage;
/// The latest visit's recorded verdict: `option: reason`.
final String? verdict;
/// The first non-blank line of the latest visit's handoff output.
final String? handoff;
/// The latest visit's recorded diagnostic when it failed.
final String? failure;
}
/// The facts [run] recorded for [stageKey].
StageRunFacts stageRunFacts(JsonMap run, String stageKey) {
final steps = run['steps'];
final list = steps is List
? steps.whereType<Map>().map(JsonMap.from).toList()
: const <JsonMap>[];
final visits = visitsByStage(list)[stageKey] ?? const <JsonMap>[];
if (visits.isEmpty) return const StageRunFacts(visits: 0);
final latest = visits.last;
final status = _text(latest['status']);
final seconds = durationSeconds(
_text(latest['started_at']),
_text(latest['finished_at']),
);
var tokens = 0;
var tokensKnown = false;
var cost = 0.0;
var costKnown = false;
for (final visit in visits) {
final usage = stageTokenUsage(visit);
if (usage == null) continue;
tokens += usage.total;
tokensKnown = true;
final visitCost = usage.cost;
if (visitCost != null) {
cost += visitCost;
costKnown = true;
}
}
final verdict = latest['verdict'];
String? verdictText;
if (verdict is Map) {
final option = _text(verdict['option']);
final reason = _firstLine(verdict['reason']);
verdictText = [?option, ?reason].join(': ');
if (verdictText.isEmpty) verdictText = null;
}
final failed = status != null && _failed(status);
return StageRunFacts(
visits: visits.length,
status: status,
duration: seconds == null ? null : formatDuration(seconds),
usage: tokensKnown || costKnown
? [
if (tokensKnown) '${formatTokenCount(tokens)} tok',
if (costKnown) '\$${cost.toStringAsFixed(2)}',
].join(' · ')
: null,
verdict: verdictText,
handoff: _firstLine(latest['output']),
failure: failed ? _firstLine(latest['diagnostic']) : null,
);
}
bool _failed(String status) {
final word = status.trim().toLowerCase();
return word == 'failed' || word == 'error' || word == 'blocked';
}
String? _text(dynamic value) {
final text = '${value ?? ''}'.trim();
return text.isEmpty ? null : text;
}
String? _firstLine(dynamic value) {
final text = _text(value);
if (text == null) return null;
for (final line in text.split('\n')) {
final trimmed = line.trim().replaceFirst(RegExp(r'^#+\s*'), '');
if (trimmed.isNotEmpty) return trimmed;
}
return null;
}
@@ -0,0 +1,246 @@
import 'dart:convert';
import 'check_stage.dart';
import 'graph_definition.dart';
import 'graph_protocol.dart';
import 'stage_definition.dart';
/// The kind of stage a popover names in its type chip.
enum StageKind { model, check, deliveryGate, findings, human, other, terminal }
/// The tool set a model stage runs with when it declares no `tools` block: the
/// server's legacy bundle (`legacyTools` in `internal/stage/tools.go`).
const List<String> defaultStageTools = [
'read',
'glob',
'grep',
'edit',
'shell',
];
/// One declared outgoing route: `outcome → target`.
typedef StageRoute = ({String outcome, String target});
/// A compact, read-only digest of one stage declaration for the graph's stage
/// popover. Pure data: built from the stage JSON the definition graph carries;
/// a field the declaration omits stays empty rather than guessed.
class StageSummary {
const StageSummary({
required this.key,
required this.kind,
required this.typeLabel,
this.meta = const [],
this.tools = const [],
this.toolsDefault = false,
this.permissions = const [],
this.skills = const [],
this.prompt,
this.commands = const [],
this.gate = const [],
this.limits = const [],
this.routes = const [],
});
final String key;
final StageKind kind;
/// The type chip's word: `Model`, `Check`, `Findings gate`, ...
final String typeLabel;
/// Short configuration chips in reading order: harness, model, effort,
/// timeout, retries, budget.
final List<String> meta;
/// The model stage's tools, in declared order.
final List<String> tools;
/// True when [tools] is the server default because no block was declared.
final bool toolsDefault;
/// Permission allow-lists as `edit: path, path` lines.
final List<String> permissions;
final List<String> skills;
/// A model stage's prompt or a human stage's operator instructions.
final String? prompt;
/// A check stage's commands, one per line.
final List<String> commands;
/// A findings gate's severity and origin facts.
final List<String> gate;
/// Limit facts: `max 3 visits`, `on fail`, `exhausted: decide`.
final List<String> limits;
/// Declared routes, for a terminal the routes into it.
final List<StageRoute> routes;
}
/// The digest of [key] in [graph], or null when the version does not declare
/// it (a terminal is summarised by its incoming routes instead).
StageSummary? stageSummaryFor(dynamic graph, String key) {
if (isTerminalTarget(key)) {
return StageSummary(
key: key,
kind: StageKind.terminal,
typeLabel: 'End',
routes: [
for (final edge in graphEdges(graph))
if (edge.target == key)
(outcome: edge.label, target: nodeDisplayLabel(edge.source)),
],
);
}
final stage = stageDefinitionFor(graph, key);
if (stage == null) return null;
final type = effectiveStageType(stage['type']).trim();
final kind = switch (type) {
'model' => StageKind.model,
'check' => isDeliveryGate(stage) ? StageKind.deliveryGate : StageKind.check,
'findings' => StageKind.findings,
'human' => StageKind.human,
_ => StageKind.other,
};
final configs = _strings(stage['configs']);
final blocks = _strings(stage['blocks']);
final declaredTools = blocks['tools'];
final tools = kind != StageKind.model
? const <String>[]
: declaredTools == null
? defaultStageTools
: _lines(declaredTools);
final prompt = (blocks['prompt'] ?? _text(stage['prompt'])).trim();
return StageSummary(
key: key,
kind: kind,
typeLabel: stageKindLabel(kind, type),
meta: _meta(kind, configs),
tools: tools,
toolsDefault: kind == StageKind.model && declaredTools == null,
permissions: _permissions(blocks['permissions']),
skills: _lines(blocks['skills'] ?? ''),
prompt:
(kind == StageKind.model ||
kind == StageKind.human ||
kind == StageKind.other) &&
prompt.isNotEmpty
? prompt
: null,
commands: kind == StageKind.check || kind == StageKind.deliveryGate
? checkCommands(stage)
: const [],
gate: kind == StageKind.findings
? [
'min severity ${configs['severity'] ?? 'important'}',
'origin ${configs['origin'] ?? 'introduced'}',
]
: const [],
limits: _limits(stage['limits']),
routes: [
for (final edge in graphEdges({
'stages': [stage],
}))
(outcome: edge.label, target: nodeDisplayLabel(edge.target)),
],
);
}
/// The type chip's word for [kind]; an unknown type keeps its own name.
String stageKindLabel(StageKind kind, [String type = '']) => switch (kind) {
StageKind.model => 'Model',
StageKind.check => 'Check',
StageKind.deliveryGate => 'Delivery gate',
StageKind.findings => 'Findings gate',
StageKind.human => 'Human',
StageKind.terminal => 'End',
StageKind.other =>
type.isEmpty ? 'Stage' : '${type[0].toUpperCase()}${type.substring(1)}',
};
/// A model id without its vendor prefix and date stamp:
/// `anthropic/claude-sonnet-4-5-20250929` reads `claude-sonnet-4-5`.
String shortModelName(String model) {
var name = model.trim();
final slash = name.lastIndexOf('/');
if (slash >= 0) name = name.substring(slash + 1);
return name.replaceFirst(RegExp(r'-\d{8}$'), '');
}
List<String> _meta(StageKind kind, Map<String, String> configs) {
String? config(String key) {
final value = configs[key]?.trim();
return value == null || value.isEmpty ? null : value;
}
final harness = config('harness');
final provider = config('provider');
final model = config('model');
final effort = config('reasoning_effort');
final timeout = config('timeout') ?? config('command_timeout');
final retries = config('retries');
final budget = config('budget_usd');
final tokens = config('budget_tokens');
return [
?harness,
if (model != null)
shortModelName(model)
else if (provider != null && harness == null)
provider,
if (effort != null) '$effort effort',
if (timeout != null) '$timeout timeout',
if (retries != null) retries == '1' ? '1 retry' : '$retries retries',
if (budget != null) '\$$budget budget',
if (tokens != null) '$tokens tokens max',
if (config('keep_going') == 'true') 'keep going',
];
}
List<String> _permissions(String? text) {
if (text == null || text.trim().isEmpty) return const [];
try {
final decoded = jsonDecode(text);
if (decoded is! Map) return [text.trim()];
return [
for (final entry in decoded.entries)
'${entry.key}: ${entry.value is List && (entry.value as List).isEmpty
? 'denied'
: entry.value is List
? (entry.value as List).join(', ')
: _text(entry.value)}',
];
} on FormatException {
return [text.trim()];
}
}
List<String> _limits(dynamic limits) {
if (limits is! Map) return const [];
final maxVisits = int.tryParse(_text(limits['max_visits']));
final on = limits['on'];
final exhausted = _text(limits['on_exhausted']).trim();
return [
if (maxVisits != null && maxVisits > 0)
maxVisits == 1 ? 'max 1 visit' : 'max $maxVisits visits',
if (on is List && on.isNotEmpty) 'on ${on.map(_text).join(', ')}',
if (exhausted.isNotEmpty) 'when exhausted: $exhausted',
];
}
Map<String, String> _strings(dynamic value) => value is Map
? {for (final entry in value.entries) _text(entry.key): _text(entry.value)}
: const {};
List<String> _lines(String text) => [
for (final line in text.split('\n'))
if (line.trim().isNotEmpty) line.trim(),
];
String _text(dynamic value) {
if (value == null) return '';
if (value is num && value == value.roundToDouble()) {
return value.toInt().toString();
}
return '$value';
}
@@ -0,0 +1,145 @@
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import '../routing/route_models.dart';
import 'graph_edge_layer.dart';
/// The run graph's route painting: the landed `GraphEdgePainter` geometry
/// (paths and arrowheads) with the two route classes run evidence needs on one
/// passive layer. No route is re-routed and no style is assumed here.
/// A passive canvas that draws taken routes as solid, arrowed strokes and
/// untaken routes as dashed, arrowless strokes behind them.
///
/// The caller supplies the already-routed [executedRoutes] and
/// [untakenRoutes], the graph-space [canvasSize] and its native theme colours.
/// The layer never takes pointer input, so nodes and labels keep their gestures.
class RunGraphEdgeLayer extends StatelessWidget {
const RunGraphEdgeLayer({
super.key,
required this.executedRoutes,
required this.untakenRoutes,
required this.canvasSize,
required this.executedColor,
required this.untakenColor,
required this.strokeWidth,
});
final List<EdgeRoute> executedRoutes;
final List<EdgeRoute> untakenRoutes;
final Size canvasSize;
final Color executedColor;
final Color untakenColor;
final double strokeWidth;
@override
Widget build(BuildContext context) => CustomPaint(
size: canvasSize,
painter: RunGraphEdgePainter(
executedRoutes: executedRoutes,
untakenRoutes: untakenRoutes,
executedColor: executedColor,
untakenColor: untakenColor,
strokeWidth: strokeWidth,
),
);
}
/// Paints a [RunGraphEdgeLayer].
///
/// Executed routes reuse the landed [GraphEdgePainter] path and arrow geometry;
/// untaken routes are the same polyline broken into native-sized dashes and
/// never receive an arrowhead. Public so the compositor and its tests share one
/// decision about which class of route gets an arrow.
class RunGraphEdgePainter extends CustomPainter {
RunGraphEdgePainter({
required this.executedRoutes,
required this.untakenRoutes,
required this.executedColor,
required this.untakenColor,
required this.strokeWidth,
}) : assert(strokeWidth > 0),
_executed = GraphEdgePainter(
routes: executedRoutes,
color: executedColor,
strokeWidth: strokeWidth,
),
_executedLine = Paint()
..color = executedColor
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
_untakenLine = Paint()
..color = untakenColor
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
_arrow = Paint()
..color = executedColor
..style = PaintingStyle.fill;
final List<EdgeRoute> executedRoutes;
final List<EdgeRoute> untakenRoutes;
final Color executedColor;
final Color untakenColor;
final double strokeWidth;
final GraphEdgePainter _executed;
final Paint _executedLine;
final Paint _untakenLine;
final Paint _arrow;
/// Dash and gap lengths in graph space; a dash never becomes a route style.
static const double dashLength = 12;
static const double dashGap = 8;
@override
void paint(Canvas canvas, Size size) {
if (executedRoutes.isEmpty && untakenRoutes.isEmpty) return;
canvas.save();
canvas.clipRect(Offset.zero & size);
for (final route in untakenRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(dashedPath(route), _untakenLine);
}
for (final route in executedRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(_executed.linePath(route), _executedLine);
}
for (final route in executedRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(_executed.arrowPath(route), _arrow);
}
canvas.restore();
}
/// The route's polyline split into [dashLength] segments separated by
/// [dashGap], following every orthogonal bend without smoothing.
Path dashedPath(EdgeRoute route) {
final source = _executed.linePath(route);
final dashed = Path();
for (final metric in source.computeMetrics()) {
var start = 0.0;
while (start < metric.length) {
final end = start + dashLength < metric.length
? start + dashLength
: metric.length;
dashed.addPath(metric.extractPath(start, end), Offset.zero);
start = end + dashGap;
}
}
return dashed;
}
/// Passive like the landed edge layer: every point misses.
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(RunGraphEdgePainter oldDelegate) =>
oldDelegate.executedColor != executedColor ||
oldDelegate.untakenColor != untakenColor ||
oldDelegate.strokeWidth != strokeWidth ||
!listEquals(oldDelegate.executedRoutes, executedRoutes) ||
!listEquals(oldDelegate.untakenRoutes, untakenRoutes);
}
@@ -0,0 +1,89 @@
import 'package:flutter/material.dart';
import '../routing/route_models.dart';
import 'graph_edge_layer.dart';
/// Softly emphasises every route into or out of one stage (the stage whose
/// popover is open): a translucent wider stroke under the plain edges' own
/// lines. Quieter than a hovered edge, which still paints above it.
class StageEdgesHighlightPainter extends CustomPainter {
StageEdgesHighlightPainter({
required this.routes,
required this.color,
required this.strokeWidth,
});
final List<EdgeRoute> routes;
final Color color;
final double strokeWidth;
@override
void paint(Canvas canvas, Size size) {
if (routes.isEmpty) return;
final geometry = GraphEdgePainter(
routes: routes,
color: color,
strokeWidth: strokeWidth,
);
final halo = Paint()
..color = color.withValues(alpha: 0.16)
..strokeWidth = strokeWidth * 5
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round
..strokeCap = StrokeCap.round;
final line = Paint()
..color = color.withValues(alpha: 0.7)
..strokeWidth = strokeWidth * 1.5
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round;
for (final route in routes) {
if (route.points.length < 2) continue;
final path = geometry.linePath(route);
canvas.drawPath(path, halo);
canvas.drawPath(path, line);
}
}
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(StageEdgesHighlightPainter oldDelegate) =>
oldDelegate.color != color ||
oldDelegate.strokeWidth != strokeWidth ||
oldDelegate.routes.length != routes.length ||
!_same(oldDelegate.routes, routes);
static bool _same(List<EdgeRoute> a, List<EdgeRoute> b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
}
/// The soft highlight for [stage]'s routes, or nothing when none is open.
Widget graphStageEdgesHighlight({
required BuildContext context,
required GraphRouting routing,
required String? stage,
required double edgeWidth,
}) {
if (stage == null) return const SizedBox.shrink();
final routes = [
for (final route in routing.routes)
if (route.source == stage || route.target == stage) route,
];
if (routes.isEmpty) return const SizedBox.shrink();
return IgnorePointer(
child: CustomPaint(
key: ValueKey('graph-stage-edges:$stage'),
size: Size(routing.width, routing.height),
painter: StageEdgesHighlightPainter(
routes: routes,
color: Theme.of(context).colorScheme.primary,
strokeWidth: edgeWidth,
),
),
);
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/glass_pill.dart';
import 'graph_viewport_controller.dart';
import 'graph_viewport_scope.dart';
/// The fit control's web wording (`Fit graph to view`).
const String graphFitLabel = 'Fit graph to view';
@@ -46,6 +47,7 @@ class GraphViewport extends StatefulWidget {
}
class _GraphViewportState extends State<GraphViewport> {
final GlobalKey _viewportKey = GlobalKey(debugLabel: 'graph-viewport-box');
Size? _scheduledViewport;
Size? _scheduledContent;
@@ -97,20 +99,26 @@ class _GraphViewportState extends State<GraphViewport> {
fit: StackFit.expand,
children: [
Positioned.fill(
child: InteractiveViewer(
key: const Key('graph-viewport'),
transformationController: widget.controller.transformation,
constrained: false,
// The graph owns its own bounds (fit and the visible-pan clamp),
// so the viewer must not impose a second, cover-the-viewport
// boundary that would fight the fit scale.
boundaryMargin: const EdgeInsets.all(double.infinity),
minScale: widget.controller.minScale,
maxScale: widget.controller.maxScale,
clipBehavior: Clip.hardEdge,
child: SizedBox.fromSize(
size: widget.contentSize,
child: widget.child,
key: _viewportKey,
child: GraphViewportScope(
transform: widget.controller.transformation,
viewportKey: _viewportKey,
viewportSize: viewport,
child: InteractiveViewer(
key: const Key('graph-viewport'),
transformationController: widget.controller.transformation,
constrained: false,
// The graph owns its own bounds (fit and the visible-pan clamp),
// so the viewer must not impose a second, cover-the-viewport
// boundary that would fight the fit scale.
boundaryMargin: const EdgeInsets.all(double.infinity),
minScale: widget.controller.minScale,
maxScale: widget.controller.maxScale,
clipBehavior: Clip.hardEdge,
child: SizedBox.fromSize(
size: widget.contentSize,
child: widget.child,
),
),
),
),
@@ -0,0 +1,34 @@
import 'package:flutter/widgets.dart';
/// What a graph canvas can learn about the pan/zoom viewport around it: the
/// transform it follows and the visible box it must stay inside.
///
/// [GraphViewport] provides it; a canvas drawn without one (a still preview,
/// a test) has no scope and uses its overlay's bounds instead.
class GraphViewportScope extends InheritedWidget {
const GraphViewportScope({
super.key,
required this.transform,
required this.viewportKey,
required this.viewportSize,
required super.child,
});
/// Notifies on every pan, zoom and fit.
final Listenable transform;
/// The key of the visible viewport box, for its on-screen origin.
final GlobalKey viewportKey;
/// The visible viewport's extent.
final Size viewportSize;
static GraphViewportScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<GraphViewportScope>();
@override
bool updateShouldNotify(GraphViewportScope oldWidget) =>
oldWidget.transform != transform ||
oldWidget.viewportKey != viewportKey ||
oldWidget.viewportSize != viewportSize;
}
@@ -1,21 +1,28 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/graph_definition.dart';
import '../domain/stage_summary.dart';
import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.dart';
import '../painting/stage_edges_highlight.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'graph_edge_hover.dart';
import 'graph_stage_node.dart';
import 'graph_stage_popover.dart';
import 'stage_popover_card.dart';
/// The measured definition canvas at any viewport size and selection.
///
/// Used by both the inline [GraphViewport] and the expanded presentation: the
/// passive edge layer paints behind the native nodes and outcome labels, and
/// every node reports selection through [onSelected].
/// passive edge layer paints behind the native nodes and outcome labels.
/// Tapping a node opens its stage popover (the declaration at a glance); the
/// popover's "Open definition" reports the node through [onSelected].
class DefinitionGraphCanvas extends StatelessWidget {
const DefinitionGraphCanvas({
super.key,
required this.graph,
required this.nodes,
required this.layout,
required this.routing,
@@ -24,6 +31,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
required this.onSelected,
});
/// The definition the nodes came from, for each stage's declaration.
final JsonMap graph;
final List<GraphNode> nodes;
final GraphLayout layout;
final GraphRouting routing;
@@ -37,12 +46,34 @@ class DefinitionGraphCanvas extends StatelessWidget {
for (final node in nodes) node.key: node,
};
final size = Size(routing.width, routing.height);
return GraphEdgeHover(
layout: layout,
routing: routing,
describe: describeGraphEdge,
builder: (context, highlighted, select) =>
_canvas(context, nodesByKey, size, highlighted, select),
return GraphStagePopover(
nodeRects: {
for (final box in layout.nodes)
box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height),
},
cardBuilder: (context, stage, close) => StagePopoverCard(
label: nodesByKey[stage]?.label ?? stage,
summary: stageSummaryFor(graph, stage),
onClose: close,
onOpenDefinition: () {
close();
onSelected(stage);
},
),
builder: (context, open, toggle) => GraphEdgeHover(
layout: layout,
routing: routing,
describe: describeGraphEdge,
builder: (context, highlighted, select) => _canvas(
context,
nodesByKey,
size,
highlighted,
select,
open,
toggle,
),
),
);
}
@@ -52,6 +83,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
Size size,
int? highlighted,
ValueChanged<int> select,
String? open,
ValueChanged<String> toggle,
) {
return Stack(
clipBehavior: Clip.none,
@@ -66,6 +99,14 @@ class DefinitionGraphCanvas extends StatelessWidget {
strokeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphStageEdgesHighlight(
context: context,
routing: routing,
stage: open,
edgeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
@@ -83,8 +124,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
height: box.height,
child: GraphStageNode(
node: nodesByKey[box.key]!,
selected: box.key == selectedStage,
onSelected: onSelected,
selected: box.key == selectedStage || box.key == open,
onSelected: toggle,
),
),
for (final label in routing.labels)
@@ -107,6 +107,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
edges: edges,
extents: extents,
labelExtents: labelExtents,
metrics: graphMetricsOf(context),
);
return (layout, routing);
}
@@ -175,6 +176,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
contentSize: size,
onExpand: () => _openExpanded(nodes, layout, routing, size),
child: DefinitionGraphCanvas(
graph: widget.graph,
nodes: nodes,
layout: layout,
routing: routing,
@@ -215,6 +217,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
selectedStage: widget.selectedStage,
onSelected: widget.onSelected,
canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas(
graph: widget.graph,
nodes: nodes,
layout: layout,
routing: routing,
@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../layout/layout_models.dart';
import '../layout/linear_graph_layout.dart';
import '../routing/route_models.dart';
/// Centralized graph spacing, not component dimensions. Rank separation follows
@@ -27,6 +29,25 @@ RoutingConfig graphCanvasRoutingConfig() => RoutingConfig(
boundsPadding: 12,
);
/// The drawing's spacings under the design at [context]: the web's metrics,
/// or a dense design's tighter gaps, lanes and padding (Compact), so its
/// smaller nodes are not left adrift in a comfortable layout.
LinearGraphMetrics graphMetricsOf(BuildContext context) =>
AppDesignTokens.of(context).density.dense
? _denseGraphMetrics
: const LinearGraphMetrics();
const LinearGraphMetrics _denseGraphMetrics = LinearGraphMetrics(
hGap: 32,
pad: 16,
laneSpacing: 20,
terminalGap: 16,
trackStep: 16,
portSpacing: 8,
labelPadding: 6,
labelGap: 2,
);
/// The native theme roles one definition graph canvas needs.
///
/// No palette, font family or size is defined here: every value comes from the
@@ -1,6 +1,9 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../../ui/status/run_status_icon.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../domain/graph_definition.dart';
/// One content-sized stage node as an ordinary native control.
@@ -56,7 +59,7 @@ class GraphStageNode extends StatelessWidget {
button: true,
selected: selected,
label: _label,
child: _materialCard(onPressed, content),
child: _materialCard(context, onPressed, content),
),
);
return active ? StageActivityHalo(child: control) : control;
@@ -66,13 +69,29 @@ class GraphStageNode extends StatelessWidget {
/// which assumes one line and cuts into a wrapped label's first and last
/// line. A card keeps the rounded-rectangle surface the web node uses, and
/// [selected] only chooses between two stock emphasis levels.
Widget _materialCard(VoidCallback onPressed, Widget content) {
Widget _materialCard(
BuildContext context,
VoidCallback onPressed,
Widget content,
) {
// A dense design draws a smaller node: half the inset and a 32px
// least height on a pointer device (40px on touch).
final density = AppDesignTokens.of(context).density;
final body = InkWell(
onTap: onPressed,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: kMinInteractiveDimension),
constraints: BoxConstraints(
minHeight: density.dense
? math.max(32, density.minTouchRow)
: kMinInteractiveDimension,
),
child: Padding(
padding: _contentPadding,
padding: density.dense
? EdgeInsets.symmetric(
horizontal: density.space(_contentPadding.left) + 4,
vertical: density.space(_contentPadding.top),
)
: _contentPadding,
child: Align(
// A terminal box widens to give each incoming route its own port;
// its label stays centred in it.
@@ -0,0 +1,271 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../viewport/graph_viewport_scope.dart';
import 'stage_popover_position.dart';
/// Builds the canvas with [openStage] (or null) and the node tap handler.
typedef GraphStagePopoverCanvasBuilder =
Widget Function(
BuildContext context,
String? openStage,
ValueChanged<String> toggle,
);
/// Builds one stage's popover content; [close] dismisses it.
typedef GraphStagePopoverCardBuilder =
Widget Function(BuildContext context, String stage, VoidCallback close);
/// Below this viewport width (or height) the card cannot sit beside a node
/// with room to read, so the stage opens in a bottom sheet instead.
const double graphStagePopoverMinWidth = 440;
const double graphStagePopoverMinHeight = 300;
/// A stage popover over a graph canvas: tapping (or pressing Enter on) a node
/// opens a small card anchored to it, with a nub pointing at the node.
///
/// The card is built only while open, in the overlay, and lays out against
/// the live pan/zoom transform so it follows its node; it stays inside the
/// viewport. A tap outside it (a tap, not a pan: a drag still pans the graph
/// under it), Escape, or tapping the same node again closes it. On a narrow
/// or short viewport the same content opens in a bottom sheet instead.
class GraphStagePopover extends StatefulWidget {
const GraphStagePopover({
super.key,
required this.nodeRects,
required this.cardBuilder,
required this.builder,
});
/// Every openable node's box in canvas (graph) space.
final Map<String, Rect> nodeRects;
final GraphStagePopoverCardBuilder cardBuilder;
final GraphStagePopoverCanvasBuilder builder;
@override
State<GraphStagePopover> createState() => _GraphStagePopoverState();
}
class _GraphStagePopoverState extends State<GraphStagePopover> {
final OverlayPortalController _portal = OverlayPortalController();
final GlobalKey _canvasKey = GlobalKey(debugLabel: 'graph-popover-canvas');
final GlobalKey _cardKey = GlobalKey(debugLabel: 'graph-popover-card');
final FocusNode _cardFocus = FocusNode(debugLabel: 'graph-stage-popover');
FocusNode? _returnFocus;
String? _open;
bool _routed = false;
final Map<int, Offset> _downs = {};
@override
void didUpdateWidget(GraphStagePopover oldWidget) {
super.didUpdateWidget(oldWidget);
final open = _open;
if (open != null && !widget.nodeRects.containsKey(open)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _close();
});
}
}
@override
void dispose() {
_unroute();
_cardFocus.dispose();
super.dispose();
}
bool _useSheet() {
final scope = GraphViewportScope.maybeOf(context);
final size = scope?.viewportSize ?? MediaQuery.sizeOf(context);
return size.width < graphStagePopoverMinWidth ||
size.height < graphStagePopoverMinHeight;
}
void _toggle(String stage) {
if (_open == stage) {
_close();
return;
}
if (!widget.nodeRects.containsKey(stage)) return;
if (Overlay.maybeOf(context) == null || _useSheet()) {
_openSheet(stage);
return;
}
_returnFocus ??= FocusManager.instance.primaryFocus;
setState(() => _open = stage);
_portal.show();
_route();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _open != null) _cardFocus.requestFocus();
});
}
void _close() {
if (_open == null) return;
final hadFocus = _cardFocus.hasFocus;
setState(() => _open = null);
_portal.hide();
_unroute();
final back = _returnFocus;
_returnFocus = null;
if (hadFocus && back != null && back.context != null) back.requestFocus();
}
Future<void> _openSheet(String stage) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
builder: (sheet) => Padding(
key: const Key('graph-stage-sheet'),
padding: const EdgeInsets.only(bottom: 8),
child: widget.cardBuilder(
sheet,
stage,
// Synchronous, so an action that pops or pushes next (Open visit
// from a full-screen graph page) acts on the page under the sheet.
() => Navigator.of(sheet).pop(),
),
),
);
}
// A global route sees every pointer while the card is open: a tap (down and
// up within touch slop) outside the card and outside its own node closes
// it; a drag never does, so panning keeps the card on its node.
void _route() {
if (_routed) return;
GestureBinding.instance.pointerRouter.addGlobalRoute(_onPointer);
_routed = true;
}
void _unroute() {
if (!_routed) return;
GestureBinding.instance.pointerRouter.removeGlobalRoute(_onPointer);
_routed = false;
_downs.clear();
}
void _onPointer(PointerEvent event) {
if (event is PointerDownEvent) {
_downs[event.pointer] = event.position;
} else if (event is PointerCancelEvent) {
_downs.remove(event.pointer);
} else if (event is PointerUpEvent) {
final down = _downs.remove(event.pointer);
if (down == null) return;
if ((event.position - down).distance > kTouchSlop) return;
if (_contains(_cardKey, event.position) || _onOpenNode(event.position)) {
return;
}
_close();
}
}
bool _contains(GlobalKey key, Offset global) {
final box = key.currentContext?.findRenderObject();
if (box is! RenderBox || !box.attached || !box.hasSize) return false;
return (Offset.zero & box.size).contains(box.globalToLocal(global));
}
bool _onOpenNode(Offset global) {
final rect = widget.nodeRects[_open];
final box = _canvasKey.currentContext?.findRenderObject();
if (rect == null || box is! RenderBox || !box.attached) return false;
return rect.contains(box.globalToLocal(global));
}
RenderBox? _box(GlobalKey key) {
final box = key.currentContext?.findRenderObject();
return box is RenderBox ? box : null;
}
@override
Widget build(BuildContext context) {
final canvas = KeyedSubtree(
key: _canvasKey,
child: widget.builder(context, _open, _toggle),
);
if (Overlay.maybeOf(context) == null) return canvas;
return OverlayPortal(
controller: _portal,
overlayChildBuilder: _overlay,
child: canvas,
);
}
Widget _overlay(BuildContext context) {
final stage = _open;
final rect = stage == null ? null : widget.nodeRects[stage];
if (stage == null || rect == null) return const SizedBox.shrink();
final scope = GraphViewportScope.maybeOf(context);
final surface = stagePopoverSurface(context);
return StagePopoverPosition(
key: const Key('graph-stage-popover'),
anchorBox: () => _box(_canvasKey),
anchorRect: rect,
boundsBox: () => scope == null ? null : _box(scope.viewportKey),
boundsSize: scope?.viewportSize,
safeArea: MediaQuery.paddingOf(this.context),
relayout: scope?.transform,
fill: surface.fill,
border: surface.border,
radius: surface.radius,
elevation: surface.elevation,
shadowColor: surface.shadow,
child: Focus(
focusNode: _cardFocus,
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
_close();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusTraversalGroup(
child: Material(
key: _cardKey,
color: surface.fill,
elevation: surface.elevation,
shadowColor: surface.shadow,
shape: RoundedRectangleBorder(
side: surface.border,
borderRadius: BorderRadius.circular(surface.radius),
),
clipBehavior: Clip.antiAlias,
child: widget.cardBuilder(context, stage, _close),
),
),
),
);
}
}
/// The popover's surface in the current design: Classic floats a raised card
/// with a hairline; a flat design (Terminal, Paper, Compact) draws its own
/// panel fill and frame with no shadow, at the design's corner radius.
({Color fill, BorderSide border, double radius, double elevation, Color shadow})
stagePopoverSurface(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final tokens = AppDesignTokens.of(context);
final flat = tokens.flat;
return (
fill: flat
? tokens.panelFill(colors, colors.surfaceContainer)
: colors.surfaceContainerHigh,
border:
tokens.frameSide ??
BorderSide(color: colors.outlineVariant.withValues(alpha: 0.7)),
radius: tokens.radius ?? 14,
elevation: flat ? 0 : (theme.popupMenuTheme.elevation ?? 3).toDouble() + 3,
shadow: theme.popupMenuTheme.shadowColor ?? colors.shadow,
);
}
@@ -1,158 +1,22 @@
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/graph_definition.dart';
import '../domain/run_graph_state.dart';
import '../domain/stage_run_facts.dart';
import '../domain/stage_summary.dart';
import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.dart';
import '../painting/run_graph_edge_layer.dart';
import '../painting/stage_edges_highlight.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'graph_edge_hover.dart';
import 'graph_stage_node.dart';
import 'measured_child.dart';
import 'graph_stage_popover.dart';
import 'run_graph_parts.dart';
import 'stage_popover_card.dart';
/// The run graph's canvas primitives: split route painting and measurement of
/// the exact status-bearing nodes the run renderer places.
///
/// This keeps the landed `GraphEdgePainter` geometry (paths and arrowheads) and
/// adds only what run evidence needs: two route classes on one passive layer.
/// No node is invented, no route is re-routed and no style is assumed here.
/// A passive canvas that draws taken routes as solid, arrowed strokes and
/// untaken routes as dashed, arrowless strokes behind them.
///
/// The caller supplies the already-routed [executedRoutes] and
/// [untakenRoutes], the graph-space [canvasSize] and its native theme colours.
/// The layer never takes pointer input, so nodes and labels keep their gestures.
class RunGraphEdgeLayer extends StatelessWidget {
const RunGraphEdgeLayer({
super.key,
required this.executedRoutes,
required this.untakenRoutes,
required this.canvasSize,
required this.executedColor,
required this.untakenColor,
required this.strokeWidth,
});
final List<EdgeRoute> executedRoutes;
final List<EdgeRoute> untakenRoutes;
final Size canvasSize;
final Color executedColor;
final Color untakenColor;
final double strokeWidth;
@override
Widget build(BuildContext context) => CustomPaint(
size: canvasSize,
painter: RunGraphEdgePainter(
executedRoutes: executedRoutes,
untakenRoutes: untakenRoutes,
executedColor: executedColor,
untakenColor: untakenColor,
strokeWidth: strokeWidth,
),
);
}
/// Paints a [RunGraphEdgeLayer].
///
/// Executed routes reuse the landed [GraphEdgePainter] path and arrow geometry;
/// untaken routes are the same polyline broken into native-sized dashes and
/// never receive an arrowhead. Public so the compositor and its tests share one
/// decision about which class of route gets an arrow.
class RunGraphEdgePainter extends CustomPainter {
RunGraphEdgePainter({
required this.executedRoutes,
required this.untakenRoutes,
required this.executedColor,
required this.untakenColor,
required this.strokeWidth,
}) : assert(strokeWidth > 0),
_executed = GraphEdgePainter(
routes: executedRoutes,
color: executedColor,
strokeWidth: strokeWidth,
),
_executedLine = Paint()
..color = executedColor
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
_untakenLine = Paint()
..color = untakenColor
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
_arrow = Paint()
..color = executedColor
..style = PaintingStyle.fill;
final List<EdgeRoute> executedRoutes;
final List<EdgeRoute> untakenRoutes;
final Color executedColor;
final Color untakenColor;
final double strokeWidth;
final GraphEdgePainter _executed;
final Paint _executedLine;
final Paint _untakenLine;
final Paint _arrow;
/// Dash and gap lengths in graph space; a dash never becomes a route style.
static const double dashLength = 12;
static const double dashGap = 8;
@override
void paint(Canvas canvas, Size size) {
if (executedRoutes.isEmpty && untakenRoutes.isEmpty) return;
canvas.save();
canvas.clipRect(Offset.zero & size);
for (final route in untakenRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(dashedPath(route), _untakenLine);
}
for (final route in executedRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(_executed.linePath(route), _executedLine);
}
for (final route in executedRoutes) {
if (route.points.length < 2) continue;
canvas.drawPath(_executed.arrowPath(route), _arrow);
}
canvas.restore();
}
/// The route's polyline split into [dashLength] segments separated by
/// [dashGap], following every orthogonal bend without smoothing.
Path dashedPath(EdgeRoute route) {
final source = _executed.linePath(route);
final dashed = Path();
for (final metric in source.computeMetrics()) {
var start = 0.0;
while (start < metric.length) {
final end = start + dashLength < metric.length
? start + dashLength
: metric.length;
dashed.addPath(metric.extractPath(start, end), Offset.zero);
start = end + dashGap;
}
}
return dashed;
}
/// Passive like the landed edge layer: every point misses.
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(RunGraphEdgePainter oldDelegate) =>
oldDelegate.executedColor != executedColor ||
oldDelegate.untakenColor != untakenColor ||
oldDelegate.strokeWidth != strokeWidth ||
!listEquals(oldDelegate.executedRoutes, executedRoutes) ||
!listEquals(oldDelegate.untakenRoutes, untakenRoutes);
}
export '../painting/run_graph_edge_layer.dart';
export 'run_graph_parts.dart';
/// The run canvas: split route classes behind status-bearing native nodes, with
/// outcome labels only for routes the run actually took.
@@ -160,9 +24,16 @@ class RunGraphEdgePainter extends CustomPainter {
/// [layout] and [routing] are the caller's measured geometry. The canvas never
/// changes them and never assumes a node size; the caller supplies the pan/zoom
/// viewport around this content.
///
/// Tapping a stage opens its popover: the declaration with what the run
/// recorded for it. "Open visit" reports a visited stage through
/// [onStageSelected]; "Open definition" reports it through [onOpenDefinition].
class RunGraphCanvas extends StatelessWidget {
const RunGraphCanvas({
super.key,
required this.graph,
required this.run,
required this.onOpenDefinition,
required this.nodes,
required this.layout,
required this.routing,
@@ -173,6 +44,10 @@ class RunGraphCanvas extends StatelessWidget {
this.selectedStage,
});
/// The run's pinned definition and the run detail, for the popover.
final JsonMap graph;
final JsonMap run;
final ValueChanged<String> onOpenDefinition;
final List<GraphNode> nodes;
final GraphLayout layout;
final GraphRouting routing;
@@ -204,6 +79,63 @@ class RunGraphCanvas extends StatelessWidget {
route,
taken: state.routeOrder(route.source, route.outcome, route.target).length,
);
return GraphStagePopover(
nodeRects: {
for (final box in layout.nodes)
if (!(nodesByKey[box.key]?.terminal ?? true))
box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height),
},
cardBuilder: (context, stage, close) =>
_card(nodesByKey[stage]?.label ?? stage, stage, close),
builder: (context, open, toggle) => _hover(
context,
nodesByKey,
executed,
untaken,
executedIds,
size,
activeStage,
executedColor,
describe,
open,
toggle,
),
);
}
Widget _card(String label, String stage, VoidCallback close) {
final visited = state.isStageVisited(stage);
return StagePopoverCard(
label: label,
summary: stageSummaryFor(graph, stage),
facts: stageRunFacts(run, stage),
onClose: close,
onOpenDefinition: () {
close();
onOpenDefinition(stage);
},
onOpenVisit: !visited
? null
: () {
close();
onStageSelected(stage);
},
);
}
Widget _hover(
BuildContext context,
Map<String, GraphNode> nodesByKey,
List<EdgeRoute> executed,
List<EdgeRoute> untaken,
Set<int> executedIds,
Size size,
String? activeStage,
Color executedColor,
String Function(EdgeRoute) describe,
String? open,
ValueChanged<String> toggle,
) {
return GraphEdgeHover(
layout: layout,
routing: routing,
@@ -221,6 +153,14 @@ class RunGraphCanvas extends StatelessWidget {
strokeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphStageEdgesHighlight(
context: context,
routing: routing,
stage: open,
edgeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
@@ -239,6 +179,8 @@ class RunGraphCanvas extends StatelessWidget {
highlighted,
select,
describe,
open,
toggle,
),
],
),
@@ -254,6 +196,8 @@ class RunGraphCanvas extends StatelessWidget {
int? highlighted,
ValueChanged<int> select,
String Function(EdgeRoute) describe,
String? open,
ValueChanged<String> toggle,
) {
return [
for (final box in layout.nodes)
@@ -265,11 +209,10 @@ class RunGraphCanvas extends StatelessWidget {
child: RunGraphNode(
node: nodesByKey[box.key]!,
recordedStatus: recordedStatuses[box.key],
selected: box.key == selectedStage,
selected: box.key == selectedStage || box.key == open,
active: box.key == activeStage,
opensVisit:
!nodesByKey[box.key]!.terminal && state.isStageVisited(box.key),
onSelected: onStageSelected,
interactive: !nodesByKey[box.key]!.terminal,
onSelected: toggle,
),
),
// A run labels only the routes that actually happened, and the route
@@ -312,184 +255,3 @@ class RunGraphCanvas extends StatelessWidget {
color: color,
);
}
/// A taken route's label led by its place in the run (`2`, or `2, 5` for a
/// loop), so the path reads in order.
///
/// The canvas places this widget and [RunGraphMeasurements] measures the same
/// one, so the routed label box covers the order badge as well as the text.
class RunRouteLabel extends StatelessWidget {
const RunRouteLabel({
super.key,
required this.edgeId,
required this.label,
required this.order,
required this.style,
required this.color,
});
final int edgeId;
final String label;
final List<int> order;
final TextStyle style;
final Color color;
@override
Widget build(BuildContext context) {
final text = Text(label, style: style);
if (order.isEmpty) return text;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
key: ValueKey('run-route-order:$edgeId'),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
order.join(', '),
style: const TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 10,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: 4),
text,
],
);
}
}
/// One placed run node. A visited stage is the native control with its recorded
/// status; an unvisited node and a terminal are labels with no tap target or
/// button semantics, because neither owns a recorded visit to open. [active]
/// marks the run's recorded current stage while it executes; it only adds the
/// live halo, never a visit or a control.
class RunGraphNode extends StatelessWidget {
const RunGraphNode({
super.key,
required this.node,
required this.recordedStatus,
required this.opensVisit,
required this.onSelected,
this.selected = false,
this.active = false,
});
final GraphNode node;
final String? recordedStatus;
final bool opensVisit;
final bool selected;
final bool active;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final status = recordedStatus;
if (opensVisit) {
return GraphStageNode(
node: node,
recordedStatus: status,
selected: selected,
active: active,
onSelected: onSelected,
);
}
return Semantics(
container: true,
label: graphNodeSemanticsLabel(node, status),
child: ExcludeSemantics(
child: IgnorePointer(
child: GraphStageNode(
node: node,
recordedStatus: status,
active: active,
onSelected: (_) {},
),
),
),
);
}
}
/// Measures the status-bearing run nodes and every route label offstage.
///
/// A visited node is taller than the same node without its recorded status, so
/// the measurement must use the exact widget the canvas places. Sizes are
/// reported after layout and callers schedule the placement frame.
class RunGraphMeasurements extends StatelessWidget {
const RunGraphMeasurements({
super.key,
required this.nodes,
required this.edges,
required this.maxNodeWidth,
required this.labelStyle,
required this.recordedStatuses,
required this.state,
required this.onNodeSize,
required this.onLabelSize,
});
final List<GraphNode> nodes;
final List<GraphEdge> edges;
final double maxNodeWidth;
final TextStyle labelStyle;
final Map<String, String?> recordedStatuses;
/// The run whose route order badges lead the taken labels.
final RunGraphState state;
final void Function(String, Size) onNodeSize;
/// Receives each edge's label size keyed by its edge id, because two edges
/// with the same outcome can carry different order badges.
final void Function(int, Size) onLabelSize;
@override
Widget build(BuildContext context) => Offstage(
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: 0,
maxWidth: double.infinity,
minHeight: 0,
maxHeight: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final node in nodes)
MeasuredChild(
key: ValueKey(
'run-node:${node.key}:${node.label}:'
'${recordedStatuses[node.key] ?? ''}',
),
onSize: (size) => onNodeSize(node.key, size),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxNodeWidth),
child: GraphStageNode(
node: node,
recordedStatus: recordedStatuses[node.key],
onSelected: (_) {},
),
),
),
for (final edge in edges)
MeasuredChild(
key: ValueKey('run-label:${edge.id}'),
onSize: (size) => onLabelSize(edge.id, size),
child: RunRouteLabel(
edgeId: edge.id,
label: edge.label,
order: state.routeOrder(edge.source, edge.outcome, edge.target),
style: labelStyle,
color: const Color(0x00000000),
),
),
],
),
),
);
}
@@ -0,0 +1,190 @@
import 'package:flutter/material.dart';
import '../domain/graph_definition.dart';
import '../domain/run_graph_state.dart';
import 'graph_stage_node.dart';
import 'measured_child.dart';
/// The run canvas's placed pieces: taken-route labels, run nodes and the
/// offstage measurement of exactly those widgets.
/// A taken route's label led by its place in the run (`2`, or `2, 5` for a
/// loop), so the path reads in order.
///
/// The canvas places this widget and [RunGraphMeasurements] measures the same
/// one, so the routed label box covers the order badge as well as the text.
class RunRouteLabel extends StatelessWidget {
const RunRouteLabel({
super.key,
required this.edgeId,
required this.label,
required this.order,
required this.style,
required this.color,
});
final int edgeId;
final String label;
final List<int> order;
final TextStyle style;
final Color color;
@override
Widget build(BuildContext context) {
final text = Text(label, style: style);
if (order.isEmpty) return text;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
key: ValueKey('run-route-order:$edgeId'),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
order.join(', '),
style: const TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 10,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: 4),
text,
],
);
}
}
/// One placed run node. A stage is the native control with its recorded status
/// (none when unvisited) and opens its popover; a terminal is a label with no
/// tap target or button semantics, because it has no declaration. [active]
/// marks the run's recorded current stage while it executes; it only adds the
/// live halo, never a visit or a control.
class RunGraphNode extends StatelessWidget {
const RunGraphNode({
super.key,
required this.node,
required this.recordedStatus,
required this.interactive,
required this.onSelected,
this.selected = false,
this.active = false,
});
final GraphNode node;
final String? recordedStatus;
final bool interactive;
final bool selected;
final bool active;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final status = recordedStatus;
if (interactive) {
return GraphStageNode(
node: node,
recordedStatus: status,
selected: selected,
active: active,
onSelected: onSelected,
);
}
return Semantics(
container: true,
label: graphNodeSemanticsLabel(node, status),
child: ExcludeSemantics(
child: IgnorePointer(
child: GraphStageNode(
node: node,
recordedStatus: status,
active: active,
onSelected: (_) {},
),
),
),
);
}
}
/// Measures the status-bearing run nodes and every route label offstage.
///
/// A visited node is taller than the same node without its recorded status, so
/// the measurement must use the exact widget the canvas places. Sizes are
/// reported after layout and callers schedule the placement frame.
class RunGraphMeasurements extends StatelessWidget {
const RunGraphMeasurements({
super.key,
required this.nodes,
required this.edges,
required this.maxNodeWidth,
required this.labelStyle,
required this.recordedStatuses,
required this.state,
required this.onNodeSize,
required this.onLabelSize,
});
final List<GraphNode> nodes;
final List<GraphEdge> edges;
final double maxNodeWidth;
final TextStyle labelStyle;
final Map<String, String?> recordedStatuses;
/// The run whose route order badges lead the taken labels.
final RunGraphState state;
final void Function(String, Size) onNodeSize;
/// Receives each edge's label size keyed by its edge id, because two edges
/// with the same outcome can carry different order badges.
final void Function(int, Size) onLabelSize;
@override
Widget build(BuildContext context) => Offstage(
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: 0,
maxWidth: double.infinity,
minHeight: 0,
maxHeight: double.infinity,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final node in nodes)
MeasuredChild(
key: ValueKey(
'run-node:${node.key}:${node.label}:'
'${recordedStatuses[node.key] ?? ''}',
),
onSize: (size) => onNodeSize(node.key, size),
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxNodeWidth),
child: GraphStageNode(
node: node,
recordedStatus: recordedStatuses[node.key],
onSelected: (_) {},
),
),
),
for (final edge in edges)
MeasuredChild(
key: ValueKey('run-label:${edge.id}'),
onSize: (size) => onLabelSize(edge.id, size),
child: RunRouteLabel(
edgeId: edge.id,
label: edge.label,
order: state.routeOrder(edge.source, edge.outcome, edge.target),
style: labelStyle,
color: const Color(0x00000000),
),
),
],
),
),
);
}
@@ -13,6 +13,7 @@ import '../viewport/graph_viewport_controller.dart';
import 'graph_canvas_style.dart';
import 'run_graph_canvas.dart';
import 'run_graph_header.dart';
import 'stage_definition_view.dart';
export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted;
@@ -140,6 +141,7 @@ class _RunGraphViewState extends State<RunGraphView> {
edges: edges,
extents: extents,
labelExtents: labelExtents,
metrics: graphMetricsOf(context),
);
return (layout, routing);
}
@@ -326,6 +328,9 @@ class _RunGraphViewState extends State<RunGraphView> {
required String? selectedStage,
required ValueChanged<String> onStageSelected,
}) => RunGraphCanvas(
graph: widget.graph ?? const {},
run: widget.run,
onOpenDefinition: _openDefinition,
nodes: nodes,
layout: layout,
routing: routing,
@@ -336,6 +341,23 @@ class _RunGraphViewState extends State<RunGraphView> {
onStageSelected: onStageSelected,
);
/// The full definition page for [stage], pinned to this run's version.
void _openDefinition(String stage) {
final graph = widget.graph;
if (graph == null) return;
final id = widget.run['pipeline_id'];
final version = widget.run['version'];
final name = '${widget.run['name'] ?? ''}'.trim();
openStageDefinition(
context,
graph: graph,
stageKey: stage,
pipelineId: id is num ? id.toInt() : 0,
pipelineName: name,
version: version is num ? version.toInt() : 0,
);
}
void _openExpanded(
List<GraphNode> nodes,
GraphLayout layout,
@@ -0,0 +1,290 @@
import 'package:flutter/material.dart';
import '../../../ui/status/run_status_icon.dart';
import '../domain/stage_run_facts.dart';
import '../domain/stage_summary.dart';
import 'graph_stage_node.dart';
import 'stage_popover_parts.dart';
/// The undeclared-stage line, when this version has no declaration for a node.
const String stagePopoverUndeclared =
'This stage is not declared in this pipeline version.';
/// The compact content of one stage's popover: a header with the stage's name,
/// type and (for a run) its recorded status, then the declaration's facts, the
/// prompt or its type's equivalent, limits and routes, and the actions.
///
/// Built only while the popover is open. Nothing here is fetched: [summary] is
/// the pinned declaration and [facts] what the run recorded, if anything.
class StagePopoverCard extends StatelessWidget {
const StagePopoverCard({
super.key,
required this.label,
required this.summary,
required this.onClose,
required this.onOpenDefinition,
this.facts,
this.onOpenVisit,
});
final String label;
final StageSummary? summary;
final StageRunFacts? facts;
final VoidCallback onClose;
final VoidCallback onOpenDefinition;
/// Opens the stage's latest recorded visit; null when it has none.
final VoidCallback? onOpenVisit;
@override
Widget build(BuildContext context) {
final summary = this.summary;
final facts = this.facts;
final sections = <Widget>[
if (facts != null && facts.visits > 0) ..._runSections(context, facts),
if (summary == null)
Text(stagePopoverUndeclared, style: popoverMuted(context))
else
..._definitionSections(context, summary),
];
return Semantics(
container: true,
explicitChildNodes: true,
label: '$label details',
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_header(context, summary, facts),
if (sections.isNotEmpty)
Flexible(
child: SingleChildScrollView(
key: const Key('stage-popover-body'),
padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var i = 0; i < sections.length; i++) ...[
if (i > 0) const SizedBox(height: 12),
sections[i],
],
],
),
),
),
_actions(context),
],
),
);
}
Widget _header(
BuildContext context,
StageSummary? summary,
StageRunFacts? facts,
) {
final theme = Theme.of(context);
final status = facts?.status;
final chips = <Widget>[
if (summary != null)
PopoverChip(
key: const Key('stage-popover-type'),
label: summary.typeLabel,
icon: stageKindIcon(summary.kind),
tone: PopoverChipTone.accent,
),
if (status != null)
PopoverChip(
key: const Key('stage-popover-status'),
label: status,
dot: runStatusColorOf(context, graphStatusState(status)),
),
if (facts != null && facts.visits > 0)
PopoverChip(
key: const Key('stage-popover-visits'),
label: '×${facts.visits}',
tooltip: facts.visits == 1 ? '1 visit' : '${facts.visits} visits',
),
if (facts?.duration case final duration?)
PopoverChip(label: duration, icon: Icons.schedule),
if (facts?.usage case final usage?) PopoverChip(label: usage),
];
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 4, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
key: const Key('stage-popover-title'),
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (chips.isNotEmpty) ...[
const SizedBox(height: 6),
Wrap(spacing: 6, runSpacing: 6, children: chips),
],
],
),
),
),
IconButton(
key: const Key('stage-popover-close'),
tooltip: 'Close',
visualDensity: VisualDensity.compact,
iconSize: 18,
onPressed: onClose,
icon: const Icon(Icons.close),
),
],
),
);
}
List<Widget> _runSections(BuildContext context, StageRunFacts facts) {
final colors = Theme.of(context).colorScheme;
return [
if (facts.failure case final failure?)
PopoverNote(
key: const Key('stage-popover-failure'),
icon: Icons.error_outline,
color: colors.error,
text: failure,
),
if (facts.verdict case final verdict?)
PopoverSection(
label: 'Verdict',
child: Text(verdict, key: const Key('stage-popover-verdict')),
),
if (facts.handoff case final handoff?)
PopoverSection(
label: 'Handoff',
child: Text(
handoff,
key: const Key('stage-popover-handoff'),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
];
}
List<Widget> _definitionSections(BuildContext context, StageSummary s) {
return [
if (s.meta.isNotEmpty)
Wrap(
key: const Key('stage-popover-meta'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.meta) PopoverChip(label: item)],
),
if (s.tools.isNotEmpty)
PopoverSection(
label: s.toolsDefault ? 'Tools · default' : 'Tools',
child: Wrap(
key: const Key('stage-popover-tools'),
spacing: 6,
runSpacing: 6,
children: [
for (final tool in s.tools)
PopoverChip(label: tool, icon: toolIcon(tool), mono: true),
],
),
),
if (s.permissions.isNotEmpty) PopoverPermissions(lines: s.permissions),
if (s.skills.isNotEmpty)
PopoverSection(
label: 'Skills',
child: Wrap(
spacing: 6,
runSpacing: 6,
children: [for (final skill in s.skills) PopoverChip(label: skill)],
),
),
if (s.prompt case final prompt?)
PopoverSection(
label: s.kind == StageKind.human ? 'Operator instructions' : 'Prompt',
child: PopoverPrompt(text: prompt),
),
if (s.commands.isNotEmpty)
PopoverSection(
label: 'Commands',
child: PopoverCommands(commands: s.commands),
),
if (s.gate.isNotEmpty)
PopoverSection(
label: 'Gate',
child: Wrap(
key: const Key('stage-popover-gate'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.gate) PopoverChip(label: item)],
),
),
if (s.limits.isNotEmpty)
PopoverSection(
label: 'Limits',
child: Wrap(
key: const Key('stage-popover-limits'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.limits) PopoverChip(label: item)],
),
),
if (s.routes.isNotEmpty)
PopoverSection(
label: s.kind == StageKind.terminal ? 'Routes in' : 'Routes',
child: Wrap(
key: const Key('stage-popover-routes'),
spacing: 6,
runSpacing: 6,
children: [
for (final route in s.routes)
s.kind == StageKind.terminal
? PopoverRouteChip(from: route.target, to: route.outcome)
: PopoverRouteChip(from: route.outcome, to: route.target),
],
),
),
];
}
Widget _actions(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: colors.outlineVariant)),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 4,
children: [
if (onOpenVisit != null)
TextButton.icon(
key: const Key('stage-popover-open-visit'),
onPressed: onOpenVisit,
icon: const Icon(Icons.history, size: 18),
label: const Text('Open visit'),
),
FilledButton.tonalIcon(
key: const Key('stage-popover-open-definition'),
onPressed: onOpenDefinition,
icon: const Icon(Icons.description_outlined, size: 18),
label: const Text('Open definition'),
),
],
),
),
);
}
}
@@ -0,0 +1,170 @@
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../domain/stage_summary.dart';
import 'graph_stage_node.dart';
/// The stage popover's compact facts: chips for configs, tools and routes,
/// and the icons and corners they share.
TextStyle? popoverMuted(BuildContext context) {
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
/// The corners of the popover's inner pieces (chips, blocks): the design's
/// own radius, else a soft 8 (chips 6).
BorderRadius popoverCorners(BuildContext context, double designed) =>
AppDesignTokens.of(context).corners(BorderRadius.circular(designed));
/// The icon of a stage's type chip.
IconData stageKindIcon(StageKind kind) => switch (kind) {
StageKind.model => Icons.auto_awesome_outlined,
StageKind.check => checkStageIcon(delivery: false),
StageKind.deliveryGate => checkStageIcon(delivery: true),
StageKind.findings => Icons.filter_alt_outlined,
StageKind.human => Icons.person_outline,
StageKind.terminal => Icons.flag_outlined,
StageKind.other => Icons.widgets_outlined,
};
/// A tool chip's icon.
IconData toolIcon(String tool) => switch (tool) {
'read' => Icons.visibility_outlined,
'glob' => Icons.folder_open_outlined,
'grep' => Icons.search,
'edit' => Icons.edit_outlined,
'shell' => Icons.terminal,
'websearch' => Icons.travel_explore,
'webfetch' => Icons.public,
_ when tool.startsWith('mcp:') => Icons.extension_outlined,
_ => Icons.build_outlined,
};
enum PopoverChipTone { neutral, accent }
/// One compact fact: a tinted label, optionally led by an icon or a status dot.
class PopoverChip extends StatelessWidget {
const PopoverChip({
super.key,
required this.label,
this.icon,
this.dot,
this.tone = PopoverChipTone.neutral,
this.mono = false,
this.tooltip,
});
final String label;
final IconData? icon;
final Color? dot;
final PopoverChipTone tone;
final bool mono;
final String? tooltip;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final accent = tone == PopoverChipTone.accent;
final foreground = accent
? colors.onSecondaryContainer
: colors.onSurfaceVariant;
final base = theme.textTheme.labelMedium ?? const TextStyle();
final style = base.copyWith(
color: foreground,
fontFamily: mono ? appMonospaceFamily : null,
height: 1.2,
);
final size = (style.fontSize ?? 12) * 1.15;
Widget chip = DecoratedBox(
decoration: BoxDecoration(
color: accent
? colors.secondaryContainer
: colors.surfaceContainerHighest,
borderRadius: popoverCorners(context, 6),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (dot != null) ...[
Container(
width: 7,
height: 7,
decoration: BoxDecoration(color: dot, shape: BoxShape.circle),
),
const SizedBox(width: 5),
] else if (icon != null) ...[
Icon(icon, size: size, color: foreground),
const SizedBox(width: 4),
],
Flexible(child: Text(label, style: style)),
],
),
),
);
final tip = tooltip;
if (tip != null) chip = Tooltip(message: tip, child: chip);
return chip;
}
}
/// One route as `from → to`. The arrow is an icon, not a glyph: a design's
/// interface face may not carry U+2192.
class PopoverRouteChip extends StatelessWidget {
const PopoverRouteChip({super.key, required this.from, required this.to});
final String from;
final String to;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final style = (theme.textTheme.labelMedium ?? const TextStyle()).copyWith(
color: colors.onSurfaceVariant,
height: 1.2,
);
return Semantics(
label: '$from to $to',
excludeSemantics: true,
child: DecoratedBox(
decoration: BoxDecoration(
color: colors.surfaceContainerHighest,
borderRadius: popoverCorners(context, 6),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(from, style: style)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Icon(
Icons.arrow_forward,
size: (style.fontSize ?? 12) * 1.1,
color: colors.outline,
),
),
Flexible(
child: Text(
to,
style: style.copyWith(
color: colors.onSurface,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,308 @@
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import 'stage_popover_chips.dart';
export 'stage_popover_chips.dart';
/// The stage popover's larger pieces: labelled sections, the clamped prompt
/// block, the command list and the collapsed permissions line.
/// A small muted label over its content.
class PopoverSection extends StatelessWidget {
const PopoverSection({super.key, required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
letterSpacing: 0.4,
),
),
const SizedBox(height: 6),
DefaultTextStyle.merge(style: theme.textTheme.bodyMedium, child: child),
],
);
}
}
/// A one-line notice with an icon, e.g. the recorded failure reason.
class PopoverNote extends StatelessWidget {
const PopoverNote({
super.key,
required this.icon,
required this.color,
required this.text,
});
final IconData icon;
final Color color;
final String text;
@override
Widget build(BuildContext context) {
final style = Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: color);
return DecoratedBox(
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: popoverCorners(context, 8),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: 8),
Expanded(child: Text(text, style: style)),
],
),
),
);
}
}
/// The inset block a prompt or command list sits in.
class PopoverBlock extends StatelessWidget {
const PopoverBlock({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
color: colors.surface,
border: Border.all(color: colors.outlineVariant.withValues(alpha: 0.6)),
borderRadius: popoverCorners(context, 8),
),
child: Padding(padding: const EdgeInsets.all(12), child: child),
);
}
}
/// A prompt as typeset markdown, held to about ten lines with a fade until
/// "Show all" expands it in place.
class PopoverPrompt extends StatefulWidget {
const PopoverPrompt({super.key, required this.text});
final String text;
/// Collapsed height in lines of the body face.
static const int collapsedLines = 10;
@override
State<PopoverPrompt> createState() => _PopoverPromptState();
}
class _PopoverPromptState extends State<PopoverPrompt> {
bool _expanded = false;
bool _overflows = false;
bool _onMetrics(ScrollMetricsNotification notification) {
final overflows = notification.metrics.maxScrollExtent > 0.5;
if (overflows != _overflows) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _overflows = overflows);
});
}
return true;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final body = theme.textTheme.bodyMedium ?? const TextStyle();
final scaler = MediaQuery.textScalerOf(context);
final line = scaler.scale(body.fontSize ?? 14) * (body.height ?? 1.43);
// Headings a step down from the transcript's: in a compact card a
// prompt's `## Goal` is a label, not a page title.
final text = theme.textTheme;
final heading = text.titleSmall?.copyWith(fontWeight: FontWeight.w700);
final markdown = Theme(
data: theme.copyWith(
textTheme: text.copyWith(
headlineSmall: text.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
titleLarge: heading,
titleMedium: heading,
),
),
child: DefaultTextStyle.merge(
style: body,
child: ChatMarkdownView(text: widget.text),
),
);
final Widget content = _expanded
? markdown
: NotificationListener<ScrollMetricsNotification>(
onNotification: _onMetrics,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: line * PopoverPrompt.collapsedLines,
),
child: _fade(
SingleChildScrollView(
physics: const NeverScrollableScrollPhysics(),
primary: false,
child: markdown,
),
),
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
PopoverBlock(
child: KeyedSubtree(
key: const Key('stage-popover-prompt'),
child: content,
),
),
if (_overflows || _expanded)
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton(
key: const Key('stage-popover-show-all'),
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 4),
),
onPressed: () => setState(() => _expanded = !_expanded),
child: Text(_expanded ? 'Show less' : 'Show all'),
),
),
],
);
}
Widget _fade(Widget child) {
if (!_overflows) return child;
return ShaderMask(
blendMode: BlendMode.dstIn,
shaderCallback: (bounds) => LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: const [Color(0xFFFFFFFF), Color(0x00FFFFFF)],
stops: [
bounds.height <= 0 ? 0 : (1 - 36 / bounds.height).clamp(0.0, 1.0),
1,
],
).createShader(bounds),
child: child,
);
}
}
/// A check stage's commands, one per line in the monospace face.
class PopoverCommands extends StatelessWidget {
const PopoverCommands({super.key, required this.commands});
final List<String> commands;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme.bodySmall?.copyWith(
fontFamily: appMonospaceFamily,
height: 1.5,
);
final prompt = theme.colorScheme.onSurfaceVariant;
return PopoverBlock(
child: SelectableText.rich(
key: const Key('stage-popover-commands'),
TextSpan(
style: style,
children: [
for (var i = 0; i < commands.length; i++) ...[
if (i > 0) const TextSpan(text: '\n'),
TextSpan(
text: r'$ ',
style: TextStyle(color: prompt),
),
TextSpan(text: commands[i]),
],
],
),
),
);
}
}
/// The permission allow-lists behind one collapsed "Permissions" line.
class PopoverPermissions extends StatefulWidget {
const PopoverPermissions({super.key, required this.lines});
final List<String> lines;
@override
State<PopoverPermissions> createState() => _PopoverPermissionsState();
}
class _PopoverPermissionsState extends State<PopoverPermissions> {
bool _open = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final muted = theme.colorScheme.onSurfaceVariant;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
InkWell(
key: const Key('stage-popover-permissions'),
borderRadius: popoverCorners(context, 6),
onTap: () => setState(() => _open = !_open),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
Icon(
_open ? Icons.expand_more : Icons.chevron_right,
size: 18,
color: muted,
),
const SizedBox(width: 2),
Text(
'Permissions',
style: theme.textTheme.labelSmall?.copyWith(
color: muted,
fontWeight: FontWeight.w600,
letterSpacing: 0.4,
),
),
],
),
),
),
if (_open)
Padding(
padding: const EdgeInsetsDirectional.only(start: 20, top: 4),
child: Text(
widget.lines.join('\n'),
key: const Key('stage-popover-permission-lines'),
style: theme.textTheme.bodySmall?.copyWith(
fontFamily: appMonospaceFamily,
height: 1.5,
),
),
),
],
);
}
}
@@ -0,0 +1,368 @@
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Where a stage popover sits relative to its node.
enum StagePopoverSide { above, below, right, left, over }
/// Places one popover card beside an anchor node, inside a bounding box, and
/// paints the nub that points at the node.
///
/// It fills its overlay but hit-tests only the card, so the graph under it
/// keeps every gesture. The anchor is a rectangle in [anchorBox]'s own space
/// (the graph canvas, inside the pan/zoom transform); it is mapped through the
/// live transform at layout, and [relayout] (the viewport transform) lays the
/// card out again on every pan or zoom, so it follows the node.
class StagePopoverPosition extends SingleChildRenderObjectWidget {
const StagePopoverPosition({
super.key,
required this.anchorBox,
required this.anchorRect,
required this.boundsBox,
required this.boundsSize,
this.safeArea = EdgeInsets.zero,
required this.relayout,
required this.fill,
required this.border,
required this.radius,
required this.elevation,
required this.shadowColor,
super.child,
});
final RenderBox? Function() anchorBox;
final Rect anchorRect;
/// The visible box the card must stay inside, and its extent; a null box
/// uses the overlay itself.
final RenderBox? Function() boundsBox;
final Size? boundsSize;
/// Insets of the screen the card must also keep clear of (floating bars
/// drawn over the viewport's edges).
final EdgeInsets safeArea;
final Listenable? relayout;
final Color fill;
final BorderSide border;
final double radius;
final double elevation;
final Color shadowColor;
@override
RenderStagePopoverPosition createRenderObject(BuildContext context) =>
RenderStagePopoverPosition(
anchorBox: anchorBox,
anchorRect: anchorRect,
boundsBox: boundsBox,
boundsSize: boundsSize,
safeArea: safeArea,
relayout: relayout,
fill: fill,
border: border,
radius: radius,
elevation: elevation,
shadowColor: shadowColor,
);
@override
void updateRenderObject(
BuildContext context,
RenderStagePopoverPosition renderObject,
) {
renderObject
..anchorBox = anchorBox
..anchorRect = anchorRect
..boundsBox = boundsBox
..boundsSize = boundsSize
..safeArea = safeArea
..relayout = relayout
..fill = fill
..border = border
..radius = radius
..elevation = elevation
..shadowColor = shadowColor;
}
}
class RenderStagePopoverPosition extends RenderShiftedBox {
RenderStagePopoverPosition({
required this.anchorBox,
required this._anchorRect,
required this.boundsBox,
required this._boundsSize,
required this._safeArea,
required this._relayout,
required this.fill,
required this.border,
required this.radius,
required this.elevation,
required this.shadowColor,
}) : super(null);
/// The card's widest extent.
static const double maxCardWidth = 400;
/// The card's tallest extent; a longer card scrolls its body.
static const double maxCardHeight = 560;
/// The space kept between the card and the viewport's edges.
static const double margin = 8;
/// The nub's depth; its base is twice as wide.
static const double nub = 7;
/// The gap between the node and the nub's tip.
static const double gap = 3;
RenderBox? Function() anchorBox;
RenderBox? Function() boundsBox;
Color fill;
BorderSide border;
double radius;
double elevation;
Color shadowColor;
Rect _anchorRect;
set anchorRect(Rect value) {
if (value == _anchorRect) return;
_anchorRect = value;
markNeedsLayout();
}
EdgeInsets _safeArea;
set safeArea(EdgeInsets value) {
if (value == _safeArea) return;
_safeArea = value;
markNeedsLayout();
}
Size? _boundsSize;
set boundsSize(Size? value) {
if (value == _boundsSize) return;
_boundsSize = value;
markNeedsLayout();
}
Listenable? _relayout;
set relayout(Listenable? value) {
if (value == _relayout) return;
if (attached) _relayout?.removeListener(markNeedsLayout);
_relayout = value;
if (attached) _relayout?.addListener(markNeedsLayout);
markNeedsLayout();
}
/// Where the card went in the last layout, for tests and the nub.
StagePopoverSide side = StagePopoverSide.above;
bool _visible = false;
Offset _tip = Offset.zero;
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_relayout?.addListener(markNeedsLayout);
}
@override
void detach() {
_relayout?.removeListener(markNeedsLayout);
super.detach();
}
Rect _bounds() {
final whole = _safeArea.deflateRect(Offset.zero & size);
final box = boundsBox();
final extent = _boundsSize;
if (box == null || !box.attached || extent == null) {
return whole.deflate(margin);
}
final origin = MatrixUtils.transformPoint(
box.getTransformTo(this),
Offset.zero,
);
return (origin & extent).intersect(whole).deflate(margin);
}
Rect? _anchor() {
final box = anchorBox();
if (box == null || !box.attached) return null;
return MatrixUtils.transformRect(box.getTransformTo(this), _anchorRect);
}
@override
void performLayout() {
size = constraints.biggest;
final card = child;
// Mapping through the ancestors' paint transforms reads their sizes (a
// page transition's translation does); a layout callback is the sanctioned
// scope for that, as it is for a LayoutBuilder.
var mapped = (bounds: Rect.zero, anchor: null as Rect?);
invokeLayoutCallback<BoxConstraints>((_) {
mapped = (bounds: _bounds(), anchor: _anchor());
});
final bounds = mapped.bounds;
final anchor = mapped.anchor;
_visible =
card != null &&
anchor != null &&
bounds.width > 0 &&
bounds.height > 0 &&
anchor.overlaps(bounds);
if (!_visible || card == null || anchor == null) {
card?.layout(const BoxConstraints.tightFor(width: 0, height: 0));
return;
}
final width = math.min(maxCardWidth, bounds.width);
var cardSize = _layoutCard(
card,
width,
math.min(maxCardHeight, bounds.height),
);
final reach = gap + nub;
final above = anchor.top - reach - bounds.top;
final below = bounds.bottom - anchor.bottom - reach;
final right = bounds.right - anchor.right - reach;
final left = anchor.left - reach - bounds.left;
if (cardSize.height <= above) {
side = StagePopoverSide.above;
} else if (cardSize.height <= below) {
side = StagePopoverSide.below;
} else if (cardSize.width <= right) {
side = StagePopoverSide.right;
} else if (cardSize.width <= left) {
side = StagePopoverSide.left;
} else if (math.max(above, below) >= 160) {
// Too tall for either side whole: take the roomier one and scroll.
side = above >= below ? StagePopoverSide.above : StagePopoverSide.below;
cardSize = _layoutCard(
card,
width,
math.min(maxCardHeight, math.max(above, below)),
);
} else {
side = StagePopoverSide.over;
}
final parentData = card.parentData! as BoxParentData;
double clampX(double x) => x.clamp(
bounds.left,
math.max(bounds.left, bounds.right - cardSize.width),
);
double clampY(double y) => y.clamp(
bounds.top,
math.max(bounds.top, bounds.bottom - cardSize.height),
);
final center = anchor.center;
final inset = radius + nub + 2;
switch (side) {
case StagePopoverSide.above:
case StagePopoverSide.below:
final x = clampX(center.dx - cardSize.width / 2);
final y = side == StagePopoverSide.above
? anchor.top - reach - cardSize.height
: anchor.bottom + reach;
parentData.offset = Offset(x, y);
final tipX = center.dx
.clamp(x + inset, math.max(x + inset, x + cardSize.width - inset))
.toDouble();
_tip = Offset(
tipX,
side == StagePopoverSide.above
? anchor.top - gap
: anchor.bottom + gap,
);
case StagePopoverSide.right:
case StagePopoverSide.left:
final y = clampY(center.dy - cardSize.height / 2);
final x = side == StagePopoverSide.right
? anchor.right + reach
: anchor.left - reach - cardSize.width;
parentData.offset = Offset(x, y);
final tipY = center.dy
.clamp(y + inset, math.max(y + inset, y + cardSize.height - inset))
.toDouble();
_tip = Offset(
side == StagePopoverSide.right
? anchor.right + gap
: anchor.left - gap,
tipY,
);
case StagePopoverSide.over:
parentData.offset = Offset(
clampX(center.dx - cardSize.width / 2),
clampY(center.dy - cardSize.height / 2),
);
}
}
Size _layoutCard(RenderBox card, double width, double height) {
card.layout(
BoxConstraints(maxWidth: width, maxHeight: math.max(0, height)),
parentUsesSize: true,
);
return card.size;
}
/// The nub as a triangle whose base overlaps the card's edge by the
/// border, so the card's own frame line does not cross it.
Path _nubPath() {
final t = _tip;
final b = border.width;
return switch (side) {
StagePopoverSide.above =>
Path()
..moveTo(t.dx - nub, t.dy - nub - b)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub, t.dy - nub - b),
StagePopoverSide.below =>
Path()
..moveTo(t.dx - nub, t.dy + nub + b)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub, t.dy + nub + b),
StagePopoverSide.right =>
Path()
..moveTo(t.dx + nub + b, t.dy - nub)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub + b, t.dy + nub),
StagePopoverSide.left =>
Path()
..moveTo(t.dx - nub - b, t.dy - nub)
..lineTo(t.dx, t.dy)
..lineTo(t.dx - nub - b, t.dy + nub),
StagePopoverSide.over => Path(),
};
}
@override
void paint(PaintingContext context, Offset offset) {
final card = child;
if (!_visible || card == null) return;
final hasNub = side != StagePopoverSide.over;
final nubPath = _nubPath().shift(offset);
if (hasNub && elevation > 0) {
context.canvas.drawShadow(
Path.from(nubPath)..close(),
shadowColor,
elevation,
false,
);
}
super.paint(context, offset);
if (!hasNub) return;
context.canvas.drawPath(Path.from(nubPath)..close(), Paint()..color = fill);
if (border.width > 0 && border.style != BorderStyle.none) {
context.canvas.drawPath(
nubPath,
Paint()
..color = border.color
..style = PaintingStyle.stroke
..strokeWidth = border.width
..strokeJoin = StrokeJoin.miter,
);
}
}
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) =>
_visible && super.hitTestChildren(result, position: position);
}
@@ -12,8 +12,8 @@ export 'notification_service_status.dart';
/// The app's handle on Android background delivery: a native foreground
/// service (android/…/notify/NotificationService.kt) that keeps its own
/// socket to the server and shows the server's notifications, so the ntfy app
/// is not needed. Other platforms have no service ([supported] is false).
/// socket to the server and shows the server's notifications while the app
/// is closed. Other platforms have no service ([supported] is false).
abstract interface class NotificationServiceBridge {
bool get supported;
@@ -4,6 +4,7 @@ import '../../../ui/status/run_status_icon.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../domain/check_step_output.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The note under a command whose recorded output the server cut short.
const String checkOutputTruncated =
@@ -99,7 +100,9 @@ class RunCheckCommandRow extends StatelessWidget {
DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: Padding(
padding: const EdgeInsets.all(12),
@@ -12,6 +12,7 @@ import '../../../ui/layout/sticky_section.dart';
import '../../../ui/text/live_elapsed_builder.dart';
import '../../../ui/text/monospace.dart';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The Summary tab: the run's identity, the recorded facts as one grid,
/// the stored original prompt with its copy control and the collapsible Input
@@ -231,7 +232,9 @@ Widget _materialBlock(BuildContext context, DetailSummaryRow row) {
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
),
child: SelectableText(
row.value,
@@ -9,6 +9,7 @@ import '../../../ui/text/live_elapsed_builder.dart';
import '../../pipelines/pipeline_format.dart' show formatDuration;
import '../domain/run_models.dart';
import 'run_detail_content.dart';
import '../../../ui/theme/app_design_tokens.dart';
/// The Timeline tab's recorded visits, one shared list row per visit.
///
@@ -116,7 +117,9 @@ class RunTimelineRow extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(10),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(10)),
),
child: Text(
label,
@@ -5,6 +5,7 @@ import '../../../core/transport/pipelines_client.dart'
show configuredGatewayEndpoint;
import '../../../ui/layout/app_list_avatar.dart';
import '../../../ui/layout/app_overflow_menu.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../../artifacts/domain/artifact_kind.dart';
import '../../artifacts/domain/artifact_record.dart';
import '../../artifacts/ui/artifact_tile.dart';
@@ -48,9 +49,11 @@ Widget? searchArtifactThumbnail(BuildContext context, JsonMap hit) {
return null;
}
return ClipRRect(
borderRadius: BorderRadius.circular(8),
borderRadius: AppDesignTokens.of(
context,
).denseCorners(BorderRadius.circular(8)),
child: SizedBox.square(
dimension: kAppListAvatarSize,
dimension: appListAvatarSize(context),
child: ArtifactThumbnail(
key: ValueKey('search.thumbnail.${hit['target']}'),
artifact: record,
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
import '../chat/workspace/chat_center_stage_controller.dart';
import '../chat/workspace/chat_float_shortcut.dart';
import '../chat/workspace/chat_list_hidden_controller.dart';
import '../chat/workspace/chat_pane_cycle.dart';
import '../terminal/terminal_shortcuts.dart';
import '../../shell/detached/detached_window_scope.dart';
import '../../shell/windows/window_shortcuts.dart';
@@ -197,6 +198,13 @@ class KeyboardShortcutRegistry {
action: 'Focus the neighbouring chat pane',
keys: _apple ? 'Cmd+Shift+Arrows' : 'Ctrl+Shift+Arrows',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Next or previous chat pane on screen',
keys: chatPaneCycleShortcutLabel(platform),
caveat:
'On a wide window with more than one chat shown: the tiled panes left to right, then top to bottom, then the floating chat windows, wrapping around. The pane\'s message input takes the keyboard and its border flashes. No chat opens or closes. In the terminal the keys go to the terminal.',
),
KeyboardShortcutEntry(
group: KeyboardShortcutGroup.chat,
action: 'Move the active chat pane',
@@ -2,9 +2,9 @@ import 'package:flutter/foundation.dart';
import '../../core/api_gateway.dart';
/// One server-side ntfy notification choice, in the server's wire key.
class NtfySetting {
const NtfySetting(this.key, this.label, {this.subtitle});
/// One server-side notification choice, in the server's wire key.
class NotificationSetting {
const NotificationSetting(this.key, this.label, {this.subtitle});
final String key;
final String label;
@@ -13,36 +13,30 @@ class NtfySetting {
final String? subtitle;
}
/// The server's global notification choices, in display order.
/// The server's global notification choices, in display order. They are
/// stored on the server, so they apply to every signed-in device.
///
/// `run_finished` (server default off) makes every run end notify; without it
/// only runs started with "Notify me" announce their success or failure.
const ntfySettings = <NtfySetting>[
NtfySetting(
const notificationSettings = <NotificationSetting>[
NotificationSetting(
'run_finished',
'Notify when any run ends',
subtitle: 'Otherwise only runs started with Notify me',
),
NtfySetting('chat_needs_you', 'Chat needs your answer or approval'),
NtfySetting('chat_reply_finished', 'Chat reply finished'),
NotificationSetting('chat_needs_you', 'Chat needs your answer or approval'),
NotificationSetting('chat_reply_finished', 'Chat reply finished'),
];
/// The server's switch for also publishing to ntfy. Optional: older servers
/// do not send it, and Settings hides the switch then.
const ntfyEnabledSetting = NtfySetting(
'ntfy_enabled',
'Also send to ntfy',
subtitle: 'For devices that still use the ntfy app',
);
/// Loads and changes the server's ntfy notification settings through the
/// shared gateway (`notification_settings` / `set_notification_settings`).
/// Loads and changes the server's notification settings through the shared
/// gateway (`notification_settings` / `set_notification_settings`).
///
/// A toggle shows the new value at once and is reverted, with the server's
/// refusal as [error], when the write fails. Every reply carries all keys, so
/// the stored result always replaces the local copy.
class NtfySettingsController extends ChangeNotifier {
NtfySettingsController(this.gateway);
/// the stored result always replaces the local copy. Keys the app does not
/// show (such as a retired one an older server still sends) are ignored.
class NotificationSettingsController extends ChangeNotifier {
NotificationSettingsController(this.gateway);
final ApiGateway gateway;
@@ -119,15 +113,13 @@ class NtfySettingsController extends ChangeNotifier {
throw const FormatException('the reply carried no notification settings');
}
final result = <String, bool>{};
for (final setting in ntfySettings) {
for (final setting in notificationSettings) {
final value = raw[setting.key];
if (value is! bool) {
throw FormatException('the reply is missing ${setting.key}');
}
result[setting.key] = value;
}
final ntfy = raw[ntfyEnabledSetting.key];
if (ntfy is bool) result[ntfyEnabledSetting.key] = ntfy;
return result;
}
@@ -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(
@@ -56,6 +56,7 @@ class SettingsDesignSection extends StatelessWidget {
subtitle: Text(design.description),
secondary: DesignSwatchPreview(
swatch: design.swatch(Theme.of(context).brightness),
lines: design.swatchLines,
),
),
],
@@ -64,12 +65,14 @@ class SettingsDesignSection extends StatelessWidget {
);
}
/// A design's small preview in the picker: its page with a line of its ink
/// and a dot of its accent, framed by a hairline.
/// A design's small preview in the picker: its page with [lines] lines of
/// its ink (the last one short) and a dot of its accent, framed by a
/// hairline. A dense design draws more, tighter lines in the same page.
class DesignSwatchPreview extends StatelessWidget {
const DesignSwatchPreview({super.key, required this.swatch});
const DesignSwatchPreview({super.key, required this.swatch, this.lines = 2});
final DesignSwatch swatch;
final int lines;
@override
Widget build(BuildContext context) => ExcludeSemantics(
@@ -89,10 +92,14 @@ class DesignSwatchPreview extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(height: 2, color: swatch.ink),
for (var line = 1; line < lines; line += 1)
Container(height: lines > 2 ? 1 : 2, color: swatch.ink),
FractionallySizedBox(
widthFactor: 0.6,
child: Container(height: 2, color: swatch.ink),
child: Container(
height: lines > 2 ? 1 : 2,
color: swatch.ink,
),
),
],
),
@@ -12,8 +12,8 @@ const deviceDeliveryTitle = 'Notifications in Pipelines';
const deviceDeliverySwitchLabel = 'Receive notifications in Pipelines';
const deviceDeliveryNote =
'Pipelines keeps its own connection to the server and shows its '
'notifications, so the ntfy app is no longer needed. Android shows a '
'quiet "Pipelines is connected" notification while it runs.';
'notifications even while the app is closed. Android shows a quiet '
'"Pipelines is connected" notification while it runs.';
const deviceDeliveryBatteryLabel = 'Allow background delivery';
const deviceDeliveryNotificationsLabel = 'Allow notifications';
const deviceDeliveryWarningTitle = 'Delivery can pause while idle';
+13 -11
View File
@@ -33,16 +33,17 @@ class SettingsGroup extends StatelessWidget {
final footer = this.footer;
final theme = Theme.of(context);
final tokens = AppDesignTokens.of(context);
final inset = settingsRowInsetOf(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (title != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
settingsRowInset,
padding: EdgeInsetsDirectional.fromSTEB(
inset,
0,
settingsRowInset,
settingsTitleGap,
inset,
tokens.density.space(settingsTitleGap),
),
child: Semantics(
header: true,
@@ -74,7 +75,7 @@ class SettingsGroup extends StatelessWidget {
Divider(
height: 1,
thickness: 1,
indent: settingsRowInset,
indent: inset,
color: theme.colorScheme.outlineVariant,
),
child,
@@ -92,11 +93,12 @@ class SettingsGroup extends StatelessWidget {
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
final text = DefaultTextStyle.merge(style: style, child: footer);
final inset = settingsRowInsetOf(context);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
settingsRowInset,
settingsFieldGap + 2,
settingsRowInset,
padding: EdgeInsetsDirectional.fromSTEB(
inset,
AppDesignTokens.of(context).density.space(settingsFieldGap + 2),
inset,
0,
),
child: text,
@@ -124,8 +126,8 @@ class SettingsGroupItem extends StatelessWidget {
width: double.infinity,
child: Padding(
padding: EdgeInsetsDirectional.symmetric(
horizontal: settingsRowInset,
vertical: 12,
horizontal: settingsRowInsetOf(context),
vertical: AppDesignTokens.of(context).density.space(12),
),
child: child,
),

Some files were not shown because too many files have changed in this diff Show More