diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index b8b00508..07980476 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -25,6 +25,7 @@ import '../ui/sessions/chat_color_picker.dart'; import '../ui/sessions/session_actions.dart'; import '../ui/sessions/session_row_content.dart'; import '../ui/transcript/chat_markdown_view.dart'; +import '../ui/transcript/chat_message_bubble.dart'; import '../ui/transcript/chat_message_view.dart'; import '../ui/transcript/chat_transcript_selection.dart'; import '../ui/transcript/chat_injected_rows.dart'; @@ -989,360 +990,366 @@ class _ChatThreadViewState extends State { } @override - Widget build(BuildContext context) => AnimatedBuilder( - animation: Listenable.merge([ - _controller.transcriptChanges, - _composer.deliveries, - _shellRuns.membership, - ]), - builder: (context, _) { - final cupertino = - chatControlsStyleOf(context) == ChatControlsStyle.cupertino; - final messages = _visibleMessages(); - final cards = chatCardRows( - permissions: _controller.permissionFrames, - forms: _controller.questionForms, - answerFor: _controller.permissionAnswerFor, - permissionErrorFor: _controller.permissionErrorFor, - formErrorFor: _controller.questionErrorFor, - ); - // Answered approvals and questions fold into their turn's chips, like - // tool calls; only cards still waiting on the operator stay full cards. - // A turn that changed files carries its summary for the change chip. - final allRows = attachChatTurnDiffs( - groupSettledQuestions( - groupSettledPermissions( - withChatShownItems( - transcriptRows( - messages, - trailing: cards, - running: - _controller.running && - !_reconnecting && - !_staleTranscript && - !cards.any(chatCardAwaitingOperator), - awaitingResponse: - _controller.awaitingResponse && - !_reconnecting && - !_staleTranscript && - !cards.any(chatCardAwaitingOperator), - liveMessageId: _controller.liveAssistantMessageId, + Widget build(BuildContext context) => ChatBubbleColor( + // The operator's own bubbles take a soft wash of the chat's colour. + name: chatSessionColor(widget.session), + child: AnimatedBuilder( + animation: Listenable.merge([ + _controller.transcriptChanges, + _composer.deliveries, + _shellRuns.membership, + ]), + builder: (context, _) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final messages = _visibleMessages(); + final cards = chatCardRows( + permissions: _controller.permissionFrames, + forms: _controller.questionForms, + answerFor: _controller.permissionAnswerFor, + permissionErrorFor: _controller.permissionErrorFor, + formErrorFor: _controller.questionErrorFor, + ); + // Answered approvals and questions fold into their turn's chips, like + // tool calls; only cards still waiting on the operator stay full cards. + // A turn that changed files carries its summary for the change chip. + final allRows = attachChatTurnDiffs( + groupSettledQuestions( + groupSettledPermissions( + withChatShownItems( + transcriptRows( + messages, + trailing: cards, + running: + _controller.running && + !_reconnecting && + !_staleTranscript && + !cards.any(chatCardAwaitingOperator), + awaitingResponse: + _controller.awaitingResponse && + !_reconnecting && + !_staleTranscript && + !cards.any(chatCardAwaitingOperator), + liveMessageId: _controller.liveAssistantMessageId, + ), + // Placed only against a loaded transcript, so an entry never + // leads an empty one and then jumps down when history arrives. + _controller.loaded ? _controller.shown : const [], + hasMore: _controller.hasMore, ), - // Placed only against a loaded transcript, so an entry never - // leads an empty one and then jumps down when history arrives. - _controller.loaded ? _controller.shown : const [], - hasMore: _controller.hasMore, ), ), - ), - _controller.turnDiffs, - ); - // A transcript held from before a socket gap may still say a compaction is - // running even when the repair's read is refused. That running state is - // stale, so no compaction notice is derived from it until a fresh read or - // frame replaces the transcript. Fresh failure notices still report. - // - // Notices report recorded conditions only: a refused read/watch and a - // running compaction. A dismissal keeps one hidden until its condition - // changes. A running compaction's own activity line is that notice, so it - // is not drawn twice; hiding it when dismissed is the whole dismissal. - final allNotices = _reconnecting - ? const [] - : chatNotices( - historyError: _controller.error, - liveError: _controller.subscriptionError, - messages: _staleTranscript ? const [] : _controller.messages, - ); - final notices = _dismissals.visible(allNotices); - final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction); - // The operator's own shell commands sit among the turns by start time; - // dismissed ones fold into a chip under the answer that followed them. - final rows = attachChatShellHistory( - withChatShellRunRows([ - for (final row in allRows) - if (!_hiddenRunningCompaction(row)) row, - ], _shellRuns.runs), - _shellRuns.dismissedRuns, - ); - // Older pages prepend messages and a live frame can append one, so a - // folded assistant turn's first message id is not a stable identity. - // ChatRowKeys carries a turn's key forward while it still holds any of - // its previous messages, keeping the element (and its open disclosures) - // across paging and streaming. - final keys = _rowKeys.forRows(rows); - final split = _splitFor(rows); - final initialLoad = !_controller.loaded && _controller.loading; - final historyNotice = _noticeOf( - notices, - ChatNoticeKind.connectionRefused, - ); - final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure); - final messageIds = _messageIds(); - final newMessages = chatNewMessageCount(messageIds, _newestAtRelease); - final showJump = chatShowsJumpToLatest( - following: _following, - distanceFromBottom: _distanceFromBottom, - itemCount: messageIds.length, - ); - // Place the first loaded transcript and keep a following view at the end. - // Scheduling after the build means the new extent is already laid out. - _scheduleFollow(); - // Under the app shell the conversation takes over the app's bar (title, - // Back, model, information) instead of drawing a second bar below it. - final inShellBar = ShellBar.available(context); - // The measured header owns its space so scrolled text never falls - // behind the controls; the transcript ends at the composer's top edge, so - // nothing renders behind the composer and the viewport shrinks as the - // composer grows. - // Every input of the composer comes from this widget's configuration, - // the composer, the images and the running state. - final composerBar = _chrome.widgetFor( - 'composer', - _controller.running, - [widget, _composer, _images], - () => ChatComposerBar( - key: ValueKey('chat-composer-${widget.sessionId}'), - composer: _composer, - running: _controller.running, - commands: _commandActions(), - picker: widget.attachmentPicker, - images: _images, - placeholder: chatComposerPlaceholderFor( - '${widget.session?['directory'] ?? ''}', + _controller.turnDiffs, + ); + // A transcript held from before a socket gap may still say a compaction is + // running even when the repair's read is refused. That running state is + // stale, so no compaction notice is derived from it until a fresh read or + // frame replaces the transcript. Fresh failure notices still report. + // + // Notices report recorded conditions only: a refused read/watch and a + // running compaction. A dismissal keeps one hidden until its condition + // changes. A running compaction's own activity line is that notice, so it + // is not drawn twice; hiding it when dismissed is the whole dismissal. + final allNotices = _reconnecting + ? const [] + : chatNotices( + historyError: _controller.error, + liveError: _controller.subscriptionError, + messages: _staleTranscript ? const [] : _controller.messages, + ); + final notices = _dismissals.visible(allNotices); + final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction); + // The operator's own shell commands sit among the turns by start time; + // dismissed ones fold into a chip under the answer that followed them. + final rows = attachChatShellHistory( + withChatShellRunRows([ + for (final row in allRows) + if (!_hiddenRunningCompaction(row)) row, + ], _shellRuns.runs), + _shellRuns.dismissedRuns, + ); + // Older pages prepend messages and a live frame can append one, so a + // folded assistant turn's first message id is not a stable identity. + // ChatRowKeys carries a turn's key forward while it still holds any of + // its previous messages, keeping the element (and its open disclosures) + // across paging and streaming. + final keys = _rowKeys.forRows(rows); + final split = _splitFor(rows); + final initialLoad = !_controller.loaded && _controller.loading; + final historyNotice = _noticeOf( + notices, + ChatNoticeKind.connectionRefused, + ); + final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure); + final messageIds = _messageIds(); + final newMessages = chatNewMessageCount(messageIds, _newestAtRelease); + final showJump = chatShowsJumpToLatest( + following: _following, + distanceFromBottom: _distanceFromBottom, + itemCount: messageIds.length, + ); + // Place the first loaded transcript and keep a following view at the end. + // Scheduling after the build means the new extent is already laid out. + _scheduleFollow(); + // Under the app shell the conversation takes over the app's bar (title, + // Back, model, information) instead of drawing a second bar below it. + final inShellBar = ShellBar.available(context); + // The measured header owns its space so scrolled text never falls + // behind the controls; the transcript ends at the composer's top edge, so + // nothing renders behind the composer and the viewport shrinks as the + // composer grows. + // Every input of the composer comes from this widget's configuration, + // the composer, the images and the running state. + final composerBar = _chrome.widgetFor( + 'composer', + _controller.running, + [widget, _composer, _images], + () => ChatComposerBar( + key: ValueKey('chat-composer-${widget.sessionId}'), + composer: _composer, + running: _controller.running, + commands: _commandActions(), + picker: widget.attachmentPicker, + images: _images, + placeholder: chatComposerPlaceholderFor( + '${widget.session?['directory'] ?? ''}', + ), + chatColor: chatSessionColor(widget.session), + pasteTarget: widget.pasteTarget, + runShell: _shellRuns.start, + backgroundTasks: ChatBackgroundTasks( + key: ValueKey('chat-background-tasks-${widget.sessionId}'), + gateway: widget.gateway, + sessionId: widget.sessionId, + syncToken: widget.syncToken, + ), ), - chatColor: chatSessionColor(widget.session), - pasteTarget: widget.pasteTarget, - runShell: _shellRuns.start, - backgroundTasks: ChatBackgroundTasks( - key: ValueKey('chat-background-tasks-${widget.sessionId}'), - gateway: widget.gateway, - sessionId: widget.sessionId, - syncToken: widget.syncToken, - ), - ), - ); - final page = FloatingBarOverlay( - bar: ChatPaneBarReveal(bar: composerBar), - child: SegmentedBarOverlay( - reserveSpace: true, - bar: ChatPaneBarReveal(bar: _header(context, inShellBar)), - child: NotificationListener( - onNotification: _onScrollMetrics, - child: NotificationListener( - onNotification: _onScrollNotification, - child: LayoutBuilder( - builder: (context, constraints) { - // Rows keep to the centred reading column on a wide - // window; the margins beside it still scroll the list. - final side = chatReadingInset(constraints.maxWidth); - // Answers draw Copy in a strip left of the column; every - // other row keeps to the column by insetting past it. - final gutter = chatCopyGutter(constraints.maxWidth); - final media = MediaQuery.paddingOf(context); - final transcript = [ - for (var index = 0; index < rows.length; index++) - Padding( - key: ValueKey(keys[index]), - padding: EdgeInsets.only( - left: - 16 + - (rows[index]['kind'] == 'assistant' ? 0 : gutter), - right: 16, - ), - // Slivers mount only visible rows. Defer constructing - // their chips and checking cached widgets until then, - // rather than visiting the entire history per delta. - child: ChatCopyGutter( - width: rows[index]['kind'] == 'assistant' - ? gutter - : 0, - child: Builder( - builder: (_) => _entering( - rows[index], - _transcriptRow( + ); + final page = FloatingBarOverlay( + bar: ChatPaneBarReveal(bar: composerBar), + child: SegmentedBarOverlay( + reserveSpace: true, + bar: ChatPaneBarReveal(bar: _header(context, inShellBar)), + child: NotificationListener( + onNotification: _onScrollMetrics, + child: NotificationListener( + onNotification: _onScrollNotification, + child: LayoutBuilder( + builder: (context, constraints) { + // Rows keep to the centred reading column on a wide + // window; the margins beside it still scroll the list. + final side = chatReadingInset(constraints.maxWidth); + // Answers draw Copy in a strip left of the column; every + // other row keeps to the column by insetting past it. + final gutter = chatCopyGutter(constraints.maxWidth); + final media = MediaQuery.paddingOf(context); + final transcript = [ + for (var index = 0; index < rows.length; index++) + Padding( + key: ValueKey(keys[index]), + padding: EdgeInsets.only( + left: + 16 + + (rows[index]['kind'] == 'assistant' + ? 0 + : gutter), + right: 16, + ), + // Slivers mount only visible rows. Defer constructing + // their chips and checking cached widgets until then, + // rather than visiting the entire history per delta. + child: ChatCopyGutter( + width: rows[index]['kind'] == 'assistant' + ? gutter + : 0, + child: Builder( + builder: (_) => _entering( rows[index], - keys[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition( - rows[index], - ) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition( + rows[index], + ) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), ), ), ), ), - ), - ]; - _rowWidgets.prune(); - final stack = Stack( - children: [ - // At rest the first item starts below the floating bar; - // the viewport itself ends above the composer. - // Bottom-anchored at the split row, the newest rows are - // laid out first and older ones only when scrolled to. - ChatTranscriptSelectionArea( - child: ChatTranscriptScrollView( - key: ValueKey( - 'chat-thread-${widget.sessionId}', - ), - controller: _scroll, - splitAfter: split < 0 - ? null - : ValueKey(keys[split]), - padding: EdgeInsets.fromLTRB( - side - gutter, - media.top + 8, - side, - 8, - ), - children: chatCopyGutterInset(gutter, transcript, [ - if (initialLoad) - Padding( - key: const Key('chat-thread-loading'), - padding: const EdgeInsets.all(16), - child: Center( - child: cupertino - ? const CupertinoActivityIndicator() - : const CircularProgressIndicator(), + ]; + _rowWidgets.prune(); + final stack = Stack( + children: [ + // At rest the first item starts below the floating bar; + // the viewport itself ends above the composer. + // Bottom-anchored at the split row, the newest rows are + // laid out first and older ones only when scrolled to. + ChatTranscriptSelectionArea( + child: ChatTranscriptScrollView( + key: ValueKey( + 'chat-thread-${widget.sessionId}', + ), + controller: _scroll, + splitAfter: split < 0 + ? null + : ValueKey(keys[split]), + padding: EdgeInsets.fromLTRB( + side - gutter, + media.top + 8, + side, + 8, + ), + children: chatCopyGutterInset(gutter, transcript, [ + if (initialLoad) + Padding( + key: const Key('chat-thread-loading'), + padding: const EdgeInsets.all(16), + child: Center( + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ), ), - ), - if (_controller.hasMore) - Padding( - key: const Key('chat-load-older'), - padding: const EdgeInsets.symmetric( - horizontal: 16, + if (_controller.hasMore) + Padding( + key: const Key('chat-load-older'), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: cupertino + ? CupertinoButton( + padding: EdgeInsets.zero, + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ) + : TextButton( + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ), + ), ), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: cupertino - ? CupertinoButton( - padding: EdgeInsets.zero, - onPressed: _controller.loading - ? null - : _controller.loadOlder, - child: const Text('Load older'), - ) - : TextButton( - onPressed: _controller.loading - ? null - : _controller.loadOlder, - child: const Text('Load older'), - ), + if (historyNotice != null) + _ChatNoticeLine( + key: const Key('chat-history-error'), + notice: historyNotice, + onDismiss: _dismiss, + onRetry: _controller.load, ), - ), - if (historyNotice != null) - _ChatNoticeLine( - key: const Key('chat-history-error'), - notice: historyNotice, - onDismiss: _dismiss, - onRetry: _controller.load, - ), - if (liveNotice != null) - _ChatNoticeLine( - key: const Key('chat-live-error'), - notice: liveNotice, - onDismiss: _dismiss, - onRetry: _controller.resync, - ), - if (_controller.loaded && - allRows.isEmpty && - allNotices.isEmpty && - _commandNotices.isEmpty && - _controller.error == null) - const Padding( - key: Key('chat-thread-empty'), - padding: EdgeInsets.all(16), - child: Text('No messages in this chat yet.'), - ), - ...transcript, - // Messages the server holds queued (one sent before - // a reload, or from another device) follow the - // transcript: none has reached the harness yet. - for (final prompt - in _controller.queuedOutsideTranscript) - Padding( - key: ValueKey( - 'chat-queued-${prompt['operation_id']}', + if (liveNotice != null) + _ChatNoticeLine( + key: const Key('chat-live-error'), + notice: liveNotice, + onDismiss: _dismiss, + onRetry: _controller.resync, ), - padding: const EdgeInsets.symmetric( - horizontal: 16, + if (_controller.loaded && + allRows.isEmpty && + allNotices.isEmpty && + _commandNotices.isEmpty && + _controller.error == null) + const Padding( + key: Key('chat-thread-empty'), + padding: EdgeInsets.all(16), + child: Text('No messages in this chat yet.'), ), - child: _queuedRow(prompt, cupertino), - ), - // Messages the server has not accepted follow the - // transcript until they are retried or edited. - for (final send in _composer.deliveries.unsent) - Padding( - key: ValueKey( - 'chat-unsent-${send.operationId}', + ...transcript, + // Messages the server holds queued (one sent before + // a reload, or from another device) follow the + // transcript: none has reached the harness yet. + for (final prompt + in _controller.queuedOutsideTranscript) + Padding( + key: ValueKey( + 'chat-queued-${prompt['operation_id']}', + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: _queuedRow(prompt, cupertino), ), - padding: const EdgeInsets.symmetric( - horizontal: 16, + // Messages the server has not accepted follow the + // transcript until they are retried or edited. + for (final send in _composer.deliveries.unsent) + Padding( + key: ValueKey( + 'chat-unsent-${send.operationId}', + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: _unsentRow(send, cupertino), ), - child: _unsentRow(send, cupertino), - ), - // The conversation's own command lines sit after the - // turns, as on the web; they are never bubbles. - for (final notice in _commandNotices) - _ChatNoticeLine( - key: ValueKey( - 'chat-command-notice-${notice.condition}', + // The conversation's own command lines sit after the + // turns, as on the web; they are never bubbles. + for (final notice in _commandNotices) + _ChatNoticeLine( + key: ValueKey( + 'chat-command-notice-${notice.condition}', + ), + notice: notice, + onDismiss: _dismiss, ), - notice: notice, - onDismiss: _dismiss, - ), - ]), - ), - ), - if (showJump) - PositionedDirectional( - end: side + 16, - bottom: 16, - child: _ChatJumpToLatest( - key: const Key('chat-jump-to-latest'), - label: chatJumpToLatestLabel(newMessages), - cupertino: cupertino, - onPressed: _followLatest, + ]), ), ), - ], - ); - return AboveFloatingBar(child: stack); - }, + if (showJump) + PositionedDirectional( + end: side + 16, + bottom: 16, + child: _ChatJumpToLatest( + key: const Key('chat-jump-to-latest'), + label: chatJumpToLatestLabel(newMessages), + cupertino: cupertino, + onPressed: _followLatest, + ), + ), + ], + ); + return AboveFloatingBar(child: stack); + }, + ), ), ), ), - ), - ); - // The bar and the jump control float over the transcript and the - // composer sits below it; the wheel over them scrolls it, as a page - // scrolls under fixed bars. - final column = VerticalWheelForwarder(controller: _scroll, child: page); - final wideFiles = - _filesVisible && MediaQuery.sizeOf(context).width >= 700; - final content = wideFiles - ? Row( - children: [ - Expanded(child: column), - SizedBox( - width: filesPanelWidth(MediaQuery.sizeOf(context).width), - child: FilesPanel(controller: _files), - ), - ], - ) - : column; - if (!inShellBar) return content; - // The conversation draws its own floating bar; the page shows none. - final title = widget.title.trim(); - return ShellBar( - barless: true, - title: title.isEmpty ? null : title, - child: content, - ); - }, + ); + // The bar and the jump control float over the transcript and the + // composer sits below it; the wheel over them scrolls it, as a page + // scrolls under fixed bars. + final column = VerticalWheelForwarder(controller: _scroll, child: page); + final wideFiles = + _filesVisible && MediaQuery.sizeOf(context).width >= 700; + final content = wideFiles + ? Row( + children: [ + Expanded(child: column), + SizedBox( + width: filesPanelWidth(MediaQuery.sizeOf(context).width), + child: FilesPanel(controller: _files), + ), + ], + ) + : column; + if (!inShellBar) return content; + // The conversation draws its own floating bar; the page shows none. + final title = widget.title.trim(); + return ShellBar( + barless: true, + title: title.isEmpty ? null : title, + child: content, + ); + }, + ), ); /// The floating bar: Back where this page can go back (a pushed phone page, diff --git a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart index f9d0c776..97cf9203 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_bubble.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_bubble.dart @@ -1,7 +1,34 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -/// The operator's turn: a neutral filled, evenly rounded bubble with no border, +import '../sessions/chat_color_palette.dart'; + +/// How strongly a coloured chat's shade washes the operator's bubbles over +/// the host's neutral bubble fill. Text keeps the host's colours. +const double chatBubbleTint = 0.22; + +/// The open chat's colour name for the operator's bubbles below it; a chat +/// with no colour (or no scope) keeps the host's neutral bubble. +class ChatBubbleColor extends InheritedWidget { + const ChatBubbleColor({super.key, required this.name, required super.child}); + + final String? name; + + static String? of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.name; + + @override + bool updateShouldNotify(ChatBubbleColor old) => old.name != name; +} + +/// [base] washed with the open chat's shade, or [base] for an uncoloured chat. +Color chatBubbleFill(BuildContext context, Color base) { + final shade = chatColorShade(context, ChatBubbleColor.of(context)); + if (shade == null) return base; + return Color.alphaBlend(shade.withValues(alpha: chatBubbleTint), base); +} + +/// The operator's turn: a filled (neutral, or softly in the chat's colour), evenly rounded bubble with no border, /// in the host's own surface roles. The agent's turn has no bubble at all; its /// text sits on the page, so only the operator's words are enclosed. class ChatUserBubble extends StatelessWidget { @@ -25,7 +52,10 @@ class ChatUserBubble extends StatelessWidget { if (cupertino) { return DecoratedBox( decoration: BoxDecoration( - color: CupertinoColors.systemGrey5.resolveFrom(context), + color: chatBubbleFill( + context, + CupertinoColors.systemGrey5.resolveFrom(context), + ), borderRadius: _radius, ), child: Padding(padding: _padding, child: child), @@ -34,7 +64,10 @@ class ChatUserBubble extends StatelessWidget { // A Material surface (not a bare DecoratedBox) so a disclosure ListTile // inside the bubble keeps its ink and background. return Material( - color: Theme.of(context).colorScheme.surfaceContainerHighest, + color: chatBubbleFill( + context, + Theme.of(context).colorScheme.surfaceContainerHighest, + ), clipBehavior: Clip.antiAlias, shape: const RoundedRectangleBorder(borderRadius: _radius), child: Padding(padding: _padding, child: child), diff --git a/app/test/features/chat/ui/transcript/chat_bubble_color_test.dart b/app/test/features/chat/ui/transcript/chat_bubble_color_test.dart new file mode 100644 index 00000000..9b6f1846 --- /dev/null +++ b/app/test/features/chat/ui/transcript/chat_bubble_color_test.dart @@ -0,0 +1,125 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_bubble.dart'; + +void main() { + Future pump( + WidgetTester tester, { + required bool cupertino, + String? color, + Brightness brightness = Brightness.light, + }) async { + final bubble = ChatBubbleColor( + name: color, + child: ChatUserBubble(cupertino: cupertino, child: const Text('Hello')), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), + home: Center(child: bubble), + ) + : MaterialApp( + theme: ThemeData(brightness: brightness), + home: Scaffold(body: Center(child: bubble)), + ), + ); + } + + Color materialFill(WidgetTester tester) => tester + .widget( + find + .descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(Material), + ) + .first, + ) + .color!; + + Color cupertinoFill(WidgetTester tester) => + (tester + .widget( + find + .descendant( + of: find.byType(ChatUserBubble), + matching: find.byType(DecoratedBox), + ) + .first, + ) + .decoration + as BoxDecoration) + .color!; + + for (final brightness in Brightness.values) { + testWidgets('Material ${brightness.name}: a coloured chat washes the ' + 'bubble softly; an uncoloured chat keeps the host fill', ( + tester, + ) async { + await pump(tester, cupertino: false, brightness: brightness); + final neutral = materialFill(tester); + final context = tester.element(find.byType(ChatUserBubble)); + expect(neutral, Theme.of(context).colorScheme.surfaceContainerHighest); + + await pump( + tester, + cupertino: false, + color: 'teal', + brightness: brightness, + ); + final tinted = materialFill(tester); + expect(tinted, isNot(neutral)); + expect(tinted.a, 1); + // Soft: every channel stays within the tint's share of the neutral fill. + for (final (a, b) in [ + (tinted.r, neutral.r), + (tinted.g, neutral.g), + (tinted.b, neutral.b), + ]) { + expect((a - b).abs(), lessThanOrEqualTo(chatBubbleTint + 0.01)); + } + // The text keeps the host's colour. + final style = DefaultTextStyle.of( + tester.element(find.text('Hello')), + ).style; + await pump(tester, cupertino: false, brightness: brightness); + expect( + DefaultTextStyle.of(tester.element(find.text('Hello'))).style.color, + style.color, + ); + }); + } + + testWidgets('Cupertino: a coloured chat washes the bubble; none keeps grey', ( + tester, + ) async { + await pump(tester, cupertino: true); + final neutral = cupertinoFill(tester); + expect( + neutral, + CupertinoColors.systemGrey5.resolveFrom( + tester.element(find.byType(ChatUserBubble)), + ), + ); + await pump(tester, cupertino: true, color: 'blue'); + expect(cupertinoFill(tester), isNot(neutral)); + await pump(tester, cupertino: true, color: 'not-a-colour'); + expect(cupertinoFill(tester), neutral); + }); + + testWidgets('a bubble with no colour scope stays neutral', (tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ChatUserBubble(cupertino: false, child: Text('Hello')), + ), + ), + ); + final context = tester.element(find.byType(ChatUserBubble)); + expect( + materialFill(tester), + Theme.of(context).colorScheme.surfaceContainerHighest, + ); + }); +}