diff --git a/documentation/chat-and-messaging.md b/documentation/chat-and-messaging.md index 53a47331..68aec5f2 100644 --- a/documentation/chat-and-messaging.md +++ b/documentation/chat-and-messaging.md @@ -40,13 +40,17 @@ From the Contacts screen, tap any Chat-type contact to open the ChatScreen. ### Input Bar -- **Send action button** (left, ⊕ icon): Opens a menu with **Send GIF** (GIF picker bottom sheet) and **Share my location** +The composer is a rounded bubble at the bottom of the chat with one round button beside it. With a chat background set, the bubble floats over the background. + +- **Round button** (right): shows **+** while the field is empty and **Send** once you type. **+** opens the send action menu: **Send GIF** (GIF picker bottom sheet), **Share my location**, **Share contact**, and, when set up, image uploads - **Share my location**: Sends your radio's current position (from the radio, not the phone's GPS) as a location pin. You're asked for a label (default: your node name) before sending; the keyboard's Send key confirms. If the radio reports no usable position (none set, or 0,0), the item is hidden and a snackbar says "Your radio has no location set". Location shares follow the same send cooldown as typed messages and are never sent as a reply. In channel chat the menu also holds **Send low-res image over radio** when image messages are set up -- **Translation button** (optional, between GIF and text field): Shown only when translation is enabled in App Settings. Tap to configure outgoing-message translation language and on/off toggle. -- **Text field** (center): Auto-capitalization, enforces UTF-8 byte limit in real-time -- **Send button** (right): Submits the message +- **Text field**: Auto-capitalization, enforces the UTF-8 byte limit in real time. It grows to five lines (fewer with very large text while the keyboard is open), then scrolls +- **Byte counter**: appears in the bottom-right of the bubble once a message passes 70 % of the limit, and turns red near the limit +- **Translation button** (inside the bubble, right): Shown only when translation is enabled in App Settings. Tap to configure outgoing-message translation language and on/off toggle. +- **Reply preview**: In channel chat, replying shows the quoted message at the top of the bubble with a **✕** to cancel and, when the original had a region, the region chip - On desktop: Enter/Numpad Enter also submits -- When a GIF is selected, the text field shows an inline GIF preview with a dismiss button +- When a GIF is selected, the bubble shows a GIF preview with a remove button; Enter sends it +- With no radio connected, the bubble says so and a **Connect** button takes the place of the round button ## Message Types diff --git a/documentation/design.md b/documentation/design.md index 423b53aa..ed6abd85 100644 --- a/documentation/design.md +++ b/documentation/design.md @@ -147,6 +147,15 @@ Icon sizes in use: 24 for tile and banner icons, 20 for menu icons and small act **IconButton.** Always set `tooltip:` with a localized string. It is the accessible name. +**Chat composer.** Direct and channel chats share `ChatComposer` (`widgets/chat_composer.dart`); change it there, not per screen. + +- Panel: no divider; `scheme.surface` without a chat background, transparent over one (the screens pass the composer as `ChatBackdrop.footer`, and `ChatBackdrop.hasBackgroundOf` tells it a background is drawn). Margins 12 on the sides, 8 above and below. +- Bubble: radius `kComposerBubbleRadius` (20), no outline, `surfaceContainerHigh` fill, or the incoming-bubble colour (`MessageBubbleColors`, `surfaceContainerLow`) over a background. One line is 48 tall; the field grows to `kComposerMaxLines` (5), fewer when large text and the keyboard leave little room, then scrolls. Buttons stay bottom-aligned. +- Inside the bubble: a reply quote at the top (`ChatComposerQuote`: 4px leading bar in `primary`, title, one-line content, ✕), the field or the GIF preview, the translate button on the right, and the byte counter bottom-right only past 70 % of the limit (`ByteCountedTextField(counterOnlyNearLimit: true)`). +- One round button beside the bubble, 44 drawn in a 48 touch target: `+` (the action menu) while the field is empty, Send in `primary` once there is text. The swap fades and scales for 150 ms, instantly when `MediaQuery.disableAnimations` is set. +- Offline, `OfflineComposerBar` uses the same panel, bubble and height, with Connect in place of the round button (below the bubble on narrow or large-text layouts). +- Full-width strips that are not part of the draft (image send progress) go in `header`, above the bubble. + ## 6. Sheets, dialogs and pages What the code does: @@ -183,7 +192,7 @@ Rules for new UI: | Background sync | `SyncProgressAppBarBottom`. | | Empty | `EmptyState` with an icon, a short title, and an action when there is an obvious next step. Use a separate "no results" state (`Icons.search_off`) when a search or filter hides everything. | | Error | A snackbar for a failed action. `ErrorRetryCard` for a failed load the user can retry. Never show raw exception text alone. | -| Companion radio disconnected | Main and chat screens stay open, read-only ([offline mode](offline-mode.md)). Decide with `isRadioReadOnly(connector)` / `context.radioReadOnly` (`lib/utils/radio_guard.dart`): disable menu items (`PopupMenuItem(enabled: false)`, drop destructive colors) and buttons, hide FABs, and call `ensureRadioConnected(context)` as the safety net in handlers. The chat composer shows `OfflineComposerBar`. Repeater screens stay open with `RadioDisconnectedBanner` at the top and disable radio-dependent actions. Settings rows that need the radio pass `onTap: null` and show `settings_requiresConnection` as the subtitle (`settings_screen.dart`). | +| Companion radio disconnected | Main and chat screens stay open, read-only ([offline mode](offline-mode.md)). Decide with `isRadioReadOnly(connector)` / `context.radioReadOnly` (`lib/utils/radio_guard.dart`): disable menu items (`PopupMenuItem(enabled: false)`, drop destructive colors) and buttons, hide FABs, and call `ensureRadioConnected(context)` as the safety net in handlers. The chat composer shows `OfflineComposerBar` in the same bubble and margins. Repeater screens stay open with `RadioDisconnectedBanner` at the top and disable radio-dependent actions. Settings rows that need the radio pass `onTap: null` and show `settings_requiresConnection` as the subtitle (`settings_screen.dart`). | | Feature unsupported by firmware | Disabled row with a subtitle that says why (`settings_requiresFirmware('v1.10')`). | | Remote value not fetched yet | See below. | diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 67a397ab..02aedafa 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -843,12 +843,16 @@ class _ChannelChatScreenState extends State { ? _buildSearchResults(_loadSearchEntries) : SafeArea( top: false, + // The composer panel pads the bottom inset itself, so the + // background runs behind it to the screen edge. + bottom: false, child: Column( children: [ Expanded( child: ChatBackdrop( - key: _messageAreaKey, + contentKey: _messageAreaKey, chatKey: ChatBackgroundService.channelKey(widget.channel), + footer: _buildInputBar(), child: Consumer( builder: (context, connector, child) { final messages = connector.getChannelMessages( @@ -1064,7 +1068,6 @@ class _ChannelChatScreenState extends State { ), ), ), - _buildInputBar(), ], ), ), @@ -2633,47 +2636,23 @@ class _ChannelChatScreenState extends State { ); } - Widget _buildReplyBanner(double textScale) { + Widget _buildComposerReplyQuote(double textScale) { final message = _replyingToMessage!; final scheme = Theme.of(context).colorScheme; final replyRegion = message.region; - return Container( - width: double.infinity, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - decoration: BoxDecoration( - color: scheme.surfaceContainerHigh, - border: Border( - bottom: BorderSide(color: scheme.outlineVariant, width: 1), - ), + return ChatComposerQuote( + title: context.l10n.chat_replyingTo(message.senderName), + content: _buildReplyContent( + message.text, + textScale, + color: scheme.onSurfaceVariant, + maxLines: 1, + gifSize: 48, ), - child: Row( - children: [ - Icon(Icons.reply, size: 18, color: scheme.primary), - const SizedBox(width: 8), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - context.l10n.chat_replyingTo(message.senderName), - style: MeshTheme.mono( - fontSize: 12 * textScale, - fontWeight: FontWeight.w700, - color: scheme.primary, - ), - ), - _buildReplyContent( - message.text, - textScale, - color: scheme.onSurfaceVariant, - maxLines: 1, - gifSize: 48, - ), - ], - ), - ), - if (replyRegion?.isNotEmpty ?? false) - InkWell( + onDismiss: _cancelReply, + dismissTooltip: context.l10n.chat_cancelReply, + trailing: (replyRegion?.isNotEmpty ?? false) + ? InkWell( borderRadius: BorderRadius.circular(MeshRadii.xs), onTap: () => setState(() => _useReplyRegion = !_useReplyRegion), child: Container( @@ -2691,6 +2670,8 @@ class _ChannelChatScreenState extends State { ), child: Text( context.l10n.channels_regionSetTo(replyRegion!), + maxLines: 1, + overflow: TextOverflow.ellipsis, style: MeshTheme.mono( fontSize: 12 * textScale, @@ -2704,17 +2685,8 @@ class _ChannelChatScreenState extends State { ), ), ), - ), - const SizedBox(width: 4), - IconButton( - icon: const Icon(Icons.close, size: 18), - tooltip: context.l10n.chat_cancelReply, - onPressed: _cancelReply, - color: scheme.onSurfaceVariant, - constraints: const BoxConstraints(minWidth: 44, minHeight: 44), - ), - ], - ), + ) + : null, ); } @@ -2790,18 +2762,17 @@ class _ChannelChatScreenState extends State { : null, onSend: _sendMessage, sendTooltip: context.l10n.chat_sendMessage, - header: [ - if (replyTo != null) - Builder( - builder: (context) { - final textScale = context.select( - (service) => service.scale, - ); - return _buildReplyBanner(textScale); - }, - ), - if (_imageSendTotal > 0) _buildImageSendProgress(scheme), - ], + header: [if (_imageSendTotal > 0) _buildImageSendProgress(scheme)], + replyPreview: replyTo == null + ? null + : Builder( + builder: (context) { + final textScale = context.select( + (service) => service.scale, + ); + return _buildComposerReplyQuote(textScale); + }, + ), actionsBuilder: () { final connector = context.read(); return [ diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index ad509b82..ece6eb3f 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -624,10 +624,11 @@ class _ChatScreenState extends State { children: [ Expanded( child: ChatBackdrop( - key: _messageAreaKey, + contentKey: _messageAreaKey, chatKey: ChatBackgroundService.contactKey( widget.contact, ), + footer: _buildInputBar(connector), child: Stack( children: [ messages.isEmpty @@ -640,7 +641,6 @@ class _ChatScreenState extends State { ), ), ), - _buildInputBar(connector), ], ); }, diff --git a/lib/widgets/byte_count_input.dart b/lib/widgets/byte_count_input.dart index 5872b192..3fe70b5b 100644 --- a/lib/widgets/byte_count_input.dart +++ b/lib/widgets/byte_count_input.dart @@ -62,6 +62,14 @@ class ByteCountedTextField extends StatelessWidget { final int? softLimitBytes; final String? softLimitNote; + /// Lines the field grows to before it scrolls internally. Null (the + /// default) grows without limit. + final int? maxLines; + + /// Show the counter row only once usage passes [warningThreshold], and give + /// it no space until then. By default the row keeps its height while hidden. + final bool counterOnlyNearLimit; + const ByteCountedTextField({ super.key, required this.maxBytes, @@ -80,6 +88,8 @@ class ByteCountedTextField extends StatelessWidget { this.encoder, this.softLimitBytes, this.softLimitNote, + this.maxLines, + this.counterOnlyNearLimit = false, }); @override @@ -92,7 +102,9 @@ class ByteCountedTextField extends StatelessWidget { : value.text; final usedBytes = utf8.encode(effectiveText).length; final ratio = maxBytes > 0 ? usedBytes / maxBytes : 0.0; - final showCounter = !(hideCounterWhenEmpty && value.text.isEmpty); + final showCounter = counterOnlyNearLimit + ? ratio > warningThreshold + : !(hideCounterWhenEmpty && value.text.isEmpty); final showSoftLimitNote = softLimitNote != null && softLimitBytes != null && @@ -104,12 +116,27 @@ class ByteCountedTextField extends StatelessWidget { ? Theme.of(context).colorScheme.tertiary : Theme.of(context).colorScheme.onSurfaceVariant; + final softNote = showSoftLimitNote + ? Text( + softLimitNote!, + style: TextStyle( + fontSize: 12, + color: Theme.of(context).colorScheme.tertiary, + ), + ) + : null; + final counter = Text( + '$usedBytes / $maxBytes', + style: TextStyle(fontSize: 12, color: counterColor), + ); + return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ TextField( - maxLines: null, + minLines: maxLines == null ? null : 1, + maxLines: maxLines, controller: controller, focusNode: focusNode, autofocus: autofocus, @@ -134,32 +161,32 @@ class ByteCountedTextField extends StatelessWidget { textInputAction: textInputAction, onSubmitted: onSubmitted, ), - Opacity( - opacity: showCounter ? 1 : 0, - child: Padding( - padding: const EdgeInsets.only(top: 4, right: 4), - child: Row( - children: [ - Expanded( - child: showSoftLimitNote - ? Text( - softLimitNote!, - style: TextStyle( - fontSize: 12, - color: Theme.of(context).colorScheme.tertiary, - ), - ) - : const SizedBox.shrink(), - ), - const SizedBox(width: 8), - Text( - '$usedBytes / $maxBytes', - style: TextStyle(fontSize: 12, color: counterColor), - ), - ], + if (counterOnlyNearLimit && showCounter) + // Right-aligned, and wraps rather than overflowing at large + // text sizes in a narrow field. + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 12, 8), + child: Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + children: [?softNote, counter], + ), + ) + else if (!counterOnlyNearLimit) + Opacity( + opacity: showCounter ? 1 : 0, + child: Padding( + padding: const EdgeInsets.only(top: 4, right: 4), + child: Row( + children: [ + Expanded(child: softNote ?? const SizedBox.shrink()), + const SizedBox(width: 8), + counter, + ], + ), ), ), - ), ], ); }, diff --git a/lib/widgets/chat_background.dart b/lib/widgets/chat_background.dart index fe56a12e..219ec7bd 100644 --- a/lib/widgets/chat_background.dart +++ b/lib/widgets/chat_background.dart @@ -42,26 +42,79 @@ ChatBackgroundService? _maybeService( } /// Draws [chatKey]'s background (its own, or the theme's) behind [child]. +/// +/// A [footer] (the chat composer) sits below [child] over the same +/// background and can ask [ChatBackdrop.hasBackgroundOf] whether one is +/// drawn. [contentKey] marks the message area above the footer. class ChatBackdrop extends StatelessWidget { final String chatKey; final Widget child; + final Widget? footer; + final Key? contentKey; - const ChatBackdrop({super.key, required this.chatKey, required this.child}); + const ChatBackdrop({ + super.key, + required this.chatKey, + required this.child, + this.footer, + this.contentKey, + }); + + /// Whether the nearest [ChatBackdrop] draws a background behind its footer. + static bool hasBackgroundOf(BuildContext context) => + context + .dependOnInheritedWidgetOfExactType<_ChatBackdropScope>() + ?.hasBackground ?? + false; @override Widget build(BuildContext context) { final background = _maybeService(context)?.resolve(chatKey); - if (background == null) return child; + final footer = this.footer; + if (footer == null) { + if (background == null) return child; + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fill(child: ChatBackgroundLayer(background: background)), + child, + ], + ); + } return Stack( fit: StackFit.expand, children: [ - Positioned.fill(child: ChatBackgroundLayer(background: background)), - child, + Positioned.fill( + child: background == null + ? const SizedBox.shrink() + : ChatBackgroundLayer(background: background), + ), + Column( + children: [ + Expanded( + child: KeyedSubtree(key: contentKey, child: child), + ), + _ChatBackdropScope( + hasBackground: background != null, + child: footer, + ), + ], + ), ], ); } } +class _ChatBackdropScope extends InheritedWidget { + final bool hasBackground; + + const _ChatBackdropScope({required this.hasBackground, required super.child}); + + @override + bool updateShouldNotify(_ChatBackdropScope oldWidget) => + hasBackground != oldWidget.hasBackground; +} + /// Paints one [ChatBackground], faded toward the theme's surface color. class ChatBackgroundLayer extends StatelessWidget { final ChatBackground background; diff --git a/lib/widgets/chat_composer.dart b/lib/widgets/chat_composer.dart index c988d215..4f59efaa 100644 --- a/lib/widgets/chat_composer.dart +++ b/lib/widgets/chat_composer.dart @@ -8,10 +8,12 @@ import '../services/app_settings_service.dart'; import '../theme/mesh_theme.dart'; import '../utils/radio_guard.dart'; import 'byte_count_input.dart'; +import 'chat_background.dart'; import 'connect_sheet.dart'; import 'gif_message.dart'; import 'gif_picker.dart'; import 'mesh_ui.dart'; +import 'message_bubble_frame.dart'; import 'message_translation_button.dart'; import '../theme/theme_icons.dart'; @@ -54,10 +56,60 @@ Future showComposerTranslationOptions(BuildContext context) async { ); } -/// The message composer shared by the direct and channel chat screens: -/// "+" action menu, optional translation toggle, byte-counted text field (or -/// GIF preview) and send button. [header] widgets (reply banner, progress) -/// are stacked above the row. +/// Corner radius of the compose bubble and the offline bar. +const double kComposerBubbleRadius = 20; + +/// Lines the compose field grows to before it scrolls. +const int kComposerMaxLines = 5; + +/// Fill of the compose bubble: the incoming-bubble colour over a chat +/// background so it stays readable, otherwise a raised surface. +Color composerBubbleColor(BuildContext context) { + return ChatBackdrop.hasBackgroundOf(context) + ? MessageBubbleColors.of(context, isOutgoing: false).background + : Theme.of(context).colorScheme.surfaceContainerHigh; +} + +/// The bottom panel holding the compose bubble: transparent over a chat +/// background, solid surface otherwise. 12dp side and 8dp vertical margins +/// (8dp on the trailing side, where the round button's touch target adds 2). +class _ComposerPanel extends StatelessWidget { + final List header; + final Widget child; + + const _ComposerPanel({this.header = const [], required this.child}); + + @override + Widget build(BuildContext context) { + final content = SafeArea( + top: false, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ...header, + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 10, 8), + child: child, + ), + ], + ), + ); + if (ChatBackdrop.hasBackgroundOf(context)) return content; + return ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: content, + ); + } +} + +/// The message composer shared by the direct and channel chat screens. +/// +/// A rounded compose bubble (optional [replyPreview], then the byte-counted +/// text field or a GIF preview, with the translation toggle on its right) +/// and one round button beside it: "+" (the [actionsBuilder] menu) while the +/// field is empty, Send once there is text. [header] widgets (e.g. image +/// send progress) are stacked full-width above the bubble. class ChatComposer extends StatelessWidget { final TextEditingController controller; final FocusNode focusNode; @@ -74,6 +126,12 @@ class ChatComposer extends StatelessWidget { final ValueChanged onAction; final List header; + /// Shown inside the top of the bubble, usually a [ChatComposerQuote]. + final Widget? replyPreview; + + /// Marks the compose bubble (and the offline bar's bubble). + static const bubbleKey = ValueKey('chat-composer-bubble'); + const ChatComposer({ super.key, required this.controller, @@ -87,6 +145,7 @@ class ChatComposer extends StatelessWidget { this.softLimitNote, this.encoder, this.header = const [], + this.replyPreview, }); Future _openActionMenu(BuildContext buttonContext) async { @@ -128,7 +187,6 @@ class ChatComposer extends StatelessWidget { @override Widget build(BuildContext context) { - final scheme = Theme.of(context).colorScheme; // Offline the chat is read-only. The draft stays in [controller] (owned // by the screen) and is back when the radio reconnects. if (context.radioReadOnly) return const OfflineComposerBar(); @@ -140,26 +198,40 @@ class ChatComposer extends StatelessWidget { s.settings.translationTargetLanguageCode, ), ); - return Container( + final scheme = Theme.of(context).colorScheme; + final replyPreview = this.replyPreview; + final bubble = DecoratedBox( + key: ChatComposer.bubbleKey, decoration: BoxDecoration( - color: scheme.surface, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + color: composerBubbleColor(context), + borderRadius: BorderRadius.circular(kComposerBubbleRadius), ), - child: SafeArea( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ...header, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (replyPreview != null) Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, + padding: const EdgeInsets.fromLTRB(6, 6, 6, 0), + child: replyPreview, + ), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) { + final gifId = GifHelper.parseGif(value.text); + if (gifId != null) { + return _buildGifPreview(context, gifId, scheme); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.end, children: [ - Builder( - builder: (buttonContext) => IconButton( - icon: const Icon(Icons.add_circle_outline), - tooltip: context.l10n.chat_selectSendAction, - onPressed: () => _openActionMenu(buttonContext), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) => _buildTextField( + context, + scheme, + constraints.maxHeight, + ), ), ), if (translation.$1) @@ -168,50 +240,34 @@ class ChatComposer extends StatelessWidget { languageCode: translation.$3, onPressed: () => showComposerTranslationOptions(context), ), - Expanded( - child: ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - final gifId = GifHelper.parseGif(value.text); - if (gifId != null) { - return _buildGifPreview(context, gifId, scheme); - } - return _buildTextField(context, scheme); - }, - ), - ), - const SizedBox(width: 6), - ValueListenableBuilder( - valueListenable: controller, - builder: (context, value, _) { - final hasText = value.text.trim().isNotEmpty; - return IconButton.filled( - icon: const ThemedIcon(ThemeIconSlot.send, size: 20), - tooltip: sendTooltip, - style: IconButton.styleFrom( - backgroundColor: hasText - ? scheme.primary - : scheme.surfaceContainerHighest, - foregroundColor: hasText - ? scheme.onPrimary - : scheme.onSurfaceVariant, - minimumSize: const Size(40, 40), - shape: const CircleBorder(), - ), - onPressed: hasText - ? () { - HapticFeedback.lightImpact(); - onSend(); - } - : null, - ); - }, - ), ], - ), + ); + }, + ), + ], + ), + ); + return _ComposerPanel( + header: header, + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded(child: bubble), + const SizedBox(width: 4), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) => _ComposerRoundButton( + hasText: value.text.trim().isNotEmpty, + sendTooltip: sendTooltip, + actionsTooltip: context.l10n.chat_selectSendAction, + onSend: () { + HapticFeedback.lightImpact(); + onSend(); + }, + onOpenActions: _openActionMenu, ), - ], - ), + ), + ], ), ); } @@ -232,39 +288,57 @@ class ChatComposer extends StatelessWidget { } return KeyEventResult.ignored; }, - child: Row( - children: [ - Expanded( - child: ClipRRect( - borderRadius: BorderRadius.circular(12), - child: GifMessage( - url: 'https://media.giphy.com/media/$gifId/giphy.gif', - backgroundColor: scheme.surfaceContainerHighest, - fallbackTextColor: scheme.onSurface.withValues(alpha: 0.6), - maxSize: 160, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 8, 0, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Align( + alignment: AlignmentDirectional.centerStart, + child: ClipRRect( + borderRadius: BorderRadius.circular(MeshRadii.md), + child: GifMessage( + url: 'https://media.giphy.com/media/$gifId/giphy.gif', + backgroundColor: scheme.surfaceContainerHighest, + fallbackTextColor: scheme.onSurfaceVariant, + maxSize: 160, + ), + ), ), ), - ), - const SizedBox(width: 8), - IconButton( - icon: const Icon(Icons.close), - tooltip: context.l10n.chat_removeGif, - onPressed: () { - controller.clear(); - focusNode.requestFocus(); - }, - ), - ], + IconButton( + icon: const Icon(Icons.close), + tooltip: context.l10n.chat_removeGif, + onPressed: () { + controller.clear(); + focusNode.requestFocus(); + }, + ), + ], + ), ), ); } - Widget _buildTextField(BuildContext context, ColorScheme scheme) { - OutlineInputBorder border(Color color, [double width = 1]) => - OutlineInputBorder( - borderRadius: BorderRadius.circular(MeshRadii.md), - borderSide: BorderSide(color: color, width: width), - ); + /// [maxHeight] is the room the chat leaves the composer: above the + /// keyboard, since the screen's body resizes for it. + Widget _buildTextField( + BuildContext context, + ColorScheme scheme, + double maxHeight, + ) { + // Five lines, or fewer when large text and a short window leave little + // room, so the field takes no more than about a quarter of the chat. + // Never one line: that stops wrapping and the keyboard's newline key. + final room = maxHeight.isFinite + ? maxHeight + : MediaQuery.sizeOf(context).height; + final lineHeight = MediaQuery.textScalerOf(context).scale(16) * 1.5; + final maxLines = (room / 4 / lineHeight).floor().clamp( + 2, + kComposerMaxLines, + ); return ByteCountedTextField( maxBytes: maxBytes, softLimitBytes: softLimitBytes, @@ -274,85 +348,240 @@ class ChatComposer extends StatelessWidget { hintText: context.l10n.chat_typeMessage, onSubmitted: (_) => onSend(), encoder: encoder, + maxLines: maxLines, + counterOnlyNearLimit: true, decoration: InputDecoration( hintText: context.l10n.chat_typeMessage, - border: border(scheme.outlineVariant), - enabledBorder: border(scheme.outlineVariant), - focusedBorder: border(scheme.primary, 1.5), - filled: true, - fillColor: scheme.surfaceContainerLow, - contentPadding: const EdgeInsets.symmetric( - horizontal: 18, - vertical: 12, - ), + hintStyle: TextStyle(color: scheme.onSurfaceVariant), + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + filled: false, + isDense: true, + // A 24dp line plus 12 above and below: 48dp on one line, level with + // the round button beside the bubble. + contentPadding: const EdgeInsetsDirectional.fromSTEB(16, 12, 8, 12), ), ); } } -/// Stands in for the composer while no radio is connected. -class OfflineComposerBar extends StatelessWidget { - const OfflineComposerBar({super.key}); +/// The round button beside the compose bubble: "+" while the field is +/// empty, Send once there is text. Drawn at 44dp in a 48dp touch target. +class _ComposerRoundButton extends StatelessWidget { + final bool hasText; + final String sendTooltip; + final String actionsTooltip; + final VoidCallback onSend; + final ValueChanged onOpenActions; + + const _ComposerRoundButton({ + required this.hasText, + required this.sendTooltip, + required this.actionsTooltip, + required this.onSend, + required this.onOpenActions, + }); + + static const _visualSize = Size(44, 44); @override Widget build(BuildContext context) { final scheme = Theme.of(context).colorScheme; - return Container( - decoration: BoxDecoration( - color: scheme.surfaceContainerLow, - border: Border(top: BorderSide(color: scheme.outlineVariant, width: 1)), + ButtonStyle style(Color background, Color foreground) => + IconButton.styleFrom( + backgroundColor: background, + foregroundColor: foreground, + fixedSize: _visualSize, + minimumSize: _visualSize, + padding: EdgeInsets.zero, + tapTargetSize: MaterialTapTargetSize.padded, + shape: const CircleBorder(), + ); + final Widget button = hasText + ? IconButton.filled( + key: const ValueKey('composer-send'), + icon: const ThemedIcon(ThemeIconSlot.send, size: 22), + tooltip: sendTooltip, + style: style(scheme.primary, scheme.onPrimary), + onPressed: onSend, + ) + : Builder( + key: const ValueKey('composer-actions'), + builder: (buttonContext) => IconButton.filled( + icon: const Icon(Icons.add, size: 28), + tooltip: actionsTooltip, + style: style(composerBubbleColor(context), scheme.onSurface), + onPressed: () => onOpenActions(buttonContext), + ), + ); + return SizedBox.square( + dimension: kMinInteractiveDimension, + child: AnimatedSwitcher( + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 150), + transitionBuilder: (child, animation) => FadeTransition( + opacity: animation, + child: ScaleTransition( + scale: Tween(begin: 0.6, end: 1).animate(animation), + child: child, + ), + ), + child: button, ), - child: SafeArea( + ); + } +} + +/// A quoted message inside the top of the compose bubble ("Replying to +/// Bob"): a coloured bar on the leading edge, [title], [content], optional +/// [trailing] controls and a dismiss button. +class ChatComposerQuote extends StatelessWidget { + final String title; + final Widget content; + final Widget? trailing; + final VoidCallback onDismiss; + final String dismissTooltip; + + const ChatComposerQuote({ + super.key, + required this.title, + required this.content, + required this.onDismiss, + required this.dismissTooltip, + this.trailing, + }); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final background = scheme.surfaceContainerHighest; + final accent = readableAccent(scheme.primary, background); + final trailing = this.trailing; + return ClipRRect( + borderRadius: BorderRadius.circular(MeshRadii.md), + child: DecoratedBox( + decoration: BoxDecoration( + color: background, + border: BorderDirectional(start: BorderSide(color: accent, width: 4)), + ), child: Padding( - padding: const EdgeInsets.fromLTRB(16, 10, 12, 10), + padding: const EdgeInsetsDirectional.fromSTEB(10, 6, 0, 6), child: LayoutBuilder( - builder: (context, constraints) { - final message = Row( - children: [ - Icon( - Icons.cloud_off, - color: scheme.onSurfaceVariant, - size: 24, + builder: (context, constraints) => Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w700, + color: accent, + ), + ), + content, + ], ), - const SizedBox(width: 12), - Expanded( - child: Text( - context.l10n.chat_composerOffline, - style: Theme.of( - context, - ).textTheme.bodyLarge?.copyWith(color: scheme.onSurface), + ), + // The quote shares its row with Send, so a long trailing + // control (a region chip) must not squeeze out the message + // or the dismiss button. + if (trailing != null) + ConstrainedBox( + constraints: BoxConstraints( + maxWidth: constraints.maxWidth * 0.4, ), + child: trailing, ), - ], - ); - // Side by side when there is room; otherwise the button goes - // under the message so large text never squeezes it. - final roomy = - constraints.maxWidth / - MediaQuery.textScalerOf(context).scale(1) >= - 420; - if (roomy) { - return Row( - children: [ - Expanded(child: message), - const SizedBox(width: 8), - const ConnectButton(), - ], - ); - } - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - message, - const SizedBox(height: 8), - const ConnectButton(), - ], - ); - }, + IconButton( + icon: const Icon(Icons.close), + tooltip: dismissTooltip, + color: scheme.onSurfaceVariant, + onPressed: onDismiss, + ), + ], + ), ), ), ), ); } } + +/// Stands in for the composer while no radio is connected, in the same +/// bubble and margins so the chat doesn't jump on connect or disconnect. +class OfflineComposerBar extends StatelessWidget { + const OfflineComposerBar({super.key}); + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final message = ConstrainedBox( + constraints: const BoxConstraints(minHeight: kMinInteractiveDimension), + child: DecoratedBox( + key: ChatComposer.bubbleKey, + decoration: BoxDecoration( + color: composerBubbleColor(context), + borderRadius: BorderRadius.circular(kComposerBubbleRadius), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Row( + children: [ + Icon(Icons.cloud_off, color: scheme.onSurfaceVariant, size: 24), + const SizedBox(width: 12), + Expanded( + child: Text( + context.l10n.chat_composerOffline, + style: Theme.of( + context, + ).textTheme.bodyLarge?.copyWith(color: scheme.onSurface), + ), + ), + ], + ), + ), + ), + ); + return _ComposerPanel( + child: LayoutBuilder( + builder: (context, constraints) { + // Side by side when there is room; otherwise the button goes + // under the message so large text never squeezes it. + final roomy = + constraints.maxWidth / + MediaQuery.textScalerOf(context).scale(1) >= + 420; + if (roomy) { + return Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded(child: message), + const SizedBox(width: 4), + const ConnectButton(), + ], + ); + } + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + message, + const SizedBox(height: 8), + const Align( + alignment: AlignmentDirectional.centerEnd, + child: ConnectButton(), + ), + ], + ); + }, + ), + ); + } +} diff --git a/test/screens/chat_composer_screens_test.dart b/test/screens/chat_composer_screens_test.dart new file mode 100644 index 00000000..2dea12ce --- /dev/null +++ b/test/screens/chat_composer_screens_test.dart @@ -0,0 +1,206 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:provider/single_child_widget.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/review_mode/review_radio.dart'; +import 'package:meshcore_open/screens/channel_chat_screen.dart'; +import 'package:meshcore_open/screens/chat_screen.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/ble_debug_log_service.dart'; +import 'package:meshcore_open/services/chat_text_scale_service.dart'; +import 'package:meshcore_open/services/image_codec_service.dart'; +import 'package:meshcore_open/services/map_tile_cache_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/received_image_store.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/services/translation_service.dart'; +import 'package:meshcore_open/services/ui_view_state_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/chat_background.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; +import 'package:meshcore_open/widgets/message_bubble_frame.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +/// Both chat screens show the same composer, as the footer of the chat +/// background, and the channel reply preview sits inside its bubble. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + final tempDir = Directory.systemTemp.createTempSync('chat_composer_test'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('plugins.flutter.io/path_provider'), + (call) async => tempDir.path, + ); + + setUpAll(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + Finder composerIn(Type screen) => find.descendant( + of: find.descendant( + of: find.byType(screen), + matching: find.byType(ChatBackdrop), + ), + matching: find.byType(ChatComposer), + ); + + testWidgets('DM chat shows the redesigned composer', (tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final contact = connector.contacts.firstWhere((c) => c.type == advTypeChat); + await _pump(tester, providers, ChatScreen(contact: contact)); + + expect(composerIn(ChatScreen), findsOneWidget); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget); + expect(find.byIcon(Icons.add_circle_outline), findsNothing); + + await tester.enterText(find.byType(TextField), 'hello'); + await _settle(tester); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsNothing); + expect(find.byTooltip(_l10n.chat_sendMessageTo(contact.name)), findsOne); + await _tearDown(tester); + }); + + testWidgets('channel chat shows the same composer with the reply preview ' + 'inside the bubble', (tester) async { + final (connector, providers) = _shared ??= await _connect(tester); + final channel = connector.channels[0]; + await _pump(tester, providers, ChannelChatScreen(channel: channel)); + + expect(composerIn(ChannelChatScreen), findsOneWidget); + expect(find.byTooltip(_l10n.chat_selectSendAction), findsOneWidget); + expect(find.byType(ChatComposerQuote), findsNothing); + + final incoming = connector + .getChannelMessages(channel) + .lastWhere((m) => !m.isOutgoing); + final bubble = find.ancestor( + of: find.textContaining(incoming.text, findRichText: true), + matching: find.byType(MessageBubbleFrame), + ); + await tester.longPressAt(tester.getTopLeft(bubble) + const Offset(4, 4)); + await _settle(tester); + await tester.tap(find.text(_l10n.chat_reply)); + await _settle(tester); + + final quote = find.byType(ChatComposerQuote); + expect( + find.descendant(of: find.byKey(ChatComposer.bubbleKey), matching: quote), + findsOneWidget, + ); + expect(find.text(_l10n.chat_replyingTo(incoming.senderName)), findsOne); + + await tester.tap(find.byTooltip(_l10n.chat_cancelReply)); + await _settle(tester); + expect(quote, findsNothing); + await _tearDown(tester); + }); +} + +Future _pump( + WidgetTester tester, + List providers, + Widget home, +) async { + await tester.pumpWidget( + MultiProvider( + providers: providers, + child: MaterialApp( + theme: MeshTheme.light(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + await _settle(tester); +} + +Future _settle(WidgetTester tester) async { + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } +} + +Future _tearDown(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(minutes: 1)); +} + +/// One review-radio connection shared by the tests. +(MeshCoreConnector, List)? _shared; + +Future<(MeshCoreConnector, List)> _connect( + WidgetTester tester, +) async { + final storage = StorageService(); + final connector = MeshCoreConnector(); + final retry = MessageRetryService(); + final settings = AppSettingsService(); + final translation = TranslationService(settings); + await tester.runAsync(() async { + await settings.loadSettings(); + connector.initialize( + retryService: retry, + pathHistoryService: PathHistoryService(storage), + appSettingsService: settings, + translationService: translation, + ); + connector.reviewRadioFactoryForTest = () => ReviewRadio( + scheduledMessageInterval: const Duration(hours: 1), + ackDelay: const Duration(hours: 1), + replyDelay: const Duration(hours: 1), + ); + await connector.connectReview(); + final end = DateTime.now().add(const Duration(seconds: 8)); + while ((connector.contacts.isEmpty || connector.channels.isEmpty) && + DateTime.now().isBefore(end)) { + await Future.delayed(const Duration(milliseconds: 25)); + } + }); + expect(connector.channels, isNotEmpty); + + return ( + connector, + [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider.value(value: retry), + ChangeNotifierProvider.value(value: PathHistoryService(storage)), + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: BleDebugLogService()), + ChangeNotifierProvider.value(value: AppDebugLogService()), + ChangeNotifierProvider.value(value: ChatTextScaleService()), + ChangeNotifierProvider.value(value: translation), + ChangeNotifierProvider.value(value: UiViewStateService()), + Provider.value(value: storage), + ChangeNotifierProvider.value( + value: MapTileCacheService(appSettingsService: settings), + ), + ChangeNotifierProvider.value(value: TimeoutPredictionService(storage)), + ChangeNotifierProvider.value(value: ImageCodecService(settings)), + ChangeNotifierProvider.value(value: ReceivedImageStore()), + ], + ); +} diff --git a/test/widgets/chat_composer_test.dart b/test/widgets/chat_composer_test.dart new file mode 100644 index 00000000..dd56e995 --- /dev/null +++ b/test/widgets/chat_composer_test.dart @@ -0,0 +1,512 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/helpers/gif_helper.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/chat_background.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/chat_background_service.dart'; +import 'package:meshcore_open/services/chat_background_image_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/theme/mesh_theme.dart'; +import 'package:meshcore_open/widgets/byte_count_input.dart'; +import 'package:meshcore_open/widgets/chat_background.dart'; +import 'package:meshcore_open/widgets/chat_composer.dart'; +import 'package:meshcore_open/widgets/connect_sheet.dart'; +import 'package:meshcore_open/widgets/gif_message.dart'; +import 'package:meshcore_open/widgets/message_translation_button.dart'; + +final _l10n = lookupAppLocalizations(const Locale('en')); + +class _Connector extends MeshCoreConnector { + bool connected = true; + + @override + bool get isConnected => connected; +} + +class _Harness { + final controller = TextEditingController(); + final focusNode = FocusNode(); + final connector = _Connector(); + late final AppSettingsService settings; + late final ChatBackgroundService backgrounds; + int sends = 0; + final actions = []; + + void dispose() { + controller.dispose(); + focusNode.dispose(); + connector.dispose(); + } +} + +Future<_Harness> _harness(WidgetTester tester) async { + final h = _Harness(); + // A date with no holiday nearby, so no holiday chat background applies. + h.settings = AppSettingsService(clock: () => DateTime(2026, 7, 1)); + await tester.runAsync(h.settings.loadSettings); + h.backgrounds = ChatBackgroundService( + h.settings, + imageStore: InMemoryChatBackgroundImageStore(), + ); + addTearDown(h.dispose); + return h; +} + +Widget _app( + _Harness h, { + int maxBytes = 160, + Widget? replyPreview, + bool disableAnimations = false, + Brightness brightness = Brightness.light, +}) { + final composer = ChatComposer( + controller: h.controller, + focusNode: h.focusNode, + maxBytes: maxBytes, + onSend: () => h.sends++, + sendTooltip: _l10n.chat_sendMessage, + actionsBuilder: () => [ + ChatComposerAction( + id: 'gif', + icon: Icons.gif_box, + label: _l10n.chat_sendGif, + ), + ], + onAction: h.actions.add, + replyPreview: replyPreview, + ); + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: h.connector), + ChangeNotifierProvider.value(value: h.settings), + ChangeNotifierProvider.value(value: h.backgrounds), + ], + child: MaterialApp( + theme: brightness == Brightness.light + ? MeshTheme.light() + : MeshTheme.dark(), + locale: const Locale('en'), + localizationsDelegates: const [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: disableAnimations), + child: child!, + ), + home: Scaffold( + body: ChatBackdrop( + chatKey: 'contact:test', + footer: composer, + child: const SizedBox.expand(), + ), + ), + ), + ); +} + +Finder get _plus => find.byTooltip(_l10n.chat_selectSendAction); +Finder get _send => find.byTooltip(_l10n.chat_sendMessage); +Finder get _bubble => find.byKey(ChatComposer.bubbleKey); + +Future _type(WidgetTester tester, String text) async { + await tester.enterText(find.byType(TextField), text); + await tester.pumpAndSettle(); +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + testWidgets('right circle is + when empty and Send with text', ( + tester, + ) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + // No separate "+" on the left: one round button only. + expect(_plus, findsOneWidget); + expect(_send, findsNothing); + expect(find.byIcon(Icons.add_circle_outline), findsNothing); + + // "+" opens the screen's action menu. + await tester.tap(_plus); + await tester.pumpAndSettle(); + await tester.tap(find.text(_l10n.chat_sendGif)); + await tester.pumpAndSettle(); + expect(h.actions, ['gif']); + + // Whitespace doesn't count as text. + await _type(tester, ' '); + expect(_plus, findsOneWidget); + + await _type(tester, 'On my way'); + expect(_plus, findsNothing); + expect(_send, findsOneWidget); + await tester.tap(_send); + expect(h.sends, 1); + + await _type(tester, ''); + expect(_plus, findsOneWidget); + expect(_send, findsNothing); + }); + + testWidgets('round button has a 48dp touch target and sits right of the ' + 'bubble', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final plus = find.widgetWithIcon(IconButton, Icons.add); + final size = tester.getSize(plus); + expect(size.width, greaterThanOrEqualTo(48)); + expect(size.height, greaterThanOrEqualTo(48)); + expect( + tester.getTopLeft(plus).dx, + greaterThanOrEqualTo(tester.getTopRight(_bubble).dx), + ); + // Single-line bubble is about one touch target tall. + expect(tester.getSize(_bubble).height, inInclusiveRange(44, 52)); + }); + + testWidgets('swap animates, and is instant with animations disabled', ( + tester, + ) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + // Mid-transition both icons are on screen. + expect(_plus, findsOneWidget); + expect(_send, findsOneWidget); + await tester.pumpAndSettle(); + expect(_plus, findsNothing); + + final reduced = await _harness(tester); + await tester.pumpWidget(_app(reduced, disableAnimations: true)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi'); + await tester.pump(); + await tester.pump(); + expect(_plus, findsNothing); + expect(_send, findsOneWidget); + }); + + testWidgets('field grows to 5 lines then scrolls, buttons stay at the ' + 'bottom', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 1000)); + await tester.pumpAndSettle(); + + final field = tester.widget(find.byType(TextField)); + expect(field.minLines, 1); + expect(field.maxLines, kComposerMaxLines); + + await _type(tester, 'one'); + final oneLine = tester.getSize(find.byType(TextField)).height; + final sendBottom = tester.getBottomLeft(_send).dy; + final bubbleBottom = tester.getBottomLeft(_bubble).dy; + + await _type(tester, List.filled(5, 'line').join('\n')); + final fiveLines = tester.getSize(find.byType(TextField)).height; + expect(fiveLines, greaterThan(oneLine * 2)); + + await _type(tester, List.filled(12, 'line').join('\n')); + expect(tester.getSize(find.byType(TextField)).height, fiveLines); + + // The panel grows upwards; the send button keeps its place at the + // bottom of the bubble. + expect(tester.getBottomLeft(_send).dy, sendBottom); + expect(tester.getBottomLeft(_bubble).dy, bubbleBottom); + }); + + testWidgets('a short window still lets the field wrap onto two lines', ( + tester, + ) async { + tester.view.physicalSize = const Size(600, 260); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 2.0; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 1000)); + await tester.pumpAndSettle(); + + expect( + tester.widget(find.byType(TextField)).maxLines, + greaterThanOrEqualTo(2), + ); + }); + + testWidgets('byte counter shows only past the warning threshold and ' + 'takes no space before', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h, maxBytes: 20)); + await tester.pumpAndSettle(); + final emptyHeight = tester.getSize(_bubble).height; + + await _type(tester, 'a' * 14); // 70 %: not past the threshold + expect(find.text('14 / 20'), findsNothing); + expect(tester.getSize(_bubble).height, emptyHeight); + + await _type(tester, 'a' * 15); + final counter = find.text('15 / 20'); + expect(counter, findsOneWidget); + expect(find.descendant(of: _bubble, matching: counter), findsOneWidget); + // Bottom-right of the bubble. + expect( + tester.getCenter(counter).dx, + greaterThan(tester.getCenter(_bubble).dx), + ); + expect( + tester.getCenter(counter).dy, + greaterThan(tester.getCenter(find.byType(TextField)).dy), + ); + + // The byte limit itself is unchanged. + await _type(tester, 'a' * 30); + expect(h.controller.text.length, 20); + }); + + testWidgets('ByteCountedTextField defaults are unchanged for other ' + 'screens', (tester) async { + final controller = TextEditingController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ByteCountedTextField(maxBytes: 20, controller: controller), + ), + ), + ); + final field = tester.widget(find.byType(TextField)); + expect(field.maxLines, isNull); + // The counter row keeps its place while hidden. + expect(find.text('0 / 20'), findsOneWidget); + }); + + testWidgets('reply preview renders inside the top of the bubble and can ' + 'be dismissed', (tester) async { + final h = await _harness(tester); + var dismissed = false; + await tester.pumpWidget( + _app( + h, + replyPreview: ChatComposerQuote( + title: _l10n.chat_replyingTo('Bob'), + content: const Text('see you at camp'), + onDismiss: () => dismissed = true, + dismissTooltip: _l10n.chat_cancelReply, + ), + ), + ); + await tester.pumpAndSettle(); + + final quote = find.byType(ChatComposerQuote); + expect(find.descendant(of: _bubble, matching: quote), findsOneWidget); + expect(find.text(_l10n.chat_replyingTo('Bob')), findsOneWidget); + expect( + tester.getBottomLeft(quote).dy, + lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy), + ); + + await tester.tap(find.byTooltip(_l10n.chat_cancelReply)); + expect(dismissed, isTrue); + }); + + testWidgets('GIF preview sits in the bubble, sends on Enter and can be ' + 'removed', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + h.controller.text = GifHelper.encodeGif('abc123'); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + + expect( + find.descendant(of: _bubble, matching: find.byType(GifMessage)), + findsOneWidget, + ); + expect(find.byType(TextField), findsNothing); + expect(_send, findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(h.sends, 1); + + await tester.tap(find.byTooltip(_l10n.chat_removeGif)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + expect(h.controller.text, isEmpty); + expect(find.byType(TextField), findsOneWidget); + expect(_plus, findsOneWidget); + }); + + testWidgets('translate button sits inside the bubble when enabled', ( + tester, + ) async { + final h = await _harness(tester); + await tester.runAsync(() => h.settings.setTranslationEnabled(true)); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final translate = find.byType(MessageTranslationButton); + expect(find.descendant(of: _bubble, matching: translate), findsOneWidget); + expect( + tester.getCenter(translate).dx, + greaterThan(tester.getCenter(find.byType(TextField)).dx), + ); + expect( + find.descendant(of: translate, matching: find.byType(Tooltip)), + findsOneWidget, + ); + }); + + testWidgets('panel is solid without a chat background and transparent ' + 'over one', (tester) async { + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + + final scheme = MeshTheme.light().colorScheme; + Color bubbleColor() => + ((tester.widget(_bubble).decoration as BoxDecoration) + .color) + as Color; + final panelFill = find.ancestor( + of: _bubble, + matching: find.byWidgetPredicate( + (w) => w is ColoredBox && w.color == scheme.surface, + ), + ); + expect(panelFill, findsOneWidget); + expect(bubbleColor(), scheme.surfaceContainerHigh); + + await tester.runAsync( + () => h.backgrounds.setChatBackground( + 'contact:test', + const ChatBackground.color(Color(0xFF1E3A8A)), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(ChatBackgroundLayer), findsOneWidget); + expect(panelFill, findsNothing); + // Incoming-bubble colour keeps the text readable over the background. + expect(bubbleColor(), scheme.surfaceContainerLow); + }); + + testWidgets('offline bar uses the same bubble and height as the composer', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final h = await _harness(tester); + await tester.pumpWidget(_app(h)); + await tester.pumpAndSettle(); + final composerTop = tester.getTopLeft(_bubble).dy; + final composerHeight = tester.getSize(_bubble).height; + + h.connector.connected = false; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + + expect(find.byType(OfflineComposerBar), findsOneWidget); + expect(find.byType(TextField), findsNothing); + expect(find.byType(ConnectButton), findsOneWidget); + expect(find.text(_l10n.chat_composerOffline), findsOneWidget); + final decoration = + tester.widget(_bubble).decoration as BoxDecoration; + expect( + decoration.borderRadius, + BorderRadius.circular(kComposerBubbleRadius), + ); + expect(tester.getSize(_bubble).height, composerHeight); + expect(tester.getTopLeft(_bubble).dy, composerTop); + + // The draft survives and comes back with the radio. + h.controller.text = 'draft'; + h.connector.connected = true; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(TextField)).controller?.text, + 'draft', + ); + }); + + for (final scale in [1.3, 2.0]) { + for (final brightness in Brightness.values) { + testWidgets('fits 320dp at ${scale}x text (${brightness.name})', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 568); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = scale; + addTearDown(tester.view.reset); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final h = await _harness(tester); + await tester.runAsync(() => h.settings.setTranslationEnabled(true)); + await tester.pumpWidget( + _app( + h, + maxBytes: 20, + brightness: brightness, + replyPreview: ChatComposerQuote( + title: _l10n.chat_replyingTo('A very long sender name here'), + content: const Text( + 'a long quoted message that must ellipsize', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + onDismiss: () {}, + dismissTooltip: _l10n.chat_cancelReply, + // A long region chip, as a channel reply shows. + trailing: Text( + _l10n.channels_regionSetTo('north-west-valley'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byTooltip(_l10n.chat_cancelReply), findsOneWidget); + await _type(tester, 'a' * 19); + expect(tester.takeException(), isNull); + + // With the keyboard up, a long draft still fits: the field caps its + // lines to the room left. + tester.view.viewInsets = const FakeViewPadding(bottom: 260); + await _type(tester, List.filled(8, 'line').join('\n')); + expect(tester.takeException(), isNull); + tester.view.resetViewInsets(); + await tester.pumpAndSettle(); + + h.connector.connected = false; + h.connector.notifyListeners(); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + } + } +}