Chat bar: Next chat button cycles to the next chat in list order

This commit is contained in:
2026-11-04 18:22:27 +00:00
parent fa6c0864db
commit 9a7adf88ab
9 changed files with 425 additions and 8 deletions
@@ -0,0 +1,38 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
/// The open chat's Next chat button: the platform's icon button, labelled
/// "Next chat", that opens the chat after this one in the list.
///
/// It stays in the bar rather than leaving for the More menu on a narrow
/// bar (it is not [SegmentedOverflowable]): it is the one-tap way to cycle
/// chats on a phone, so the title gives up the room instead.
class ChatNextChatButton extends StatelessWidget {
const ChatNextChatButton({super.key, required this.onPressed});
static const label = 'Next chat';
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.arrow_right_to_line),
),
);
}
return IconButton(
tooltip: label,
onPressed: onPressed,
icon: const Icon(Icons.keyboard_tab),
);
}
}
@@ -14,6 +14,7 @@ import '../domain/chat_attachment_picker.dart';
import '../domain/chat_colors.dart';
import '../domain/chat_transcript.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_next_chat_button.dart';
import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart';
import '../ui/transcript/chat_markdown_view.dart';
@@ -86,10 +87,15 @@ class ChatThreadView extends StatefulWidget {
this.onSessionClosed,
this.fileBridge = const ArtifactFileBridge(),
this.onColorSelected,
this.onNextChat,
});
final ApiGateway gateway;
/// Opens the chat after this one in the list (wrapping to the first), from
/// the bar's Next chat button; null when there is no other chat to open.
final VoidCallback? onNextChat;
/// Sets the chat's shared colour (a palette name, null for none) from the
/// information sheet; null leaves the sheet without the Colour choice.
final ValueChanged<String?>? onColorSelected;
@@ -1195,6 +1201,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
answeredBy: answeredBy,
),
if (hasMode) _modeControl(),
if (widget.onNextChat case final next?)
ChatNextChatButton(key: const Key('chat-next'), onPressed: next),
],
);
}
@@ -0,0 +1,24 @@
import '../../../core/api_gateway.dart';
import 'chat_sessions.dart';
/// The rows the chat list draws, top to bottom: the [query]'s matches in
/// Starred, then Chats by directory, then Closed, leaving out every section
/// [isOpen] reports folded. Ctrl+1…Ctrl+9 and Next chat both count these.
List<JsonMap> chatSessionsShown(
List<JsonMap> sessions, {
required String query,
required bool Function(String title) isOpen,
}) => chatSessionsInListOrder(
chatSessionSections(filterChatSessions(sessions, query)),
isOpen: isOpen,
);
/// The row after [currentId] in [shown], wrapping from the last row to the
/// first. A chat not among [shown] (its section is folded) moves to the
/// first row. Null when no other row is shown, so there is nothing to move to.
JsonMap? chatSessionAfter(List<JsonMap> shown, String currentId) {
final index = shown.indexWhere((row) => '${row['id'] ?? ''}' == currentId);
final others = index < 0 ? shown.length : shown.length - 1;
if (others < 1) return null;
return shown[(index + 1) % shown.length];
}
+52
View File
@@ -6,6 +6,7 @@ import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import '../../core/api_gateway.dart';
import 'conversation/chat_models.dart';
@@ -16,6 +17,8 @@ import 'conversation/chat_transcript_cache.dart';
import 'conversation/composer_focus_request.dart';
import 'data/chat_repository.dart';
import 'domain/chat_commands.dart';
import 'domain/chat_cycle.dart';
import 'ui/sessions/chat_sessions_body.dart';
import 'ui/sessions/chat_sessions_controller.dart';
import 'ui/sessions/chat_sessions_screen.dart';
@@ -95,6 +98,51 @@ class _ChatScreenState extends State<ChatScreen> {
/// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer.
final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests();
/// The list's folded sections, kept here so Next chat counts the rows the
/// list draws.
final ChatSectionFolds _folds = ChatSectionFolds();
/// Whether the last build offered Next chat, so a list change rebuilds only
/// when that changes.
bool _offeredNext = false;
@override
void initState() {
super.initState();
_sessions.addListener(_nextChanged);
_folds.addListener(_nextChanged);
}
/// The chat after [id] as the list draws it (Starred, then Chats by
/// directory, then Closed, skipping folded sections), wrapping around. The
/// embedded list has no search field, so no query narrows it.
JsonMap? _nextAfter(String id) => chatSessionAfter(
chatSessionsShown(_sessions.sessions, query: '', isOpen: _folds.isOpen),
id,
);
/// Next chat opens that row exactly as a tap on it would.
void _openNext(String id) {
final next = _nextAfter(id);
if (next != null) _open(next);
}
void _nextChanged() {
if (!mounted) return;
final id = _selected;
final offered = id != null && _nextAfter(id) != null;
if (offered == _offeredNext) return;
// The list may load while it builds; rebuild after that frame.
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() {});
});
} else {
setState(() {});
}
}
String? get _selected {
final routed = widget.initialSessionId;
if (routed != null && routed.isNotEmpty) return routed;
@@ -261,6 +309,7 @@ class _ChatScreenState extends State<ChatScreen> {
void dispose() {
_page.dispose();
_sessions.dispose();
_folds.dispose();
_composerFocus.dispose();
super.dispose();
}
@@ -287,6 +336,7 @@ class _ChatScreenState extends State<ChatScreen> {
onSessionRenamed: (title) => _renamed(selected, title),
onSessionClosed: _closed,
onColorSelected: (color) => _sessions.setColor(selected, color),
onNextChat: _offeredNext ? () => _openNext(selected) : null,
);
return ChatComposerFocusScope(
sessionId: selected,
@@ -298,6 +348,7 @@ class _ChatScreenState extends State<ChatScreen> {
@override
Widget build(BuildContext context) {
final selected = _selected;
_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
// chat, which has no Back: another row, `/close` or a route change swaps it.
@@ -318,6 +369,7 @@ class _ChatScreenState extends State<ChatScreen> {
embedded: true,
syncToken: widget.syncToken,
controller: _sessions,
folds: _folds,
onOpen: _open,
onShortcutOpen: _openByShortcut,
onSessions: _adoptRows,
@@ -10,14 +10,17 @@ import 'session_row_style.dart';
typedef ChatSessionSection = ({String title, List<JsonMap> sessions});
/// Which list sections are folded away, kept by the list's screen so the
/// keyboard shortcuts count only rows on screen. Closed starts folded.
class ChatSectionFolds {
/// keyboard shortcuts and Next chat count only rows on screen. Closed starts
/// folded. It notifies when a section folds or unfolds.
class ChatSectionFolds extends ChangeNotifier {
final Set<String> _folded = {'Closed'};
bool isOpen(String title) => !_folded.contains(title);
void set(String title, bool open) =>
open ? _folded.remove(title) : _folded.add(title);
void set(String title, bool open) {
final changed = open ? _folded.remove(title) : _folded.add(title);
if (changed) notifyListeners();
}
}
/// Groups the visible sessions the way the server reports them.
@@ -11,6 +11,7 @@ import '../../../../shell/shell_bar.dart';
import '../../../../shell/shell_list_shortcuts.dart';
import '../../data/chat_repository.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_cycle.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_color_picker.dart';
@@ -35,6 +36,7 @@ class ChatSessionsScreen extends StatefulWidget {
this.controller,
this.activeSessionId,
this.publishShellBar,
this.folds,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@@ -71,6 +73,10 @@ class ChatSessionsScreen extends StatefulWidget {
/// Null makes this screen own its own.
final ChatSessionsController? controller;
/// Which sections are folded, when the destination keeps them (Next chat
/// counts the same rows); null makes this screen keep its own.
final ChatSectionFolds? folds;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
@@ -85,7 +91,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
..activeSessionId = widget.activeSessionId
..refresh();
final _search = TextEditingController();
final _folds = ChatSectionFolds();
late final ChatSectionFolds _folds = widget.folds ?? ChatSectionFolds();
Timer? _undoTimer;
String? _markedActiveSessionId;
@@ -140,6 +146,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
_undoTimer?.cancel();
_controller.removeListener(_reportSessions);
if (widget.controller == null) _controller.dispose();
if (widget.folds == null) _folds.dispose();
_search.dispose();
super.dispose();
}
@@ -203,9 +210,9 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
/// Ctrl+N: opens the Nth row the list draws (Starred first, then Chats by
/// directory, then Closed while it is unfolded), searched as shown.
bool _openIndex(int index) {
final visible = filterChatSessions(_controller.sessions, _search.text);
final rows = chatSessionsInListOrder(
chatSessionSections(visible),
final rows = chatSessionsShown(
_controller.sessions,
query: _search.text,
isOpen: _folds.isOpen,
);
if (index < 0 || index >= rows.length) return false;
+28
View File
@@ -0,0 +1,28 @@
# Next chat button
An open chat's bar ends with a Next chat icon button (Material
`Icons.keyboard_tab`, Cupertino `CupertinoIcons.arrow_right_to_line`; tooltip
and semantics "Next chat"). It opens the chat after the current one and wraps
from the last to the first, for one-tap cycling on a phone.
- Order: exactly the rows the list draws, the same rows Ctrl+1…Ctrl+9 count
(`chatSessionsShown` in `lib/features/chat/domain/chat_cycle.dart`):
Starred by name, then Chats grouped by directory, then Closed. A folded
section's chats are skipped: they are not on screen, and Closed starts
folded, so cycling never wanders into closed chats unless the operator
unfolded them. A chat whose own section is folded moves to the first row.
The destination now owns the `ChatSectionFolds` and passes it to the list.
- Hidden when no other row is shown (one chat, or one plus folded ones).
- Opening goes through `ChatScreen._open`, the same path as a row tap: the
route names the new chat, the list row selection follows, and on a phone the
existing detail page swaps its content (one Back still returns to the list;
no page is stacked).
- The button is not `SegmentedOverflowable`, so a narrow bar keeps it beside
the model and mode pills instead of moving it into More.
- No keyboard shortcut: Ctrl+Tab never reaches a web page (Chrome keeps it),
and a shell-wide binding would mean editing `lib/shell/`.
Tests: `test/features/chat/domain/chat_cycle_test.dart`,
`test/features/chat/chat_next_chat_test.dart`. Captures (560x1000, Material and
Cupertino, fixture `chats=3`): chat 3 open, Next opens chat 1 (wrap), three
presses return to chat 3.
@@ -0,0 +1,191 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:pipelines_app/ui/layout/app_list_row.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'conversation/chat_thread_fixtures.dart';
/// Server recency order: the list shows Starred by name (apple, Zed), then
/// Chats by directory (Recent, Second in /w; Other in /v), then Closed folded.
const _rows = <JsonMap>[
{'id': 'r', 'title': 'Recent', 'directory': '/w'},
{'id': 'd', 'title': 'Other', 'directory': '/v'},
{'id': 'c', 'title': 'Done', 'directory': '/w', 'closed_at': 1},
{'id': 's', 'title': 'Second', 'directory': '/w'},
{'id': 'z', 'title': 'Zed', 'directory': '/w', 'starred': true},
{'id': 'a', 'title': 'apple', 'directory': '/v', 'starred': true},
];
class _Gateway extends FakeChatGateway {
_Gateway(this.rows);
final List<JsonMap> rows;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type == 'chat_sessions') {
return Future.value({
'chat_sessions': [
for (final row in rows) {...row},
],
});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
return super.call(type, fields);
}
}
/// The app's routing: the route names the open chat; selecting one replaces
/// the route, Back returns to the list.
Future<ValueNotifier<String?>> _pump(
WidgetTester tester,
Size size, {
List<JsonMap> rows = _rows,
}) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _Gateway(rows)..history = (_) async => chatPage(const []);
addTearDown(gateway.close);
final route = ValueNotifier<String?>(null);
addTearDown(route.dispose);
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) => ValueListenableBuilder<String?>(
valueListenable: route,
builder: (context, id, _) => ChatScreen(
gateway: gateway,
initialSessionId: id,
onSessionSelected: (next) => route.value = next,
onBack: () => route.value = null,
),
),
},
),
),
);
await tester.pumpAndSettle();
return route;
}
Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id'));
final _next = find.byKey(const Key('chat-next'));
bool _rowSelected(WidgetTester tester, String id) =>
tester.widget<AppListRow>(find.byKey(Key('chat-row-$id'))).selected;
Future<void> _pressNext(WidgetTester tester) async {
await tester.tap(_next);
await tester.pumpAndSettle();
}
void main() {
testWidgets('wide: Next chat walks the list order, wraps, syncs the row', (
tester,
) async {
final route = await _pump(tester, const Size(1280, 800));
await tester.tap(find.byKey(const Key('chat-row-a')));
await tester.pumpAndSettle();
expect(_thread('a'), findsOneWidget);
expect(
tester
.widget<IconButton>(
find.descendant(of: _next, matching: find.byType(IconButton)),
)
.tooltip,
'Next chat',
);
final visited = <String>[];
for (var i = 0; i < 5; i++) {
await _pressNext(tester);
visited.add(route.value!);
expect(_thread(route.value!), findsOneWidget);
expect(_rowSelected(tester, route.value!), isTrue);
}
// Closed is folded, so Done is skipped; after the last row comes the
// first again.
expect(visited, ['z', 'r', 's', 'd', 'a']);
expect(_rowSelected(tester, 'd'), isFalse);
final navigator = tester.state<NavigatorState>(
find.byType(Navigator).first,
);
expect(navigator.canPop(), isFalse);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('phone: Next chat replaces the open page, never stacks one', (
tester,
) async {
final route = await _pump(tester, const Size(390, 844));
await tester.tap(find.text('Second'));
await tester.pumpAndSettle();
expect(_thread('s'), findsOneWidget);
await _pressNext(tester);
expect(route.value, 'd');
expect(_thread('d'), findsOneWidget);
expect(_thread('s'), findsNothing);
await _pressNext(tester);
expect(route.value, 'a', reason: 'wraps past the last row');
// One Back leaves the chat: no earlier chat page waits beneath it.
await tester.pageBack();
await tester.pumpAndSettle();
expect(route.value, isNull);
expect(_thread('a'), findsNothing);
final navigator = tester.state<NavigatorState>(
find.byType(Navigator).first,
);
expect(navigator.canPop(), isFalse);
expect(_rowSelected(tester, 'a'), isFalse);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('only one chat to show hides Next chat', (tester) async {
await _pump(
tester,
const Size(390, 844),
rows: const [
{'id': 'r', 'title': 'Recent', 'directory': '/w'},
{'id': 'c', 'title': 'Done', 'directory': '/w', 'closed_at': 1},
],
);
await tester.tap(find.text('Recent'));
await tester.pumpAndSettle();
expect(_thread('r'), findsOneWidget);
expect(_next, findsNothing);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('unfolding Closed offers Next chat and includes its rows', (
tester,
) async {
final route = await _pump(
tester,
const Size(1280, 800),
rows: const [
{'id': 'r', 'title': 'Recent', 'directory': '/w'},
{'id': 'c', 'title': 'Done', 'directory': '/w', 'closed_at': 1},
],
);
await tester.tap(find.text('Recent'));
await tester.pumpAndSettle();
expect(_next, findsNothing);
await tester.tap(find.text('Closed'));
await tester.pumpAndSettle();
expect(_next, findsOneWidget);
await _pressNext(tester);
expect(route.value, 'c');
await tester.pumpWidget(const SizedBox.shrink());
});
}
@@ -0,0 +1,66 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_cycle.dart';
List<String> _ids(List<JsonMap> rows) => [
for (final row in rows) '${row['id']}',
];
String? _after(List<JsonMap> rows, String id) =>
chatSessionAfter(rows, id)?['id'] as String?;
bool _closedFolded(String title) => title != 'Closed';
void main() {
// Server recency order; the list regroups it.
final sessions = <JsonMap>[
{'id': 'r', 'title': 'Recent', 'directory': '/w'},
{'id': 'd', 'title': 'Other', 'directory': '/v'},
{'id': 'c', 'title': 'Done', 'directory': '/w', 'closed_at': 1},
{'id': 's', 'title': 'Second', 'directory': '/w'},
{'id': 'z', 'title': 'Zed', 'directory': '/w', 'starred': true},
{'id': 'a', 'title': 'apple', 'directory': '/v', 'starred': true},
];
test('shown rows: Starred by name, Chats by directory, folded skipped', () {
final folded = chatSessionsShown(
sessions,
query: '',
isOpen: _closedFolded,
);
expect(_ids(folded), ['a', 'z', 'r', 's', 'd']);
final open = chatSessionsShown(sessions, query: '', isOpen: (_) => true);
expect(_ids(open), ['a', 'z', 'r', 's', 'd', 'c']);
final searched = chatSessionsShown(
sessions,
query: 'o',
isOpen: (_) => true,
);
expect(_ids(searched), ['d', 's', 'c']);
});
test('next wraps from the last row to the first', () {
final rows = chatSessionsShown(sessions, query: '', isOpen: _closedFolded);
var id = 'a';
final visited = <String>[];
for (var i = 0; i < rows.length; i++) {
id = _after(rows, id)!;
visited.add(id);
}
expect(visited, ['z', 'r', 's', 'd', 'a']);
});
test('a chat in a folded section moves to the first shown row', () {
final rows = chatSessionsShown(sessions, query: '', isOpen: _closedFolded);
expect(_after(rows, 'c'), 'a');
});
test('nothing to move to without another shown row', () {
final one = <JsonMap>[
{'id': 'only'},
];
expect(_after(one, 'only'), isNull);
expect(_after(const [], 'only'), isNull);
expect(_after(one, 'elsewhere'), 'only');
});
}