App: chat colours, Ctrl+1-9 opens the Nth list item, starred chats alphabetical

A chat's colour is picked from its row menu (Colour...), a long-press or
the chat information sheet. The list shows it as a leading bar, a faint
row tint and a coloured avatar; the open chat shows a faint wash under its
top bar. Shades are Cupertino's dynamic system colours and Material
swatches tuned per brightness. Changes from other devices apply live.

Ctrl+1...Ctrl+9 open the Nth item of the open tab's list (chats, runs,
pipelines) in on-screen order, also while typing. Starred chats are sorted
by name, case-insensitively, as one alphabetical group.
This commit is contained in:
2026-11-03 11:05:38 +00:00
parent a4c191a416
commit f7b5958d64
28 changed files with 1319 additions and 42 deletions
@@ -0,0 +1,47 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_colors.dart';
import '../ui/sessions/chat_color_palette.dart';
/// The open chat's colour as a faint wash behind the top of the page: it
/// shows through the glass bar and fades out just below it, so even without
/// the list beside it the chat carries a gentle reminder of which one it is.
/// It sits under the transcript and takes no taps, so text contrast and
/// hit-testing are untouched. Nothing is drawn for a chat with no colour.
class ChatColorWash extends StatelessWidget {
const ChatColorWash({super.key, required this.session});
final JsonMap? session;
@override
Widget build(BuildContext context) {
final color = chatColorShade(context, chatSessionColor(session));
if (color == null) return const SizedBox.shrink();
final strength = chatColorDarkSurface(context) ? 0.20 : 0.14;
// The bar's height arrives as top padding; the wash reaches a little
// past it so the fade reads under the bar, not as an edge at it.
final height = MediaQuery.paddingOf(context).top + 72;
return Positioned(
top: 0,
left: 0,
right: 0,
height: height,
child: IgnorePointer(
child: DecoratedBox(
key: const Key('chat-color-wash'),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
color.withValues(alpha: strength),
color.withValues(alpha: 0),
],
),
),
),
),
);
}
}
@@ -11,14 +11,17 @@ import '../data/chat_repository.dart';
import '../domain/chat_activity_detail.dart'; import '../domain/chat_activity_detail.dart';
import '../domain/chat_notice.dart'; import '../domain/chat_notice.dart';
import '../domain/chat_attachment_picker.dart'; import '../domain/chat_attachment_picker.dart';
import '../domain/chat_colors.dart';
import '../domain/chat_transcript.dart'; import '../domain/chat_transcript.dart';
import '../ui/sessions/chat_adaptive.dart'; import '../ui/sessions/chat_adaptive.dart';
import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart'; import '../ui/sessions/session_actions.dart';
import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_view.dart'; import '../ui/transcript/chat_message_view.dart';
import '../ui/transcript/chat_injected_rows.dart'; import '../ui/transcript/chat_injected_rows.dart';
import 'chat_account_usage_section.dart'; import 'chat_account_usage_section.dart';
import 'chat_background_tasks.dart'; import 'chat_background_tasks.dart';
import 'chat_color_wash.dart';
import 'chat_command_actions.dart'; import 'chat_command_actions.dart';
import 'chat_composer_bar.dart'; import 'chat_composer_bar.dart';
import 'chat_composer_controller.dart'; import 'chat_composer_controller.dart';
@@ -75,9 +78,14 @@ class ChatThreadView extends StatefulWidget {
this.onCreatedSession, this.onCreatedSession,
this.onSessionRenamed, this.onSessionRenamed,
this.onSessionClosed, this.onSessionClosed,
this.onColorSelected,
}); });
final ApiGateway gateway; final ApiGateway gateway;
/// 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;
final String sessionId; final String sessionId;
final VoidCallback onBack; final VoidCallback onBack;
@@ -337,11 +345,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
context: context, context: context,
builder: (sheetContext) => Align( builder: (sheetContext) => Align(
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
child: SafeArea( child: SafeArea(child: CupertinoPopupSurface(child: _infoSheet())),
child: CupertinoPopupSurface(
child: _ChatInfoSheet(controller: _controller),
),
),
), ),
); );
return; return;
@@ -351,10 +355,16 @@ class _ChatThreadViewState extends State<ChatThreadView> {
showDragHandle: true, showDragHandle: true,
isScrollControlled: true, isScrollControlled: true,
useSafeArea: true, useSafeArea: true,
builder: (sheetContext) => _ChatInfoSheet(controller: _controller), builder: (sheetContext) => _infoSheet(),
); );
} }
Widget _infoSheet() => _ChatInfoSheet(
controller: _controller,
color: chatSessionColor(widget.session),
onColorSelected: widget.onColorSelected,
);
/// The transcript in recorded order; a sent turn is part of it from the /// The transcript in recorded order; a sent turn is part of it from the
/// moment it is sent (ChatThreadController.insertLocal). /// moment it is sent (ChatThreadController.insertLocal).
List<JsonMap> _visibleMessages() => _controller.messages; List<JsonMap> _visibleMessages() => _controller.messages;
@@ -927,6 +937,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_rowWidgets.prune(); _rowWidgets.prune();
return Stack( return Stack(
children: [ children: [
// Behind everything: the chat's colour under the bar.
ChatColorWash(session: widget.session),
// At rest the first item starts below the floating bar // At rest the first item starts below the floating bar
// and the last one ends above the floating composer. // and the last one ends above the floating composer.
// Bottom-anchored at the split row, the newest rows are // Bottom-anchored at the split row, the newest rows are
@@ -1541,9 +1553,15 @@ String _chatInfoDollars(num value) {
/// The "Chat information" panel. It rebuilds from the controller, so metrics /// The "Chat information" panel. It rebuilds from the controller, so metrics
/// that arrive while it is open replace the displayed snapshot. /// that arrive while it is open replace the displayed snapshot.
class _ChatInfoSheet extends StatelessWidget { class _ChatInfoSheet extends StatelessWidget {
const _ChatInfoSheet({required this.controller}); const _ChatInfoSheet({
required this.controller,
this.color,
this.onColorSelected,
});
final ChatThreadController controller; final ChatThreadController controller;
final String? color;
final ValueChanged<String?>? onColorSelected;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -1562,6 +1580,8 @@ class _ChatInfoSheet extends StatelessWidget {
cupertino: cupertino, cupertino: cupertino,
doneKey: const Key('chat-info-close'), doneKey: const Key('chat-info-close'),
), ),
if (onColorSelected case final onSelected?)
ChatColorSection(selected: color, onSelected: onSelected),
for (final metric in _chatInfoMetrics(controller.usage)) for (final metric in _chatInfoMetrics(controller.usage))
_ChatInfoRow(metric: metric, cupertino: cupertino), _ChatInfoRow(metric: metric, cupertino: cupertino),
ChatAccountUsageSection( ChatAccountUsageSection(
@@ -182,6 +182,12 @@ class ChatRepository {
gateway.call('chat_star', { gateway.call('chat_star', {
'chat_query': {'session_id': sessionId, 'starred': starred}, 'chat_query': {'session_id': sessionId, 'starred': starred},
}); });
/// Sets the shared highlight colour by palette name; null clears it.
Future<JsonMap> setColor(String sessionId, String? color) =>
gateway.call('chat_color', {
'chat_query': {'session_id': sessionId, 'color': color},
});
Future<JsonMap> close(String sessionId) => gateway.call('chat_close', { Future<JsonMap> close(String sessionId) => gateway.call('chat_close', {
'chat_query': {'session_id': sessionId}, 'chat_query': {'session_id': sessionId},
}); });
@@ -0,0 +1,23 @@
/// The fixed palette of shared chat highlight colours, by the names the
/// server stores, in picker order. Each host renders its own tuned shade.
const chatColorNames = [
'red',
'orange',
'amber',
'green',
'teal',
'blue',
'purple',
'pink',
];
/// The session's highlight name, or null when it has none (or one this
/// client does not know).
String? chatSessionColor(Map<String, dynamic>? session) {
final name = '${session?['color'] ?? ''}'.trim();
return chatColorNames.contains(name) ? name : null;
}
/// The colour's name as a person reads it.
String chatColorLabel(String name) =>
name.isEmpty ? name : name[0].toUpperCase() + name.substring(1);
@@ -34,6 +34,62 @@ List<({String directory, List<JsonMap> sessions})> groupChatSessions(
.toList(); .toList();
} }
/// The list's sections in on-screen order: Starred (open chats, by name, so
/// each keeps its place), Chats (open, server recency) and Closed (server
/// recency). Empty sections are left out.
List<({String title, List<JsonMap> sessions})> chatSessionSections(
List<JsonMap> visible,
) {
bool closed(JsonMap s) => s['closed_at'] != null;
bool starred(JsonMap s) => s['starred'] == true && !closed(s);
final sections = [
(
title: 'Starred',
sessions: sortStarredChatSessions(visible.where(starred)),
),
(
title: 'Chats',
sessions: visible.where((s) => !starred(s) && !closed(s)).toList(),
),
(title: 'Closed', sessions: visible.where(closed).toList()),
];
return [
for (final section in sections)
if (section.sessions.isNotEmpty) section,
];
}
/// Starred chats alphabetically by their shown title, ignoring case; equal
/// titles keep a fixed order by id.
List<JsonMap> sortStarredChatSessions(Iterable<JsonMap> sessions) =>
sessions.toList()..sort((a, b) {
final byTitle = chatSessionTitle(
a,
).toLowerCase().compareTo(chatSessionTitle(b).toLowerCase());
if (byTitle != 0) return byTitle;
return '${a['id'] ?? ''}'.compareTo('${b['id'] ?? ''}');
});
/// Whether a section's rows are split under directory headings. Starred keeps
/// its alphabetical order whole, so a name is always in the same place.
bool chatSectionGroupsByDirectory(String title) => title != 'Starred';
/// The rows of [sections] in the order the list draws them: each open
/// section's rows, directory group by directory group. A folded section
/// draws no rows.
List<JsonMap> chatSessionsInListOrder(
List<({String title, List<JsonMap> sessions})> sections, {
required bool Function(String title) isOpen,
}) => [
for (final section in sections)
if (isOpen(section.title))
if (chatSectionGroupsByDirectory(section.title))
for (final group in groupChatSessions(section.sessions))
...group.sessions
else
...section.sessions,
];
String chatSessionActivity({required bool running, required bool unseen}) => String chatSessionActivity({required bool running, required bool unseen}) =>
running running
? 'streaming' ? 'streaming'
+1
View File
@@ -252,6 +252,7 @@ class _ChatScreenState extends State<ChatScreen> {
onCreatedSession: _openCreated, onCreatedSession: _openCreated,
onSessionRenamed: (title) => _renamed(selected, title), onSessionRenamed: (title) => _renamed(selected, title),
onSessionClosed: _closed, onSessionClosed: _closed,
onColorSelected: (color) => _sessions.setColor(selected, color),
); );
} }
@@ -0,0 +1,49 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/chat_colors.dart';
import 'chat_adaptive.dart';
/// The host's own shade for a chat colour name, tuned for the current
/// brightness: Cupertino's dynamic system colours, and Material's standard
/// swatches (a deeper tone on light surfaces, a lighter one on dark), so the
/// mark keeps its contrast in both. Null for no (or an unknown) colour.
Color? chatColorShade(BuildContext context, String? name) {
if (name == null || !chatColorNames.contains(name)) return null;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
final CupertinoDynamicColor color = switch (name) {
'red' => CupertinoColors.systemRed,
'orange' => CupertinoColors.systemOrange,
'amber' => CupertinoColors.systemYellow,
'green' => CupertinoColors.systemGreen,
'teal' => CupertinoColors.systemTeal,
'blue' => CupertinoColors.systemBlue,
'purple' => CupertinoColors.systemPurple,
_ => CupertinoColors.systemPink,
};
return color.resolveFrom(context);
}
final dark = Theme.of(context).brightness == Brightness.dark;
final MaterialColor swatch = switch (name) {
'red' => Colors.red,
'orange' => Colors.orange,
'amber' => Colors.amber,
'green' => Colors.green,
'teal' => Colors.teal,
'blue' => Colors.blue,
'purple' => Colors.purple,
_ => Colors.pink,
};
if (dark) return swatch.shade300;
return switch (name) {
'orange' || 'amber' => swatch.shade800,
'red' || 'teal' || 'purple' || 'pink' => swatch.shade600,
_ => swatch.shade700,
};
}
/// Whether the surrounding theme is dark, on either host.
bool chatColorDarkSurface(BuildContext context) =>
chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? CupertinoTheme.brightnessOf(context) == Brightness.dark
: Theme.of(context).brightness == Brightness.dark;
@@ -0,0 +1,192 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/layout/app_sheet_header.dart';
import '../../domain/chat_colors.dart';
import 'chat_adaptive.dart';
import 'chat_color_palette.dart';
/// The chat colour choices: None, then the palette, as the host's own icon
/// buttons. The chosen one shows a check. It keeps its own selection, so a
/// pick shows at once inside a sheet that the list's rebuild cannot reach.
class ChatColorSwatches extends StatefulWidget {
const ChatColorSwatches({
super.key,
required this.selected,
required this.onSelected,
});
/// The current colour name, or null for none.
final String? selected;
final ValueChanged<String?> onSelected;
@override
State<ChatColorSwatches> createState() => _ChatColorSwatchesState();
}
class _ChatColorSwatchesState extends State<ChatColorSwatches> {
late String? _selected = widget.selected;
@override
void didUpdateWidget(covariant ChatColorSwatches oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selected != widget.selected) _selected = widget.selected;
}
void _pick(String? name) {
setState(() => _selected = name);
widget.onSelected(name);
}
@override
Widget build(BuildContext context) {
return Wrap(
spacing: 4,
runSpacing: 4,
children: [
_swatch(context, null),
for (final name in chatColorNames) _swatch(context, name),
],
);
}
Widget _swatch(BuildContext context, String? name) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final selected = _selected == name;
final label = name == null ? 'No colour' : chatColorLabel(name);
final muted = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final color = chatColorShade(context, name) ?? muted;
final IconData icon = name == null
? (cupertino ? CupertinoIcons.nosign : Icons.block)
: selected
? (cupertino
? CupertinoIcons.checkmark_circle_fill
: Icons.check_circle)
: (cupertino ? CupertinoIcons.circle_fill : Icons.circle);
final glyph = Icon(icon, color: color, size: 32);
// The None choice has no fill to check, so its selection is a ring.
final mark = name == null && selected
? DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: color, width: 2),
),
child: Padding(padding: const EdgeInsets.all(2), child: glyph),
)
: glyph;
final button = cupertino
? CupertinoButton(
padding: const EdgeInsets.all(4),
minimumSize: const Size.square(kMinInteractiveDimensionCupertino),
onPressed: () => _pick(name),
child: mark,
)
: IconButton(
tooltip: label,
isSelected: selected,
onPressed: () => _pick(name),
icon: mark,
);
return Semantics(
key: Key('chat-color-${name ?? 'none'}'),
button: true,
selected: selected,
label: label,
excludeSemantics: true,
onTap: () => _pick(name),
child: button,
);
}
}
/// A titled "Colour" section: the heading, then the swatches.
class ChatColorSection extends StatelessWidget {
const ChatColorSection({
super.key,
required this.selected,
required this.onSelected,
this.padding = const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6),
});
final String? selected;
final ValueChanged<String?> onSelected;
final EdgeInsetsGeometry padding;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final labelStyle =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant,
);
return Padding(
key: const Key('chat-color-section'),
padding: padding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Colour', style: labelStyle),
const SizedBox(height: 4),
ChatColorSwatches(selected: selected, onSelected: onSelected),
],
),
);
}
}
/// Lets the operator pick [title]'s colour in a sheet. Each pick applies at
/// once through [onSelected]; Done closes the sheet.
Future<void> showChatColorPicker(
BuildContext context, {
required String title,
required String? selected,
required ValueChanged<String?> onSelected,
}) async {
final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
Widget content(BuildContext sheet) => Column(
key: const Key('chat-color-sheet'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AppSheetHeader(
title: 'Colour for $title',
cupertino: cupertino,
doneKey: const Key('chat-color-done'),
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(20, 4, 20, 20),
child: ChatColorSwatches(selected: selected, onSelected: onSelected),
),
],
);
if (cupertino) {
await showCupertinoModalPopup<void>(
context: context,
builder: (sheet) => Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: CupertinoPopupSurface(
child: SingleChildScrollView(child: content(sheet)),
),
),
),
);
return;
}
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
isScrollControlled: true,
useSafeArea: true,
builder: (sheet) => SingleChildScrollView(child: content(sheet)),
);
}
@@ -9,6 +9,17 @@ import 'session_row_style.dart';
typedef ChatSessionSection = ({String title, List<JsonMap> sessions}); 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 {
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);
}
/// Groups the visible sessions the way the server reports them. /// Groups the visible sessions the way the server reports them.
class ChatSessionsBody extends StatelessWidget { class ChatSessionsBody extends StatelessWidget {
const ChatSessionsBody({ const ChatSessionsBody({
@@ -22,14 +33,17 @@ class ChatSessionsBody extends StatelessWidget {
required this.onClose, required this.onClose,
required this.onReopen, required this.onReopen,
required this.onStar, required this.onStar,
this.onColor,
required this.onHide, required this.onHide,
required this.onClearSearch, required this.onClearSearch,
required this.isUnseen, required this.isUnseen,
required this.errorFor, required this.errorFor,
this.folds,
this.activeSessionId, this.activeSessionId,
this.onDismissError, this.onDismissError,
}); });
final ChatSectionFolds? folds;
final List<JsonMap> sessions; final List<JsonMap> sessions;
final String? activeSessionId; final String? activeSessionId;
final String query; final String query;
@@ -40,6 +54,7 @@ class ChatSessionsBody extends StatelessWidget {
final ValueChanged<JsonMap> onClose; final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen; final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar; final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap>? onColor;
final ValueChanged<JsonMap> onHide; final ValueChanged<JsonMap> onHide;
final VoidCallback onClearSearch; final VoidCallback onClearSearch;
final bool Function(JsonMap) isUnseen; final bool Function(JsonMap) isUnseen;
@@ -49,27 +64,7 @@ class ChatSessionsBody extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final visible = filterChatSessions(sessions, query); final visible = filterChatSessions(sessions, query);
final sections = <ChatSessionSection>[ final sections = chatSessionSections(visible);
if (visible.any((s) => s['starred'] == true && s['closed_at'] == null))
(
title: 'Starred',
sessions: visible
.where((s) => s['starred'] == true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['starred'] != true && s['closed_at'] == null))
(
title: 'Chats',
sessions: visible
.where((s) => s['starred'] != true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['closed_at'] != null))
(
title: 'Closed',
sessions: visible.where((s) => s['closed_at'] != null).toList(),
),
];
final emptyMessage = sessions.isEmpty final emptyMessage = sessions.isEmpty
? error == null ? error == null
? 'No chat sessions on this server yet.' ? 'No chat sessions on this server yet.'
@@ -82,6 +77,7 @@ class ChatSessionsBody extends StatelessWidget {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoSessionList( return CupertinoSessionList(
sections: sections, sections: sections,
folds: folds,
activeSessionId: activeSessionId, activeSessionId: activeSessionId,
emptyMessage: visible.isEmpty ? emptyMessage : null, emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles, duplicateTitles: duplicateTitles,
@@ -90,6 +86,7 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose, onClose: onClose,
onReopen: onReopen, onReopen: onReopen,
onStar: onStar, onStar: onStar,
onColor: onColor,
onHide: onHide, onHide: onHide,
onClearSearch: clearSearch, onClearSearch: clearSearch,
isUnseen: isUnseen, isUnseen: isUnseen,
@@ -99,6 +96,7 @@ class ChatSessionsBody extends StatelessWidget {
} }
return MaterialSessionList( return MaterialSessionList(
sections: sections, sections: sections,
folds: folds,
activeSessionId: activeSessionId, activeSessionId: activeSessionId,
emptyMessage: visible.isEmpty ? emptyMessage : null, emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles, duplicateTitles: duplicateTitles,
@@ -107,6 +105,7 @@ class ChatSessionsBody extends StatelessWidget {
onClose: onClose, onClose: onClose,
onReopen: onReopen, onReopen: onReopen,
onStar: onStar, onStar: onStar,
onColor: onColor,
onHide: onHide, onHide: onHide,
onClearSearch: clearSearch, onClearSearch: clearSearch,
isUnseen: isUnseen, isUnseen: isUnseen,
@@ -74,6 +74,7 @@ class ChatSessionsController extends ChangeNotifier {
} }
void _onFrame(JsonMap frame) { void _onFrame(JsonMap frame) {
if (frame['type'] == 'chat_session_changed') return _sessionChanged(frame);
final effect = chatSessionFrameEffect(frame); final effect = chatSessionFrameEffect(frame);
if (effect == null) return; if (effect == null) return;
final id = effect.sessionId; final id = effect.sessionId;
@@ -86,6 +87,38 @@ class ChatSessionsController extends ChangeNotifier {
if (effect.attention && id == activeSessionId) _scheduleActiveAck(id); if (effect.attention && id == activeSessionId) _scheduleActiveAck(id);
} }
/// Another device changed a chat's shared colour, star or title: the row
/// takes the server's values at once, with no re-list. Each field the
/// registry row omits is cleared, since omitted means unset on the wire.
void _sessionChanged(JsonMap frame) {
final changed = frame['chat_session'];
if (changed is! Map) return;
final id = '${changed['id'] ?? ''}';
if (id.isEmpty || _disposed) return;
var found = false;
_sessions = [
for (final row in _sessions)
if ('${row['id'] ?? ''}' == id)
() {
found = true;
final next = <String, dynamic>{...row};
for (final key in const ['color', 'starred', 'starred_at']) {
if (changed.containsKey(key)) {
next[key] = changed[key];
} else {
next.remove(key);
}
}
final title = '${changed['title'] ?? ''}'.trim();
if (title.isNotEmpty) next['title'] = title;
return next;
}()
else
row,
];
if (found) _notify();
}
void _bindAckSync(AttentionAckSync? sync) { void _bindAckSync(AttentionAckSync? sync) {
if (identical(sync, _ackSync)) return; if (identical(sync, _ackSync)) return;
_ackSync?.removeListener(_ackChanged); _ackSync?.removeListener(_ackChanged);
@@ -245,6 +278,13 @@ class ChatSessionsController extends ChangeNotifier {
patch: {'starred': starred}, patch: {'starred': starred},
); );
/// Sets [sessionId]'s shared colour (a palette name, null for none).
Future<void> setColor(String sessionId, String? color) => _mutate(
sessionId,
() => repository.setColor(sessionId, color),
patch: {'color': color},
);
Future<void> close(String sessionId) => _mutate( Future<void> close(String sessionId) => _mutate(
sessionId, sessionId,
() => repository.close(sessionId), () => repository.close(sessionId),
@@ -8,8 +8,12 @@ import '../../../../ui/layout/content_width.dart';
import '../../../../core/api_gateway.dart'; import '../../../../core/api_gateway.dart';
import '../../../../shell/shell_bar.dart'; import '../../../../shell/shell_bar.dart';
import '../../../../shell/shell_list_shortcuts.dart';
import '../../data/chat_repository.dart'; import '../../data/chat_repository.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart'; import 'chat_adaptive.dart';
import 'chat_color_picker.dart';
import 'chat_session_local.dart'; import 'chat_session_local.dart';
import 'chat_sessions_body.dart'; import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart'; import 'chat_sessions_controller.dart';
@@ -76,6 +80,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
..activeSessionId = widget.activeSessionId ..activeSessionId = widget.activeSessionId
..refresh(); ..refresh();
final _search = TextEditingController(); final _search = TextEditingController();
final _folds = ChatSectionFolds();
Timer? _undoTimer; Timer? _undoTimer;
String? _markedActiveSessionId; String? _markedActiveSessionId;
@@ -182,6 +187,26 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
void _star(JsonMap session) => void _star(JsonMap session) =>
_controller.star(_sessionId(session), session['starred'] != true); _controller.star(_sessionId(session), session['starred'] != true);
Future<void> _color(JsonMap session) => showChatColorPicker(
context,
title: chatSessionTitle(session),
selected: chatSessionColor(session),
onSelected: (color) => _controller.setColor(_sessionId(session), color),
);
/// 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),
isOpen: _folds.isOpen,
);
if (index < 0 || index >= rows.length) return false;
_open(rows[index]);
return true;
}
Future<void> _hide(JsonMap session) async { Future<void> _hide(JsonMap session) async {
await _controller.hide(_sessionId(session)); await _controller.hide(_sessionId(session));
_undoTimer?.cancel(); _undoTimer?.cancel();
@@ -235,7 +260,9 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
onClose: _close, onClose: _close,
onReopen: _reopen, onReopen: _reopen,
onStar: _star, onStar: _star,
onColor: _color,
onHide: _hide, onHide: _hide,
folds: _folds,
onClearSearch: () { onClearSearch: () {
_search.clear(); _search.clear();
setState(() {}); setState(() {});
@@ -278,7 +305,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
child: ShellBadge( child: ShellBadge(
kind: ShellBadgeKind.unread, kind: ShellBadgeKind.unread,
count: _controller.sessions.where(_controller.isUnseen).length, count: _controller.sessions.where(_controller.isUnseen).length,
child: body, child: ShellListShortcut(onOpenIndex: _openIndex, child: body),
), ),
); );
} }
@@ -7,7 +7,7 @@ import 'chat_adaptive.dart';
import 'session_row_style.dart'; import 'session_row_style.dart';
import '../../../../ui/layout/app_overflow_menu.dart'; import '../../../../ui/layout/app_overflow_menu.dart';
enum SessionAction { star, rename, close, reopen, hide } enum SessionAction { star, color, rename, close, reopen, hide }
/// The close confirmation's body, matching the web client's explanation. /// The close confirmation's body, matching the web client's explanation.
String closeChatConfirmation(String title) => String closeChatConfirmation(String title) =>
@@ -50,6 +50,7 @@ List<({SessionAction action, String label})> _items(JsonMap session) {
action: SessionAction.star, action: SessionAction.star,
label: session['starred'] == true ? 'Unstar' : 'Star', label: session['starred'] == true ? 'Unstar' : 'Star',
), ),
(action: SessionAction.color, label: 'Colour…'),
(action: SessionAction.rename, label: 'Rename…'), (action: SessionAction.rename, label: 'Rename…'),
isClosed isClosed
? (action: SessionAction.reopen, label: 'Reopen') ? (action: SessionAction.reopen, label: 'Reopen')
@@ -17,15 +17,18 @@ class CupertinoSessionList extends StatelessWidget {
required this.onClose, required this.onClose,
required this.onReopen, required this.onReopen,
required this.onStar, required this.onStar,
this.onColor,
required this.onHide, required this.onHide,
required this.onClearSearch, required this.onClearSearch,
required this.isUnseen, required this.isUnseen,
required this.errorFor, required this.errorFor,
this.folds,
this.activeSessionId, this.activeSessionId,
this.onDismissError, this.onDismissError,
}); });
final List<ChatSessionSection> sections; final List<ChatSessionSection> sections;
final ChatSectionFolds? folds;
final String? activeSessionId; final String? activeSessionId;
final String? emptyMessage; final String? emptyMessage;
final Set<String> duplicateTitles; final Set<String> duplicateTitles;
@@ -34,6 +37,7 @@ class CupertinoSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose; final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen; final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar; final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap>? onColor;
final ValueChanged<JsonMap> onHide; final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch; final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen; final bool Function(JsonMap) isUnseen;
@@ -71,6 +75,7 @@ class CupertinoSessionList extends StatelessWidget {
Widget _section(ChatSessionSection section) => chatSessionSection( Widget _section(ChatSessionSection section) => chatSessionSection(
section: section, section: section,
folds: folds ?? ChatSectionFolds(),
directoryHeader: _DirectoryHeader.new, directoryHeader: _DirectoryHeader.new,
row: (session, {required divider}) => chatSessionRowItem( row: (session, {required divider}) => chatSessionRowItem(
session, session,
@@ -80,6 +85,7 @@ class CupertinoSessionList extends StatelessWidget {
isUnseen: isUnseen, isUnseen: isUnseen,
onOpen: onOpen, onOpen: onOpen,
onStar: onStar, onStar: onStar,
onColor: onColor,
onRename: onRename, onRename: onRename,
onClose: onClose, onClose: onClose,
onReopen: onReopen, onReopen: onReopen,
@@ -15,13 +15,16 @@ typedef SessionListItem = ({Key key, WidgetBuilder build});
/// screen. Material and Cupertino supply their own directory header. /// screen. Material and Cupertino supply their own directory header.
Widget chatSessionSection({ Widget chatSessionSection({
required ChatSessionSection section, required ChatSessionSection section,
required ChatSectionFolds folds,
required Widget Function(String directory) directoryHeader, required Widget Function(String directory) directoryHeader,
required SessionListItem Function(JsonMap session, {required bool divider}) required SessionListItem Function(JsonMap session, {required bool divider})
row, row,
required String? Function(String sessionId) errorFor, required String? Function(String sessionId) errorFor,
required ValueChanged<String>? onDismissError, required ValueChanged<String>? onDismissError,
}) { }) {
final groups = groupChatSessions(section.sessions); final groups = chatSectionGroupsByDirectory(section.title)
? groupChatSessions(section.sessions)
: [(directory: '', sessions: section.sessions)];
final items = <SessionListItem>[ final items = <SessionListItem>[
for (final group in groups) ...[ for (final group in groups) ...[
if (groups.length > 1) if (groups.length > 1)
@@ -67,7 +70,8 @@ Widget chatSessionSection({
key: ValueKey('chat-section-${section.title}'), key: ValueKey('chat-section-${section.title}'),
title: section.title, title: section.title,
count: section.sessions.length, count: section.sessions.length,
initiallyOpen: section.title != 'Closed', initiallyOpen: folds.isOpen(section.title),
onOpenChanged: (open) => folds.set(section.title, open),
itemCount: items.length, itemCount: items.length,
itemKey: (index) => items[index].key, itemKey: (index) => items[index].key,
itemBuilder: (context, index) => items[index].build(context), itemBuilder: (context, index) => items[index].build(context),
@@ -83,6 +87,7 @@ SessionListItem chatSessionRowItem(
required bool Function(JsonMap) isUnseen, required bool Function(JsonMap) isUnseen,
required ValueChanged<JsonMap> onOpen, required ValueChanged<JsonMap> onOpen,
required ValueChanged<JsonMap> onStar, required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap>? onColor,
required ValueChanged<JsonMap> onRename, required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose, required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen, required ValueChanged<JsonMap> onReopen,
@@ -99,6 +104,7 @@ SessionListItem chatSessionRowItem(
divider: divider, divider: divider,
onOpen: onOpen, onOpen: onOpen,
onStar: onStar, onStar: onStar,
onColor: onColor,
onRename: onRename, onRename: onRename,
onClose: onClose, onClose: onClose,
onReopen: onReopen, onReopen: onReopen,
@@ -16,15 +16,18 @@ class MaterialSessionList extends StatelessWidget {
required this.onClose, required this.onClose,
required this.onReopen, required this.onReopen,
required this.onStar, required this.onStar,
this.onColor,
required this.onHide, required this.onHide,
required this.onClearSearch, required this.onClearSearch,
required this.isUnseen, required this.isUnseen,
required this.errorFor, required this.errorFor,
this.folds,
this.activeSessionId, this.activeSessionId,
this.onDismissError, this.onDismissError,
}); });
final List<ChatSessionSection> sections; final List<ChatSessionSection> sections;
final ChatSectionFolds? folds;
final String? activeSessionId; final String? activeSessionId;
final String? emptyMessage; final String? emptyMessage;
final Set<String> duplicateTitles; final Set<String> duplicateTitles;
@@ -33,6 +36,7 @@ class MaterialSessionList extends StatelessWidget {
final ValueChanged<JsonMap> onClose; final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen; final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar; final ValueChanged<JsonMap> onStar;
final ValueChanged<JsonMap>? onColor;
final ValueChanged<JsonMap> onHide; final ValueChanged<JsonMap> onHide;
final VoidCallback? onClearSearch; final VoidCallback? onClearSearch;
final bool Function(JsonMap) isUnseen; final bool Function(JsonMap) isUnseen;
@@ -80,6 +84,7 @@ class MaterialSessionList extends StatelessWidget {
final heading = SectionHeadingStyle.of(context); final heading = SectionHeadingStyle.of(context);
return chatSessionSection( return chatSessionSection(
section: section, section: section,
folds: folds ?? ChatSectionFolds(),
directoryHeader: (directory) => ListTile( directoryHeader: (directory) => ListTile(
dense: true, dense: true,
leading: const Icon(Icons.folder_outlined), leading: const Icon(Icons.folder_outlined),
@@ -96,6 +101,7 @@ class MaterialSessionList extends StatelessWidget {
isUnseen: isUnseen, isUnseen: isUnseen,
onOpen: onOpen, onOpen: onOpen,
onStar: onStar, onStar: onStar,
onColor: onColor,
onRename: onRename, onRename: onRename,
onClose: onClose, onClose: onClose,
onReopen: onReopen, onReopen: onReopen,
@@ -5,8 +5,10 @@ import '../../../../core/api_gateway.dart';
import '../../../../ui/layout/app_list_avatar.dart'; import '../../../../ui/layout/app_list_avatar.dart';
import '../../../../ui/layout/app_list_row.dart'; import '../../../../ui/layout/app_list_row.dart';
import '../../../../ui/text/relative_time_label.dart'; import '../../../../ui/text/relative_time_label.dart';
import '../../domain/chat_colors.dart';
import '../../domain/chat_sessions.dart'; import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart'; import 'chat_adaptive.dart';
import 'chat_color_palette.dart';
import 'session_actions.dart'; import 'session_actions.dart';
import 'session_harness_icon.dart'; import 'session_harness_icon.dart';
import 'session_row_style.dart'; import 'session_row_style.dart';
@@ -16,8 +18,10 @@ import 'session_row_style.dart';
/// ///
/// An unread chat is emphasised (heavier title, accent time) with an accent /// An unread chat is emphasised (heavier title, accent time) with an accent
/// dot ending its line; a starred chat shows a small star after its title; a /// dot ending its line; a starred chat shows a small star after its title; a
/// running chat carries an activity badge on its avatar. A narrow pane drops /// running chat carries an activity badge on its avatar. A chat with a colour
/// the avatar and time but keeps the menu, the list's only way to its actions. /// wears it as a bar on the row's leading edge, a faint row tint and a
/// coloured avatar. A narrow pane drops the avatar and time but keeps the
/// colour bar and the menu, the list's only way to its actions.
class ChatSessionRow extends StatelessWidget { class ChatSessionRow extends StatelessWidget {
const ChatSessionRow({ const ChatSessionRow({
super.key, super.key,
@@ -28,10 +32,12 @@ class ChatSessionRow extends StatelessWidget {
this.unseen = false, this.unseen = false,
this.divider = true, this.divider = true,
this.duplicateTitles = const {}, this.duplicateTitles = const {},
this.onLongPress,
}); });
final JsonMap session; final JsonMap session;
final ValueChanged<JsonMap> onOpen; final ValueChanged<JsonMap> onOpen;
final VoidCallback? onLongPress;
final ValueChanged<SessionAction> onAction; final ValueChanged<SessionAction> onAction;
final bool selected; final bool selected;
final bool unseen; final bool unseen;
@@ -58,6 +64,8 @@ class ChatSessionRow extends StatelessWidget {
divider: divider, divider: divider,
keepMenuWhenCompact: true, keepMenuWhenCompact: true,
onTap: () => onOpen(session), onTap: () => onOpen(session),
onLongPress: onLongPress,
accent: chatColorShade(context, chatSessionColor(session)),
leading: ChatSessionAvatar( leading: ChatSessionAvatar(
session: session, session: session,
running: session['running'] == true && !unseen, running: session['running'] == true && !unseen,
@@ -161,7 +169,15 @@ class ChatSessionAvatar extends StatelessWidget {
chatControlsStyleOf(context) == ChatControlsStyle.cupertino; chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final Color fill; final Color fill;
final Color mark; final Color mark;
if (cupertino) { final color = chatColorShade(context, chatSessionColor(session));
if (color != null) {
// The chat's colour is its identity, selected or not; the row's own
// fill marks the selection.
mark = color;
fill = color.withValues(
alpha: chatColorDarkSurface(context) ? 0.26 : 0.16,
);
} else if (cupertino) {
final primary = CupertinoTheme.of(context).primaryColor; final primary = CupertinoTheme.of(context).primaryColor;
fill = selected fill = selected
? primary.withValues(alpha: 0.2) ? primary.withValues(alpha: 0.2)
@@ -19,6 +19,7 @@ Widget memoChatSessionRow({
required bool divider, required bool divider,
required ValueChanged<JsonMap> onOpen, required ValueChanged<JsonMap> onOpen,
required ValueChanged<JsonMap> onStar, required ValueChanged<JsonMap> onStar,
required ValueChanged<JsonMap>? onColor,
required ValueChanged<JsonMap> onRename, required ValueChanged<JsonMap> onRename,
required ValueChanged<JsonMap> onClose, required ValueChanged<JsonMap> onClose,
required ValueChanged<JsonMap> onReopen, required ValueChanged<JsonMap> onReopen,
@@ -34,6 +35,7 @@ Widget memoChatSessionRow({
divider, divider,
onOpen, onOpen,
onStar, onStar,
onColor,
onRename, onRename,
onClose, onClose,
onReopen, onReopen,
@@ -46,8 +48,11 @@ Widget memoChatSessionRow({
unseen: unseen, unseen: unseen,
divider: divider, divider: divider,
onOpen: onOpen, onOpen: onOpen,
// A long-press is the touch way to the colour, the row's quick mark.
onLongPress: onColor == null ? null : () => onColor(session),
onAction: (action) => switch (action) { onAction: (action) => switch (action) {
SessionAction.star => onStar(session), SessionAction.star => onStar(session),
SessionAction.color => onColor?.call(session),
SessionAction.rename => onRename(session), SessionAction.rename => onRename(session),
SessionAction.close => onClose(session), SessionAction.close => onClose(session),
SessionAction.reopen => onReopen(session), SessionAction.reopen => onReopen(session),
@@ -3,6 +3,7 @@ import '../../../ui/layout/app_list_row.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../shell/shell_list_shortcuts.dart';
import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/status/run_status_icon.dart'; import '../../../ui/status/run_status_icon.dart';
import '../pipeline_format.dart'; import '../pipeline_format.dart';
@@ -53,7 +54,18 @@ class PipelineListPanel extends StatelessWidget {
child: PipelineProgress(label: 'Refreshing pipelines'), child: PipelineProgress(label: 'Refreshing pipelines'),
), ),
]; ];
return _content(context, header); // Ctrl+1…Ctrl+9 open the Nth pipeline shown, filtered and sorted.
return ShellListShortcut(
onOpenIndex: (index) {
if (!controller.pipelinesLoaded) return false;
final items = controller.visiblePipelines;
if (index >= items.length) return false;
final pipeline = items[index];
controller.openPipeline(pipeline.id, version: pipeline.version);
return true;
},
child: _content(context, header),
);
} }
/// A state without rows: the controls stay at the top, below the bar. /// A state without rows: the controls stay at the top, below the bar.
+18 -2
View File
@@ -12,6 +12,7 @@ import '../../attention/runtime/attention_store.dart';
import '../../attention/ui/needs_you_runs_heading.dart'; import '../../attention/ui/needs_you_runs_heading.dart';
import '../domain/run_models.dart'; import '../domain/run_models.dart';
import '../../../shell/shell_bar.dart'; import '../../../shell/shell_bar.dart';
import '../../../shell/shell_list_shortcuts.dart';
import 'run_list_row.dart'; import 'run_list_row.dart';
import 'runs_controller.dart'; import 'runs_controller.dart';
import 'runs_filter_options.dart'; import 'runs_filter_options.dart';
@@ -79,7 +80,7 @@ class RunsList extends StatelessWidget {
title: bar.title, title: bar.title,
subtitle: bar.subtitle, subtitle: bar.subtitle,
actions: bar.actions, actions: bar.actions,
child: _list(context), child: _shortcutList(context),
); );
} }
final actions = [ final actions = [
@@ -110,11 +111,26 @@ class RunsList extends StatelessWidget {
child: ShellBadge( child: ShellBadge(
kind: ShellBadgeKind.running, kind: ShellBadgeKind.running,
count: controller.runs.where((run) => run['executing'] == true).length, count: controller.runs.where((run) => run['executing'] == true).length,
child: _list(context), child: _shortcutList(context),
), ),
); );
} }
/// The list under the shell's Ctrl+1…Ctrl+9, which open the Nth run shown
/// (filtered and sorted as on screen). Select mode keeps keys for itself.
Widget _shortcutList(BuildContext context) => ShellListShortcut(
onOpenIndex: (index) {
if (controller.selection.active) return false;
final runs = controller.visibleRuns;
if (index >= runs.length) return false;
final id = runs[index]['id'];
if (id is! num) return false;
onSelected(id);
return true;
},
child: _list(context),
);
Widget _ownBar(BuildContext context, List<Widget> bar) => Column( Widget _ownBar(BuildContext context, List<Widget> bar) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
+9
View File
@@ -10,6 +10,7 @@ import 'attention_badge.dart';
import 'destination.dart'; import 'destination.dart';
import 'list_detail.dart'; import 'list_detail.dart';
import 'shell_bar.dart'; import 'shell_bar.dart';
import 'shell_list_shortcuts.dart';
class AdaptiveShell extends StatefulWidget { class AdaptiveShell extends StatefulWidget {
const AdaptiveShell({ const AdaptiveShell({
@@ -222,7 +223,15 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
/// Handles this before focused text controls can insert or traverse on /// Handles this before focused text controls can insert or traverse on
/// Ctrl+Tab. The handler is scoped to the shell's lifetime, not onboarding. /// Ctrl+Tab. The handler is scoped to the shell's lifetime, not onboarding.
///
/// Ctrl+1…Ctrl+9 open the Nth item of the open tab's list the same way, in
/// the list's on-screen order; a page (Settings) has no list.
bool _handleDestinationKeyEvent(KeyEvent event) { bool _handleDestinationKeyEvent(KeyEvent event) {
final listIndex = shellListShortcutIndex(event, HardwareKeyboard.instance);
if (listIndex != null) {
if (!shellTabDestinations.contains(_selected)) return false;
return _bar.lists.open(_selected, listIndex);
}
if (event is! KeyDownEvent || if (event is! KeyDownEvent ||
event.logicalKey != LogicalKeyboardKey.tab || event.logicalKey != LogicalKeyboardKey.tab ||
!HardwareKeyboard.instance.isControlPressed) { !HardwareKeyboard.instance.isControlPressed) {
+4
View File
@@ -1,6 +1,7 @@
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
import 'destination.dart'; import 'destination.dart';
import 'shell_list_shortcuts.dart';
/// What the open screen of a tab puts in the app bar: its title, a Back /// What the open screen of a tab puts in the app bar: its title, a Back
/// control and its actions. Absent, the bar shows the tab's own name. /// control and its actions. Absent, the bar shows the tab's own name.
@@ -65,6 +66,9 @@ class ShellBarRegistry extends ChangeNotifier {
final _Notifier _bar = _Notifier(); final _Notifier _bar = _Notifier();
final _Notifier _badgeNotifier = _Notifier(); final _Notifier _badgeNotifier = _Notifier();
/// How each tab's list opens its Nth item (Ctrl+1…Ctrl+9).
final ShellListShortcuts lists = ShellListShortcuts();
/// The destination whose bar is on screen; null treats every destination /// The destination whose bar is on screen; null treats every destination
/// as shown. Bar changes of other destinations are kept without notifying: /// as shown. Bar changes of other destinations are kept without notifying:
/// the host rebuilds when it changes the focus. /// the host rebuilds when it changes the focus.
+98
View File
@@ -0,0 +1,98 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'destination.dart';
import 'shell_bar.dart';
/// Opens the Nth item of a tab's list: what each tab's list screen published
/// for Ctrl+1…Ctrl+9. One opener per tab; the latest mounted list wins.
class ShellListShortcuts {
final Map<AppDestination, (Object, bool Function(int index))> _openers = {};
/// Opens the item at [index] (0-based, on-screen order) of [destination]'s
/// list; false when the tab publishes no list or has no such item.
bool open(AppDestination destination, int index) =>
_openers[destination]?.$2(index) ?? false;
void _set(
AppDestination destination,
Object owner,
bool Function(int) open,
) => _openers[destination] = (owner, open);
void _clear(AppDestination destination, Object owner) {
if (_openers[destination]?.$1 == owner) _openers.remove(destination);
}
}
/// The 0-based list index a Ctrl+1…Ctrl+9 key event names, or null for any
/// other event. Shift, Alt and Meta must be up, so system and browser chords
/// built on the digits are left alone.
int? shellListShortcutIndex(KeyEvent event, HardwareKeyboard keyboard) {
if (event is! KeyDownEvent ||
!keyboard.isControlPressed ||
keyboard.isShiftPressed ||
keyboard.isAltPressed ||
keyboard.isMetaPressed) {
return null;
}
final index = _digits.indexOf(event.logicalKey);
return index < 0 ? null : index;
}
const _digits = [
LogicalKeyboardKey.digit1,
LogicalKeyboardKey.digit2,
LogicalKeyboardKey.digit3,
LogicalKeyboardKey.digit4,
LogicalKeyboardKey.digit5,
LogicalKeyboardKey.digit6,
LogicalKeyboardKey.digit7,
LogicalKeyboardKey.digit8,
LogicalKeyboardKey.digit9,
];
/// Publishes, while mounted, how its tab's list opens its Nth item, so the
/// shell's Ctrl+1…Ctrl+9 open it from anywhere in the tab (also while a text
/// field has focus). [onOpenIndex] reads the list at key time, in on-screen
/// order, and reports whether an item was opened. Outside a shell it does
/// nothing.
class ShellListShortcut extends StatefulWidget {
const ShellListShortcut({
super.key,
required this.onOpenIndex,
required this.child,
});
final bool Function(int index) onOpenIndex;
final Widget child;
@override
State<ShellListShortcut> createState() => _ShellListShortcutState();
}
class _ShellListShortcutState extends State<ShellListShortcut> {
final Object _owner = Object();
ShellBarScope? _scope;
bool _open(int index) => mounted && widget.onOpenIndex(index);
@override
void didChangeDependencies() {
super.didChangeDependencies();
final scope = ShellBarScope.maybeOf(context);
if (scope == _scope) return;
_scope?.registry.lists._clear(_scope!.destination, _owner);
_scope = scope;
scope?.registry.lists._set(scope.destination, _owner, _open);
}
@override
void dispose() {
_scope?.registry.lists._clear(_scope!.destination, _owner);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
+34 -3
View File
@@ -16,6 +16,11 @@ const double _avatarGap = 12;
/// Keys on a row's highlight surface and inset divider, for tests. /// Keys on a row's highlight surface and inset divider, for tests.
const appListRowSurfaceKey = ValueKey<String>('app-list-row-surface'); const appListRowSurfaceKey = ValueKey<String>('app-list-row-surface');
const appListRowDividerKey = ValueKey<String>('app-list-row-divider'); const appListRowDividerKey = ValueKey<String>('app-list-row-divider');
const appListRowAccentKey = ValueKey<String>('app-list-row-accent');
bool _darkSurface(BuildContext context, bool cupertino) => cupertino
? CupertinoTheme.brightnessOf(context) == Brightness.dark
: Theme.of(context).brightness == Brightness.dark;
/// The app's one list row (runs, pipelines, chats, search results, /// The app's one list row (runs, pipelines, chats, search results,
/// schedules), on both hosts. /// schedules), on both hosts.
@@ -55,8 +60,14 @@ class AppListRow extends StatelessWidget {
this.keepMenuWhenCompact = false, this.keepMenuWhenCompact = false,
this.compactWidth = kAppListRowCompactWidth, this.compactWidth = kAppListRowCompactWidth,
this.cupertino, this.cupertino,
this.accent,
}); });
/// The item's own colour (a chat's highlight): a bar on the row's leading
/// edge and a faint tint under an unselected row. The selected fill still
/// marks the open row, so the two never read as one another.
final Color? accent;
final Widget title; final Widget title;
final Widget? leading; final Widget? leading;
final String? time; final String? time;
@@ -143,19 +154,23 @@ class AppListRow extends StatelessWidget {
], ],
), ),
); );
final surface = cupertino final tint = accent?.withValues(
alpha: _darkSurface(context, cupertino) ? 0.12 : 0.07,
);
Widget surface = cupertino
? _CupertinoRowSurface( ? _CupertinoRowSurface(
tapKey: tapKey, tapKey: tapKey,
onTap: onTap, onTap: onTap,
onLongPress: onLongPress, onLongPress: onLongPress,
selected: selected, selected: selected,
tint: tint,
child: content, child: content,
) )
: Material( : Material(
key: appListRowSurfaceKey, key: appListRowSurfaceKey,
color: selected color: selected
? selectedColor(context, cupertino: false) ? selectedColor(context, cupertino: false)
: Colors.transparent, : tint ?? Colors.transparent,
child: InkWell( child: InkWell(
key: tapKey, key: tapKey,
onTap: onTap, onTap: onTap,
@@ -163,6 +178,18 @@ class AppListRow extends StatelessWidget {
child: content, child: content,
), ),
); );
if (accent case final accent?) {
surface = DecoratedBox(
key: appListRowAccentKey,
position: DecorationPosition.foreground,
decoration: BoxDecoration(
border: BorderDirectional(
start: BorderSide(color: accent, width: 4),
),
),
child: surface,
);
}
if (!divider) return surface; if (!divider) return surface;
// The divider stays under the text column; a checkbox's width is // The divider stays under the text column; a checkbox's width is
// not known here, so a selectable row's divider starts at the inset. // not known here, so a selectable row's divider starts at the inset.
@@ -324,9 +351,13 @@ class _CupertinoRowSurface extends StatefulWidget {
required this.onTap, required this.onTap,
required this.selected, required this.selected,
this.onLongPress, this.onLongPress,
this.tint,
required this.child, required this.child,
}); });
/// The unselected row's tint, transparent when null.
final Color? tint;
final Key? tapKey; final Key? tapKey;
final VoidCallback? onTap; final VoidCallback? onTap;
final VoidCallback? onLongPress; final VoidCallback? onLongPress;
@@ -350,7 +381,7 @@ class _CupertinoRowSurfaceState extends State<_CupertinoRowSurface> {
? CupertinoColors.systemGrey4.resolveFrom(context) ? CupertinoColors.systemGrey4.resolveFrom(context)
: widget.selected : widget.selected
? AppListRow.selectedColor(context, cupertino: true) ? AppListRow.selectedColor(context, cupertino: true)
: const Color(0x00000000); : widget.tint ?? const Color(0x00000000);
final enabled = widget.onTap != null; final enabled = widget.onTap != null;
return GestureDetector( return GestureDetector(
key: widget.tapKey, key: widget.tapKey,
@@ -22,11 +22,15 @@ class SliverCollapsibleListSection extends StatefulWidget {
this.itemKey, this.itemKey,
this.count, this.count,
this.initiallyOpen = true, this.initiallyOpen = true,
this.onOpenChanged,
}); });
final String title; final String title;
final int? count; final int? count;
final bool initiallyOpen; final bool initiallyOpen;
/// Reports the operator opening or folding the section.
final ValueChanged<bool>? onOpenChanged;
final int itemCount; final int itemCount;
final IndexedWidgetBuilder itemBuilder; final IndexedWidgetBuilder itemBuilder;
@@ -131,5 +135,8 @@ class _SliverCollapsibleListSectionState
); );
} }
void _toggle() => setState(() => _open = !_open); void _toggle() {
setState(() => _open = !_open);
widget.onOpenChanged?.call(_open);
}
} }
@@ -0,0 +1,189 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'conversation/chat_thread_fixtures.dart';
/// Recency order puts the plain chat first; the starred ones lead the list
/// alphabetically all the same.
class _Gateway extends FakeChatGateway {
final rows = <JsonMap>[
{'id': 'r', 'title': 'Recent', 'directory': '/w'},
{'id': 'z', 'title': 'Zed', 'directory': '/w', 'starred': true},
{
'id': 'a',
'title': 'apple',
'directory': '/w',
'starred': true,
'color': 'green',
},
];
@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_color') {
final query = fields['chat_query'] as JsonMap;
final row = rows.firstWhere((r) => r['id'] == query['session_id']);
row['color'] = query['color'];
calls.add((type: type, fields: fields));
return Future.value({'chat_session': row});
}
if (type == 'chat_shells') return Future.value({'chat_shells': []});
return super.call(type, fields);
}
}
Future<_Gateway> _pumpShell(
WidgetTester tester,
Size size, {
TargetPlatform platform = TargetPlatform.android,
Brightness brightness = Brightness.light,
}) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final gateway = _Gateway()..history = (_) async => chatPage(const []);
addTearDown(gateway.close);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: platform, brightness: brightness),
home: AdaptiveShell(
cupertino: platform == TargetPlatform.iOS,
destination: AppDestination.chat,
destinationBodies: {
AppDestination.chat: (_) => ChatScreen(gateway: gateway),
},
),
),
);
await tester.pumpAndSettle();
return gateway;
}
Future<void> _ctrl(WidgetTester tester, LogicalKeyboardKey digit) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(digit);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
}
Finder _thread(String id) => find.byKey(ValueKey('chat-thread-$id'));
void main() {
testWidgets('starred chats lead the list alphabetically', (tester) async {
await _pumpShell(tester, const Size(1280, 800));
final apple = tester.getTopLeft(find.byKey(const Key('chat-row-a'))).dy;
final zed = tester.getTopLeft(find.byKey(const Key('chat-row-z'))).dy;
final recent = tester.getTopLeft(find.byKey(const Key('chat-row-r'))).dy;
expect(apple, lessThan(zed));
expect(zed, lessThan(recent));
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Ctrl+N opens the Nth chat shown, also from the composer', (
tester,
) async {
await _pumpShell(tester, const Size(1280, 800));
await _ctrl(tester, LogicalKeyboardKey.digit1);
expect(_thread('a'), findsOneWidget, reason: 'Starred apple is first');
await _ctrl(tester, LogicalKeyboardKey.digit3);
expect(_thread('r'), findsOneWidget);
// Typing in the composer: the chord still switches chats and types
// nothing.
final field = find.descendant(
of: find.byKey(const ValueKey('chat-composer-r')),
matching: find.byType(EditableText),
);
await tester.tap(field);
await tester.enterText(field, 'draft');
await tester.pump();
expect(tester.widget<EditableText>(field).focusNode.hasFocus, isTrue);
await _ctrl(tester, LogicalKeyboardKey.digit2);
expect(_thread('z'), findsOneWidget);
expect(_thread('r'), findsNothing);
// Past the end nothing changes.
await _ctrl(tester, LogicalKeyboardKey.digit9);
expect(_thread('z'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
testWidgets('Ctrl+N opens the chat as its own page on a phone', (
tester,
) async {
await _pumpShell(tester, const Size(390, 844));
await _ctrl(tester, LogicalKeyboardKey.digit2);
expect(_thread('z'), findsOneWidget);
final navigator = tester.state<NavigatorState>(
find.byType(Navigator).first,
);
expect(navigator.canPop(), isTrue);
await tester.pumpWidget(const SizedBox.shrink());
});
for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) {
for (final brightness in Brightness.values) {
final host =
'${platform == TargetPlatform.iOS ? 'Cupertino' : 'Material'} '
'${brightness.name}';
testWidgets('$host: a coloured chat washes its top; the info sheet '
'changes the colour', (tester) async {
final gateway = await _pumpShell(
tester,
const Size(1280, 800),
platform: platform,
brightness: brightness,
);
await _ctrl(tester, LogicalKeyboardKey.digit1);
expect(_thread('a'), findsOneWidget);
expect(find.byKey(const Key('chat-color-wash')), findsOneWidget);
final washRect = tester.getRect(
find.byKey(const Key('chat-color-wash')),
);
final pane = tester.getRect(
find.byKey(const ValueKey('chat-detail-pane')),
);
expect(washRect.top, pane.top);
expect(washRect.height, lessThan(pane.height / 4));
final box = tester.widget<DecoratedBox>(
find.byKey(const Key('chat-color-wash')),
);
final gradient =
(box.decoration as BoxDecoration).gradient! as LinearGradient;
expect(gradient.colors.first.a, lessThanOrEqualTo(0.2));
expect(gradient.colors.last.a, 0);
// A plain chat has none.
await _ctrl(tester, LogicalKeyboardKey.digit3);
expect(find.byKey(const Key('chat-color-wash')), findsNothing);
await tester.tap(find.byKey(const Key('chat-info')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-section')), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-color-blue')));
await tester.pumpAndSettle();
expect(gateway.calls.last.fields, {
'chat_query': {'session_id': 'r', 'color': 'blue'},
});
await tester.tap(find.byKey(const Key('chat-info-close')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-wash')), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
}
}
}
@@ -0,0 +1,72 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/domain/chat_colors.dart';
import 'package:pipelines_app/features/chat/domain/chat_sessions.dart';
List<String> _ids(Iterable<JsonMap> rows) => [
for (final row in rows) '${row['id']}',
];
void main() {
// Server recency order: the newest first.
final rows = <JsonMap>[
{'id': 'c1', 'title': 'zeta', 'directory': '/b', 'starred': true},
{'id': 'c2', 'title': 'Recent', 'directory': '/a'},
{'id': 'c3', 'title': 'Alpha', 'directory': '/b', 'starred': true},
{'id': 'c4', 'title': 'Older', 'directory': '/b'},
{'id': 'c6', 'title': 'beta', 'directory': '/a', 'starred': true},
{'id': 'c5', 'title': 'Beta', 'directory': '/c', 'starred': true},
{'id': 'c7', 'title': 'Oldest', 'directory': '/a'},
{'id': 'c8', 'title': 'Done', 'closed_at': 1, 'starred': true},
];
test('starred chats are alphabetical, ignoring case, ties by id', () {
final sections = chatSessionSections(rows);
expect(sections.map((s) => s.title), ['Starred', 'Chats', 'Closed']);
expect(_ids(sections[0].sessions), ['c3', 'c5', 'c6', 'c1']);
// The other sections keep the server's recency order.
expect(_ids(sections[1].sessions), ['c2', 'c4', 'c7']);
expect(_ids(sections[2].sessions), ['c8']);
});
test('a starred chat keeps its place when another is used', () {
final used = [rows[2], ...rows.where((r) => r['id'] != 'c3')];
expect(
_ids(chatSessionSections(used).first.sessions),
_ids(chatSessionSections(rows).first.sessions),
);
});
test(
'list order: starred whole, then chats by directory, folded skipped',
() {
final sections = chatSessionSections(rows);
expect(
_ids(chatSessionsInListOrder(sections, isOpen: (t) => t != 'Closed')),
['c3', 'c5', 'c6', 'c1', 'c2', 'c7', 'c4'],
);
expect(_ids(chatSessionsInListOrder(sections, isOpen: (_) => true)), [
'c3',
'c5',
'c6',
'c1',
'c2',
'c7',
'c4',
'c8',
]);
expect(
_ids(chatSessionsInListOrder(sections, isOpen: (t) => t == 'Chats')),
['c2', 'c7', 'c4'],
);
},
);
test('only palette names are colours', () {
expect(chatSessionColor({'color': 'teal'}), 'teal');
expect(chatSessionColor({'color': '#ff0000'}), isNull);
expect(chatSessionColor({}), isNull);
expect(chatSessionColor(null), isNull);
expect(chatColorNames, hasLength(8));
});
}
@@ -0,0 +1,269 @@
import 'package:flutter/cupertino.dart';
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/data/chat_repository.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_controller.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import 'package:pipelines_app/features/chat/ui/sessions/session_row_content.dart';
import 'package:pipelines_app/ui/layout/app_list_avatar.dart';
import 'package:pipelines_app/ui/layout/app_list_row.dart';
import 'chat_test_harness.dart';
import 'fake_chat_gateway.dart';
/// A server whose list keeps each accepted colour, as the registry does.
FakeChatGateway _gateway() {
final rows = <JsonMap>[
{'id': 's1', 'title': 'Teal chat', 'directory': '/w', 'color': 'teal'},
{'id': 's2', 'title': 'Plain chat', 'directory': '/w'},
];
final gateway = FakeChatGateway();
gateway.sessionsHandler = () async => {
'chat_sessions': [
for (final row in rows) {...row},
],
};
gateway.actionHandler = (type, fields) async {
if (type != 'chat_color') return const {};
final query = fields['chat_query'] as JsonMap;
final row = rows.firstWhere((r) => r['id'] == query['session_id']);
final color = query['color'];
color == null ? row.remove('color') : row['color'] = color;
return {'chat_session': row};
};
return gateway;
}
Future<void> _pump(
WidgetTester tester,
FakeChatGateway gateway, {
required bool cupertino,
required Brightness brightness,
}) async {
final screen = ChatSessionsScreen(
gateway: gateway,
onOpen: (_) {},
localStore: MemoryChatSessionLocalStore(),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
theme: CupertinoThemeData(brightness: brightness),
home: MediaQuery(
data: MediaQueryData(platformBrightness: brightness),
child: screen,
),
)
: MaterialApp(
theme: ThemeData(
platform: TargetPlatform.android,
brightness: brightness,
),
home: screen,
),
);
await tester.pumpAndSettle();
}
Finder _accent(String id) => find.descendant(
of: find.byKey(Key('chat-row-$id')),
matching: find.byKey(appListRowAccentKey),
);
Color _accentColor(WidgetTester tester, String id) {
final box = tester.widget<DecoratedBox>(_accent(id));
final border = (box.decoration as BoxDecoration).border as BorderDirectional;
return border.start.color;
}
void main() {
for (final cupertino in [false, true]) {
for (final brightness in Brightness.values) {
final host = '${cupertino ? 'Cupertino' : 'Material'} ${brightness.name}';
testWidgets('$host: a coloured chat wears its colour, a plain one none', (
tester,
) async {
await _pump(
tester,
_gateway(),
cupertino: cupertino,
brightness: brightness,
);
expect(_accent('s1'), findsOneWidget);
expect(_accent('s2'), findsNothing);
final accent = _accentColor(tester, 's1');
// The avatar takes the same colour as the bar.
final avatar = tester.widget<AppListAvatar>(
find.descendant(
of: find.byKey(const Key('chat-row-s1')),
matching: find.byType(AppListAvatar),
),
);
expect(avatar.foreground, accent);
// A teal shade, not the host's accent or a grey.
expect(accent.g, greaterThan(accent.r));
expect(accent.b, greaterThan(accent.r));
// The row tint is faint: the selected fill stays the stronger mark.
final tint = cupertino
? tester
.widget<ColoredBox>(
find.descendant(
of: find.byKey(const Key('chat-row-s1')),
matching: find.byKey(appListRowSurfaceKey),
),
)
.color
: tester
.widget<Material>(
find.descendant(
of: find.byKey(const Key('chat-row-s1')),
matching: find.byKey(appListRowSurfaceKey),
),
)
.color!;
expect(tint.a, inInclusiveRange(0.05, 0.13));
// Shades are tuned per brightness.
final shade = accent.computeLuminance();
if (brightness == Brightness.dark) {
expect(shade, greaterThan(0.2));
} else {
expect(shade, lessThan(0.55));
}
});
testWidgets('$host: the row menu sets and clears the colour', (
tester,
) async {
final gateway = _gateway();
await _pump(
tester,
gateway,
cupertino: cupertino,
brightness: brightness,
);
await tester.tap(
find.descendant(
of: find.byKey(const Key('chat-actions-s2')),
matching: find.byType(cupertino ? CupertinoButton : IconButton),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Colour…'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-sheet')), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-color-purple')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_color'), {
'chat_query': {'session_id': 's2', 'color': 'purple'},
});
// The row shows it at once, before the list re-reads.
expect(_accent('s2'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-color-none')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_color'), {
'chat_query': {'session_id': 's2', 'color': null},
});
await tester.tap(find.byKey(const Key('chat-color-done')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-sheet')), findsNothing);
});
}
}
testWidgets('a long-press on a row opens the colour choice', (tester) async {
final gateway = _gateway();
await _pump(
tester,
gateway,
cupertino: false,
brightness: Brightness.light,
);
await tester.longPress(find.text('Plain chat'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-sheet')), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-color-red')));
await tester.pumpAndSettle();
expect(gateway.lastFields('chat_color'), {
'chat_query': {'session_id': 's2', 'color': 'red'},
});
});
testWidgets('the selected coloured row keeps its colour and selection', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(
body: ChatSessionRow(
session: const {'id': 's1', 'title': 'T', 'color': 'amber'},
selected: true,
onOpen: (_) {},
onAction: (_) {},
),
),
),
);
final surface = tester.widget<Material>(find.byKey(appListRowSurfaceKey));
final context = tester.element(find.byType(ChatSessionRow));
expect(
surface.color,
AppListRow.selectedColor(context, cupertino: false),
reason: 'The selected fill, not the tint, marks the open row',
);
expect(find.byKey(appListRowAccentKey), findsOneWidget);
});
group('controller', () {
late FakeChatGateway gateway;
late ChatSessionsController controller;
setUp(() async {
gateway = _gateway();
controller = ChatSessionsController(
ChatRepository(gateway),
localStore: MemoryChatSessionLocalStore(),
);
await controller.refresh();
});
tearDown(() => controller.dispose());
JsonMap row(String id) =>
controller.sessions.firstWhere((s) => s['id'] == id);
test('another device\'s change arrives live without a re-list', () async {
final lists = gateway.count('chat_sessions');
gateway.pushed.add({
'type': 'chat_session_changed',
'chat_session': {
'id': 's2',
'title': 'Plain chat',
'color': 'pink',
'starred': true,
'starred_at': 5,
},
});
await pumpEventQueue();
expect(row('s2')['color'], 'pink');
expect(row('s2')['starred'], isTrue);
// An omitted colour is a cleared one.
gateway.pushed.add({
'type': 'chat_session_changed',
'chat_session': {'id': 's1', 'title': 'Teal chat'},
});
await pumpEventQueue();
expect(row('s1').containsKey('color'), isFalse);
expect(gateway.count('chat_sessions'), lists);
});
test('a refused colour is undone and the reason shown', () async {
gateway.failures['chat_color'] = 'unknown chat colour';
await controller.setColor('s2', 'blue');
expect(row('s2')['color'], isNull);
expect(controller.errorFor('s2'), contains('unknown chat colour'));
});
});
}
+70
View File
@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/shell/adaptive_shell.dart';
import 'package:pipelines_app/shell/destination.dart';
import 'package:pipelines_app/shell/shell_list_shortcuts.dart';
void main() {
testWidgets('Ctrl+1…9 reach only the open tab\'s list; other chords pass', (
tester,
) async {
final opened = <(AppDestination, int)>[];
final field = FocusNode();
addTearDown(field.dispose);
Widget list(AppDestination destination) => ShellListShortcut(
onOpenIndex: (index) {
if (index > 4) return false;
opened.add((destination, index));
return true;
},
child: TextField(focusNode: field),
);
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destination: AppDestination.runs,
destinationBodies: {
AppDestination.runs: (_) => list(AppDestination.runs),
AppDestination.pipelines: (_) => list(AppDestination.pipelines),
},
),
),
);
await tester.pumpAndSettle();
field.requestFocus();
await tester.pump();
Future<void> press(
LogicalKeyboardKey key, {
List<LogicalKeyboardKey> held = const [LogicalKeyboardKey.controlLeft],
}) async {
for (final modifier in held) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyEvent(key);
for (final modifier in held.reversed) {
await tester.sendKeyUpEvent(modifier);
}
await tester.pump();
}
await press(LogicalKeyboardKey.digit1);
await press(LogicalKeyboardKey.digit5);
expect(opened, [(AppDestination.runs, 0), (AppDestination.runs, 4)]);
opened.clear();
await press(
LogicalKeyboardKey.digit2,
held: [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.shiftLeft],
);
await press(
LogicalKeyboardKey.digit2,
held: [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.metaLeft],
);
await press(LogicalKeyboardKey.digit2, held: const []);
await press(LogicalKeyboardKey.digit0);
expect(opened, isEmpty);
expect(field.hasFocus, isTrue);
});
}