diff --git a/lib/features/boards/views/boards_screen.dart b/lib/features/boards/views/boards_screen.dart index 0b7196a28..424026df8 100644 --- a/lib/features/boards/views/boards_screen.dart +++ b/lib/features/boards/views/boards_screen.dart @@ -30,6 +30,7 @@ import 'package:prism_plurality/shared/widgets/prism_segmented_control.dart'; import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; // --------------------------------------------------------------------------- // SharedPreferences key — persists the last viewed sub-tab index. @@ -183,16 +184,23 @@ class _BoardsScreenState extends ConsumerState { // Top bar // --------------------------------------------------------------------------- -class _BoardsTopBar extends StatelessWidget implements PreferredSizeWidget { +class _BoardsTopBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const _BoardsTopBar({required this.onComposeTap}); final VoidCallback onComposeTap; @override - Size get preferredSize => const Size.fromHeight(kToolbarHeight); + Size get preferredSize => const Size.fromHeight(PrismTokens.topBarHeight); @override - Widget build(BuildContext context) { + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + return _buildBar( + context, + ).preferredHeightFor(context, availableWidth: availableWidth); + } + + PrismTopBar _buildBar(BuildContext context) { return PrismTopBar( title: context.l10n.boardsScreenTitle, leading: const _BoardsMemberFilterButton(), @@ -206,6 +214,9 @@ class _BoardsTopBar extends StatelessWidget implements PreferredSizeWidget { ], ); } + + @override + Widget build(BuildContext context) => _buildBar(context); } // --------------------------------------------------------------------------- diff --git a/lib/features/boards/views/member_board_screen.dart b/lib/features/boards/views/member_board_screen.dart index 108526135..44da789f0 100644 --- a/lib/features/boards/views/member_board_screen.dart +++ b/lib/features/boards/views/member_board_screen.dart @@ -13,6 +13,7 @@ import 'package:prism_plurality/features/boards/widgets/board_actor_selector.dar import 'package:prism_plurality/features/members/providers/members_providers.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/widgets/clamped_body.dart'; import 'package:prism_plurality/shared/widgets/adaptive_detail_surface.dart'; import 'package:prism_plurality/shared/widgets/empty_state.dart'; @@ -21,6 +22,7 @@ import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; /// Full paginated list of public board posts by or about a given member. /// @@ -71,7 +73,7 @@ void _openMemberBoardPost(BuildContext context, String postId) { // --------------------------------------------------------------------------- class _MemberBoardTopBar extends StatelessWidget - implements PreferredSizeWidget { + implements PreferredSizeWidget, PrismScaledHeight { const _MemberBoardTopBar({ required this.member, required this.memberName, @@ -83,10 +85,19 @@ class _MemberBoardTopBar extends StatelessWidget final VoidCallback onComposeTap; @override - Size get preferredSize => const Size.fromHeight(kToolbarHeight); + Size get preferredSize => const Size.fromHeight(PrismTokens.topBarHeight); @override - Widget build(BuildContext context) { + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + return _buildBar( + context, + ).preferredHeightFor(context, availableWidth: availableWidth); + } + + @override + Widget build(BuildContext context) => _buildBar(context); + + PrismTopBar _buildBar(BuildContext context) { final l10n = context.l10n; final leadingAvatar = member != null diff --git a/lib/features/boards/widgets/board_message_section.dart b/lib/features/boards/widgets/board_message_section.dart index fe81869b7..6761e317f 100644 --- a/lib/features/boards/widgets/board_message_section.dart +++ b/lib/features/boards/widgets/board_message_section.dart @@ -70,14 +70,20 @@ class BoardMessageSection extends ConsumerWidget { color: theme.colorScheme.primary, ), const SizedBox(width: 8), - Text( - l10n.memberSectionBoardMessages, - style: theme.textTheme.labelLarge?.copyWith( - color: theme.colorScheme.primary, - fontWeight: FontWeight.w600, + // The title takes the leftover width and wraps; while it kept its + // intrinsic width behind a Spacer it pushed the actor selector and + // the compose action off the card (measured 80 / 127px over at + // 3.375x). Selector identity, actions and keys are unchanged. + Expanded( + child: Text( + l10n.memberSectionBoardMessages, + style: theme.textTheme.labelLarge?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w600, + ), ), ), - const Spacer(), + const SizedBox(width: 8), const BoardActorSelector(), PrismInlineIconButton( icon: AppIcons.add, diff --git a/lib/features/boards/widgets/post_tile.dart b/lib/features/boards/widgets/post_tile.dart index f4900f3e6..63314fcee 100644 --- a/lib/features/boards/widgets/post_tile.dart +++ b/lib/features/boards/widgets/post_tile.dart @@ -24,8 +24,13 @@ import 'package:prism_plurality/shared/widgets/prism_markdown_text.dart'; import 'package:prism_plurality/shared/widgets/member_avatar.dart'; import 'package:prism_plurality/shared/widgets/prism_dialog.dart'; import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_surface.dart'; +/// The same visibility word is rendered by the pill and measured by its header. +String _audienceLabel(String audience) => + audience == 'public' ? 'public' : 'private'; + // --------------------------------------------------------------------------- // Inline markdown stripper — for accessibility labels only. // --------------------------------------------------------------------------- @@ -272,43 +277,101 @@ class _PostTileContent extends ConsumerWidget { ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: _PostHeaderParticipants( - author: author, - target: target, - post: post, - authorColor: authorColor, - theme: theme, - l10n: l10n, - prefer: prefer, - ), - ), - const SizedBox(width: 8), - if (showAudiencePill) ...[ - _AudiencePill(audience: post.audience, theme: theme), - const SizedBox(width: 8), - ], - Text( - _formatTimestamp(post.writtenAt, context), + // Measured fit, not a container that reflows on its own: the metadata + // keeps today's inline position beside the participant strip whenever it + // fits next to the strip's non-shrinkable pieces, and a long user name + // keeps ellipsising on that one line. Only metadata that genuinely cannot + // fit - the 3.375x case that overflowed by 90px - takes its own line, and + // it then wraps internally rather than overflowing the card. + child: LayoutBuilder( + builder: (context, constraints) { + final timestampLabel = _formatTimestamp( + post.writtenAt, + context, + ); + final hasMenu = hasActions && isDesktopOrWeb; + final fitsInline = + _headerMetaWidth( + context, + theme: theme, + timestamp: timestampLabel, + audience: post.audience, + showAudiencePill: showAudiencePill, + hasMenu: hasMenu, + ) + + 8 + + _headerStripFixedWidth( + context, + theme: theme, + hasTargetAvatar: post.targetMemberId != null, + ) <= + constraints.maxWidth; + + final participants = _PostHeaderParticipants( + author: author, + target: target, + post: post, + authorColor: authorColor, + theme: theme, + l10n: l10n, + prefer: prefer, + ); + final timestamp = Text( + timestampLabel, style: theme.textTheme.labelMedium?.copyWith( color: theme.colorScheme.onSurfaceVariant.withValues( alpha: 0.7, ), fontSize: 11, ), - ), - if (hasActions && isDesktopOrWeb) ...[ - const SizedBox(width: 4), - _InlineMenuButton( - post: post, - viewerMember: viewerMember, - buildActions: _buildActions, - ), - ], - ], + ); + final pill = showAudiencePill + ? _AudiencePill(audience: post.audience, theme: theme) + : null; + final menu = hasMenu + ? _InlineMenuButton( + post: post, + viewerMember: viewerMember, + buildActions: _buildActions, + ) + : null; + + if (fitsInline) { + // Unchanged default geometry: names ellipsise, metadata inline. + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: participants), + const SizedBox(width: 8), + if (pill != null) ...[pill, const SizedBox(width: 8)], + timestamp, + if (menu != null) ...[const SizedBox(width: 4), menu], + ], + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: participants), + if (menu != null) ...[const SizedBox(width: 4), menu], + ], + ), + const SizedBox(height: 4), + Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 2, + children: [?pill, timestamp], + ), + ], + ); + }, ), ), ), @@ -406,6 +469,79 @@ class _PostTileContent extends ConsumerWidget { return card; } + /// Width of one line of [text] as the header paints it. + /// + /// [style] is the style handed to `Text`; [prismTextStyleForMeasurement] applies the + /// ambient [DefaultTextStyle] merge and the bold-text flag exactly as `Text` does, and + /// the painter gets the inherited locale and height behaviour, so the measured line and + /// the painted line resolve the same face. + double _headerLineWidth(BuildContext context, String text, TextStyle? style) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final width = painter.width; + painter.dispose(); + return width; + } + + /// Width the header metadata needs side by side, from the strings and styles it + /// actually renders: the visibility word in the pill (+ its 16dp padding and the + /// 8dp gap before it), the formatted timestamp, and the desktop menu when present. + double _headerMetaWidth( + BuildContext context, { + required ThemeData theme, + required String timestamp, + required String audience, + required bool showAudiencePill, + required bool hasMenu, + }) { + var width = _headerLineWidth( + context, + timestamp, + theme.textTheme.labelMedium?.copyWith(fontSize: 11), + ); + if (showAudiencePill) { + width += + 8 + + 16 + + _headerLineWidth( + context, + _audienceLabel(audience), + theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.w600, + fontSize: 10, + ), + ); + } + if (hasMenu) width += 4 + 26; // 4dp gap + the 18dp icon in its 4dp padding. + return width; + } + + /// Width the participant strip cannot give away: the author avatar and its gap, the + /// gaps around the "to" connector, the connector itself, and the target avatar when + /// the post has one. Both names are flexible and ellipsise, so they count as zero - + /// a long name must never force the metadata off the line on its own. + double _headerStripFixedWidth( + BuildContext context, { + required ThemeData theme, + required bool hasTargetAvatar, + }) { + final to = _headerLineWidth( + context, + 'to', + theme.textTheme.labelMedium?.copyWith(fontSize: 12), + ); + return 22 + 6 + 8 + to + 8 + (hasTargetAvatar ? 22 + 6 : 0); + } + String _formatTimestamp(DateTime dt, BuildContext context) { final diff = DateTime.now().difference(dt); if (diff.inSeconds < 60) return 'just now'; @@ -550,7 +686,7 @@ class _AudiencePill extends StatelessWidget { borderRadius: BorderRadius.circular(PrismShapes.of(context).radius(8)), ), child: Text( - isPublic ? 'public' : 'private', + _audienceLabel(audience), style: theme.textTheme.labelSmall?.copyWith( color: color, fontWeight: FontWeight.w600, diff --git a/lib/features/chat/emoji/emoji_name_completion.dart b/lib/features/chat/emoji/emoji_name_completion.dart new file mode 100644 index 000000000..657cc26f8 --- /dev/null +++ b/lib/features/chat/emoji/emoji_name_completion.dart @@ -0,0 +1,465 @@ +/// Colon-triggered Unicode emoji name completion for the chat composer. +/// +/// Scope is deliberately narrow: this turns `:prefix` typed at the caret into a +/// bounded list of matches from the emoji data the app already ships for the +/// picker ([prismEmojiSet]). It adds no data, no custom/uploaded emoji, no +/// network call and no per-system schema. +/// +/// Token rules and ranking are pure Dart so they can be tested without a widget +/// tree; the code-context guard borrows the chat renderer's own Markdown +/// grammar rather than re-implementing it. +library; + +import 'dart:convert'; + +import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:markdown/markdown.dart' as md; +import 'package:prism_plurality/features/chat/utils/chat_markdown_syntax.dart'; +import 'package:prism_plurality/shared/emoji/prism_emoji_set.dart'; + +/// Upper bound on rows shown for one query. +const int emojiCompletionMaxResults = 8; + +/// Longest `:name` token body that may open the completion popup. +const int emojiCompletionMaxPrefixLength = 40; + +/// Characters allowed in a token body (`:grinning_face`, `:upside-down`, ...). +final RegExp _nameBodyRegex = RegExp(r'^[a-z0-9_+\-]+$'); + +final RegExp _nameCharRegex = RegExp(r'^[A-Za-z0-9_+\-]$'); + +/// Characters that may directly precede the trigger `:`. +/// +/// Start-of-draft, whitespace and opening delimiters only. This single rule +/// rejects URL schemes (a colon after a letter) and clock times (a colon after +/// a digit) without a URL or time parser. +const String _triggerPrecedingChars = ' \t\n\r([{<"\''; + +/// Code points that must never be split by an insertion at the caret: +/// combining marks, ZWJ, the emoji variation selector, skin-tone modifiers and +/// regional indicators (flag halves). +final RegExp _clusterContinuingRegex = RegExp( + r'^[\p{M}\u200D\uFE0F\u{1F3FB}-\u{1F3FF}\u{1F1E6}-\u{1F1FF}]$', + unicode: true, +); + +/// Anything that could possibly start a code construct: a backtick or tilde +/// fence, inline code, a blockquote, a tab-indented line, or an indented code +/// line. A draft without any of these cannot contain code, so it never needs a +/// parse - that keeps long plain text completing without an AST. +final RegExp _codeStarterRegex = RegExp(r'[`~>\t]|^ {4}', multiLine: true); + +/// First of the 32 Unicode noncharacters used as analysis-only markers. +const int _firstMarkerCodeUnit = 0xFDD0; + +/// Number of marker candidates (U+FDD0..U+FDEF). +const int _markerCandidateCount = 0x20; + +/// A live `:name` token whose caret sits at the end of the token. +@immutable +class EmojiCompletionTrigger { + const EmojiCompletionTrigger({ + required this.start, + required this.end, + required this.prefix, + }); + + /// Index of the trigger `:` in the draft. + final int start; + + /// Caret offset; the token is replaced in `[start, end)`. + final int end; + + /// Lowercased token body typed after the `:`. + final String prefix; + + @override + bool operator ==(Object other) => + other is EmojiCompletionTrigger && + other.start == start && + other.end == end && + other.prefix == prefix; + + @override + int get hashCode => Object.hash(start, end, prefix); + + @override + String toString() => + 'EmojiCompletionTrigger(start: $start, end: $end, prefix: $prefix)'; +} + +/// Detect a `:name` completion token for [selection] in [text]. +/// +/// Returns null for anything that is not a single, unambiguous token ending at +/// a collapsed caret: ranges, half-typed names, URL schemes, clock times, code +/// spans and blocks, over-long tokens and grapheme-cluster interiors. +EmojiCompletionTrigger? detectEmojiCompletionTrigger( + String text, + TextSelection selection, { + TextRange composing = TextRange.empty, +}) { + if (!selection.isValid || !selection.isCollapsed) return null; + return detectEmojiCompletionTriggerAt( + text, + selection.baseOffset, + composing: composing, + ); +} + +/// [detectEmojiCompletionTrigger] for a raw caret offset. +EmojiCompletionTrigger? detectEmojiCompletionTriggerAt( + String text, + int caret, { + TextRange composing = TextRange.empty, +}) { + if (caret < 1 || caret > text.length) return null; + + // An active IME composition owns the text around the caret: completing it + // would fight the input method and could split a composed character. + if (composing.isValid && !composing.isCollapsed) return null; + + // The caret must not sit inside a grapheme cluster, and must sit at the end + // of the token: a caret in the middle of `:smile` has no single meaning. + if (caret < text.length) { + if (_isClusterContinuingAt(text, caret)) return null; + if (_isNameCharacterAt(text, caret)) return null; + } + + final colonIndex = text.lastIndexOf(':', caret - 1); + if (colonIndex < 0) return null; + + if (colonIndex > 0 && + !_triggerPrecedingChars.contains(text[colonIndex - 1])) { + return null; + } + + final body = text.substring(colonIndex + 1, caret); + if (body.isEmpty || body.length > emojiCompletionMaxPrefixLength) { + return null; + } + final prefix = body.toLowerCase(); + if (!_nameBodyRegex.hasMatch(prefix)) return null; + + // Markdown code context: a colon inside `code` or a fenced block is literal + // text, not a completion trigger. + if (isInsideCodeContext(text, colonIndex)) return null; + + return EmojiCompletionTrigger(start: colonIndex, end: caret, prefix: prefix); +} + +/// Whether the `:` at [colon] in [draft] sits inside code the chat renderer +/// would parse as code. +/// +/// [colon] must be the `:` of an already validated `:name` token; anything else +/// fails closed, because substituting a different character could change the +/// structure the probe relies on. +/// +/// The full draft is parsed with the same grammar and preprocessing as the +/// message bubble ([chatExtensionSet], [escapeLeadingHeadings]) after a single +/// analysis-only noncharacter replaces the colon, so a closing backtick *after* +/// the caret is still seen. The draft itself is never modified, and the marker +/// never reaches the controller, the draft cache or a sent message. +/// +/// Nothing is cached here: the work is bounded per call (token checks, then a +/// parse of at most [chatMarkdownParseLimit] characters) and no draft or AST is +/// retained afterwards, so a long draft cannot outlive the composer through this +/// check. The only cache in this library is the emoji search memo in +/// [EmojiNameIndex], which holds the normalized prefix and limit, never a draft. +bool isInsideCodeContext(String draft, int colon) { + if (colon < 0 || colon >= draft.length) return false; + if (draft.codeUnitAt(colon) != 0x3A) return true; // not a token colon + + // Cheap necessary condition first: a draft with no code starter cannot hold + // code, so long plain text still completes without building an AST. + if (!_codeStarterRegex.hasMatch(draft)) return false; + + return _classifyCodeContext(draft, colon); +} + +bool _classifyCodeContext(String draft, int colon) { + // Shared renderer budget: over it we do not parse, and only the optional + // suggestions hide. Input, draft, selection and send are untouched. + if (draft.length > chatMarkdownParseLimit) return true; + + final marker = _chooseMarker(draft); + if (marker == null) return true; // every candidate occurs: fail closed + + final probe = escapeLeadingHeadings( + draft.replaceRange(colon, colon + 1, marker), + ); + if (probe.length > chatMarkdownParseLimit) return true; + + final List nodes; + try { + nodes = _parseChatMarkdown(probe); + } catch (_) { + return true; // fail closed rather than guess + } + + final survived = nodes.any((node) => node.textContent.contains(marker)); + if (!survived) return true; // consumed by a destination, title, info string + if (_markerInsideCode(nodes, marker)) return true; + + // Conservative editing intent: a span the user is still typing stays + // suppressed even though the renderer shows literal text (see + // `_opensUnfinishedSpanOnCaretLine`). + return _opensUnfinishedSpanOnCaretLine(draft, colon); +} + +/// The analysis probe for [draft] with the marker substituted at [colon]. +/// +/// Test-only: it supports the marker-invariance and collision assertions (the +/// probe must parse to the same tree as the draft, with the colon swapped for a +/// noncharacter). Production code goes through [isInsideCodeContext]. +@visibleForTesting +String emojiCodeContextProbe(String draft, int colon) { + final marker = + _chooseMarker(draft) ?? String.fromCharCode(_firstMarkerCodeUnit); + return escapeLeadingHeadings(draft.replaceRange(colon, colon + 1, marker)); +} + +/// Pick the first noncharacter (U+FDD0..U+FDEF) that the draft does not already +/// contain, so the analysis marker is unambiguous. +String? _chooseMarker(String draft) { + for (var i = 0; i < _markerCandidateCount; i++) { + final candidate = String.fromCharCode(_firstMarkerCodeUnit + i); + if (!draft.contains(candidate)) return candidate; + } + return null; +} + +List _parseChatMarkdown(String text) { + final document = md.Document( + extensionSet: chatExtensionSet, + encodeHtml: false, + ); + return document.parseLines(const LineSplitter().convert(text)); +} + +bool _markerInsideCode(List nodes, String marker) { + var inside = false; + void visit(md.Node node) { + if (inside || node is! md.Element) return; + if ((node.tag == 'code' || node.tag == 'pre') && + node.textContent.contains(marker)) { + inside = true; + return; + } + for (final child in node.children ?? const []) { + visit(child); + } + } + + for (final node in nodes) { + visit(node); + } + return inside; +} + +/// Whether the colon sits after an unescaped backtick run on its own line that +/// no equal-length run closes later in the draft. +/// +/// This is the one deliberate deviation from final-render parity: while a span is +/// still being typed, completion stays suppressed. Restricting it to the colon's +/// line keeps an escaped backtick, a closed multiline span, and stray runs from +/// an earlier line from suppressing ordinary text. +bool _opensUnfinishedSpanOnCaretLine(String draft, int colon) { + final lineStart = draft.lastIndexOf('\n', colon - 1) + 1; + final openRuns = <({int length, int start})>[]; + var index = 0; + while (index < draft.length) { + if (draft.codeUnitAt(index) != 0x60) { + index++; + continue; + } + var runLength = 1; + while (index + runLength < draft.length && + draft.codeUnitAt(index + runLength) == 0x60) { + runLength++; + } + if (!_isEscapedAt(draft, index)) { + final matching = openRuns.lastIndexWhere( + (run) => run.length == runLength, + ); + if (matching >= 0) { + openRuns.removeAt(matching); + } else { + openRuns.add((length: runLength, start: index)); + } + } + index += runLength; + } + return openRuns.any((run) => run.start >= lineStart && run.start < colon); +} + +bool _isEscapedAt(String text, int index) { + var backslashes = 0; + var cursor = index - 1; + while (cursor >= 0 && text.codeUnitAt(cursor) == 0x5C) { + backslashes++; + cursor--; + } + return backslashes.isOdd; +} + +bool _isNameCharacterAt(String text, int index) { + final codePoint = _codePointAt(text, index); + return _nameCharRegex.hasMatch(String.fromCharCode(codePoint)); +} + +bool _isClusterContinuingAt(String text, int index) { + final codePoint = _codePointAt(text, index); + return _clusterContinuingRegex.hasMatch(String.fromCharCode(codePoint)); +} + +int _codePointAt(String text, int index) { + final unit = text.codeUnitAt(index); + final isHighSurrogate = unit >= 0xD800 && unit <= 0xDBFF; + if (!isHighSurrogate || index + 1 >= text.length) return unit; + final next = text.codeUnitAt(index + 1); + if (next < 0xDC00 || next > 0xDFFF) return unit; + return 0x10000 + ((unit - 0xD800) << 10) + (next - 0xDC00); +} + +/// Pre-built, lowercased index over one emoji catalog. +/// +/// The index is built once per catalog and reused; queries keep a single-entry +/// memo (last prefix to results), so there is no unbounded prefix cache. +class EmojiNameIndex { + EmojiNameIndex._(this._entries); + + /// Index over the shipped picker catalog. + static final EmojiNameIndex catalog = EmojiNameIndex.fromCategories( + prismEmojiSet, + ); + + /// Build an index from an arbitrary catalog, e.g. a fixture in tests. + factory EmojiNameIndex.fromCategories(List categories) { + final seen = {}; + final entries = <_IndexedEmoji>[]; + for (final category in categories) { + for (final emoji in category.emoji) { + if (!seen.add(emoji.emoji)) continue; + final keywords = emoji.keywords + .where((keyword) => keyword.isNotEmpty) + .toList(growable: false); + if (keywords.isEmpty) continue; + // The first keyword segment is the CLDR annotation + // (`grinning face | grinning | face | ...`). + entries.add( + _IndexedEmoji( + emoji: emoji, + label: keywords.first, + primary: keywords.first.toLowerCase(), + keywords: keywords + .map((keyword) => keyword.toLowerCase()) + .toList(growable: false), + ), + ); + } + } + return EmojiNameIndex._(List<_IndexedEmoji>.unmodifiable(entries)); + } + + final List<_IndexedEmoji> _entries; + String? _memoPrefix; + int? _memoLimit; + List _memoResults = const []; + + /// Matches for [prefix], best first, at most [limit] rows. + /// + /// The single cache entry is keyed by the normalized prefix **and** the + /// effective limit, so changing either recomputes (a longer list must never + /// be served for a smaller request). Empty input and non-positive limits + /// return an empty list without touching the entry. + List search(String prefix, {int limit = emojiCompletionMaxResults}) { + final query = prefix.trim().toLowerCase(); + if (query.isEmpty || limit <= 0) return const []; + // Callers cannot raise the popup's row cap. + final effectiveLimit = limit > emojiCompletionMaxResults + ? emojiCompletionMaxResults + : limit; + if (_memoPrefix == query && _memoLimit == effectiveLimit) { + return _memoResults; + } + + final scored = <(int, _IndexedEmoji)>[]; + for (final entry in _entries) { + final tier = entry.tierFor(query); + if (tier != null) scored.add((tier, entry)); + } + + scored.sort((a, b) { + final byTier = a.$1.compareTo(b.$1); + if (byTier != 0) return byTier; + final byLabelLength = a.$2.label.length.compareTo(b.$2.label.length); + if (byLabelLength != 0) return byLabelLength; + return a.$2.emoji.emoji.compareTo(b.$2.emoji.emoji); + }); + + final results = List.unmodifiable( + scored.take(effectiveLimit).map((scoredEntry) => scoredEntry.$2.emoji), + ); + _memoPrefix = query; + _memoLimit = effectiveLimit; + _memoResults = results; + return results; + } +} + +/// Convenience wrapper over [EmojiNameIndex.catalog]. +List searchEmojiNames( + String prefix, { + int limit = emojiCompletionMaxResults, + EmojiNameIndex? index, +}) { + return (index ?? EmojiNameIndex.catalog).search(prefix, limit: limit); +} + +class _IndexedEmoji { + const _IndexedEmoji({ + required this.emoji, + required this.label, + required this.primary, + required this.keywords, + }); + + final Emoji emoji; + + /// Annotation in its shipped casing, used for display and accessibility. + final String label; + + /// Lowercased annotation. + final String primary; + + /// Lowercased keyword segments, including the annotation itself. + final List keywords; + + /// Rank of this emoji for [query], or null when it does not match. + /// + /// 0 exact annotation, 1 annotation prefix, 2 exact keyword, 3 keyword + /// prefix, 4 annotation word-boundary substring, 5 keyword substring. + int? tierFor(String query) { + if (primary == query) return 0; + if (primary.startsWith(query)) return 1; + + var exactKeyword = false; + var prefixKeyword = false; + var containsKeyword = false; + for (final keyword in keywords) { + if (keyword == query) { + exactKeyword = true; + break; + } + if (keyword.startsWith(query)) prefixKeyword = true; + if (!containsKeyword && keyword.contains(query)) containsKeyword = true; + } + if (exactKeyword) return 2; + if (prefixKeyword) return 3; + if (primary.contains(' $query')) return 4; + if (containsKeyword) return 5; + return null; + } +} diff --git a/lib/features/chat/utils/chat_markdown_syntax.dart b/lib/features/chat/utils/chat_markdown_syntax.dart index 9527863ad..1ed2e9387 100644 --- a/lib/features/chat/utils/chat_markdown_syntax.dart +++ b/lib/features/chat/utils/chat_markdown_syntax.dart @@ -334,6 +334,13 @@ void debugResetChatStylesheetCache() { // Extension set // --------------------------------------------------------------------------- +/// Longest text the chat pipeline parses as Markdown. +/// +/// Shared by the message bubble's render fast path and the composer's `:name` +/// code-context check so the two cannot drift. Above this length the bubble +/// renders plain text, and the composer hides its optional emoji suggestions. +const int chatMarkdownParseLimit = 2000; + /// CommonMark block syntaxes + [SpoilerSyntax] and [MentionSyntax] inline, /// for chat rendering. final md.ExtensionSet chatExtensionSet = diff --git a/lib/features/chat/views/chat_screen.dart b/lib/features/chat/views/chat_screen.dart index cca8bc0fe..e83f64227 100644 --- a/lib/features/chat/views/chat_screen.dart +++ b/lib/features/chat/views/chat_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -39,6 +40,7 @@ import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; import 'package:prism_plurality/shared/widgets/sliver_pinned_top_bar.dart'; import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; import 'package:prism_plurality/shared/widgets/prism_popup_menu.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; const _kLastChatSubTabKey = 'chat.last_sub_tab'; @@ -49,6 +51,12 @@ const _kGroupChatsTabPreferenceValue = 1; enum _ChatSubTab { directMessages, groupChats } +/// Room the chat list keeps below its pinned bar + switcher header before the +/// header gives up pinning and scrolls with the content: enough for a couple of +/// conversation tiles. Only this composite header opts in; a plain bar keeps the +/// default (pinned whenever it fits at all). +const double _chatHeaderMinBodyExtent = 120.0; + /// Main conversation list screen. class ChatScreen extends ConsumerStatefulWidget { const ChatScreen({super.key}); @@ -526,17 +534,32 @@ class _ChatScreenState extends ConsumerState }, child: CustomScrollView( slivers: [ - SliverPinnedTopBar( - child: _ChatTopBar( - activeTab: _activeTab, - onTabSelected: _selectTab, - speakingAs: speakingAs, - hasArchived: hasArchived, - showArchived: showArchived, - onSearchTap: () => context.go('${AppRoutePaths.chat}/search'), - onArchiveTap: () => - ref.read(showArchivedProvider.notifier).toggle(), - onCreateTap: () => _showCreateSheet(context), + // The unread counts are watched here, around the header alone, so a + // badge change rebuilds the pinned bar instead of re-enumerating the + // whole conversation list. The counts reach the bar as immutable + // fields, so the measured height and the rendered switcher always see + // the same badges. + Consumer( + builder: (context, ref, _) => SliverPinnedTopBar( + // This header is a bar plus a switcher and grows with the text + // scale, so on a viewport too short for both it and a usable list + // (landscape with the keyboard up) it scrolls instead of + // squeezing the list away. Ordinary bars keep the default (pinned + // whenever they fit). + minBodyExtent: _chatHeaderMinBodyExtent, + child: _ChatTopBar( + activeTab: _activeTab, + onTabSelected: _selectTab, + speakingAs: speakingAs, + hasArchived: hasArchived, + showArchived: showArchived, + onSearchTap: () => context.go('${AppRoutePaths.chat}/search'), + onArchiveTap: () => + ref.read(showArchivedProvider.notifier).toggle(), + onCreateTap: () => _showCreateSheet(context), + groupUnread: ref.watch(unreadGroupCountProvider), + dmUnread: ref.watch(unreadDmCountProvider), + ), ), ), @@ -840,7 +863,8 @@ class _PickSpeakerBanner extends StatelessWidget { } } -class _ChatTopBar extends ConsumerWidget implements PreferredSizeWidget { +class _ChatTopBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const _ChatTopBar({ required this.activeTab, required this.onTabSelected, @@ -850,6 +874,8 @@ class _ChatTopBar extends ConsumerWidget implements PreferredSizeWidget { required this.onSearchTap, required this.onArchiveTap, required this.onCreateTap, + required this.groupUnread, + required this.dmUnread, }); final _ChatSubTab activeTab; @@ -861,58 +887,108 @@ class _ChatTopBar extends ConsumerWidget implements PreferredSizeWidget { final VoidCallback onArchiveTap; final VoidCallback onCreateTap; + /// Immutable unread counts, read once by the parent so the measured height and + /// the rendered switcher always see the same badges. + final int groupUnread; + final int dmUnread; + + /// Padding around the tab switcher. + static const double _switcherVerticalPadding = 8; + static const double _switcherHorizontalPadding = 16; + @override - Size get preferredSize => - const Size.fromHeight(PrismTokens.topBarHeight + 60); + Size get preferredSize => const Size.fromHeight( + PrismTokens.topBarHeight + + _switcherVerticalPadding * 2 + + kPrismSegmentedControlMinHeight, + ); + + /// Exact extent of the pinned band: the bar's measured height plus the padding + /// and the switcher's own height at the same width and the same badges. + /// [build] composes the identical children, so the band can neither clip them + /// nor leave a gap. + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + final barHeight = _buildBar( + context, + ).preferredHeightFor(context, availableWidth: availableWidth); + return barHeight + + _switcherVerticalPadding * 2 + + _switcherHeight(context, availableWidth); + } + + PrismTopBar _buildBar(BuildContext context) { + return PrismTopBar( + title: context.l10n.chatTitle, + leading: const _ChatMemberSelectorButton(), + actions: [ + PrismTopBarAction( + icon: AppIcons.add, + tooltip: context.l10n.chatNewConversation, + onPressed: onCreateTap, + ), + _OverflowMenuButton( + speakingAs: speakingAs, + hasArchived: hasArchived, + showArchived: showArchived, + onSearchTap: onSearchTap, + onArchiveTap: onArchiveTap, + ), + ], + ); + } + + PrismSegmentedControl<_ChatSubTab> _buildSwitcher(BuildContext context) { + return PrismSegmentedControl<_ChatSubTab>( + segments: [ + PrismSegment( + value: _ChatSubTab.groupChats, + label: context.l10n.chatTabGroupChats, + badgeCount: groupUnread, + badgeSemanticLabel: groupUnread > 0 + ? context.l10n.chatUnreadGroupsBadge(groupUnread) + : null, + ), + PrismSegment( + value: _ChatSubTab.directMessages, + label: context.l10n.chatTabDirectMessages, + badgeCount: dmUnread, + badgeSemanticLabel: dmUnread > 0 + ? context.l10n.chatUnreadDmsBadge(dmUnread) + : null, + ), + ], + selected: activeTab, + onChanged: onTabSelected, + ); + } + + /// Height of the switcher's track at the ambient text scale, measured by the + /// control itself at the width it will really be given (the band minus its + /// horizontal padding) and with the badges it will really render. + /// + /// [PrismSegmentedControl] implements [PrismScaledHeight], so there is no + /// fallback branch to keep here. + double _switcherHeight(BuildContext context, double? availableWidth) { + final width = availableWidth == null + ? null + : math.max(0.0, availableWidth - _switcherHorizontalPadding * 2); + return _buildSwitcher( + context, + ).preferredHeightFor(context, availableWidth: width); + } @override - Widget build(BuildContext context, WidgetRef ref) { - final dmUnread = ref.watch(unreadDmCountProvider); - final groupUnread = ref.watch(unreadGroupCountProvider); + Widget build(BuildContext context) { return Column( children: [ - PrismTopBar( - title: context.l10n.chatTitle, - leading: const _ChatMemberSelectorButton(), - actions: [ - PrismTopBarAction( - icon: AppIcons.add, - tooltip: context.l10n.chatNewConversation, - onPressed: onCreateTap, - ), - _OverflowMenuButton( - speakingAs: speakingAs, - hasArchived: hasArchived, - showArchived: showArchived, - onSearchTap: onSearchTap, - onArchiveTap: onArchiveTap, - ), - ], - ), + _buildBar(context), Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: PrismSegmentedControl<_ChatSubTab>( - segments: [ - PrismSegment( - value: _ChatSubTab.groupChats, - label: context.l10n.chatTabGroupChats, - badgeCount: groupUnread, - badgeSemanticLabel: groupUnread > 0 - ? context.l10n.chatUnreadGroupsBadge(groupUnread) - : null, - ), - PrismSegment( - value: _ChatSubTab.directMessages, - label: context.l10n.chatTabDirectMessages, - badgeCount: dmUnread, - badgeSemanticLabel: dmUnread > 0 - ? context.l10n.chatUnreadDmsBadge(dmUnread) - : null, - ), - ], - selected: activeTab, - onChanged: onTabSelected, + padding: const EdgeInsets.symmetric( + horizontal: _switcherHorizontalPadding, + vertical: _switcherVerticalPadding, ), + child: _buildSwitcher(context), ), ], ); diff --git a/lib/features/chat/views/conversation_screen.dart b/lib/features/chat/views/conversation_screen.dart index 9451e9bf7..498f7a989 100644 --- a/lib/features/chat/views/conversation_screen.dart +++ b/lib/features/chat/views/conversation_screen.dart @@ -24,6 +24,7 @@ import 'package:prism_plurality/shared/widgets/prism_glass_icon_button.dart'; import 'package:prism_plurality/shared/widgets/prism_loading_state.dart'; import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; /// Full chat view for a single conversation. @@ -182,25 +183,31 @@ class _ConversationScreenState extends ConsumerState { // Mark conversation as read when opened. _markAsReadIfNeeded(); - return Scaffold( - appBar: PrismGlassAppBar( - title: _conversationTitle(context, ref, conversation), - leading: widget.showBackButton - ? PrismGlassIconButton( - icon: AppIcons.arrowBackIosNewRounded, - iconSize: 18, - tooltip: context.l10n.back, - onPressed: () => context.pop(), - ) - : null, - trailing: PrismGlassIconButton( - icon: AppIcons.infoOutlineRounded, - iconSize: 20, - tooltip: context.l10n.chatConversationInfo, - onPressed: () => - ConversationInfoSheet.show(context, widget.conversationId), - ), + // `Scaffold.appBar` caps its child at the declared preferred size and + // adds the status padding to that cap itself, so the declared height is + // the bar's *content* height (the bar's own SafeArea consumes the inset). + // Everywhere else the pinned sliver asks the bar directly. + final appBar = PrismGlassAppBar( + title: _conversationTitle(context, ref, conversation), + leading: widget.showBackButton + ? PrismGlassIconButton( + icon: AppIcons.arrowBackIosNewRounded, + iconSize: 18, + tooltip: context.l10n.back, + onPressed: () => context.pop(), + ) + : null, + trailing: PrismGlassIconButton( + icon: AppIcons.infoOutlineRounded, + iconSize: 20, + tooltip: context.l10n.chatConversationInfo, + onPressed: () => + ConversationInfoSheet.show(context, widget.conversationId), ), + ); + + return Scaffold( + appBar: prismScaledPreferredSize(context, appBar), body: GestureDetector( onTap: () => FocusScope.of(context).unfocus(), behavior: HitTestBehavior.translucent, @@ -451,9 +458,7 @@ String _conversationTitle( .where((id) => id != speakingAs) .map( (id) => - participantMap[id]?.effectiveName( - preferDisplayName: prefer, - ) ?? + participantMap[id]?.effectiveName(preferDisplayName: prefer) ?? context.l10n.unknown, ) .toList(); diff --git a/lib/features/chat/views/create_conversation_sheet.dart b/lib/features/chat/views/create_conversation_sheet.dart index ed50e949f..d7e70cba3 100644 --- a/lib/features/chat/views/create_conversation_sheet.dart +++ b/lib/features/chat/views/create_conversation_sheet.dart @@ -27,6 +27,7 @@ import 'package:prism_plurality/shared/widgets/member_search_sheet.dart'; import 'package:prism_plurality/shared/widgets/selected_member_picker.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/widgets/unsaved_changes_guard.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; /// Bottom sheet for creating a new conversation (DM or group). /// @@ -586,7 +587,15 @@ class _CreateConversationSheetState child: SafeArea( child: LayoutBuilder( builder: (context, constraints) { - if (constraints.maxHeight < PrismTokens.topBarHeight) { + // Compare against the height the bar actually needs: it grows with + // the ambient text scale, so the fixed 66dp would route a bar that + // no longer fits into the Column branch. + final barHeight = prismScaledHeightOf( + context, + topBar, + availableWidth: constraints.maxWidth, + ); + if (constraints.maxHeight < barHeight) { return CustomScrollView( controller: widget.scrollController, slivers: buildBodySlivers(includeTopBar: true), diff --git a/lib/features/chat/widgets/chat_message_text.dart b/lib/features/chat/widgets/chat_message_text.dart index 09878e0fc..dbd20983f 100644 --- a/lib/features/chat/widgets/chat_message_text.dart +++ b/lib/features/chat/widgets/chat_message_text.dart @@ -55,7 +55,7 @@ class ChatMessageText extends StatefulWidget { } class _ChatMessageTextState extends State { - static const int _fastPathThreshold = 2000; + static const int _fastPathThreshold = chatMarkdownParseLimit; final _revealController = SpoilerRevealController(); final _segmentRevealControllers = {}; diff --git a/lib/features/chat/widgets/emoji_name_completion_overlay.dart b/lib/features/chat/widgets/emoji_name_completion_overlay.dart new file mode 100644 index 000000000..27352e729 --- /dev/null +++ b/lib/features/chat/widgets/emoji_name_completion_overlay.dart @@ -0,0 +1,301 @@ +import 'dart:async'; +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:prism_plurality/shared/theme/prism_shapes.dart'; +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; + +/// Glassmorphism completion list for `:name` Unicode emoji tokens. +/// +/// Shows the bounded matches produced by +/// `detectEmojiCompletionTrigger`/`searchEmojiNames` above the composer field. +/// Touch: tap a row. Keyboard: Up/Down move, Enter/Tab select, Escape dismisses +/// (the composer owns dismissal and the mention chooser keeps priority). +class EmojiNameCompletionOverlay extends StatefulWidget { + const EmojiNameCompletionOverlay({ + super.key, + required this.matches, + required this.onSelect, + required this.availableWidth, + required this.availableHeight, + }); + + /// Bounded matches, best first. An empty list renders nothing at all. + final List matches; + + /// Called with the chosen emoji; the composer replaces the token. + final ValueChanged onSelect; + + /// Width available from the anchored composer field. + final double availableWidth; + + /// Height available above the composer field (already excludes the keyboard + /// and the safe area). The list shrinks to this instead of being clipped. + final double availableHeight; + + /// Key for the popup surface, used by layout tests. + static const Key surfaceKey = Key('emojiNameCompletionSurface'); + + @override + State createState() => + EmojiNameCompletionOverlayState(); +} + +class EmojiNameCompletionOverlayState + extends State { + /// Highlighted row. Reset to the best match whenever the matches change so + /// Enter always inserts the top match for the current prefix. + int _highlightedIndex = 0; + + /// Attached to the highlighted row so keyboard navigation scrolls it into + /// view when the list is taller than the popup. + final _highlightedRowKey = GlobalKey(); + + /// Rows that fit in the popup before scrolling. + static const double _maxListHeight = 240; + + @override + void didUpdateWidget(covariant EmojiNameCompletionOverlay oldWidget) { + super.didUpdateWidget(oldWidget); + if (!_sameMatches(oldWidget.matches, widget.matches) || + _highlightedIndex >= widget.matches.length) { + _highlightedIndex = 0; + } + } + + static bool _sameMatches(List a, List b) { + if (identical(a, b)) return true; + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i].emoji != b[i].emoji) return false; + } + return true; + } + + /// Size the popup would occupy, or null when the popup renders nothing. + /// + /// [build] and [handleKeyEvent] share this single predicate: a popup with no + /// usable geometry paints nothing, so it must not consume navigation or + /// selection keys either. Without that, a hidden popup would swallow Enter and + /// insert an emoji the user never saw. + ({double width, double height})? _surfaceGeometry() { + if (widget.matches.isEmpty) return null; + final width = math.min(widget.availableWidth, _maxPopupWidth); + final height = math.min( + math.max(widget.availableHeight, 0.0), + _maxListHeight, + ); + if (width < _minUsableWidth || height <= 0) return null; + return (width: width, height: height); + } + + /// Handle keyboard navigation. Returns true if the event was consumed. + bool handleKeyEvent(KeyEvent event) { + if (event is! KeyDownEvent) return false; + if (_surfaceGeometry() == null) return false; + final count = widget.matches.length; + if (count == 0) return false; + + final key = event.logicalKey; + if (key == LogicalKeyboardKey.arrowDown) { + _moveHighlight(_highlightedIndex + 1); + return true; + } + if (key == LogicalKeyboardKey.arrowUp) { + _moveHighlight(_highlightedIndex - 1); + return true; + } + if (key == LogicalKeyboardKey.enter || + key == LogicalKeyboardKey.numpadEnter || + key == LogicalKeyboardKey.tab) { + _selectAt(_highlightedIndex); + return true; + } + if (key == LogicalKeyboardKey.escape) { + return true; // Caller owns dismissal. + } + return false; + } + + void _moveHighlight(int nextIndex) { + final count = widget.matches.length; + setState(() => _highlightedIndex = (nextIndex % count + count) % count); + WidgetsBinding.instance.addPostFrameCallback((_) { + final rowContext = _highlightedRowKey.currentContext; + if (rowContext == null || !mounted) return; + unawaited(Scrollable.ensureVisible(rowContext, alignment: 0.5)); + }); + } + + void _selectAt(int index) { + if (index < 0 || index >= widget.matches.length) return; + widget.onSelect(widget.matches[index]); + } + + @override + Widget build(BuildContext context) { + final matches = widget.matches; + // Same predicate as key handling: no room, or an anchored width too narrow + // for a readable row, means no usable surface at all. + final geometry = _surfaceGeometry(); + if (matches.isEmpty || geometry == null) return const SizedBox.shrink(); + + final theme = Theme.of(context); + final isDark = theme.brightness == Brightness.dark; + final width = geometry.width; + final listHeight = geometry.height; + + return Align( + alignment: Alignment.bottomLeft, + child: Material( + type: MaterialType.transparency, + child: SizedBox( + width: width, + child: ClipRRect( + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(16), + ), + child: BackdropFilter( + filter: ImageFilter.blur( + sigmaX: PrismTokens.glassBlurStrong, + sigmaY: PrismTokens.glassBlurStrong, + ), + child: Container( + key: EmojiNameCompletionOverlay.surfaceKey, + constraints: BoxConstraints(maxHeight: listHeight), + decoration: BoxDecoration( + color: theme.colorScheme.surface.withValues( + alpha: isDark ? 0.92 : 0.96, + ), + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(16), + ), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues( + alpha: 0.5, + ), + ), + boxShadow: [ + BoxShadow( + color: theme.colorScheme.shadow.withValues(alpha: 0.18), + blurRadius: 20, + offset: const Offset(0, 4), + ), + ], + ), + // At most eight rows, so every row is built eagerly. That + // keeps the highlighted row's context available for + // `Scrollable.ensureVisible` without a lazy-list estimate. + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (var index = 0; index < matches.length; index++) + _EmojiCompletionRow( + key: index == _highlightedIndex + ? _highlightedRowKey + : null, + emoji: matches[index], + label: _labelFor(matches[index]), + isHighlighted: index == _highlightedIndex, + onTap: () => _selectAt(index), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } + + /// The first keyword segment is the CLDR annotation; that is the name the + /// user typed a prefix of, so it is also the accessible name. + static String _labelFor(Emoji emoji) { + final keywords = emoji.keywords; + for (final keyword in keywords) { + if (keyword.isNotEmpty) return keyword; + } + return emoji.emoji; + } + + /// Narrowest popup that still shows a glyph plus a readable label. + static const double _minUsableWidth = 140; + static const double _maxPopupWidth = 320; +} + +class _EmojiCompletionRow extends StatelessWidget { + const _EmojiCompletionRow({ + super.key, + required this.emoji, + required this.label, + required this.isHighlighted, + required this.onTap, + }); + + final Emoji emoji; + final String label; + final bool isHighlighted; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final primary = theme.colorScheme.primary; + + return Semantics( + // One merged node per row: screen readers announce the glyph and its + // annotation instead of the two separate text runs. + label: '${emoji.emoji} $label', + button: true, + selected: isHighlighted, + // Child semantics are excluded so the row is announced once, so the tap + // action for assistive technology is provided here as well. + excludeSemantics: true, + onTap: onTap, + child: Container( + color: isHighlighted + ? primary.withValues(alpha: 0.12) + : Colors.transparent, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: onTap, + child: ConstrainedBox( + // Theme text styles plus a minimum target height: the row grows + // with the system text scale instead of clipping (no FittedBox and + // no fixed font size). + constraints: const BoxConstraints(minHeight: 44), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( + children: [ + Text(emoji.emoji, style: theme.textTheme.bodyLarge), + const SizedBox(width: 10), + Expanded( + child: Text( + label, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: isHighlighted + ? FontWeight.w600 + : FontWeight.w400, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/chat/widgets/mention_overlay.dart b/lib/features/chat/widgets/mention_overlay.dart index 6e64440e0..0bba63191 100644 --- a/lib/features/chat/widgets/mention_overlay.dart +++ b/lib/features/chat/widgets/mention_overlay.dart @@ -139,9 +139,7 @@ class MentionOverlayState extends ConsumerState /// Handle keyboard navigation. Returns true if the event was consumed. bool handleKeyEvent(KeyEvent event) { if (event is! KeyDownEvent) return false; - final filtered = _filteredFor( - ref.read(memberNamePreferDisplayProvider), - ); + final filtered = _filteredFor(ref.read(memberNamePreferDisplayProvider)); if (filtered.isEmpty) return false; if (event.logicalKey == LogicalKeyboardKey.arrowDown) { @@ -267,11 +265,16 @@ class MentionOverlayState extends ConsumerState child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => _select(entry), - child: SizedBox( - height: 48, + // Grow with the name's line box instead of + // pinning it inside a fixed 48dp row. + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: 48, + ), child: Padding( padding: const EdgeInsets.symmetric( horizontal: 12, + vertical: 8, ), child: Row( children: [ @@ -344,10 +347,11 @@ class _BroadcastMentionRow extends StatelessWidget { child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: onTap, - child: SizedBox( - height: 52, + // Two lines need ~77dp at 2.25x; keep 52dp as the floor only. + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), child: Row( children: [ Container( diff --git a/lib/features/chat/widgets/message_input.dart b/lib/features/chat/widgets/message_input.dart index 89e33a720..df954526c 100644 --- a/lib/features/chat/widgets/message_input.dart +++ b/lib/features/chat/widgets/message_input.dart @@ -1,6 +1,8 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:math' as math; +import 'package:emoji_picker_flutter/emoji_picker_flutter.dart' show Emoji; import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatform, visibleForTesting; import 'package:flutter/material.dart'; @@ -30,6 +32,8 @@ import 'package:prism_plurality/features/chat/utils/mention_utils.dart'; import 'package:prism_plurality/features/chat/utils/proxy_tag_matcher.dart'; import 'package:prism_plurality/features/chat/widgets/attachment_preview.dart'; import 'package:prism_plurality/features/chat/widgets/gif_picker_sheet.dart'; +import 'package:prism_plurality/features/chat/emoji/emoji_name_completion.dart'; +import 'package:prism_plurality/features/chat/widgets/emoji_name_completion_overlay.dart'; import 'package:prism_plurality/features/chat/widgets/mention_overlay.dart'; import 'package:prism_plurality/features/chat/widgets/voice_recorder.dart'; import 'package:prism_plurality/features/fronting/providers/fronting_providers.dart'; @@ -94,6 +98,15 @@ class _MessageInputState extends ConsumerState { String _mentionFilter = ''; bool _mentionMenuVisible = false; final _mentionOverlayKey = GlobalKey(); + final _emojiOverlayController = OverlayPortalController(); + final _emojiOverlayKey = GlobalKey(); + + /// Live `:name` completion token for the draft, or null when the caret is not + /// at the end of one. Computed on text/selection changes, exactly like the + /// mention filter, so the popup cannot reopen on an unrelated rebuild. + EmojiCompletionTrigger? _emojiTrigger; + List _emojiMatches = const []; + bool _emojiCompletionVisible = false; Uint8List? _stagedImageBytes; bool _isRecording = false; @@ -217,14 +230,20 @@ class _MessageInputState extends ConsumerState { if (_mentionOverlayController.isShowing) { _mentionOverlayController.hide(); } + if (_emojiOverlayController.isShowing) { + _emojiOverlayController.hide(); + } _mentionMenuVisible = false; _mentionFilter = ''; + _emojiCompletionVisible = false; + _emojiTrigger = null; + _emojiMatches = const []; _controller.dispose(); _focusNode.dispose(); super.dispose(); } - /// Detect `@` trigger and manage the mention overlay. + /// Detect `@` and `:name` triggers and manage their overlays. void _onTextChanged() { if (!mounted) return; _draftCache.write(widget.conversationId, _controller.value); @@ -240,9 +259,24 @@ class _MessageInputState extends ConsumerState { } } + // The mention chooser keeps priority: a draft cannot hold both triggers at + // one caret, and if it somehow could, `@` wins. + final nextEmojiTrigger = nextMentionVisible + ? null + : detectEmojiCompletionTrigger( + nextText, + selection, + composing: _controller.value.composing, + ); + final nextEmojiMatches = nextEmojiTrigger == null + ? const [] + : searchEmojiNames(nextEmojiTrigger.prefix); + if (_lastText == nextText && _mentionMenuVisible == nextMentionVisible && - _mentionFilter == nextMentionFilter) { + _mentionFilter == nextMentionFilter && + _emojiCompletionVisible == nextEmojiMatches.isNotEmpty && + _emojiTrigger == nextEmojiTrigger) { return; } @@ -250,6 +284,10 @@ class _MessageInputState extends ConsumerState { _lastText = nextText; _mentionMenuVisible = nextMentionVisible; _mentionFilter = nextMentionFilter; + _emojiTrigger = nextEmojiTrigger; + _emojiMatches = nextEmojiMatches; + // No matches must not leave an empty obstructing overlay. + _emojiCompletionVisible = nextEmojiMatches.isNotEmpty; }); } @@ -306,7 +344,7 @@ class _MessageInputState extends ConsumerState { }); } - double _mentionOverlayAvailableWidth(BuildContext context) { + double _composerOverlayAvailableWidth(BuildContext context) { final screenWidth = MediaQuery.sizeOf(context).width; final renderBox = _mentionFieldKey.currentContext?.findRenderObject() as RenderBox?; @@ -328,6 +366,129 @@ class _MessageInputState extends ConsumerState { }); } + /// Height left above the composer field for inline completion popups. + /// + /// The field's top edge is the ceiling: when the view resizes for the + /// keyboard the field moves up and this shrinks with it. Returns 0 when the + /// field sits near the top, so a popup is never drawn off-screen. + double _composerOverlayAvailableHeight(BuildContext context) { + const double gap = 12; + final media = MediaQuery.maybeOf(context); + final renderBox = + _mentionFieldKey.currentContext?.findRenderObject() as RenderBox?; + final screenHeight = media?.size.height ?? 0; + final fieldTop = renderBox?.localToGlobal(Offset.zero).dy ?? screenHeight; + final safeTop = media?.padding.top ?? 0; + // The field already sits above the keyboard whenever the view resizes, so + // its top edge is the real ceiling for the popup. + return math.max(0.0, fieldTop - safeTop - gap); + } + + void _syncEmojiCompletionPortal(bool shouldShow) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + if (shouldShow) { + if (!_emojiOverlayController.isShowing) { + _emojiOverlayController.show(); + } + } else if (_emojiOverlayController.isShowing) { + _emojiOverlayController.hide(); + } + }); + } + + /// Escape and completion dismissal affect the popup only, never the draft. + void _dismissEmojiCompletion() { + if (_emojiOverlayController.isShowing) { + _emojiOverlayController.hide(); + } + if (!_emojiCompletionVisible && _emojiMatches.isEmpty) return; + setState(() { + _emojiCompletionVisible = false; + _emojiMatches = const []; + }); + } + + /// Replace the live `:name` token with the chosen Unicode emoji. + /// + /// Text before the colon and after the caret is untouched; the caret lands + /// directly after the glyph and no trailing space is added. + void _onEmojiSelected(Emoji emoji) { + final trigger = _emojiTrigger; + if (trigger == null) { + _dismissEmojiCompletion(); + return; + } + final text = _controller.text; + // The caret can move between computing the popup and a stale tap landing. + // Only edit when the token is still exactly the one that was matched. + if (detectEmojiCompletionTrigger( + text, + _controller.selection, + composing: _controller.value.composing, + ) != + trigger) { + _dismissEmojiCompletion(); + return; + } + + final newText = text.replaceRange(trigger.start, trigger.end, emoji.emoji); + final caret = trigger.start + emoji.emoji.length; + + // Detach the listener across the programmatic edit so the popup does not + // reopen for the text that replaces it, then resync `_lastText` for the + // proxy-tag match and `_canSend`. + _controller.removeListener(_onTextChanged); + _controller.value = TextEditingValue( + text: newText, + selection: TextSelection.collapsed(offset: caret), + ); + _controller.addListener(_onTextChanged); + + // The listener was detached across the edit, so persist the new draft here + // rather than waiting for the next keystroke. + _draftCache.write(widget.conversationId, _controller.value); + + _emojiTrigger = null; + _emojiMatches = const []; + _emojiCompletionVisible = false; + if (_emojiOverlayController.isShowing) { + _emojiOverlayController.hide(); + } + _focusNode.requestFocus(); + setState(() => _lastText = _controller.text); + } + + /// Keyboard handling for the composer's inline completion surfaces. + /// + /// The mention chooser keeps priority over `:name` emoji completion, and a + /// consumed event is reported as handled so `_GlassTextField`'s desktop + /// Enter-to-send branch never sees an Enter that selected a row. + bool _handleComposerKeyEvent(KeyEvent event) { + if (_mentionMenuVisible) { + final consumed = + _mentionOverlayKey.currentState?.handleKeyEvent(event) ?? false; + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + _dismissMentionOverlay(); + return true; + } + if (consumed) return true; + } + + if (_emojiCompletionVisible) { + final consumed = + _emojiOverlayKey.currentState?.handleKeyEvent(event) ?? false; + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + _dismissEmojiCompletion(); + return true; + } + if (consumed) return true; + } + return false; + } + void _onMemberSelected(Member member) { _replaceMentionTriggerWith('@[${member.id}] '); } @@ -705,12 +866,15 @@ class _MessageInputState extends ConsumerState { _controller.clear(); _controller.addListener(_onTextChanged); _dismissMentionOverlay(); + _dismissEmojiCompletion(); _focusNode.requestFocus(); setState(() { _stagedImageBytes = null; _lastText = ''; _suppressedTag = null; _effectiveMatch = null; + _emojiTrigger = null; + _emojiMatches = const []; }); } @@ -826,7 +990,13 @@ class _MessageInputState extends ConsumerState { !_isRecording && (mentionCandidates.isNotEmpty || MentionOverlay.hasBroadcastAliasMatches(_mentionFilter)); + final showEmojiCompletion = + _emojiCompletionVisible && + !showMentionOverlay && + !_isSending && + _emojiMatches.isNotEmpty; _syncMentionOverlayPortal(showMentionOverlay); + _syncEmojiCompletionPortal(showEmojiCompletion); final memberMap = {for (final m in members) m.id: m}; final prefer = ref.watch(memberNamePreferDisplayProvider); _controller.updateMentionMembers(memberMap, preferDisplayName: prefer); @@ -1020,7 +1190,7 @@ class _MessageInputState extends ConsumerState { members: mentionCandidates, filter: _mentionFilter, availableWidth: - _mentionOverlayAvailableWidth(context), + _composerOverlayAvailableWidth(context), onSelect: _onMemberSelected, onBroadcastSelect: _onBroadcastMentionSelected, @@ -1028,32 +1198,49 @@ class _MessageInputState extends ConsumerState { ), ); }, - child: CompositedTransformTarget( - key: _mentionFieldKey, - link: _layerLink, - child: _GlassTextField( - controller: _controller, - focusNode: _focusNode, - minHeight: inputHeight, - onChanged: (_) => setState(() {}), - onSend: _sendMessage, - onContentInserted: _handleInsertedContent, - onPasteImage: _pasteImageFromClipboard, - onKeyEvent: _mentionMenuVisible - ? (event) { - final consumed = - _mentionOverlayKey.currentState - ?.handleKeyEvent(event) ?? - false; - if (event is KeyDownEvent && - event.logicalKey == - LogicalKeyboardKey.escape) { - _dismissMentionOverlay(); - return true; - } - return consumed; - } - : null, + child: OverlayPortal( + controller: _emojiOverlayController, + overlayChildBuilder: (context) { + return CompositedTransformFollower( + link: _layerLink, + showWhenUnlinked: false, + targetAnchor: Alignment.topLeft, + followerAnchor: Alignment.bottomLeft, + offset: const Offset(0, -8), + child: TextFieldTapRegion( + child: EmojiNameCompletionOverlay( + key: _emojiOverlayKey, + matches: _emojiMatches, + availableWidth: + _composerOverlayAvailableWidth( + context, + ), + availableHeight: + _composerOverlayAvailableHeight( + context, + ), + onSelect: _onEmojiSelected, + ), + ), + ); + }, + child: CompositedTransformTarget( + key: _mentionFieldKey, + link: _layerLink, + child: _GlassTextField( + controller: _controller, + focusNode: _focusNode, + minHeight: inputHeight, + onChanged: (_) => setState(() {}), + onSend: _sendMessage, + onContentInserted: _handleInsertedContent, + onPasteImage: _pasteImageFromClipboard, + onKeyEvent: + _mentionMenuVisible || + _emojiCompletionVisible + ? _handleComposerKeyEvent + : null, + ), ), ), ), diff --git a/lib/features/fronting/widgets/sleep_session_row.dart b/lib/features/fronting/widgets/sleep_session_row.dart index 1ace15896..f594c8642 100644 --- a/lib/features/fronting/widgets/sleep_session_row.dart +++ b/lib/features/fronting/widgets/sleep_session_row.dart @@ -43,12 +43,11 @@ class SleepSessionRow extends StatelessWidget { final isFutureDate = session.startTime.isAfter(DateTime.now()); - final hasNotes = - session.notes != null && session.notes!.isNotEmpty; + final hasNotes = session.notes != null && session.notes!.isNotEmpty; final semanticDurationWords = _semanticDuration(duration); - final qualityWord = session.quality?.localizedLabel(l10n) ?? - l10n.sleepQualityNotRated; + final qualityWord = + session.quality?.localizedLabel(l10n) ?? l10n.sleepQualityNotRated; final semanticLabel = 'Sleep on $dateLabel, $semanticDurationWords, quality $qualityWord'; @@ -66,7 +65,9 @@ class SleepSessionRow extends StatelessWidget { constraints: const BoxConstraints(minHeight: 48), child: Padding( padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 12), + horizontal: 16, + vertical: 12, + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -125,8 +126,9 @@ class SleepSessionRow extends StatelessWidget { Text( session.notes!, style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant - .withValues(alpha: 0.8), + color: theme.colorScheme.onSurfaceVariant.withValues( + alpha: 0.8, + ), fontStyle: FontStyle.italic, ), maxLines: 1, @@ -173,9 +175,7 @@ class _DateWarningChip extends StatelessWidget { decoration: BoxDecoration( color: AppColors.warning.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(12), - border: Border.all( - color: AppColors.warning.withValues(alpha: 0.4), - ), + border: Border.all(color: AppColors.warning.withValues(alpha: 0.4)), ), child: Row( mainAxisSize: MainAxisSize.min, @@ -186,10 +186,17 @@ class _DateWarningChip extends StatelessWidget { color: AppColors.warning, ), const SizedBox(width: 4), - Text( - 'Date looks off', - style: theme.textTheme.labelSmall?.copyWith( - color: AppColors.warning, + // The chip is a min-size row inside a loose column, so an un-flexed label + // kept its intrinsic width and painted past the row edge (10dp with Lexend, + // 83dp with OpenDyslexic at 3.375x on a 320dp phone). Flexible lets it wrap + // inside the chip at the requested size. The string was a hardcoded English + // literal; `sleepDateLooksOff` already ships in every locale. + Flexible( + child: Text( + context.l10n.sleepDateLooksOff, + style: theme.textTheme.labelSmall?.copyWith( + color: AppColors.warning, + ), ), ), ], diff --git a/lib/features/fronting/widgets/timeline_view.dart b/lib/features/fronting/widgets/timeline_view.dart index 32d1a5974..ed6edadf4 100644 --- a/lib/features/fronting/widgets/timeline_view.dart +++ b/lib/features/fronting/widgets/timeline_view.dart @@ -59,8 +59,6 @@ class _TimelineViewState extends ConsumerState { 0.0, ); - static const double _headerRowHeight = 56.0; - static const double _minColumnWidth = 36.0; static const double _maxColumnWidth = 48.0; static const double _wideMaxColumnWidth = 64.0; static const double _wideColumnBreakpoint = 900.0; @@ -122,6 +120,7 @@ class _TimelineViewState extends ConsumerState { final theme = Theme.of(context); final timelineState = ref.watch(timelineStateProvider); final rowsAsync = ref.watch(timelineRowsProvider); + final preferDisplayName = ref.watch(memberNamePreferDisplayProvider); final frontingTerms = watchFrontingTerms(context, ref); // Listen (not watch) for jump target — fires only on change, avoids @@ -180,27 +179,50 @@ class _TimelineViewState extends ConsumerState { return LayoutBuilder( builder: (context, constraints) { final availableWidth = constraints.maxWidth - _timeGutterWidth; - final maxColumnWidth = constraints.maxWidth >= _wideColumnBreakpoint + final baseMaxColumnWidth = constraints.maxWidth >= _wideColumnBreakpoint ? _wideMaxColumnWidth : _maxColumnWidth; - final idealColumnWidth = rows.isNotEmpty - ? (availableWidth / rows.length - _columnPadding).clamp( - _minColumnWidth, - maxColumnWidth, - ) - : maxColumnWidth; - // Viewport height for the scrollable area: - // total height minus header row and divider. - final scrollableHeight = constraints.maxHeight - _headerRowHeight - 1; + // One text-scale-aware layout owns the column width, the band height + // and the style the header renders, so the metrics it measures and the + // glyphs that get painted cannot drift apart. + final headerLayout = _TimelineHeaderLayout.resolve( + context: context, + availableWidth: availableWidth, + columnCount: rows.length, + names: rows.map( + (row) => + row.member.effectiveName(preferDisplayName: preferDisplayName), + ), + columnPadding: _columnPadding, + baseMaxColumnWidth: baseMaxColumnWidth, + ); + // A header band never takes the whole view: past that cap it scrolls + // its content, which keeps the text size instead of shrinking it. + final minGridHeight = math.min( + _TimelineHeaderLayout.minGridViewportHeight, + constraints.maxHeight, + ); + final headerBandHeight = math.min( + headerLayout.rowHeight, + math.max(0.0, constraints.maxHeight - minGridHeight - 1), + ); + // Viewport height for the scrollable area: total height minus the + // resolved header band and the divider. + final scrollableHeight = math.max( + 0.0, + constraints.maxHeight - headerBandHeight - 1, + ); return _buildTimeline( context, theme, timelineState, rows, sleepSessions, - idealColumnWidth, + headerLayout.columnWidth, availableWidth, scrollableHeight, + headerBandHeight: headerBandHeight, + headerLayout: headerLayout, ); }, ); @@ -214,8 +236,10 @@ class _TimelineViewState extends ConsumerState { List sleepSessions, double columnWidth, double availableWidth, - double scrollableViewportHeight, - ) { + double scrollableViewportHeight, { + required double headerBandHeight, + required _TimelineHeaderLayout headerLayout, + }) { final pxPerHour = timelineState.pixelsPerHour; final totalColumnWidth = columnWidth + _columnPadding; @@ -336,9 +360,11 @@ class _TimelineViewState extends ConsumerState { rows: rows, columnsWidth: columnsWidth, totalColumnWidth: totalColumnWidth, - columnWidth: columnWidth, primaryColor: theme.colorScheme.primary, brightness: theme.brightness, + nameMaxLines: headerLayout.nameMaxLines, + nameStyle: headerLayout.nameStyle, + nameSlotHeight: headerLayout.nameSlotHeight, controller: _horizontalController, ), ) @@ -347,9 +373,11 @@ class _TimelineViewState extends ConsumerState { rows: rows, columnsWidth: columnsWidth, totalColumnWidth: totalColumnWidth, - columnWidth: columnWidth, primaryColor: theme.colorScheme.primary, brightness: theme.brightness, + nameMaxLines: headerLayout.nameMaxLines, + nameStyle: headerLayout.nameStyle, + nameSlotHeight: headerLayout.nameSlotHeight, ), ], ); @@ -405,12 +433,23 @@ class _TimelineViewState extends ConsumerState { ); } + final headerRow = buildHeaderRow(); return Column( children: [ - // Sticky header row: member avatars/names + // Sticky header row: member avatars/names. The band follows the scaled + // text; in a window too short for it the row scrolls at full height. SizedBox( - height: _headerRowHeight, - child: centerShortTimeline(buildHeaderRow()), + height: headerBandHeight, + child: centerShortTimeline( + headerLayout.rowHeight > headerBandHeight + ? SingleChildScrollView( + child: SizedBox( + height: headerLayout.rowHeight, + child: headerRow, + ), + ) + : headerRow, + ), ), // Divider centerShortTimeline( @@ -655,18 +694,22 @@ class _HeaderRow extends StatelessWidget { required this.rows, required this.columnsWidth, required this.totalColumnWidth, - required this.columnWidth, required this.primaryColor, required this.brightness, + required this.nameMaxLines, + required this.nameStyle, + required this.nameSlotHeight, this.controller, }); final List rows; final double columnsWidth; final double totalColumnWidth; - final double columnWidth; final Color primaryColor; final Brightness brightness; + final int nameMaxLines; + final TextStyle nameStyle; + final double nameSlotHeight; final ScrollController? controller; @override @@ -685,9 +728,11 @@ class _HeaderRow extends StatelessWidget { row: rows[i], rowIndex: i, width: totalColumnWidth, - columnWidth: columnWidth, primaryColor: primaryColor, brightness: brightness, + maxLines: nameMaxLines, + nameStyle: nameStyle, + nameSlotHeight: nameSlotHeight, ), ), ); @@ -700,21 +745,24 @@ class _MemberHeader extends ConsumerWidget { required this.row, required this.rowIndex, required this.width, - required this.columnWidth, required this.primaryColor, required this.brightness, + required this.maxLines, + required this.nameStyle, + required this.nameSlotHeight, }); final TimelineMemberRow row; final int rowIndex; final double width; - final double columnWidth; final Color primaryColor; final Brightness brightness; + final int maxLines; + final TextStyle nameStyle; + final double nameSlotHeight; @override Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); final color = row.resolveColor(rowIndex, primaryColor, brightness); final prefer = ref.watch(memberNamePreferDisplayProvider); final name = row.member.effectiveName(preferDisplayName: prefer); @@ -736,19 +784,243 @@ class _MemberHeader extends ConsumerWidget { tintOverride: color, ), const SizedBox(height: 2), - Text( - name, - style: theme.textTheme.labelSmall?.copyWith( - fontWeight: FontWeight.w500, - color: color, - fontSize: columnWidth > 44 ? 11 : 10, + // Every column reserves the same name slot, so the avatar row and the + // first name baseline stay level whether a name takes one line or two. + SizedBox( + height: nameSlotHeight, + child: Align( + alignment: Alignment.topCenter, + // The full name stays available when the column is too narrow. + child: Tooltip( + message: name, + child: Text( + name, + style: nameStyle.copyWith(color: color), + maxLines: maxLines, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + ), ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, ), ], ), ); } } + +/// Text-scale-aware geometry for the sticky member header row. +/// +/// Keeps the released fit-to-window behavior at small/default text sizes. +/// Larger text scales the minimum and maximum slot widths independently; +/// the header grows to fit one or two lines without reducing the text size. +/// Name fitting has fixed count/length budgets, independent of history size. +@immutable +class _TimelineHeaderLayout { + const _TimelineHeaderLayout._({ + required this.columnWidth, + required this.rowHeight, + required this.nameMaxLines, + required this.nameStyle, + required this.nameSlotHeight, + }); + + /// Today's compact band, kept whenever a single scaled line fits it. + static const double defaultRowHeight = 56.0; + + /// Released column floor before applying the inherited text scale. + static const double defaultMinColumnWidth = 36.0; + + /// Shortest grid viewport a capped header band may leave. + static const double minGridViewportHeight = 48.0; + + static const double _avatarSize = 28.0; + static const double _avatarGap = 2.0; + + /// Released, unscaled width at which the label uses the larger text role. + static const double _nameFontSizeBreakpoint = 44.0; + static const double _narrowNameFontSize = 10.0; + static const double _wideNameFontSize = 11.0; + + static const int _maxMeasuredNames = 32; + static const int _maxMeasuredNameLength = 128; + + /// Fixed glyph reference for accented capitals, deep descenders, + /// punctuation and digits. Ink allowance does not scan member names. + static const String _inkProbe = 'ÉÅÇÑÖÜģgjpqyQ(),;0123'; + + /// Width of one member column, excluding the caller's column padding. + final double columnWidth; + + /// Height of the sticky header band that fits [nameStyle] and its ink. + final double rowHeight; + + /// One compact line, or two when bounded name fitting requires wrapping. + final int nameMaxLines; + + /// Height reserved for the name under the avatar, identical for every column + /// so the avatar row and the first name baseline stay level whether a name + /// takes one line or two. It is `nameMaxLines * lineHeight` from the + /// measurement above, so it adds no layout pass. + final double nameSlotHeight; + + /// Style the header name is rendered with. It is measured here, so the + /// metrics used for layout and the drawn glyphs are one style object. + final TextStyle nameStyle; + + /// Fits the released column slots to the viewport with distinct scaled bounds. + /// Name fitting is bounded and only runs once text outgrows the compact band. + static _TimelineHeaderLayout resolve({ + required BuildContext context, + required double availableWidth, + required int columnCount, + required Iterable names, + required double columnPadding, + required double baseMaxColumnWidth, + }) { + final scaler = MediaQuery.textScalerOf(context); + final direction = Directionality.of(context); + final idealColumnWidth = columnCount > 0 + ? availableWidth / columnCount - columnPadding + : baseMaxColumnWidth; + final unscaledColumnWidth = idealColumnWidth.clamp( + defaultMinColumnWidth, + baseMaxColumnWidth, + ); + // Keep the released text role: accessibility scaling must not itself + // switch a compressed 10px label into the wider 11px role. + final fontSize = unscaledColumnWidth > _nameFontSizeBreakpoint + ? _wideNameFontSize + : _narrowNameFontSize; + final style = (Theme.of(context).textTheme.labelSmall ?? const TextStyle()) + .copyWith(fontSize: fontSize, fontWeight: FontWeight.w500); + // Scale complete slots, while retaining the chart's existing gap and + // enough space for its unscaled 28px avatars at small text settings. + final slotScale = math.max(1.0, scaler.scale(fontSize) / fontSize); + final minColumnWidth = + (defaultMinColumnWidth + columnPadding) * slotScale - columnPadding; + final maxColumnWidth = + (baseMaxColumnWidth + columnPadding) * slotScale - columnPadding; + final columnWidth = idealColumnWidth.clamp(minColumnWidth, maxColumnWidth); + final lineHeight = _lineHeight(style, scaler, direction); + final inkAllowance = _inkAllowance(style, scaler, direction, lineHeight); + final compactLineFits = + _avatarSize + _avatarGap + lineHeight + inkAllowance <= + defaultRowHeight; + final nameMaxLines = + !compactLineFits && + _namesNeedSecondLine( + names, + style, + scaler, + direction, + columnWidth + columnPadding, + Localizations.maybeLocaleOf(context), + ) + ? 2 + : 1; + final rowHeight = columnCount == 0 + ? defaultRowHeight + : math.max( + defaultRowHeight, + (_avatarSize + + _avatarGap + + nameMaxLines * lineHeight + + inkAllowance) + .ceilToDouble(), + ); + return _TimelineHeaderLayout._( + columnWidth: columnWidth, + rowHeight: rowHeight, + nameMaxLines: nameMaxLines, + nameStyle: style, + nameSlotHeight: nameMaxLines * lineHeight, + ); + } + + /// Prefer two lines conservatively once a bounded name-fitting budget is + /// exhausted; do not shape arbitrary-length names or scan session history. + static bool _namesNeedSecondLine( + Iterable names, + TextStyle style, + TextScaler scaler, + TextDirection direction, + double width, + Locale? locale, + ) { + final painter = TextPainter( + textDirection: direction, + textScaler: scaler, + locale: locale, + maxLines: 1, + ); + try { + var measured = 0; + for (final name in names) { + if (measured >= _maxMeasuredNames || + name.length > _maxMeasuredNameLength) { + return true; + } + measured++; + painter.text = TextSpan(text: name, style: style); + painter.layout(maxWidth: width); + if (painter.didExceedMaxLines) return true; + } + return false; + } finally { + painter.dispose(); + } + } + + /// Laid-out line height of [style] at [scaler], i.e. what the paragraph + /// reserves for each line. + static double _lineHeight( + TextStyle style, + TextScaler scaler, + TextDirection direction, + ) { + final painter = TextPainter( + text: TextSpan(text: 'M', style: style), + textDirection: direction, + textScaler: scaler, + maxLines: 1, + )..layout(); + final height = painter.preferredLineHeight; + painter.dispose(); + return height; + } + + /// Vertical room the glyph ink needs beyond the laid-out line boxes. + /// + /// The label style fixes a line box (1.45 em here), but real faces reach past + /// it: accented capitals rise above the allocated ascent and deep descenders + /// fall below the allocated descent. The header row is a horizontally + /// scrolling list, which clips to the band, so the band must cover that ink + /// rather than let the font's shape decide whether a name is cut. The result + /// allows the larger excursion on both sides, because the name is centred in + /// the band. + static double _inkAllowance( + TextStyle style, + TextScaler scaler, + TextDirection direction, + double lineHeight, + ) { + final painter = TextPainter( + text: TextSpan(text: _inkProbe, style: style), + textDirection: direction, + textScaler: scaler, + maxLines: 1, + )..layout(); + var above = 0.0; + var below = 0.0; + for (final box in painter.getBoxesForSelection( + const TextSelection(baseOffset: 0, extentOffset: _inkProbe.length), + )) { + above = math.max(above, -box.top); + below = math.max(below, box.bottom - lineHeight); + } + painter.dispose(); + // Two extra pixels absorb subpixel ink rounding at high scale factors. + return 2 * math.max(above, below) + 2; + } +} diff --git a/lib/features/habits/services/habit_notification_service.dart b/lib/features/habits/services/habit_notification_service.dart index 31c9c623a..33e3c0bd1 100644 --- a/lib/features/habits/services/habit_notification_service.dart +++ b/lib/features/habits/services/habit_notification_service.dart @@ -176,6 +176,27 @@ class HabitNotificationService { ); } + /// Cancel every reminder owned by [habitIds] and invalidate any reschedule + /// batch that is already running. + /// + /// Used when the habit rows are gone (a reset): the IDs this service derives + /// from a habit can no longer be recovered from storage, so the caller has to + /// hand them over before they are lost. + /// + /// The batch epoch is bumped before the first await, so a stale + /// [rescheduleAll] list stops at its next loop guard instead of starting a + /// later habit whose reminders were just retracted. Every per-habit + /// generation is bumped before any cancellation is awaited and every ID is + /// attempted: a failure is rethrown only after all of them have completed, so + /// one platform error cannot strand the remaining habits. + Future cancelForHabits(Iterable habitIds) async { + ++_rescheduleGeneration; + final ids = habitIds.toSet(); + if (ids.isEmpty) return; + final cancellations = [for (final id in ids) cancelForHabit(id)]; + await Future.wait(cancellations, eagerError: false); + } + /// Reschedule notifications for all habits. /// /// [skipCurrentPeriodFor] is consulted per-habit to suppress same-period diff --git a/lib/features/habits/widgets/habit_chip.dart b/lib/features/habits/widgets/habit_chip.dart index 166bdefc6..18ba9a91a 100644 --- a/lib/features/habits/widgets/habit_chip.dart +++ b/lib/features/habits/widgets/habit_chip.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'habit_icon_metrics.dart'; import 'package:prism_plurality/domain/models/habit.dart'; import 'package:prism_plurality/domain/models/habit_completion.dart'; @@ -6,6 +7,7 @@ import 'package:prism_plurality/shared/theme/app_colors.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_pill.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; @@ -107,7 +109,9 @@ class HabitChip extends StatelessWidget { ); } if (habit.currentStreak > 0) { - if (pills.isNotEmpty) pills.add(const SizedBox(width: 6)); + // Pills only: the 6dp gap belongs to whichever container lays them out (the inline + // row interleaves it, the stacked wrap owns it as `spacing`), so it can never be + // counted twice. pills.add( PrismPill( icon: AppIcons.localFireDepartment, @@ -122,6 +126,8 @@ class HabitChip extends StatelessWidget { AppIcons.chevronRightRounded, color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.7), ); + // The chip's own 12dp side padding plus the 8dp gap before the chevron. + const chipPadding = EdgeInsets.symmetric(horizontal: 12, vertical: 8); return Material( color: onSurface.withValues(alpha: 0.05), @@ -137,32 +143,100 @@ class HabitChip extends StatelessWidget { onTap: onTap, borderRadius: borderRadius, child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - HabitLeadingCircle( - habit: habit, - color: color, - completed: isCompleted, - onQuickComplete: onQuickComplete, - ), - const SizedBox(width: 12), - Expanded( - child: Text( - habit.name, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyLarge?.copyWith( - color: onSurface.withValues(alpha: 0.9), - fontWeight: FontWeight.w600, - ), + padding: chipPadding, + child: LayoutBuilder( + builder: (context, constraints) { + // Fit from what the chip really renders. The glyph target, the gaps and + // the chevron are non-shrinkable and the title already ellipsises, so the + // pills keep today's inline position while they fit beside those pieces and + // move to their own end-aligned line only when they cannot - at the maximum + // composed scale a family glyph plus a progress and a multi-digit streak pill + // overflowed the row by 168/199px. + final fixed = + _chipLeadingExtent(context, habit.icon) + + 12 + // gap after the leading target + 8 + // gap before the pills + 8 + // gap before the chevron + 24; // chevron + final pillsWidth = _chipPillsWidth( + context, + theme: theme, + weeklyProgress: weeklyProgress, + streak: habit.currentStreak, + pillPadding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 2, ), - ), - if (pills.isNotEmpty) ...[const SizedBox(width: 8), ...pills], - const SizedBox(width: 8), - chevron, - ], + ); + final fitsInline = + pills.isEmpty || fixed + pillsWidth <= constraints.maxWidth; + + final title = Text( + habit.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyLarge?.copyWith( + color: onSurface.withValues(alpha: 0.9), + fontWeight: FontWeight.w600, + ), + ); + + if (fitsInline) { + // Unchanged default geometry: title ellipsises, pills inline. + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + HabitLeadingCircle( + habit: habit, + color: color, + completed: isCompleted, + onQuickComplete: onQuickComplete, + ), + const SizedBox(width: 12), + Expanded(child: title), + if (pills.isNotEmpty) ...[ + const SizedBox(width: 8), + for (var i = 0; i < pills.length; i++) ...[ + if (i > 0) const SizedBox(width: _chipPillGap), + pills[i], + ], + ], + const SizedBox(width: 8), + chevron, + ], + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + HabitLeadingCircle( + habit: habit, + color: color, + completed: isCompleted, + onQuickComplete: onQuickComplete, + ), + const SizedBox(width: 12), + Expanded(child: title), + const SizedBox(width: 8), + chevron, + ], + ), + const SizedBox(height: 4), + Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: _chipPillGap, + runSpacing: 2, + children: pills, + ), + ], + ); + }, ), ), ), @@ -170,6 +244,89 @@ class HabitChip extends StatelessWidget { } } +/// Gap between the chip's metadata pills. +/// +/// Used by both containers - the inline row interleaves a `SizedBox` of this width and the +/// stacked `Wrap` owns it as `spacing` - so the visual gap is identical in both layouts. +const double _chipPillGap = 6; + +/// Width of one side of a pill's border. +/// +/// `PrismPill` draws `Border.all(...)`, whose `BorderSide` width defaults to 1, so a pill +/// is two pixels wider and taller than its content. The chip's fit budget has to include +/// those two pixels per pill; no appearance changes. +const double _pillBorderSide = 1; + +/// Extent of the chip's leading completion target for [icon]. +/// +/// Shared by [HabitLeadingCircle] (which paints it) and [HabitChip] (which decides +/// whether the metadata still fits beside it), so the two can never drift. The +/// glyph keeps its requested size; only the circle grows around it. +double _chipLeadingExtent(BuildContext context, String? icon) => + habitIconExtent(context, icon, fontSize: 18, minimum: 36) + 8; + +/// Width of the metadata pills [HabitChip] may place beside the title. +double _chipPillsWidth( + BuildContext context, { + required ThemeData theme, + required (int completed, int total)? weeklyProgress, + required int streak, + required EdgeInsets pillPadding, +}) { + // Exactly the style `PrismPill` paints its label with: labelMedium, w700, height 1. + final labelStyle = theme.textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.w700, + height: 1, + ); + var width = 0.0; + var count = 0; + if (weeklyProgress != null) { + width += _chipPillWidth( + context, + '${weeklyProgress.$1}/${weeklyProgress.$2}', + labelStyle, + pillPadding, + ); + count++; + } + if (streak > 0) { + if (count > 0) width += _chipPillGap; + width += _chipPillWidth(context, '$streak', labelStyle, pillPadding); + } + return width; +} + +/// Width one pill occupies: its label as `PrismPill` paints it, plus the 14dp icon, +/// the 6dp icon gap and the pill's own horizontal padding. +/// +/// [style] is the style handed to the pill's `Text`; [prismTextStyleForMeasurement] +/// applies the ambient merge and the bold-text flag exactly as `Text` does, and the +/// painter receives the inherited locale and height behaviour, so the measured pill and +/// the painted pill resolve the same face. +double _chipPillWidth( + BuildContext context, + String label, + TextStyle? style, + EdgeInsets padding, +) { + final painter = TextPainter( + text: TextSpan( + text: label, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + // 14dp icon + 6dp gap + the pill's own horizontal padding + both border sides. + final width = + painter.width + 14 + 6 + padding.horizontal + (_pillBorderSide * 2); + painter.dispose(); + return width; +} + /// The leading completion circle used by [HabitChip]. Extracted so the /// tap-target logic is owned in one place. A `null` `onQuickComplete` /// reports the control as `enabled: false` via Semantics — used by @@ -195,6 +352,10 @@ class HabitLeadingCircle extends StatelessWidget { ? Duration.zero : const Duration(milliseconds: 240); final shapes = PrismShapes.of(context); + // One measurement drives both the circle and the target (see + // [_chipLeadingExtent]), so HabitChip's fit decision and this paint agree. + final targetExtent = _chipLeadingExtent(context, habit.icon); + final circleExtent = targetExtent - 8; return Semantics( button: true, @@ -206,14 +367,14 @@ class HabitLeadingCircle extends StatelessWidget { behavior: HitTestBehavior.opaque, onTap: onQuickComplete, child: SizedBox( - width: 40, - height: 40, + width: targetExtent, + height: targetExtent, child: Center( child: AnimatedContainer( duration: duration, curve: Curves.easeOut, - width: 36, - height: 36, + width: circleExtent, + height: circleExtent, decoration: BoxDecoration( shape: shapes.avatarShape(), borderRadius: shapes.avatarBorderRadius(), diff --git a/lib/features/habits/widgets/habit_icon_metrics.dart b/lib/features/habits/widgets/habit_icon_metrics.dart new file mode 100644 index 000000000..f836461d3 --- /dev/null +++ b/lib/features/habits/widgets/habit_icon_metrics.dart @@ -0,0 +1,43 @@ +import 'dart:math' as math; +import 'package:flutter/material.dart'; + +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; + +/// Space for the configured glyph at its actual requested text size. +/// +/// This is presentation-only work per visible habit build. No state is retained +/// and no completion history is scanned. Measure the same inherited style that +/// the Text uses rather than guessing from a font-size ratio. +double habitIconExtent( + BuildContext context, + String? icon, { + required double fontSize, + required double minimum, +}) { + if (icon == null || icon.isEmpty) return minimum; + // The glyph is a `Text` with `style: TextStyle(fontSize: ...)`, so the measurement + // resolves the style the same way `Text` does (ambient merge plus the bold-text flag) + // and passes the inherited locale and height behaviour, which is what keeps a + // fallback emoji face's box from being under-measured. + final painter = TextPainter( + text: TextSpan( + text: icon, + style: prismTextStyleForMeasurement( + context, + TextStyle(fontSize: fontSize), + ), + ), + textScaler: MediaQuery.textScalerOf(context), + textDirection: Directionality.of(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + try { + return math + .max(minimum, math.max(painter.width, painter.height) + 8) + .ceilToDouble(); + } finally { + painter.dispose(); + } +} diff --git a/lib/features/habits/widgets/habit_row.dart b/lib/features/habits/widgets/habit_row.dart index a1a030bb4..9a0c1a9b9 100644 --- a/lib/features/habits/widgets/habit_row.dart +++ b/lib/features/habits/widgets/habit_row.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'habit_icon_metrics.dart'; import 'package:prism_plurality/domain/models/habit.dart'; import 'package:prism_plurality/domain/models/habit_completion.dart'; @@ -76,6 +77,13 @@ class HabitRow extends StatelessWidget { ? Duration.zero : const Duration(milliseconds: 240); final shapes = PrismShapes.of(context); + final circleExtent = habitIconExtent( + context, + habit.icon, + fontSize: 20, + minimum: 44, + ); + final targetExtent = circleExtent + 4; // Build the subtitle pill list. Frequency is no longer shown — only // weekly progress (if weekly-frequency) and streak (if > 0). If @@ -115,6 +123,7 @@ class HabitRow extends StatelessWidget { return PrismListRow( onTap: onTap, + leadingWidth: targetExtent, leading: Semantics( button: true, enabled: onQuickComplete != null, @@ -125,14 +134,14 @@ class HabitRow extends StatelessWidget { behavior: HitTestBehavior.opaque, onTap: onQuickComplete, child: SizedBox( - width: 48, - height: 48, + width: targetExtent, + height: targetExtent, child: Center( child: AnimatedContainer( duration: circleDuration, curve: Curves.easeOut, - width: 44, - height: 44, + width: circleExtent, + height: circleExtent, decoration: BoxDecoration( shape: shapes.avatarShape(), borderRadius: shapes.avatarBorderRadius(), diff --git a/lib/features/members/views/member_detail_screen.dart b/lib/features/members/views/member_detail_screen.dart index 232131201..1d1157c36 100644 --- a/lib/features/members/views/member_detail_screen.dart +++ b/lib/features/members/views/member_detail_screen.dart @@ -46,7 +46,6 @@ import 'package:prism_plurality/features/members/widgets/custom_fields_display.d import 'package:prism_plurality/features/boards/widgets/board_message_section.dart'; import 'package:prism_plurality/features/members/widgets/notes_section.dart'; import 'package:prism_plurality/features/members/widgets/member_profile_header.dart'; -import 'package:prism_plurality/features/members/widgets/custom_field_display_widgets.dart'; import 'package:prism_plurality/shared/widgets/prism_markdown_text.dart'; import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; @@ -216,19 +215,8 @@ class _MemberDetailBody extends ConsumerWidget { final theme = Theme.of(context); return [ const SizedBox(height: 16), + // Pronouns are shown once, by the header's capsule under the name. MemberProfileHeader(member: member, isFronting: isFronting), - if (member.pronouns?.trim().isNotEmpty ?? false) ...[ - const SizedBox(height: 12), - Text( - context.l10n.memberPronounsLabel, - style: theme.textTheme.labelLarge, - ), - const SizedBox(height: 4), - FieldInlineMarkdownText( - member.pronouns!.trim(), - style: theme.textTheme.bodyLarge, - ), - ], if (member.bio != null && member.bio!.isNotEmpty) ...[ const SizedBox(height: 12), PrismMarkdownText( @@ -1024,8 +1012,14 @@ class _StatRow extends StatelessWidget { Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // `OverflowBar`: the label and value stay on one line while they fit and the + // value moves to its own end-aligned line when they do not, so a long label or + // a long duration can no longer paint past the card. + child: OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 4, + overflowAlignment: OverflowBarAlignment.end, children: [ Text(label, style: theme.textTheme.bodyMedium), Text( diff --git a/lib/features/members/widgets/custom_field_display_widgets.dart b/lib/features/members/widgets/custom_field_display_widgets.dart index 2594131d6..08811b1b3 100644 --- a/lib/features/members/widgets/custom_field_display_widgets.dart +++ b/lib/features/members/widgets/custom_field_display_widgets.dart @@ -28,7 +28,19 @@ class FieldInlineMarkdownText extends ConsumerWidget { final String data; final TextStyle? style; - final TextAlign textAlign; + + /// Block text alignment for the rendered field. + /// + /// The default stays [TextAlign.start] for every existing caller: blocks keep + /// the start edge and the markdown body stretches to the width it is given, + /// which is what multi-block field values rely on. + /// + /// Passing `null` opts into [MarkdownText]'s fit-content policy instead: the + /// rendered blocks hug their content rather than filling the available width. + /// The profile header's pronoun capsule uses that so a short capsule reads as + /// a pill instead of a full-width bar. Null keeps the default start alignment, + /// including in right-to-left layouts; it is not a direction change. + final TextAlign? textAlign; @override Widget build(BuildContext context, WidgetRef ref) { diff --git a/lib/features/members/widgets/manage_groups_sheet.dart b/lib/features/members/widgets/manage_groups_sheet.dart index 7c501967a..620feffb2 100644 --- a/lib/features/members/widgets/manage_groups_sheet.dart +++ b/lib/features/members/widgets/manage_groups_sheet.dart @@ -12,6 +12,7 @@ import 'package:prism_plurality/shared/widgets/prism_button.dart'; import 'package:prism_plurality/shared/widgets/prism_glass_icon_button.dart'; import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; /// Full-screen sheet for managing which groups a member belongs to. /// @@ -130,7 +131,14 @@ class _ManageGroupsSheetState extends ConsumerState { return LayoutBuilder( builder: (context, constraints) { - if (constraints.maxHeight < PrismTokens.topBarHeight) { + // The bar grows with the ambient text scale; compare against what it + // needs rather than the fixed 66dp. + final barHeight = prismScaledHeightOf( + context, + topBar, + availableWidth: constraints.maxWidth, + ); + if (constraints.maxHeight < barHeight) { return CustomScrollView( controller: widget.scrollController, primary: widget.scrollController == null, diff --git a/lib/features/members/widgets/member_list_view_settings_sheet.dart b/lib/features/members/widgets/member_list_view_settings_sheet.dart index da9192978..d988d807e 100644 --- a/lib/features/members/widgets/member_list_view_settings_sheet.dart +++ b/lib/features/members/widgets/member_list_view_settings_sheet.dart @@ -6,10 +6,10 @@ import 'package:prism_plurality/features/members/providers/member_groups_provide import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; -import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/widgets/prism_segmented_control.dart'; import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; import 'package:prism_plurality/shared/widgets/prism_switch_row.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; class MemberListViewSettingsSheet extends ConsumerWidget { const MemberListViewSettingsSheet({ @@ -32,243 +32,229 @@ class MemberListViewSettingsSheet extends ConsumerWidget { final frontButtonBehavior = ref.watch(membersFrontButtonBehaviorProvider); final frontingTerms = watchFrontingTerms(context, ref); - return LayoutBuilder( - builder: (context, constraints) { - if (constraints.maxHeight < PrismTokens.topBarHeight) { - return const SizedBox.shrink(); - } + final topBar = PrismSheetTopBar(title: l10n.memberListViewSettingsTitle); - return Column( - children: [ - PrismSheetTopBar(title: l10n.memberListViewSettingsTitle), - Expanded( - child: ListView( - controller: scrollController, - padding: const EdgeInsets.fromLTRB(24, 8, 24, 32), + final settings = [ + _SettingsSection( + title: l10n.memberShowGroupSectionsLabel, + child: PrismSwitchRow( + title: l10n.memberShowGroupSectionsToggle, + subtitle: l10n.memberShowGroupSectionsToggleDescription, + value: showGroups, + enabled: hasGroups, + padding: const EdgeInsets.symmetric(vertical: 10), + onChanged: (value) { + ref + .read(settingsNotifierProvider.notifier) + .updateMembersShowGroups(value); + }, + ), + ), + const SizedBox(height: 24), + AnimatedSize( + duration: const Duration(milliseconds: 200), + alignment: Alignment.topCenter, + child: showGroups + ? Column( + key: const ValueKey('view-mode-section'), + crossAxisAlignment: CrossAxisAlignment.start, children: [ _SettingsSection( - title: l10n.memberShowGroupSectionsLabel, - child: PrismSwitchRow( - title: l10n.memberShowGroupSectionsToggle, - subtitle: l10n.memberShowGroupSectionsToggleDescription, - value: showGroups, - enabled: hasGroups, - padding: const EdgeInsets.symmetric(vertical: 10), - onChanged: (value) { + title: l10n.memberListViewModeLabel, + description: l10n.memberListViewModeDescription, + child: PrismSegmentedControl( + selected: viewMode, + onChanged: (mode) { ref .read(settingsNotifierProvider.notifier) - .updateMembersShowGroups(value); + .updateMembersListViewMode(mode); }, + segments: [ + PrismSegment( + value: MembersListViewMode.groupedSections, + label: l10n.memberListViewModeGroupedSections, + ), + PrismSegment( + value: MembersListViewMode.folders, + label: l10n.memberListViewModeFolders, + ), + ], ), ), const SizedBox(height: 24), - AnimatedSize( - duration: const Duration(milliseconds: 200), - alignment: Alignment.topCenter, - child: showGroups - ? Column( - key: const ValueKey('view-mode-section'), - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - _SettingsSection( - title: l10n.memberListViewModeLabel, - description: l10n.memberListViewModeDescription, - child: - PrismSegmentedControl( - selected: viewMode, - onChanged: (mode) { - ref - .read( - settingsNotifierProvider.notifier, - ) - .updateMembersListViewMode(mode); - }, - segments: [ - PrismSegment( - value: MembersListViewMode - .groupedSections, - label: l10n - .memberListViewModeGroupedSections, - ), - PrismSegment( - value: MembersListViewMode.folders, - label: l10n.memberListViewModeFolders, - ), - ], - ), - ), - const SizedBox(height: 24), - if (viewMode == - MembersListViewMode.groupedSections) - _SettingsSection( - title: l10n.memberGroupedDefaultStateLabel, - description: - l10n.memberGroupedDefaultStateDescription, - child: - PrismSegmentedControl< - MembersGroupedDefaultState - >( - selected: groupedDefault, - onChanged: (state) { - ref - .read( - settingsNotifierProvider - .notifier, - ) - .updateMembersGroupedDefaultState( - state, - ); - final collapsed = ref.read( - collapsedGroupsProvider.notifier, - ); - switch (state) { - case MembersGroupedDefaultState - .open: - collapsed.expandAll(); - case MembersGroupedDefaultState - .closed: - collapsed.collapseAll(); - } - }, - segments: [ - PrismSegment( - value: - MembersGroupedDefaultState.open, - label: l10n - .memberGroupedDefaultStateOpen, - ), - PrismSegment( - value: MembersGroupedDefaultState - .closed, - label: l10n - .memberGroupedDefaultStateClosed, - ), - ], - ), - ) - else - _SettingsSection( - title: l10n.memberFolderVisibilityLabel, - description: - l10n.memberFolderVisibilityDescription, - child: - PrismSegmentedControl< - MembersFolderMemberVisibility - >( - selected: folderVisibility, - onChanged: (visibility) { - ref - .read( - settingsNotifierProvider - .notifier, - ) - .updateMembersFolderMemberVisibility( - visibility, - ); - }, - segments: [ - PrismSegment( - value: MembersFolderMemberVisibility - .allMembers, - label: - l10n.memberFolderVisibilityAll, - ), - PrismSegment( - value: MembersFolderMemberVisibility - .ungroupedOnly, - label: l10n - .memberFolderVisibilityUngrouped, - ), - ], - ), - ), - const SizedBox(height: 24), - ], - ) - : const SizedBox.shrink( - key: ValueKey('view-mode-hidden'), + if (viewMode == MembersListViewMode.groupedSections) + _SettingsSection( + title: l10n.memberGroupedDefaultStateLabel, + description: l10n.memberGroupedDefaultStateDescription, + child: PrismSegmentedControl( + selected: groupedDefault, + onChanged: (state) { + ref + .read(settingsNotifierProvider.notifier) + .updateMembersGroupedDefaultState(state); + final collapsed = ref.read( + collapsedGroupsProvider.notifier, + ); + switch (state) { + case MembersGroupedDefaultState.open: + collapsed.expandAll(); + case MembersGroupedDefaultState.closed: + collapsed.collapseAll(); + } + }, + segments: [ + PrismSegment( + value: MembersGroupedDefaultState.open, + label: l10n.memberGroupedDefaultStateOpen, ), - ), - _SettingsSection( - title: frontingTerms.directButtonLabel, - description: showFrontButtons - ? l10n.memberListFrontButtonsDescription( - frontingTerms.featureLower, - ) - : null, - child: Column( - children: [ - PrismSwitchRow( - title: l10n.memberListFrontButtonsTitle( - frontingTerms.directButtonLabel, + PrismSegment( + value: MembersGroupedDefaultState.closed, + label: l10n.memberGroupedDefaultStateClosed, ), - subtitle: l10n.memberListFrontButtonsSubtitle( - frontingTerms.directButtonLabel, - frontingTerms.currentlyActivePhrase, + ], + ), + ) + else + _SettingsSection( + title: l10n.memberFolderVisibilityLabel, + description: l10n.memberFolderVisibilityDescription, + child: + PrismSegmentedControl( + selected: folderVisibility, + onChanged: (visibility) { + ref + .read(settingsNotifierProvider.notifier) + .updateMembersFolderMemberVisibility( + visibility, + ); + }, + segments: [ + PrismSegment( + value: MembersFolderMemberVisibility.allMembers, + label: l10n.memberFolderVisibilityAll, + ), + PrismSegment( + value: + MembersFolderMemberVisibility.ungroupedOnly, + label: l10n.memberFolderVisibilityUngrouped, + ), + ], ), - value: showFrontButtons, - padding: const EdgeInsets.symmetric(vertical: 10), - onChanged: (value) { + ), + const SizedBox(height: 24), + ], + ) + : const SizedBox.shrink(key: ValueKey('view-mode-hidden')), + ), + _SettingsSection( + title: frontingTerms.directButtonLabel, + description: showFrontButtons + ? l10n.memberListFrontButtonsDescription(frontingTerms.featureLower) + : null, + child: Column( + children: [ + PrismSwitchRow( + title: l10n.memberListFrontButtonsTitle( + frontingTerms.directButtonLabel, + ), + subtitle: l10n.memberListFrontButtonsSubtitle( + frontingTerms.directButtonLabel, + frontingTerms.currentlyActivePhrase, + ), + value: showFrontButtons, + padding: const EdgeInsets.symmetric(vertical: 10), + onChanged: (value) { + ref + .read(settingsNotifierProvider.notifier) + .updateMembersShowFrontButtons(value); + }, + ), + AnimatedSwitcher( + duration: const Duration(milliseconds: 180), + child: showFrontButtons + ? Padding( + key: const ValueKey('member-front-behavior'), + padding: const EdgeInsets.only(top: 12), + child: _LabeledControl( + label: l10n.memberFrontButtonBehaviorLabel, + child: PrismSegmentedControl( + selected: frontButtonBehavior, + onChanged: (behavior) { ref .read(settingsNotifierProvider.notifier) - .updateMembersShowFrontButtons(value); + .updateMembersFrontButtonBehavior(behavior); }, + segments: [ + PrismSegment( + value: FrontStartBehavior.additive, + label: l10n.memberFrontButtonBehaviorAdd, + ), + PrismSegment( + value: FrontStartBehavior.replace, + label: l10n.memberFrontButtonBehaviorReplace, + ), + ], ), - AnimatedSwitcher( - duration: const Duration(milliseconds: 180), - child: showFrontButtons - ? Padding( - key: const ValueKey('member-front-behavior'), - padding: const EdgeInsets.only(top: 12), - child: _LabeledControl( - label: l10n.memberFrontButtonBehaviorLabel, - child: PrismSegmentedControl( - selected: frontButtonBehavior, - onChanged: (behavior) { - ref - .read( - settingsNotifierProvider.notifier, - ) - .updateMembersFrontButtonBehavior( - behavior, - ); - }, - segments: [ - PrismSegment( - value: FrontStartBehavior.additive, - label: - l10n.memberFrontButtonBehaviorAdd, - ), - PrismSegment( - value: FrontStartBehavior.replace, - label: l10n - .memberFrontButtonBehaviorReplace, - ), - ], - ), - ), - ) - : const SizedBox.shrink(), - ), - ], - ), - ), - const SizedBox(height: 24), - _SettingsSection( - title: l10n.memberListDisplayLabel, - child: PrismSwitchRow( - title: l10n.memberShowPronounsToggle, - subtitle: l10n.memberShowPronounsToggleDescription, - value: showPronouns, - padding: const EdgeInsets.symmetric(vertical: 10), - onChanged: (value) { - ref - .read(settingsNotifierProvider.notifier) - .updateMembersShowPronouns(value); - }, - ), - ), - ], + ), + ) + : const SizedBox.shrink(), + ), + ], + ), + ), + const SizedBox(height: 24), + _SettingsSection( + title: l10n.memberListDisplayLabel, + child: PrismSwitchRow( + title: l10n.memberShowPronounsToggle, + subtitle: l10n.memberShowPronounsToggleDescription, + value: showPronouns, + padding: const EdgeInsets.symmetric(vertical: 10), + onChanged: (value) { + ref + .read(settingsNotifierProvider.notifier) + .updateMembersShowPronouns(value); + }, + ), + ), + ]; + + return LayoutBuilder( + builder: (context, constraints) { + // The bar grows with the ambient text scale; compare against what it + // needs rather than the fixed 66dp. + final barHeight = prismScaledHeightOf( + context, + topBar, + availableWidth: constraints.maxWidth, + ); + // A pinned header must leave room for a whole minimum tap target. + // PrismSheet has already excluded safe-area/keyboard space from these + // constraints; the modal sits above the floating navigation bar. + if (constraints.maxHeight < barHeight + 44) { + return SingleChildScrollView( + controller: scrollController, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + topBar, + Padding( + padding: const EdgeInsets.fromLTRB(24, 8, 24, 32), + child: Column(children: settings), + ), + ], + ), + ); + } + + return Column( + children: [ + topBar, + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.fromLTRB(24, 8, 24, 32), + children: settings, ), ), ], diff --git a/lib/features/members/widgets/member_profile_header.dart b/lib/features/members/widgets/member_profile_header.dart index 705e2c5c8..d5dbfd4c6 100644 --- a/lib/features/members/widgets/member_profile_header.dart +++ b/lib/features/members/widgets/member_profile_header.dart @@ -10,6 +10,7 @@ import 'package:prism_plurality/features/settings/providers/terminology_provider import 'package:prism_plurality/features/members/utils/birthday.dart'; import 'package:prism_plurality/features/members/utils/member_name_style.dart'; import 'package:prism_plurality/features/members/utils/member_profile_header_resolver.dart'; +import 'package:prism_plurality/features/members/widgets/custom_field_display_widgets.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/theme/app_colors.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; @@ -17,6 +18,22 @@ import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:prism_plurality/shared/widgets/member_avatar.dart'; import 'package:prism_plurality/shared/widgets/prism_button.dart'; +/// Key for the single pronoun capsule in [MemberProfileHeader]. +/// +/// There is exactly one such capsule when the member has pronouns, and none +/// when the stored string is empty or whitespace. +const Key memberProfilePronounsCapsuleKey = Key('memberProfilePronounsCapsule'); + +/// How wide, in ems of the capsule's own text-scaled font size, the header must +/// be before the pronoun capsule stays in the avatar column. +/// +/// At or below this width the capsule moves under the avatar and uses the full +/// header width, matching the selected design reference ("about 15 em of the +/// pronoun text size"). The em is measured through the ambient [TextScaler] at +/// the body-medium role, so large and nonlinear text settings move the capsule +/// instead of squeezing the text. +const double memberProfilePronounsBesideAvatarMinEm = 15; + class MemberProfileHeader extends StatelessWidget { const MemberProfileHeader({ super.key, @@ -108,31 +125,81 @@ class _CompactMemberProfileHeader extends ConsumerWidget { preferDisplayName: ref.watch(memberNamePreferDisplayProvider), ); + final identity = _resolveMemberHeaderIdentity( + context, + ref, + member: member, + isFronting: isFronting, + foregroundColor: hasImage ? Colors.white : null, + secondaryColor: hasImage ? Colors.white.withValues(alpha: 0.82) : null, + applyTextShadow: hasImage, + onNameStyleTap: onNameStyleTap, + ); + Widget child = Padding( padding: hasImage ? const EdgeInsets.all(16) : EdgeInsets.zero, - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - _MemberHeaderAvatar( + child: LayoutBuilder( + builder: (context, constraints) { + final avatar = _MemberHeaderAvatar( member: member, size: 80, onTap: onAvatarTap, onRemove: onAvatarRemove, - ), - const SizedBox(width: 16), - Expanded( - child: _MemberHeaderMetadata( - member: member, - isFronting: isFronting, - foregroundColor: hasImage ? Colors.white : null, - secondaryColor: hasImage - ? Colors.white.withValues(alpha: 0.82) - : null, - applyTextShadow: hasImage, - onNameStyleTap: onNameStyleTap, - ), - ), - ], + ); + final pronounsBelowAvatar = + identity.pronouns != null && + _pronounsNeedFullHeaderWidth(context, constraints.maxWidth); + + if (!pronounsBelowAvatar) { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + avatar, + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + identity.nameBlock, + if (identity.pronouns != null) ...[ + const SizedBox(height: 8), + identity.pronouns!, + ], + if (identity.statusChips != null) ...[ + const SizedBox(height: 8), + identity.statusChips!, + ], + ], + ), + ), + ], + ); + } + + // Narrow for the current text size: the capsule (and the status chips + // under it) leave the avatar column and use the full header width. + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + avatar, + const SizedBox(width: 16), + Expanded(child: identity.nameBlock), + ], + ), + const SizedBox(height: 12), + identity.pronouns!, + if (identity.statusChips != null) ...[ + const SizedBox(height: 8), + identity.statusChips!, + ], + ], + ); + }, ), ); @@ -208,6 +275,18 @@ class _ClassicMemberProfileHeader extends ConsumerWidget { final resolvedName = member.effectiveName( preferDisplayName: ref.watch(memberNamePreferDisplayProvider), ); + // The classic layout already gives the identity cluster the full header + // width under the banner, so the capsule never needs to move. + final identity = _resolveMemberHeaderIdentity( + context, + ref, + member: member, + isFronting: isFronting, + titleStyle: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + onNameStyleTap: onNameStyleTap, + ); return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -242,13 +321,20 @@ class _ClassicMemberProfileHeader extends ConsumerWidget { const SizedBox(height: 54), Padding( padding: const EdgeInsets.symmetric(horizontal: 4), - child: _MemberHeaderMetadata( - member: member, - isFronting: isFronting, - titleStyle: theme.textTheme.headlineSmall?.copyWith( - fontWeight: FontWeight.bold, - ), - onNameStyleTap: onNameStyleTap, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + identity.nameBlock, + if (identity.pronouns != null) ...[ + const SizedBox(height: 8), + identity.pronouns!, + ], + if (identity.statusChips != null) ...[ + const SizedBox(height: 8), + identity.statusChips!, + ], + ], ), ), ], @@ -353,211 +439,302 @@ class _MemberHeaderAvatar extends ConsumerWidget { } } -class _MemberHeaderMetadata extends ConsumerWidget { - const _MemberHeaderMetadata({ - required this.member, - required this.isFronting, - this.foregroundColor, - this.secondaryColor, - this.titleStyle, - this.applyTextShadow = false, - this.onNameStyleTap, +/// The pieces of the member identity cluster, resolved once per build so each +/// header layout can place them without repeating style or provider work. +class _MemberHeaderIdentity { + const _MemberHeaderIdentity({ + required this.nameBlock, + this.pronouns, + this.statusChips, }); - final Member member; - final bool isFronting; - final Color? foregroundColor; - final Color? secondaryColor; - final TextStyle? titleStyle; - final bool applyTextShadow; - final VoidCallback? onNameStyleTap; + /// The name line: primary name, alternate name, and the name-style button. + final Widget nameBlock; - static const List _onImageShadows = [ - Shadow(color: Color(0x66000000), blurRadius: 8, offset: Offset(0, 1)), - ]; + /// The single pronoun display, or null when the member has no pronouns. + final Widget? pronouns; - @override - Widget build(BuildContext context, WidgetRef ref) { - final theme = Theme.of(context); - final primary = foregroundColor ?? theme.colorScheme.onSurface; - final secondary = secondaryColor ?? theme.colorScheme.onSurfaceVariant; - final birthday = _birthdayDisplay(context, member); - final shadows = applyTextShadow ? _onImageShadows : null; - final frontingTerms = watchFrontingTerms(context, ref); - - final namePresentation = ref.watch(memberNamePresentationProvider); - final primaryTitle = primaryNameFor(member, namePresentation); - final secondaryTitle = alternateNameFor(member, namePresentation); - - final pronouns = member.pronouns?.trim(); - final hasPronouns = pronouns != null && pronouns.isNotEmpty; - final titleCharBudget = - primaryTitle.length + - (secondaryTitle != null ? secondaryTitle.length + 3 : 0); - final pronounsInline = - hasPronouns && - !pronouns.contains('\n') && - !pronouns.contains('\r') && - titleCharBudget + pronouns.length + 3 <= 30; - - final baseHeadlineStyle = - titleStyle ?? - theme.textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold) ?? - const TextStyle(fontSize: 24, fontWeight: FontWeight.bold); - final headlineStyle = resolveMemberNameTextStyle( - context, - member, - baseHeadlineStyle, - defaultColor: primary, - shadows: shadows, - ); - final secondaryTitleStyle = headlineStyle.copyWith( - fontWeight: FontWeight.w400, - color: secondary, - ); - final inlinePronounsStyle = theme.textTheme.titleMedium?.copyWith( - color: secondary, - shadows: shadows, - ); + /// Age, birthday, fronting, admin and inactive chips, or null when empty. + final Widget? statusChips; +} + +const List _onImageShadows = [ + Shadow(color: Color(0x66000000), blurRadius: 8, offset: Offset(0, 1)), +]; + +/// Resolves the identity cluster for [_CompactMemberProfileHeader] and +/// [_ClassicMemberProfileHeader]. +/// +/// Pronouns are always a single capsule under the name — never part of the +/// title text and never a status chip — so the header shows one complete, +/// wrapping string. +_MemberHeaderIdentity _resolveMemberHeaderIdentity( + BuildContext context, + WidgetRef ref, { + required Member member, + required bool isFronting, + Color? foregroundColor, + Color? secondaryColor, + TextStyle? titleStyle, + bool applyTextShadow = false, + VoidCallback? onNameStyleTap, +}) { + final theme = Theme.of(context); + final primary = foregroundColor ?? theme.colorScheme.onSurface; + final secondary = secondaryColor ?? theme.colorScheme.onSurfaceVariant; + final birthday = _birthdayDisplay(context, member); + final shadows = applyTextShadow ? _onImageShadows : null; + final frontingTerms = watchFrontingTerms(context, ref); + + final namePresentation = ref.watch(memberNamePresentationProvider); + final primaryTitle = primaryNameFor(member, namePresentation); + final secondaryTitle = alternateNameFor(member, namePresentation); + + final baseHeadlineStyle = + titleStyle ?? + theme.textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold) ?? + const TextStyle(fontSize: 24, fontWeight: FontWeight.bold); + final headlineStyle = resolveMemberNameTextStyle( + context, + member, + baseHeadlineStyle, + defaultColor: primary, + shadows: shadows, + ); + final secondaryTitleStyle = headlineStyle.copyWith( + fontWeight: FontWeight.w400, + color: secondary, + ); + + final title = Text.rich( + TextSpan( + children: [ + TextSpan(text: primaryTitle, style: headlineStyle), + if (secondaryTitle != null) + TextSpan(text: ' ($secondaryTitle)', style: secondaryTitleStyle), + ], + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ); - final chips = _buildChips( + final nameBlock = onNameStyleTap == null + ? title + : Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: title), + const SizedBox(width: 6), + PrismIconButton( + icon: AppIcons.textFields, + tooltip: context.l10n.memberNameStyleTooltip, + semanticLabel: context.l10n.memberNameStyleTooltip, + size: 32, + iconSize: 17, + color: primary, + onPressed: onNameStyleTap, + ), + ], + ); + + // Empty and whitespace-only pronouns render nothing at all, so no gap is + // left behind where the capsule would have been. + final trimmedPronouns = member.pronouns?.trim(); + final pronouns = trimmedPronouns == null || trimmedPronouns.isEmpty + ? null + : trimmedPronouns; + + // Over an image the capsule and chips sit on a dark gradient, so they use the + // translucent white treatment instead of the theme's container colors. + final infoBackground = applyTextShadow + ? Colors.white.withValues(alpha: 0.16) + : theme.colorScheme.surfaceContainerHighest; + final infoForeground = applyTextShadow + ? Colors.white.withValues(alpha: 0.92) + : theme.colorScheme.onSurfaceVariant; + + return _MemberHeaderIdentity( + nameBlock: nameBlock, + pronouns: pronouns == null + ? null + : _PronounsCapsule( + pronouns: pronouns, + textStyle: _pronounsCapsuleTextStyle( + theme: theme, + color: infoForeground, + shadows: shadows, + ), + backgroundColor: infoBackground, + ), + statusChips: _buildStatusChips( context: context, theme: theme, - foreground: primary, - secondary: secondary, - pronouns: pronounsInline ? null : pronouns, + member: member, + isFronting: isFronting, + foregroundColor: foregroundColor, birthday: birthday, - shadows: shadows, frontingLabel: frontingTerms.activeSectionLabel, - ); + infoBackground: infoBackground, + infoForeground: infoForeground, + ), + ); +} - final title = Text.rich( - TextSpan( - children: [ - TextSpan(text: primaryTitle, style: headlineStyle), - if (secondaryTitle != null) - TextSpan(text: ' ($secondaryTitle)', style: secondaryTitleStyle), - if (pronounsInline) - TextSpan(text: ' · $pronouns', style: inlinePronounsStyle), - ], - ), - maxLines: 2, - overflow: TextOverflow.ellipsis, - ); +/// The capsule text role. Body-medium is the readable body size on every +/// platform (14 on phones, the desktop role elsewhere) and is deliberately not +/// derived from the name's headline size. +TextStyle _pronounsCapsuleTextStyle({ + required ThemeData theme, + required Color color, + List? shadows, +}) { + final base = theme.textTheme.bodyMedium ?? const TextStyle(fontSize: 14); + return base.copyWith( + color: color, + fontWeight: FontWeight.w500, + shadows: shadows, + ); +} - final titleRow = onNameStyleTap == null - ? title - : Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded(child: title), - const SizedBox(width: 6), - PrismIconButton( - icon: AppIcons.textFields, - tooltip: context.l10n.memberNameStyleTooltip, - semanticLabel: context.l10n.memberNameStyleTooltip, - size: 32, - iconSize: 17, - color: primary, - onPressed: onNameStyleTap!, - ), - ], - ); +/// Whether the pronoun capsule has to leave the avatar column and use the full +/// header width. +/// +/// [availableWidth] is the width the identity row actually receives from its +/// parent, and the capsule font size is resolved through the ambient +/// [TextScaler] at the body-medium role — so a nonlinear scaler is measured at +/// the role it is applied to, rather than through an assumed multiplier or a +/// UTF-16 character count. +bool _pronounsNeedFullHeaderWidth(BuildContext context, double availableWidth) { + if (!availableWidth.isFinite) return false; + final baseSize = Theme.of(context).textTheme.bodyMedium?.fontSize ?? 14; + final scaledSize = MediaQuery.textScalerOf(context).scale(baseSize); + if (scaledSize <= 0) return false; + return availableWidth <= memberProfilePronounsBesideAvatarMinEm * scaledSize; +} - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - titleRow, - if (chips.isNotEmpty) ...[ - const SizedBox(height: 8), - Wrap(spacing: 6, runSpacing: 6, children: chips), - ], - ], - ); - } +/// The single pronoun display: one wrapping capsule under the name. +/// +/// The string is rendered by [FieldInlineMarkdownText] so inline formatting and +/// member mentions keep working exactly as they do in the rest of the profile, +/// and the capsule grows with its content: no line limit, ellipsis, shrink or +/// FittedBox. Body text is shown as typed — nothing splits on "/". +class _PronounsCapsule extends StatelessWidget { + const _PronounsCapsule({ + required this.pronouns, + required this.textStyle, + required this.backgroundColor, + }); - List _buildChips({ - required BuildContext context, - required ThemeData theme, - required Color foreground, - required Color secondary, - required String? pronouns, - required String? birthday, - required List? shadows, - required String frontingLabel, - }) { - final chips = []; - - final infoBg = applyTextShadow - ? Colors.white.withValues(alpha: 0.16) - : theme.colorScheme.surfaceContainerHighest; - final infoFg = applyTextShadow - ? Colors.white.withValues(alpha: 0.92) - : theme.colorScheme.onSurfaceVariant; - - if (pronouns != null && pronouns.isNotEmpty) { - chips.add( - _Chip( - label: pronouns, - backgroundColor: infoBg, - foregroundColor: infoFg, - ), - ); - } - if (member.age != null) { - chips.add( - _Chip( - label: context.l10n.memberAgeDisplay(member.age!), - backgroundColor: infoBg, - foregroundColor: infoFg, - ), - ); - } - if (birthday != null) { - chips.add( - _Chip( - icon: AppIcons.calendarTodayOutlined, - label: birthday, - backgroundColor: infoBg, - foregroundColor: infoFg, - ), - ); - } - if (isFronting) { - chips.add( - _Chip( - icon: AppIcons.flashOn, - label: frontingLabel, - backgroundColor: AppColors.fronting( - theme.brightness, - ).withValues(alpha: 0.15), - foregroundColor: - foregroundColor ?? AppColors.fronting(theme.brightness), - ), - ); - } - if (member.isAdmin) { - chips.add( - _Chip( - icon: AppIcons.shieldOutlined, - label: context.l10n.memberAdminChip, - backgroundColor: theme.colorScheme.tertiaryContainer, - foregroundColor: theme.colorScheme.onTertiaryContainer, + final String pronouns; + final TextStyle textStyle; + final Color backgroundColor; + + /// Fixed padding: one line reads as a pill, several lines as a soft block. + /// The 16 pt radius keeps that reading at every length. + static const EdgeInsets padding = EdgeInsets.symmetric( + horizontal: 12, + vertical: 6, + ); + + @override + Widget build(BuildContext context) { + // A labelled container node keeps the pronoun role audible without excluding + // the rendered text, so links and member mentions inside the capsule stay + // their own accessible, tappable nodes. + return Semantics( + container: true, + label: context.l10n.memberPronounsLabel, + child: Container( + key: memberProfilePronounsCapsuleKey, + padding: padding, + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(16), + ), ), - ); - } - if (!member.isActive) { - chips.add( - _Chip( - icon: AppIcons.visibilityOffOutlined, - label: context.l10n.memberInactiveChip, - backgroundColor: theme.colorScheme.surfaceContainerHighest, - foregroundColor: theme.colorScheme.onSurfaceVariant, + child: FieldInlineMarkdownText( + pronouns, + style: textStyle, + // Null text alignment opts into the markdown fit-content policy, so + // the capsule hugs its text instead of stretching to the column. + textAlign: null, ), - ); - } - return chips; + ), + ); + } +} + +/// Age, birthday, fronting, admin and inactive chips. Pronouns are not chips; +/// they keep their own capsule and layout policy. +Widget? _buildStatusChips({ + required BuildContext context, + required ThemeData theme, + required Member member, + required bool isFronting, + required Color? foregroundColor, + required String? birthday, + required String frontingLabel, + required Color infoBackground, + required Color infoForeground, +}) { + final chips = []; + + if (member.age != null) { + chips.add( + _Chip( + label: context.l10n.memberAgeDisplay(member.age!), + backgroundColor: infoBackground, + foregroundColor: infoForeground, + ), + ); + } + if (birthday != null) { + chips.add( + _Chip( + icon: AppIcons.calendarTodayOutlined, + label: birthday, + backgroundColor: infoBackground, + foregroundColor: infoForeground, + ), + ); + } + if (isFronting) { + chips.add( + _Chip( + icon: AppIcons.flashOn, + label: frontingLabel, + backgroundColor: AppColors.fronting( + theme.brightness, + ).withValues(alpha: 0.15), + foregroundColor: + foregroundColor ?? AppColors.fronting(theme.brightness), + ), + ); + } + if (member.isAdmin) { + chips.add( + _Chip( + icon: AppIcons.shieldOutlined, + label: context.l10n.memberAdminChip, + backgroundColor: theme.colorScheme.tertiaryContainer, + foregroundColor: theme.colorScheme.onTertiaryContainer, + ), + ); } + if (!member.isActive) { + chips.add( + _Chip( + icon: AppIcons.visibilityOffOutlined, + label: context.l10n.memberInactiveChip, + backgroundColor: theme.colorScheme.surfaceContainerHighest, + foregroundColor: theme.colorScheme.onSurfaceVariant, + ), + ); + } + + if (chips.isEmpty) return null; + return Wrap(spacing: 6, runSpacing: 6, children: chips); } class _HeaderImage extends StatelessWidget { diff --git a/lib/features/notes/views/notes_list_screen.dart b/lib/features/notes/views/notes_list_screen.dart index f454c21ce..849eea090 100644 --- a/lib/features/notes/views/notes_list_screen.dart +++ b/lib/features/notes/views/notes_list_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/markdown/markdown_preview.dart'; @@ -34,6 +35,7 @@ import 'package:prism_plurality/shared/widgets/prism_toast.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; import 'package:prism_plurality/shared/widgets/modal_side_sheet_marker.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; @@ -197,6 +199,11 @@ class _NotesListScreenState extends ConsumerState list: (context, isWide) { setListDetailWide(isWide); return PrismPageScaffold( + // The notes header is a bar plus a filter bar and grows with the text + // scale. When a short viewport (landscape, keyboard up) cannot give it + // room for both itself and the list, it scrolls with the content + // instead of squeezing the list away. Ordinary bars keep the default. + topBarMinBodyExtent: 120, topBar: _NotesTopBar( title: l10n.memberSectionNotes, showBackButton: widget.showBackButton, @@ -481,7 +488,8 @@ class _NotesListScreenState extends ConsumerState } } -class _NotesTopBar extends StatelessWidget implements PreferredSizeWidget { +class _NotesTopBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const _NotesTopBar({ required this.title, required this.showBackButton, @@ -507,57 +515,83 @@ class _NotesTopBar extends StatelessWidget implements PreferredSizeWidget { PrismTokens.topBarHeight + (filterBar?.preferredSize.height ?? 0), ); + /// Bar plus the height the filter bar itself needs at the ambient text scale, + /// so the pinned band contains the search field and the member-chip strip + /// instead of clipping them. @override - Widget build(BuildContext context) { + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + final bar = _buildBar( + context, + ).preferredHeightFor(context, availableWidth: availableWidth); + final filter = filterBar; + if (filter == null) return bar; + // The filter bar is inset by its own horizontal padding, so it measures + // against the width it is really given. + final inset = filter is NotesFilterBar + ? NotesFilterBar.horizontalPadding + : 0.0; + return bar + + prismScaledHeightOf( + context, + filter, + availableWidth: availableWidth == null + ? null + : math.max(0.0, availableWidth - inset * 2), + ); + } + + PrismTopBar _buildBar(BuildContext context) { final l10n = context.l10n; final activeTint = Theme.of(context).colorScheme.primary; final inModalSideSheet = ModalSideSheetMarker.of(context); - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - PrismTopBar( - title: title, - leading: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (showBackButton) ...[ - PrismTopBarAction( - icon: inModalSideSheet ? AppIcons.close : AppIcons.arrowBack, - tooltip: inModalSideSheet ? l10n.close : l10n.back, - onPressed: () => closeDetailSurface(context), - ), - const SizedBox(width: 8), - ], - PrismTopBarAction( - icon: AppIcons.filterList, - tooltip: l10n.memberNoteFilterByMember, - tint: memberFilterActive ? activeTint : null, - accentIcon: memberFilterActive, - onPressed: onOpenMemberFilter, - ), - const SizedBox(width: 8), - PrismTopBarAction( - icon: AppIcons.search, - tooltip: l10n.memberNoteSearchNotes, - tint: searchActive ? activeTint : null, - accentIcon: searchActive, - onPressed: onToggleSearch, - ), - ], - ), - actions: [ + return PrismTopBar( + title: title, + leading: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (showBackButton) ...[ PrismTopBarAction( - icon: AppIcons.add, - tooltip: l10n.memberAddNoteTooltip, - onPressed: onCreateNote, + icon: inModalSideSheet ? AppIcons.close : AppIcons.arrowBack, + tooltip: inModalSideSheet ? l10n.close : l10n.back, + onPressed: () => closeDetailSurface(context), ), + const SizedBox(width: 8), ], + PrismTopBarAction( + icon: AppIcons.filterList, + tooltip: l10n.memberNoteFilterByMember, + tint: memberFilterActive ? activeTint : null, + accentIcon: memberFilterActive, + onPressed: onOpenMemberFilter, + ), + const SizedBox(width: 8), + PrismTopBarAction( + icon: AppIcons.search, + tooltip: l10n.memberNoteSearchNotes, + tint: searchActive ? activeTint : null, + accentIcon: searchActive, + onPressed: onToggleSearch, + ), + ], + ), + actions: [ + PrismTopBarAction( + icon: AppIcons.add, + tooltip: l10n.memberAddNoteTooltip, + onPressed: onCreateNote, ), - ?filterBar, ], ); } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [_buildBar(context), ?filterBar], + ); + } } class _NoteEditorPane { diff --git a/lib/features/notes/widgets/notes_filter_bar.dart b/lib/features/notes/widgets/notes_filter_bar.dart index 59e27af9e..4bc2c6f9d 100644 --- a/lib/features/notes/widgets/notes_filter_bar.dart +++ b/lib/features/notes/widgets/notes_filter_bar.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:prism_plurality/domain/models/member.dart'; @@ -5,6 +7,7 @@ import 'package:prism_plurality/shared/theme/app_icons.dart'; import 'package:prism_plurality/shared/widgets/member_chip.dart'; import 'package:prism_plurality/shared/widgets/prism_glass_icon_button.dart'; import 'package:prism_plurality/shared/widgets/prism_chip.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_text_field.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; @@ -22,7 +25,8 @@ class NotesMemberFilter { final Widget? avatar; } -class NotesFilterBar extends StatelessWidget implements PreferredSizeWidget { +class NotesFilterBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const NotesFilterBar({ super.key, required this.showSearch, @@ -46,6 +50,33 @@ class NotesFilterBar extends StatelessWidget implements PreferredSizeWidget { final List memberFilters; final ValueChanged? onClearMemberFilter; + /// Horizontal inset applied around the bar's content. + static const double horizontalPadding = 16; + + /// Height of the search slot this bar used to reserve; still the minimum, so + /// 1x geometry is unchanged. + static const double searchSlotHeight = 60; + + /// Bottom padding under the filter row. + static const double bottomPadding = 8; + + /// The same value, kept for callers that read the slot arithmetic. + static const double searchSlotBottomPadding = bottomPadding; + + /// Vertical content padding inside [PrismTextField] (12 + 12). + static const double _fieldVerticalPadding = 24; + + /// Vertical padding inside a [PrismChip] (6 + 6). + static const double _chipVerticalPadding = 12; + + /// A selected [PrismChip] draws a 1.5dp border, and `BoxDecoration.padding` adds + /// the border's dimensions to the chip's layout — so a filter chip is 3dp taller + /// than its padding plus content. Every chip in this bar is selected. + static const double _chipBorderWidth = 1.5; + + /// Gap between the search field and the chip strip when both are shown. + static const double _chipGapAbove = 8; + @override Size get preferredSize { final searchHeight = showSearch ? 60.0 : 0.0; @@ -53,6 +84,54 @@ class NotesFilterBar extends StatelessWidget implements PreferredSizeWidget { return Size.fromHeight(searchHeight + memberFilterHeight); } + /// Height the filter bar needs at the ambient text scale: the search field's + /// line box plus its content padding, the chip strip's tallest chip (label line + /// or the member avatar, which scales with the text as `MemberChip` does) plus + /// its padding, and the gaps. Never smaller than the fixed slot this bar used to + /// reserve, so nothing shrinks at normal text. + /// + /// Width does not enter: the field is single-line and the chip strip scrolls + /// horizontally, so both are one line whatever the width. + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + final theme = Theme.of(context); + final fieldStyle = theme.textTheme.bodyLarge ?? const TextStyle(); + final chipStyle = theme.textTheme.labelMedium ?? const TextStyle(); + final scaler = MediaQuery.textScalerOf(context); + + final field = showSearch + ? _fieldVerticalPadding + + prismLineHeight( + context, + fieldStyle, + text: searchQuery.isEmpty + ? context.l10n.memberNoteSearchHint + : searchQuery, + ) + : 0.0; + + var chip = 0.0; + if (memberFilters.isNotEmpty) { + var label = 0.0; + for (final filter in memberFilters) { + label = math.max( + label, + prismLineHeight(context, chipStyle, text: filter.label), + ); + } + // `MemberChip` scales its 20dp avatar with the text scale; the chip's own + // border adds `_chipBorderWidth` on each side. + chip = + _chipVerticalPadding + + _chipBorderWidth * 2 + + math.max(label, scaler.scale(20)); + } + + final gap = showSearch && chip > 0 ? _chipGapAbove : 0.0; + final measured = field + gap + chip + bottomPadding; + return math.max(preferredSize.height, measured); + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -60,7 +139,12 @@ class NotesFilterBar extends StatelessWidget implements PreferredSizeWidget { final l10n = context.l10n; return Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: const EdgeInsets.fromLTRB( + horizontalPadding, + 0, + horizontalPadding, + bottomPadding, + ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -91,7 +175,7 @@ class NotesFilterBar extends StatelessWidget implements PreferredSizeWidget { if (memberFilters.isNotEmpty) Padding( - padding: EdgeInsets.only(top: showSearch ? 8 : 0), + padding: EdgeInsets.only(top: showSearch ? _chipGapAbove : 0), child: Row( children: [ Expanded( diff --git a/lib/features/onboarding/views/onboarding_screen.dart b/lib/features/onboarding/views/onboarding_screen.dart index 9393d9ec3..2d97a6667 100644 --- a/lib/features/onboarding/views/onboarding_screen.dart +++ b/lib/features/onboarding/views/onboarding_screen.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:phosphor_flutter/phosphor_flutter.dart'; @@ -7,6 +9,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:prism_plurality/core/router/app_routes.dart'; import 'package:prism_plurality/core/router/onboarding_local_completion.dart'; +import 'package:prism_plurality/domain/preferences/fronting_terms.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; import 'package:prism_plurality/features/onboarding/widgets/welcome_step.dart'; @@ -39,6 +43,21 @@ import 'package:prism_plurality/shared/widgets/prism_inline_icon_button.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/widgets/prism_logo_tile.dart'; +// Geometry shared by the screen and its height budget. The widgets below use +// these same constants, so a measurement of the strip, the bar or the CTA can +// never drift from what is rendered. +const double kOnboardingStripVerticalPadding = 12; +const double kOnboardingStripActionSlot = 48; +const double kOnboardingStripCapsuleHeight = 4; +const double kOnboardingBarVerticalPadding = 16; +const double kOnboardingBarHorizontalPadding = 24; +const double kOnboardingBarGap = 12; +const double kCircleButtonSize = 48; +const double kPillHorizontalPadding = 32; +const double kPillVerticalPadding = 14; +const double kPillFontSize = 16; +const int kPillMaxLines = 2; + class OnboardingScreen extends ConsumerStatefulWidget { const OnboardingScreen({super.key}); @@ -116,6 +135,54 @@ class _OnboardingScreenState extends ConsumerState }); } + // Layout policy for this flow, measured from the styles and geometry that are + // actually rendered: + // * the readable minimum for the step header (its real title at its real + // style and width, up to two lines), + // * the smallest body that still shows a whole input (the name field's own + // style, padding and helper line), + // * the pinned chrome: the progress strip, and the bottom bar with the CTA's + // label measured at the width the pill really gets, + // * and whether those three fit the viewport. + final viewportWidth = MediaQuery.sizeOf(context).width; + final showStrip = !isFullScreenStep && !isCompleteStep; + final showBar = !isFullScreenStep && !isSelfManagedStep; + final showsBack = !isFirstStep && !importBusy; + final ctaLabel = isCompleteStep || isFirstStep + ? context.l10n.onboardingGetStarted + : context.l10n.onboardingContinue; + final minimumHeaderExtent = showStrip + ? _FlowLayoutBudget.minimumHeaderExtent( + context, + title: step.localizedTitle( + context, + frontingTerms: pendingFrontingTerms, + ), + titleStyle: Theme.of( + context, + ).textTheme.headlineLarge?.copyWith(fontSize: 28), + availableWidth: viewportWidth, + ) + : 0.0; + final minimumInputExtent = _FlowLayoutBudget.minimumInputExtent( + context, + availableWidth: viewportWidth, + ); + final pinnedChrome = + (showStrip + ? _FlowLayoutBudget.stripExtent( + showsCloseAction: hasExistingData && !importBusy, + ) + : 0.0) + + (showBar + ? _FlowLayoutBudget.barExtent( + context, + ctaLabel: ctaLabel, + showsBack: showsBack, + availableWidth: viewportWidth, + ) + : 0.0); + return PopScope( canPop: hasExistingData, onPopInvokedWithResult: (didPop, _) { @@ -168,165 +235,198 @@ class _OnboardingScreenState extends ConsumerState ), ), SafeArea( - child: Column( - children: [ - if (!isFullScreenStep && !isCompleteStep) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 12, - ), - child: Row( + child: LayoutBuilder( + builder: (context, constraints) { + final viewportHeight = constraints.maxHeight; + final tight = _FlowLayoutBudget.isTight( + viewportHeight: viewportHeight, + pinnedChrome: pinnedChrome, + minimumHeader: minimumHeaderExtent, + minimumInput: minimumInputExtent, + ); + // Tight: lay the same column out taller than the viewport and + // let it scroll, so the header, the input and the footer are + // all reachable and the body keeps a whole input's height. + // Otherwise the column is exactly the viewport, as before, and + // the scroll view cannot move. + final flowHeight = tight && viewportHeight.isFinite + ? pinnedChrome + + minimumHeaderExtent + + minimumInputExtent + + 1 // one dp of rounding slack for the text layout + : viewportHeight; + return SingleChildScrollView( + physics: tight + ? const ClampingScrollPhysics() + : const NeverScrollableScrollPhysics(), + child: SizedBox( + height: flowHeight.isFinite ? flowHeight : null, + child: Column( children: [ - if (hasExistingData && !importBusy) - PrismInlineIconButton( - onPressed: () { - notifier.clearAppearancePreview(); - context.go(AppRoutePaths.home); - }, - icon: AppIcons.close, - color: colorScheme.onSurface.withValues( - alpha: 0.8, + if (!isFullScreenStep && !isCompleteStep) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: kOnboardingStripVerticalPadding, + ), + child: Row( + children: [ + if (hasExistingData && !importBusy) + PrismInlineIconButton( + onPressed: () { + notifier.clearAppearancePreview(); + context.go(AppRoutePaths.home); + }, + icon: AppIcons.close, + color: colorScheme.onSurface.withValues( + alpha: 0.8, + ), + tooltip: context + .l10n + .onboardingCloseOnboarding, + ) + else + const SizedBox( + width: kOnboardingStripActionSlot, + ), + Expanded( + child: _ProgressIndicator( + steps: _progressSteps, + currentStep: step, + isDark: isDark, + primary: primary, + ), + ), + const SizedBox( + width: kOnboardingStripActionSlot, + ), + ], ), - tooltip: context.l10n.onboardingCloseOnboarding, - ) - else - const SizedBox(width: 48), - Expanded( - child: _ProgressIndicator( - steps: _progressSteps, - currentStep: step, - isDark: isDark, - primary: primary, ), - ), - const SizedBox(width: 48), - ], - ), - ), - if (!isCompleteStep && !isFullScreenStep) ...[ - const SizedBox(height: 8), - if (step == OnboardingStep.welcome) - const PrismLogoTile( - size: 56, - logoSize: 56, - shape: BoxShape.circle, - ) - else - Container( - width: 56, - height: 56, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: primary.withValues(alpha: 0.15), - ), - child: Center( - child: PhosphorIcon( - step.icon, - size: 28, - color: primary, - ), - ), - ), - const SizedBox(height: 12), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: Text( - step.localizedTitle( - context, - frontingTerms: pendingFrontingTerms, - ), - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.headlineLarge - ?.copyWith( - fontSize: 28, - color: colorScheme.onSurface, - ), - ), - ), - if (step.localizedSubtitle( - context, - frontingTerms: pendingFrontingTerms, - ) - case final subtitle?) ...[ - const SizedBox(height: 4), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 24), - child: Text( - subtitle, - textAlign: TextAlign.center, - style: theme.textTheme.bodyMedium?.copyWith( - fontSize: 15, - color: colorScheme.onSurfaceVariant, + Expanded( + child: !isCompleteStep && !isFullScreenStep + // The step header and the step body share the space + // between the pinned progress strip and the pinned + // bottom bar. The header is a fixed block of 28pt text + // above a flexible body, so at large text on a compact + // phone it used to consume the whole viewport: the body + // was laid out at zero height and the Column reported a + // large overflow. The header now negotiates its height + // with this Column (see _StepHeaderBudget) and scrolls + // inside it, so the body always keeps a usable share and + // nothing is lost - the header text stays at the size the + // user asked for, just scrollable. + ? LayoutBuilder( + builder: (context, constraints) { + final headerMaxHeight = + _StepHeaderBudget.headerMaxHeightFor( + constraints.maxHeight, + minBodyHeight: minimumInputExtent, + ); + return Column( + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxHeight: headerMaxHeight, + ), + child: SingleChildScrollView( + child: _buildStepHeader( + context: context, + step: step, + pendingFrontingTerms: + pendingFrontingTerms, + ), + ), + ), + Expanded( + child: AnimatedSwitcher( + duration: const Duration( + milliseconds: 300, + ), + child: _buildStepContent( + onboarding, + ), + ), + ), + ], + ); + }, + ) + : AnimatedSwitcher( + duration: const Duration(milliseconds: 300), + child: _buildStepContent(onboarding), + ), ), - ), - ), - ], - const SizedBox(height: 20), - ], - - Expanded( - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 300), - child: _buildStepContent(onboarding), - ), - ), - if (!isFullScreenStep && !isSelfManagedStep) - Padding( - padding: const EdgeInsets.symmetric( - horizontal: 24, - vertical: 16, - ), - child: Row( - children: [ - if (!isFirstStep && !importBusy) - _CircleButton( - icon: AppIcons.arrowBack, - onPressed: notifier.back, + if (!isFullScreenStep && !isSelfManagedStep) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: kOnboardingBarHorizontalPadding, + vertical: kOnboardingBarVerticalPadding, + ), + child: Row( + children: [ + if (!isFirstStep && !importBusy) + _CircleButton( + icon: AppIcons.arrowBack, + onPressed: notifier.back, + ), + const SizedBox(width: kOnboardingBarGap), + // The CTA takes the width left beside the Back + // control so that at large text it wraps its label + // inside the viewport instead of painting past the + // right edge on a compact phone. + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: _PillButton( + label: isCompleteStep + ? context.l10n.onboardingGetStarted + : isFirstStep + ? context.l10n.onboardingGetStarted + : context.l10n.onboardingContinue, + enabled: + notifier.canProceed && + !_isCompleting && + !importBusy, + isLoading: _isCompleting, + primary: primary, + onPressed: () { + if (isCompleteStep) { + _completeOnboarding(); + return; + } + // If an import sub-flow has registered a + // pending action, run it instead of silently + // skipping past the inline import UI. + final pending = ref.read( + onboardingPendingImportActionProvider, + ); + if (pending != null) { + pending(); + return; + } + // Empty is allowed but usually an accidental + // skip — confirm first. + if (step == + OnboardingStep.addMembers) { + _confirmThenAdvance(); + return; + } + notifier.next(); + }, + ), + ), + ), + ], + ), ), - const Spacer(), - _PillButton( - label: isCompleteStep - ? context.l10n.onboardingGetStarted - : isFirstStep - ? context.l10n.onboardingGetStarted - : context.l10n.onboardingContinue, - enabled: - notifier.canProceed && - !_isCompleting && - !importBusy, - isLoading: _isCompleting, - primary: primary, - onPressed: () { - if (isCompleteStep) { - _completeOnboarding(); - return; - } - // If an import sub-flow has registered a - // pending action, run it instead of silently - // skipping past the inline import UI. - final pending = ref.read( - onboardingPendingImportActionProvider, - ); - if (pending != null) { - pending(); - return; - } - // Empty is allowed but usually an accidental - // skip — confirm first. - if (step == OnboardingStep.addMembers) { - _confirmThenAdvance(); - return; - } - notifier.next(); - }, - ), ], ), ), - ], + ); + }, ), ), ], @@ -335,6 +435,72 @@ class _OnboardingScreenState extends ConsumerState ); } + /// Logo, title and subtitle for the current step. + /// + /// Pure presentation - no state, controllers or focus - so wrapping it in a + /// scroll view cannot disturb the step body, the flow or the busy Back guard. + Widget _buildStepHeader({ + required BuildContext context, + required OnboardingStep step, + required FrontingTermBundle pendingFrontingTerms, + }) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + final primary = colorScheme.primary; + final subtitle = step.localizedSubtitle( + context, + frontingTerms: pendingFrontingTerms, + ); + + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 8), + if (step == OnboardingStep.welcome) + const PrismLogoTile(size: 56, logoSize: 56, shape: BoxShape.circle) + else + Container( + width: 56, + height: 56, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: primary.withValues(alpha: 0.15), + ), + child: Center( + child: PhosphorIcon(step.icon, size: 28, color: primary), + ), + ), + const SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text( + step.localizedTitle(context, frontingTerms: pendingFrontingTerms), + textAlign: TextAlign.center, + style: theme.textTheme.headlineLarge?.copyWith( + fontSize: 28, + color: colorScheme.onSurface, + ), + ), + ), + if (subtitle != null) ...[ + const SizedBox(height: 4), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text( + subtitle, + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium?.copyWith( + fontSize: 15, + color: colorScheme.onSurfaceVariant, + ), + ), + ), + ], + const SizedBox(height: 20), + ], + ); + } + Widget _buildStepContent(OnboardingState onboarding) { final step = onboarding.currentStep; final n = ref.read(onboardingProvider.notifier); @@ -502,35 +668,57 @@ class _ProgressIndicator extends StatelessWidget { Widget build(BuildContext context) { final currentIndex = steps.indexOf(currentStep); - return Semantics( - label: context.l10n.onboardingProgressStep( - currentIndex + 1, - steps.length, - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: List.generate(steps.length, (index) { - final isCurrent = index == currentIndex; - final isPast = index < currentIndex; - return AnimatedContainer( - duration: const Duration(milliseconds: 300), - curve: Curves.easeInOut, - margin: const EdgeInsets.symmetric(horizontal: 2), - height: 4, - width: isCurrent ? 24 : 12, - decoration: BoxDecoration( - borderRadius: BorderRadius.circular( - PrismShapes.of(context).radius(2), - ), - color: isCurrent - ? primary - : isPast - ? primary.withValues(alpha: 0.5) - : primary.withValues(alpha: 0.2), - ), - ); - }), - ), + final semanticsLabel = context.l10n.onboardingProgressStep( + currentIndex + 1, + steps.length, + ); + // The capsules are fixed geometry, not text, so they cannot shrink with + // the scaler and 15 of them need 252dp (4dp margins + a double-width + // current capsule). Inside the header slot on a 320dp phone only 184dp is + // left, which overflowed by 68dp at *default* text. Keep the exact 24/12 + // geometry whenever it fits and scale both widths by the same factor + // when the slot is narrower, so the strip never paints past its slot at + // any width or text scale. The accessible step label is unaffected. + return LayoutBuilder( + builder: (context, constraints) { + const idealUnitWidth = 12.0; + const marginPerCapsule = 4.0; + final margins = marginPerCapsule * steps.length; + final available = constraints.maxWidth.isFinite + ? constraints.maxWidth + : margins + idealUnitWidth * (steps.length + 1); + final free = math.max(0.0, available - margins); + final unitWidth = math.min(idealUnitWidth, free / (steps.length + 1)); + return Semantics( + label: semanticsLabel, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(steps.length, (index) { + final isCurrent = index == currentIndex; + final isPast = index < currentIndex; + return AnimatedContainer( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + margin: const EdgeInsets.symmetric( + horizontal: marginPerCapsule / 2, + ), + height: 4, + width: unitWidth * (isCurrent ? 2 : 1), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(2), + ), + color: isCurrent + ? primary + : isPast + ? primary.withValues(alpha: 0.5) + : primary.withValues(alpha: 0.2), + ), + ); + }), + ), + ); + }, ); } } @@ -574,8 +762,8 @@ class _CircleButtonState extends State<_CircleButton> { duration: const Duration(milliseconds: 100), child: AnimatedContainer( duration: const Duration(milliseconds: 100), - width: 48, - height: 48, + width: kCircleButtonSize, + height: kCircleButtonSize, decoration: BoxDecoration( shape: BoxShape.circle, color: _pressed ? pressedBg : normalBg, @@ -639,7 +827,10 @@ class _PillButtonState extends State<_PillButton> { duration: const Duration(milliseconds: 100), child: AnimatedContainer( duration: const Duration(milliseconds: 150), - padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 14), + padding: const EdgeInsets.symmetric( + horizontal: kPillHorizontalPadding, + vertical: kPillVerticalPadding, + ), decoration: BoxDecoration( borderRadius: BorderRadius.circular( PrismShapes.of(context).radius(28), @@ -653,9 +844,15 @@ class _PillButtonState extends State<_PillButton> { ? PrismSpinner(color: contentColor, size: 20) : Text( widget.label, + // Same policy as PrismButton: two lines at the requested + // size, then ellipsis. The full label stays in semantics. + maxLines: kPillMaxLines, + overflow: TextOverflow.ellipsis, + softWrap: true, + textAlign: TextAlign.center, style: TextStyle( color: contentColor, - fontSize: 16, + fontSize: kPillFontSize, fontWeight: FontWeight.w600, ), ), @@ -664,3 +861,174 @@ class _PillButtonState extends State<_PillButton> { ); } } + +/// Height [text] needs at [maxWidth], measured from the style the text really +/// renders with. +/// +/// The explicit style is merged over the ambient `DefaultTextStyle` exactly as +/// `Text` does it, so family, weight, leading, locale and the text scaler all +/// come from the running app instead of a ratio invented here. +double _measuredTextHeight( + BuildContext context, { + required String text, + required TextStyle? style, + required double maxWidth, + int? maxLines, +}) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: maxLines, + ellipsis: maxLines == null ? null : '\u2026', + textHeightBehavior: prismTextHeightBehaviorFor(context), + )..layout(maxWidth: math.max(0.0, maxWidth)); + final height = painter.height; + painter.dispose(); + return height; +} + +/// Measured pieces the flow-height decision is made from. +/// +/// Every number here comes from the real resolved styles and the geometry the +/// widgets render with (the same constants they use), never from a font ratio or +/// an assumed line count. +abstract final class _FlowLayoutBudget { + /// Progress strip: its vertical padding plus the tallest thing inside it (the + /// close action when it is shown, otherwise the capsules). + static double stripExtent({required bool showsCloseAction}) { + final inner = showsCloseAction + ? kOnboardingStripActionSlot + : kOnboardingStripCapsuleHeight; + return 2 * kOnboardingStripVerticalPadding + inner; + } + + /// Bottom bar: its vertical padding plus the taller of the Back circle and the + /// CTA pill, where the pill's label is measured at the width the pill really + /// gets, with its own style and line cap. + static double barExtent( + BuildContext context, { + required String ctaLabel, + required bool showsBack, + required double availableWidth, + }) { + const barHorizontal = 2 * kOnboardingBarHorizontalPadding; + final backExtent = showsBack ? kCircleButtonSize : 0.0; + final pillMaxWidth = math.max( + 0.0, + availableWidth - + barHorizontal - + backExtent - + kOnboardingBarGap - + 2 * kPillHorizontalPadding, + ); + final labelHeight = _measuredTextHeight( + context, + text: ctaLabel, + style: const TextStyle( + fontSize: kPillFontSize, + fontWeight: FontWeight.w600, + ), + maxWidth: pillMaxWidth, + maxLines: kPillMaxLines, + ); + final pillHeight = 2 * kPillVerticalPadding + labelHeight; + final rowHeight = math.max(showsBack ? kCircleButtonSize : 0.0, pillHeight); + return 2 * kOnboardingBarVerticalPadding + rowHeight; + } + + /// The header's readable minimum: the real step title at its real style and + /// width, capped at two lines, so the header is never reduced to nothing just + /// to grow the body. + static double minimumHeaderExtent( + BuildContext context, { + required String title, + required TextStyle? titleStyle, + required double availableWidth, + }) { + return _measuredTextHeight( + context, + text: title, + style: titleStyle, + maxWidth: availableWidth - 48, + maxLines: 2, + ); + } + + /// The smallest body that still shows a whole input: the flow's tallest input + /// is the system-name field, so its own style, padding and helper line are the + /// model, measured rather than assumed. + static double minimumInputExtent( + BuildContext context, { + required double availableWidth, + }) { + final fieldLine = _measuredTextHeight( + context, + text: 'Wg', + style: SystemNameStep.fieldTextStyle(context), + maxWidth: + availableWidth - 2 * 32 - 2 * SystemNameStep.fieldHorizontalPadding, + maxLines: 1, + ); + final helperLine = _measuredTextHeight( + context, + text: 'Wg', + style: SystemNameStep.helperTextStyle(context), + maxWidth: availableWidth - 2 * 32, + maxLines: 1, + ); + // The field's own vertical padding plus a 1dp allowance for its rounded + // border, then the gap and one helper line beneath it. + return fieldLine + + 2 * SystemNameStep.fieldVerticalPadding + + 1 + + SystemNameStep.fieldToHelperGap + + helperLine; + } + + /// Whether the pinned layout can still hold the header's readable minimum and + /// a whole input between the strip and the bar. + static bool isTight({ + required double viewportHeight, + required double pinnedChrome, + required double minimumHeader, + required double minimumInput, + }) { + if (!viewportHeight.isFinite) return false; + return viewportHeight < pinnedChrome + minimumHeader + minimumInput; + } +} + +/// Height negotiation between the onboarding step header and the step body. +/// +/// The progress strip above them and the bottom bar below them are pinned, so +/// the header and the body split what is left. The header is fixed-size text +/// (a 28pt title plus a 15pt subtitle at the user's text scale) while the body +/// is the flexible one, so an unbounded header consumes the whole area: at +/// 3.375x on a 320x568 phone the title and subtitle alone are several hundred +/// dp, the body is laid out at zero height and the Column overflows - no step +/// control is reachable at all. +/// +/// The header therefore keeps its natural height whenever that leaves the body +/// at least [minBodyHeight]; past that point the header is capped and scrolls. +/// Nothing is shrunk or hidden: the title and subtitle keep the size the user +/// asked for, they are only reachable by scrolling. +abstract final class _StepHeaderBudget { + /// Never let the header take so much of [contentHeight] that the body would be + /// squeezed below what a whole input needs. + static double headerMaxHeightFor( + double contentHeight, { + required double minBodyHeight, + }) { + if (!contentHeight.isFinite) return double.infinity; + // The body reserves exactly what a whole input needs and the header takes + // the rest, scrolling inside it. When even that does not fit, the flow is in + // the tight fallback and is laid out taller than the viewport on purpose, so + // there is no case left where this would demand more than the column has. + return math.max(0.0, contentHeight - minBodyHeight); + } +} diff --git a/lib/features/onboarding/widgets/import_data_step.dart b/lib/features/onboarding/widgets/import_data_step.dart index e44402886..e18e9e3cb 100644 --- a/lib/features/onboarding/widgets/import_data_step.dart +++ b/lib/features/onboarding/widgets/import_data_step.dart @@ -2461,9 +2461,15 @@ class _BackLink extends StatelessWidget { children: [ Icon(AppIcons.arrowBackIos, size: 14, color: linkColor), const SizedBox(width: 4), - Text( - context.l10n.onboardingImportOtherOptions, - style: theme.textTheme.bodyMedium?.copyWith(color: linkColor), + // The label was a non-flex child of a min-size Row: at 1.5x it needed + // ~23dp more than the body had and the row overflowed sideways. It + // wraps at the requested size instead; the tap target and the label are + // unchanged. + Flexible( + child: Text( + context.l10n.onboardingImportOtherOptions, + style: theme.textTheme.bodyMedium?.copyWith(color: linkColor), + ), ), ], ), @@ -2486,8 +2492,11 @@ class _ActionButton extends StatelessWidget { @override Widget build(BuildContext context) { - return SizedBox( - height: 52, + // Minimum, not a fixed height: PrismButton's own padding plus a two-line + // label does not fit in 52dp once text is scaled, and a tight box lays the + // label out below its own line box. At default text this is still 52dp. + return ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), child: PrismButton( label: label, onPressed: onPressed, diff --git a/lib/features/onboarding/widgets/onboarding_data_ready_view.dart b/lib/features/onboarding/widgets/onboarding_data_ready_view.dart index 856b0d856..eb645b245 100644 --- a/lib/features/onboarding/widgets/onboarding_data_ready_view.dart +++ b/lib/features/onboarding/widgets/onboarding_data_ready_view.dart @@ -118,8 +118,11 @@ class OnboardingDataReadyView extends ConsumerWidget { ), ], const SizedBox(height: 32), - SizedBox( - height: 52, + // Minimum, not a fixed height: a tight 52dp box lays the label out + // below its own line box as soon as the text scales. Still 52dp at + // default text. + ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), child: PrismButton( onPressed: onAction, label: actionLabel, diff --git a/lib/features/onboarding/widgets/sync_device_step.dart b/lib/features/onboarding/widgets/sync_device_step.dart index 176a5f2f2..ae4eaffc3 100644 --- a/lib/features/onboarding/widgets/sync_device_step.dart +++ b/lib/features/onboarding/widgets/sync_device_step.dart @@ -320,6 +320,12 @@ class _JoinPromptView extends StatelessWidget { ), child: Row( mainAxisAlignment: MainAxisAlignment.center, + // The label was a non-flex Row child: at 3.375x on a 320dp + // phone it needed ~456dp inside a ~232dp line box and the row + // overflowed to the right by 224dp. Flexible lets it wrap at + // the requested size instead of being clipped or shrunk; the + // tap target still hugs the text at default sizes. + mainAxisSize: MainAxisSize.min, children: [ Icon( showRelayConfiguration @@ -329,11 +335,14 @@ class _JoinPromptView extends StatelessWidget { color: fg.withValues(alpha: 0.72), ), const SizedBox(width: 6), - Text( - context.l10n.syncSetupSelfHosted, - style: theme.textTheme.bodySmall?.copyWith( - color: fg.withValues(alpha: 0.72), - fontWeight: FontWeight.w600, + Flexible( + child: Text( + context.l10n.syncSetupSelfHosted, + textAlign: TextAlign.center, + style: theme.textTheme.bodySmall?.copyWith( + color: fg.withValues(alpha: 0.72), + fontWeight: FontWeight.w600, + ), ), ), ], @@ -1031,8 +1040,12 @@ class _ActionButton extends StatelessWidget { @override Widget build(BuildContext context) { - return SizedBox( - height: 52, + // Minimum, not a fixed height: PrismButton's own padding plus a two-line + // label does not fit in 52dp once text is scaled, and a tight box lays the + // label out below its own line box (1.5x needed 64dp, max needed 144dp). + // At default text this is still exactly 52dp. + return ConstrainedBox( + constraints: const BoxConstraints(minHeight: 52), child: PrismButton( onPressed: onPressed, label: label, diff --git a/lib/features/onboarding/widgets/sync_progress_view.dart b/lib/features/onboarding/widgets/sync_progress_view.dart index f5578eb39..524159009 100644 --- a/lib/features/onboarding/widgets/sync_progress_view.dart +++ b/lib/features/onboarding/widgets/sync_progress_view.dart @@ -124,75 +124,94 @@ class _SyncProgressViewState extends ConsumerState { ? state.restoreProgressFraction : null; - return Padding( - padding: const EdgeInsets.all(24), - child: Center( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - PhaseSegments(currentIndex: phase.index, totalPhases: 4), - const SizedBox(height: 48), - AnimatedSwitcher( - duration: disableAnimations - ? Duration.zero - : const Duration(milliseconds: 300), - child: showSpinner - ? PrismSpinner( - key: const ValueKey('spinner'), - color: theme.colorScheme.primary, - size: 48, - duration: const Duration(milliseconds: 2400), - ) - : restoreProgressValue != null - ? ClipRRect( - key: const ValueKey('restore-progress'), - borderRadius: BorderRadius.circular( - PrismShapes.of(context).radius(6), - ), - child: LinearProgressIndicator( - value: restoreProgressValue, - minHeight: 12, - ), - ) - : const PrismShimmerBar(key: ValueKey('shimmer')), + final Widget progressIndicator = showSpinner + ? PrismSpinner( + key: const ValueKey('spinner'), + color: theme.colorScheme.primary, + size: 48, + duration: const Duration(milliseconds: 2400), + ) + : restoreProgressValue != null + ? ClipRRect( + key: const ValueKey('restore-progress'), + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(6), ), - const SizedBox(height: 32), - Semantics( - liveRegion: true, - child: Text( - title, - style: theme.textTheme.titleLarge, - textAlign: TextAlign.center, - ), + child: LinearProgressIndicator( + value: restoreProgressValue, + minHeight: 12, ), - const SizedBox(height: 8), - Text( - subtitle, - style: theme.textTheme.bodyMedium?.copyWith( - color: mutedTextColor, + ) + : const PrismShimmerBar(key: ValueKey('shimmer')); + + // The pairing progress column is taller than a compact phone at large text + // (196dp of bottom overflow at 3.375x on 320x568), and it sat in a + // non-scrolling Center: the phase segments, the count card and the + // reassurance copy were painted below the bottom edge with no way to reach + // them. It now scrolls; the centre alignment is kept for the case where it + // fits, so nothing moves at default text. + return LayoutBuilder( + builder: (context, constraints) { + final viewportHeight = constraints.maxHeight; + final minContentHeight = viewportHeight.isFinite && viewportHeight > 48 + ? viewportHeight - 48 + : 0.0; + return SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: minContentHeight), + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + PhaseSegments(currentIndex: phase.index, totalPhases: 4), + const SizedBox(height: 48), + AnimatedSwitcher( + duration: disableAnimations + ? Duration.zero + : const Duration(milliseconds: 300), + child: progressIndicator, + ), + const SizedBox(height: 32), + Semantics( + liveRegion: true, + child: Text( + title, + style: theme.textTheme.titleLarge, + textAlign: TextAlign.center, + ), + ), + const SizedBox(height: 8), + Text( + subtitle, + style: theme.textTheme.bodyMedium?.copyWith( + color: mutedTextColor, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 32), + Hero( + tag: 'sync-progress-count-card', + child: LiveCountCard(counts: state.liveCounts), + ), + const SizedBox(height: 16), + if (showReassurance) + Text( + l10n.onboardingSyncReassurance, + style: theme.textTheme.bodySmall?.copyWith( + color: mutedTextColor, + ), + textAlign: TextAlign.center, + ) + else + const SizedBox.shrink(), + ], ), - textAlign: TextAlign.center, ), - const SizedBox(height: 32), - Hero( - tag: 'sync-progress-count-card', - child: LiveCountCard(counts: state.liveCounts), - ), - const SizedBox(height: 16), - if (showReassurance) - Text( - l10n.onboardingSyncReassurance, - style: theme.textTheme.bodySmall?.copyWith( - color: mutedTextColor, - ), - textAlign: TextAlign.center, - ) - else - const SizedBox.shrink(), - ], - ), - ), + ), + ); + }, ); } diff --git a/lib/features/onboarding/widgets/system_name_step.dart b/lib/features/onboarding/widgets/system_name_step.dart index bdfbe0753..ac3b2976b 100644 --- a/lib/features/onboarding/widgets/system_name_step.dart +++ b/lib/features/onboarding/widgets/system_name_step.dart @@ -9,6 +9,34 @@ import 'package:prism_plurality/shared/extensions/app_localizations_extension.da class SystemNameStep extends ConsumerStatefulWidget { const SystemNameStep({super.key}); + // The field and helper geometry, shared with the onboarding screen's height + // budget so its measurement can never drift from what is rendered here. + static const double fieldFontSize = 20; + static const FontWeight fieldFontWeight = FontWeight.w500; + static const double fieldVerticalPadding = 18; + static const double fieldHorizontalPadding = 20; + static const double helperFontSize = 14; + static const double fieldToHelperGap = 16; + + /// Text style of the name field, resolved for [context]. + static TextStyle fieldTextStyle(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return TextStyle( + color: isDark ? AppColors.warmWhite : AppColors.warmBlack, + fontSize: fieldFontSize, + fontWeight: fieldFontWeight, + ); + } + + /// Text style of the helper copy, resolved for [context]. + static TextStyle helperTextStyle(BuildContext context) { + final isDark = Theme.of(context).brightness == Brightness.dark; + return TextStyle( + color: isDark ? AppColors.mutedTextDark : AppColors.mutedTextLight, + fontSize: helperFontSize, + ); + } + @override ConsumerState createState() => _SystemNameStepState(); } @@ -44,7 +72,8 @@ class _SystemNameStepState extends ConsumerState { }); final onboarding = ref.watch(onboardingProvider); - final wasImported = onboarding.wasImportedFromPluralKit || + final wasImported = + onboarding.wasImportedFromPluralKit || onboarding.wasImportedFromSimplyPlural; final autoFocus = !wasImported; final isDark = Theme.of(context).brightness == Brightness.dark; @@ -52,57 +81,74 @@ class _SystemNameStepState extends ConsumerState { ? context.l10n.onboardingSystemNameHelperTextImported : context.l10n.onboardingSystemNameHelperText; - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 32), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - decoration: BoxDecoration( - color: isDark - ? AppColors.warmWhite.withValues(alpha: 0.1) - : AppColors.parchmentElevated, - borderRadius: BorderRadius.circular(PrismShapes.of(context).radius(12)), - ), - child: PrismTextField( - controller: _controller, - autofocus: autoFocus, - style: TextStyle( - color: isDark ? AppColors.warmWhite : AppColors.warmBlack, - fontSize: 20, - fontWeight: FontWeight.w500, - ), - textAlign: TextAlign.center, - hintText: context.l10n.onboardingSystemNameHint, - hintStyle: TextStyle( - color: isDark - ? AppColors.warmWhite.withValues(alpha: 0.35) - : AppColors.warmBlack.withValues(alpha: 0.35), - fontSize: 20, - ), - fieldStyle: PrismTextFieldStyle.borderless, - contentPadding: const EdgeInsets.symmetric( - horizontal: 20, - vertical: 18, - ), - onChanged: (value) { - ref.read(onboardingProvider.notifier).setSystemName(value); - }, - ), - ), - const SizedBox(height: 16), - Text( - helperText, - style: TextStyle( - color: isDark - ? AppColors.mutedTextDark - : AppColors.mutedTextLight, - fontSize: 14, + // The body is the space the screen has left between its pinned header and + // bottom bar; with the keyboard up that can be less than the field plus its + // helper copy, and the Column then reported 43 / 143 / 609dp of bottom + // overflow on a 320x568 phone at 1x / 1.5x / 3.375x with nothing to scroll. + // It scrolls now and keeps its centred look whenever it fits. The controller, + // the external-name listen, autofocus and onChanged are untouched. + return LayoutBuilder( + builder: (context, constraints) { + final viewportHeight = constraints.maxHeight; + final availableHeight = viewportHeight.isFinite && viewportHeight > 0 + ? viewportHeight + : 0.0; + return SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: availableHeight), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + decoration: BoxDecoration( + color: isDark + ? AppColors.warmWhite.withValues(alpha: 0.1) + : AppColors.parchmentElevated, + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(12), + ), + ), + child: PrismTextField( + controller: _controller, + autofocus: autoFocus, + style: SystemNameStep.fieldTextStyle(context), + textAlign: TextAlign.center, + hintText: context.l10n.onboardingSystemNameHint, + hintStyle: TextStyle( + color: isDark + ? AppColors.warmWhite.withValues(alpha: 0.35) + : AppColors.warmBlack.withValues(alpha: 0.35), + fontSize: SystemNameStep.fieldFontSize, + ), + fieldStyle: PrismTextFieldStyle.borderless, + contentPadding: const EdgeInsets.symmetric( + horizontal: SystemNameStep.fieldHorizontalPadding, + vertical: SystemNameStep.fieldVerticalPadding, + ), + onChanged: (value) { + ref + .read(onboardingProvider.notifier) + .setSystemName(value); + }, + ), + ), + const SizedBox(height: SystemNameStep.fieldToHelperGap), + Text( + helperText, + style: TextStyle( + color: isDark + ? AppColors.mutedTextDark + : AppColors.mutedTextLight, + fontSize: 14, + ), + textAlign: TextAlign.center, + ), + ], ), - textAlign: TextAlign.center, ), - ], - ), + ); + }, ); } } diff --git a/lib/features/pluralkit/widgets/pk_fronter_choice_card.dart b/lib/features/pluralkit/widgets/pk_fronter_choice_card.dart index 13c2c6b41..6116bb3b0 100644 --- a/lib/features/pluralkit/widgets/pk_fronter_choice_card.dart +++ b/lib/features/pluralkit/widgets/pk_fronter_choice_card.dart @@ -45,54 +45,74 @@ class PkFronterChoiceCard extends StatelessWidget { onTap: onTap, child: ConstrainedBox( constraints: const BoxConstraints(minHeight: 56), - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Text( - title, - style: theme.textTheme.titleMedium?.copyWith( - fontWeight: FontWeight.w600, - ), - ), - if (subtitle.isNotEmpty) ...[ - const SizedBox(height: 4), - Text( - subtitle, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, + child: LayoutBuilder( + builder: (context, constraints) { + // The recommendation badge is intrinsic (icon plus word) and is + // not a flexible child, so at large text the word alone can be + // wider than the whole card: the Expanded title then gets zero + // width and the row paints past its edge. Cap the badge to a + // share of the row so its word wraps at the requested size + // instead; the icon keeps its graphic size, nothing is scaled + // down, and the card's semantics still say "Recommended". + final badgeMaxWidth = constraints.maxWidth.isFinite + ? constraints.maxWidth * 0.45 + : double.infinity; + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w600, + ), ), - ), - ], - ], - ), - ), - if (recommended) ...[ - const SizedBox(width: 8), - Column( - mainAxisSize: MainAxisSize.min, - children: [ - PhosphorIcon( - key: const Key('pk_fronter_choice_card_recommended_icon'), - AppIcons.checkCircle, - color: theme.colorScheme.primary, - size: 20, + if (subtitle.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + subtitle, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ], ), - const SizedBox(height: 4), - Text( - recommendedLabel, - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.primary, + ), + if (recommended) ...[ + const SizedBox(width: 8), + ConstrainedBox( + constraints: BoxConstraints(maxWidth: badgeMaxWidth), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + PhosphorIcon( + key: const Key( + 'pk_fronter_choice_card_recommended_icon', + ), + AppIcons.checkCircle, + color: theme.colorScheme.primary, + size: 20, + ), + const SizedBox(height: 4), + Text( + recommendedLabel, + textAlign: TextAlign.center, + style: theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.primary, + ), + ), + ], ), ), ], - ), - ], - ], + ], + ); + }, ), ), ), diff --git a/lib/features/pluralkit/widgets/pk_who_is_fronting_sheet.dart b/lib/features/pluralkit/widgets/pk_who_is_fronting_sheet.dart index a9bd30954..5c8e71249 100644 --- a/lib/features/pluralkit/widgets/pk_who_is_fronting_sheet.dart +++ b/lib/features/pluralkit/widgets/pk_who_is_fronting_sheet.dart @@ -314,33 +314,50 @@ class PkWhoIsFrontingSheet extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - // Title - Text( - l10n.pluralkitWhosFrontingTitle, - style: theme.textTheme.titleLarge?.copyWith( - fontWeight: FontWeight.w600, + // The sheet is non-dismissible (no drag, no barrier) and the cards + // already need more height than a compact phone has at large text, + // so the body scrolls. The defer action below stays pinned: it is + // the only safe, non-mutating way out and must never be the part + // that scrolls out of reach. + Flexible( + child: SingleChildScrollView( + padding: const EdgeInsets.only(bottom: 4), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Title + Text( + l10n.pluralkitWhosFrontingTitle, + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + // Subtitle + Text( + l10n.pluralkitWhosFrontingSubtitle, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 16), + // Option cards + for (int i = 0; i < options.length; i++) ...[ + if (i > 0) const SizedBox(height: 8), + PkFronterChoiceCard( + title: _title(context, options[i], nameMap), + subtitle: _subtitle(context, options[i], nameMap), + recommended: options[i].recommended, + onTap: () => onResult( + Set.unmodifiable(options[i].resolvedLocalIds), + ), + ), + ], + ], + ), ), ), - const SizedBox(height: 8), - // Subtitle - Text( - l10n.pluralkitWhosFrontingSubtitle, - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 16), - // Option cards - for (int i = 0; i < options.length; i++) ...[ - if (i > 0) const SizedBox(height: 8), - PkFronterChoiceCard( - title: _title(context, options[i], nameMap), - subtitle: _subtitle(context, options[i], nameMap), - recommended: options[i].recommended, - onTap: () => - onResult(Set.unmodifiable(options[i].resolvedLocalIds)), - ), - ], const SizedBox(height: 16), // Decide later PrismButton( diff --git a/lib/features/reminders/widgets/create_reminder_sheet.dart b/lib/features/reminders/widgets/create_reminder_sheet.dart index 071407b89..8c497709c 100644 --- a/lib/features/reminders/widgets/create_reminder_sheet.dart +++ b/lib/features/reminders/widgets/create_reminder_sheet.dart @@ -536,8 +536,15 @@ class _LabeledRow extends StatelessWidget { @override Widget build(BuildContext context) { - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // `OverflowBar`: label and control stay side by side while they fit - the + // default look - and the control takes its own end-aligned line when the scaled + // label no longer leaves room for it. Both keep the requested text size and the + // control stays on the card (measured 223px over at 3.375x, 79px in RTL). + return OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 4, + overflowAlignment: OverflowBarAlignment.end, children: [ Text(label, style: Theme.of(context).textTheme.bodyMedium), child, diff --git a/lib/features/settings/providers/reset_data_provider.dart b/lib/features/settings/providers/reset_data_provider.dart index 008bf35a0..eff90fcd5 100644 --- a/lib/features/settings/providers/reset_data_provider.dart +++ b/lib/features/settings/providers/reset_data_provider.dart @@ -26,6 +26,7 @@ import 'package:prism_plurality/core/sync/prism_sync_providers.dart'; import 'package:prism_plurality/core/sync/relay_cleanup.dart'; import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; import 'package:prism_plurality/core/sync/sync_runtime_state.dart'; +import 'package:prism_plurality/features/habits/services/habit_notification_service.dart'; import 'package:prism_plurality/features/migration/providers/migration_providers.dart'; import 'package:prism_plurality/core/router/onboarding_local_completion.dart'; import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; @@ -291,6 +292,22 @@ enum ResetCategory { final String description; } +/// Raised when habit rows were deleted but their scheduled reminders could not +/// all be retracted. +/// +/// The deletion is committed, so this must not read as a rollback or as a plain +/// success. The message stays privacy-safe: it names no habit, carries no +/// notification or habit IDs, and the platform error behind it is only logged by +/// type. +class _HabitReminderCancellationFailure implements Exception { + const _HabitReminderCancellationFailure(); + + @override + String toString() => + 'Habit data was deleted, but some habit reminders may still fire. ' + 'Notification cleanup did not complete.'; +} + class ResetDataNotifier extends AsyncNotifier { @override Future build() async {} @@ -654,11 +671,38 @@ class ResetDataNotifier extends AsyncNotifier { Future _resetHabits() async { final db = ref.read(databaseProvider); _log('Resetting habit data'); - await db.transaction(() async { + // Capture the row IDs inside the deletion transaction: habit reminders are + // keyed by a hash of the habit ID, so once the rows are gone the IDs cannot + // be recovered and their pending notifications could never be retracted. No + // active/deleted filter — the reset removes deactivated and soft-deleted rows + // too. If the transaction fails, nothing is captured and nothing is + // cancelled. + final habitIds = await db.transaction(() async { + final rows = await db.customSelect('SELECT id FROM habits').get(); + final ids = rows.map((row) => row.read('id')).toList(); await db.customStatement('DELETE FROM habit_completions'); await db.customStatement('DELETE FROM habits'); + return ids; }); + // Observers hear about the committed delete before the reminder cleanup: if + // that cleanup fails the rows are already gone, so streams must not be left + // showing habits that no longer exist. _notifyTableChanges(['habit_completions', 'habits']); + + try { + await ref + .read(habitNotificationServiceProvider) + .cancelForHabits(habitIds); + } catch (e) { + // The delete is committed; report the reminder risk truthfully instead of + // a success or a rollback. Only the error type is logged — the platform + // error can carry notification IDs. + _log( + 'Habit data was deleted but reminder cancellation failed ' + '(${e.runtimeType}); some habit reminders may still fire', + ); + throw const _HabitReminderCancellationFailure(); + } } Future _resetSleep() async { diff --git a/lib/features/settings/views/crypto_storage_debug_screen.dart b/lib/features/settings/views/crypto_storage_debug_screen.dart index 856cea19b..3d78b5714 100644 --- a/lib/features/settings/views/crypto_storage_debug_screen.dart +++ b/lib/features/settings/views/crypto_storage_debug_screen.dart @@ -359,10 +359,16 @@ class _EngineStateCard extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); + // `OverflowBar` instead of a `Row`: label and value sit side by side while they + // fit (unchanged at the default size) and the value takes its own end-aligned + // line when the pair no longer fits, so nothing is clipped at the card edge. Widget row(String label, String value) => Padding( padding: const EdgeInsets.symmetric(vertical: 4), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + child: OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 2, + overflowAlignment: OverflowBarAlignment.end, children: [ Text( label, diff --git a/lib/features/settings/views/data_browser_screen.dart b/lib/features/settings/views/data_browser_screen.dart index 94f0d2070..cb6c8f6e8 100644 --- a/lib/features/settings/views/data_browser_screen.dart +++ b/lib/features/settings/views/data_browser_screen.dart @@ -616,7 +616,14 @@ class _ExpandableRecord extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, ), - subtitle: Row( + // A wrap, not a row: the subtitle's column bounds the list, but a `Row` lays + // its non-flex children out unbounded, so the monospace id plus the secondary + // field kept their intrinsic width and were clipped at the card edge. Here the + // secondary field moves to its own line when both no longer fit, at full size. + subtitle: Wrap( + spacing: 8, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( truncatedId, @@ -626,15 +633,13 @@ class _ExpandableRecord extends StatelessWidget { color: theme.colorScheme.onSurfaceVariant, ), ), - if (secondaryField.isNotEmpty) ...[ - const SizedBox(width: 8), + if (secondaryField.isNotEmpty) Text( secondaryField, style: theme.textTheme.bodySmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), - ], ], ), contentPadding: const EdgeInsets.fromLTRB(16, 0, 16, 12), diff --git a/lib/features/settings/views/database_diagnostics_screen.dart b/lib/features/settings/views/database_diagnostics_screen.dart index a72276b88..8a377c563 100644 --- a/lib/features/settings/views/database_diagnostics_screen.dart +++ b/lib/features/settings/views/database_diagnostics_screen.dart @@ -200,8 +200,14 @@ class _AddMemberPerfCard extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // Title and the copy/clear actions stay on one line while they fit; at a + // large text size the actions get their own end-aligned line instead of + // being pushed past the card edge. + OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 4, + overflowAlignment: OverflowBarAlignment.end, children: [ Text( 'Add-Member Timing', @@ -284,8 +290,13 @@ class _CountRow extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // Same rule as the statistics rows: `OverflowBar` keeps the pair side by side + // while it fits and gives the count its own end-aligned line when it does not. + return OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 4, + overflowAlignment: OverflowBarAlignment.end, children: [ Text(label, style: theme.textTheme.bodyMedium), countAsync.when( diff --git a/lib/features/settings/views/pin_input_screen.dart b/lib/features/settings/views/pin_input_screen.dart index 4b78edb15..7fe196ca5 100644 --- a/lib/features/settings/views/pin_input_screen.dart +++ b/lib/features/settings/views/pin_input_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -299,13 +300,11 @@ class _PinInputScreenState extends ConsumerState canOfferBiometric && biometricAvailable && biometricEnabled; final textScale = MediaQuery.textScalerOf(context).scale(1); - // Above 1.3x, the centered Spacer layout overflows on phones (especially - // when nested in onboarding under a scaled parent header) and clips the - // bottom numpad row. Switch to a scrollable layout and tighten button - // sizing so the keypad keeps fitting unscrolled where possible. - final useScrollFallback = textScale > 1.3; + // Key size policy is unchanged: keys stay a little smaller once the text is + // large, which is what keeps the pad close to fitting without scrolling. + final compactKeys = textScale > 1.3; final sizeFloor = textScale > 1.5 ? 48.0 : 56.0; - final sizeCeil = useScrollFallback ? 64.0 : 72.0; + final sizeCeil = compactKeys ? 64.0 : 72.0; final clampedSize = ((MediaQuery.of(context).size.width - 80) / 3).clamp( sizeFloor, sizeCeil, @@ -417,38 +416,52 @@ class _PinInputScreenState extends ConsumerState ), ); - final Widget content; - if (useScrollFallback) { - content = SingleChildScrollView( - physics: const ClampingScrollPhysics(), - padding: EdgeInsets.symmetric(vertical: widget.embedded ? 8 : 24), - child: Column( - children: [ - ...headerChildren, - dots, - const SizedBox(height: 24), - numpad, - ], - ), - ); - } else { - content = Column( - children: [ - if (widget.embedded) const Spacer() else const Spacer(flex: 2), - ...headerChildren, - dots, - if (widget.embedded) const Spacer() else const Spacer(flex: 2), - numpad, - const Spacer(), - ], - ); - } + // The fit is measured instead of guessed from the text scale: a short window + // overflows at 1x, and an open keyboard leaves less room at any scale. When the + // content fits, IntrinsicHeight hands the column a tight viewport height and the + // Spacer weights below reproduce the existing centred layout exactly; when it + // does not, the same children scroll instead of overflowing the bottom edge. + final content = Column( + children: [ + if (widget.embedded) const Spacer() else const Spacer(flex: 2), + ...headerChildren, + dots, + if (widget.embedded) const Spacer() else const Spacer(flex: 2), + numpad, + const Spacer(), + ], + ); final keyboardScope = NumpadKeyboardListener( onDigit: _onDigit, onBackspace: _onBackspace, enabled: !_isBusy && !_isLockedOut, - child: content, + child: LayoutBuilder( + builder: (context, constraints) { + if (!constraints.maxHeight.isFinite) return content; + // Subtract the keyboard only when the parent has not already shrunk the + // body for it: a Scaffold with resizeToAvoidBottomInset does that itself, + // and subtracting twice would leave a gap and hide reachable keys. + final insets = MediaQuery.viewInsetsOf(context).bottom; + final windowHeight = MediaQuery.sizeOf(context).height; + final alreadyResized = + insets > 0 && constraints.maxHeight <= windowHeight - insets + 1; + final availableHeight = math.max( + 0.0, + constraints.maxHeight - (alreadyResized ? 0.0 : insets), + ); + return SizedBox( + height: availableHeight, + child: SingleChildScrollView( + physics: const ClampingScrollPhysics(), + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: availableHeight), + child: IntrinsicHeight(child: content), + ), + ), + ); + }, + ), ); if (widget.embedded) return keyboardScope; diff --git a/lib/features/settings/views/pin_lock_settings_screen.dart b/lib/features/settings/views/pin_lock_settings_screen.dart index 45d4036c9..aaed474af 100644 --- a/lib/features/settings/views/pin_lock_settings_screen.dart +++ b/lib/features/settings/views/pin_lock_settings_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -530,99 +531,133 @@ class _CapturePinScreenState extends State<_CapturePinScreen> final theme = Theme.of(context); final accentColor = theme.colorScheme.primary; - final screen = Material( - color: theme.scaffoldBackgroundColor, - child: SafeArea( - child: Column( - children: [ - // Back button - Align( - alignment: Alignment.topLeft, - child: Padding( - padding: const EdgeInsets.only(left: 8, top: 8), - child: PrismInlineIconButton( - icon: AppIcons.arrowBack, - iconSize: 20, - tooltip: context.l10n.back, - // The null here lags a frame behind the final digit, so - // the tap re-checks. - onPressed: _isSubmitting - ? null - : () { - if (!_isSubmitting) Navigator.of(context).pop(); - }, - ), - ), - ), - const Spacer(flex: 2), - Text( - _title(context), - style: theme.textTheme.headlineMedium?.copyWith( - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 8), - Text( - _subtitle(context), - style: theme.textTheme.bodyMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - const SizedBox(height: 40), - AnimatedBuilder( - animation: _shakeAnimation, - builder: (context, child) => Transform.translate( - offset: Offset(_shakeAnimation.value, 0), + final backButton = Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.only(left: 8, top: 8), + child: PrismInlineIconButton( + icon: AppIcons.arrowBack, + iconSize: 20, + tooltip: context.l10n.back, + // The null here lags a frame behind the final digit, so + // the tap re-checks. + onPressed: _isSubmitting + ? null + : () { + if (!_isSubmitting) Navigator.of(context).pop(); + }, + ), + ), + ); + + final header = [ + Text( + _title(context), + style: theme.textTheme.headlineMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + _subtitle(context), + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ]; + + final dots = AnimatedBuilder( + animation: _shakeAnimation, + builder: (context, child) => Transform.translate( + offset: Offset(_shakeAnimation.value, 0), + child: child, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(_pinLength, (i) { + final filled = i < _pin.length; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: AnimatedBuilder( + animation: _dotScaleAnim, + builder: (context, child) => Transform.scale( + scale: i == _lastFilledDotIndex ? _dotScaleAnim.value : 1.0, child: child, ), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: List.generate(_pinLength, (i) { - final filled = i < _pin.length; - return Padding( - padding: const EdgeInsets.symmetric(horizontal: 10), - child: AnimatedBuilder( - animation: _dotScaleAnim, - builder: (context, child) => Transform.scale( - scale: i == _lastFilledDotIndex - ? _dotScaleAnim.value - : 1.0, - child: child, - ), - child: AnimatedContainer( - duration: const Duration(milliseconds: 150), - width: 16, - height: 16, - decoration: BoxDecoration( - shape: BoxShape.circle, - color: filled - ? accentColor - : accentColor.withValues(alpha: 0.15), - ), - ), - ), - ); - }), + child: AnimatedContainer( + duration: const Duration(milliseconds: 150), + width: 16, + height: 16, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: filled + ? accentColor + : accentColor.withValues(alpha: 0.15), + ), ), ), - const Spacer(flex: 2), + ); + }), + ), + ); + + final pad = Padding( + padding: const EdgeInsets.symmetric(horizontal: 40), + child: Column( + children: [ + for (var row = 0; row < 4; row++) Padding( - padding: const EdgeInsets.symmetric(horizontal: 40), - child: Column( - children: [ - for (var row = 0; row < 4; row++) - Padding( - padding: const EdgeInsets.only(bottom: 12), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: _buildRow(context, row), - ), - ), - ], + padding: const EdgeInsets.only(bottom: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: _buildRow(context, row), ), ), - const Spacer(), - ], + ], + ), + ); + + // The pad grows with the digit's line box, so the fit is measured against + // the height actually available (keyboard included) instead of guessed from + // the text scale: a short window can overflow at 1x, a tall one can fit at + // 3x. When the content fits, IntrinsicHeight hands the column a tight + // viewport height and the Spacer weights below reproduce the existing + // centred layout exactly; when it does not, the same children scroll and the + // whole flow stays reachable. + final content = Column( + children: [ + backButton, + const Spacer(flex: 2), + ...header, + const SizedBox(height: 40), + dots, + const Spacer(flex: 2), + pad, + const Spacer(), + ], + ); + + final screen = Material( + color: theme.scaffoldBackgroundColor, + child: SafeArea( + child: LayoutBuilder( + builder: (context, constraints) { + if (!constraints.maxHeight.isFinite) return content; + final keyboardInset = MediaQuery.viewInsetsOf(context).bottom; + final availableHeight = math.max( + 0.0, + constraints.maxHeight - keyboardInset, + ); + return SizedBox( + height: availableHeight, + child: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: availableHeight), + child: IntrinsicHeight(child: content), + ), + ), + ); + }, ), ), ); diff --git a/lib/features/settings/views/statistics_screen.dart b/lib/features/settings/views/statistics_screen.dart index 18ebf1bff..121585148 100644 --- a/lib/features/settings/views/statistics_screen.dart +++ b/lib/features/settings/views/statistics_screen.dart @@ -9,6 +9,7 @@ import 'package:prism_plurality/shared/widgets/app_shell.dart'; import 'package:prism_plurality/shared/widgets/clamped_body.dart'; import 'package:prism_plurality/shared/widgets/member_avatar.dart'; import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_loading_state.dart'; import 'package:prism_plurality/shared/widgets/prism_section_card.dart'; import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; @@ -234,8 +235,14 @@ class _StatRow extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, + // A stock `OverflowBar`: the pair stays on one line exactly as before while it + // fits, and the value moves to its own line at the end when it does not, instead + // of both keeping their intrinsic width and running past the card. + return OverflowBar( + alignment: MainAxisAlignment.spaceBetween, + spacing: 12, + overflowSpacing: 4, + overflowAlignment: OverflowBarAlignment.end, children: [ Text(label, style: theme.textTheme.bodyMedium), valueAsync.when( @@ -259,6 +266,24 @@ class _StatRow extends StatelessWidget { } } +/// Width of one line of [text] at the ambient text scale and [style]. +double _singleLineWidth(BuildContext context, String text, TextStyle? style) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final width = painter.width; + painter.dispose(); + return width; +} + class _TopFronterRow extends ConsumerWidget { const _TopFronterRow({ required this.rank, @@ -274,42 +299,93 @@ class _TopFronterRow extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final prefer = ref.watch(memberNamePreferDisplayProvider); - final name = - member?.effectiveName(preferDisplayName: prefer) ?? 'Unknown'; + final name = member?.effectiveName(preferDisplayName: prefer) ?? 'Unknown'; final emoji = member?.emoji ?? '\u2754'; + final rankStyle = theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ); + final countStyle = theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ); + final countLabel = context.l10n.statisticsSessions(sessionCount); + // The numeral is sized from the glyphs it paints, with 24dp as the alignment + // floor: a constant 24dp box broke "#10" (and "#1" at 1.5x) onto two lines. + final rankWidth = _singleLineWidth(context, '#$rank', rankStyle) + 2; + final rankExtent = rankWidth < 24 ? 24.0 : rankWidth; + + Widget rankBox() => SizedBox( + width: rankExtent, + child: Text('#$rank', style: rankStyle), + ); + + Widget avatar() => MemberAvatar( + emoji: emoji, + memberName: member?.effectiveName(preferDisplayName: prefer), + avatarImageData: member?.avatarImageData, + customColorEnabled: member?.customColorEnabled ?? false, + customColorHex: member?.customColorHex, + size: 36, + ); + return Padding( padding: const EdgeInsets.symmetric(vertical: 4), - child: Row( - children: [ - SizedBox( - width: 24, - child: Text( - '#$rank', - style: theme.textTheme.titleSmall?.copyWith( - fontWeight: FontWeight.bold, - color: theme.colorScheme.primary, + child: LayoutBuilder( + builder: (context, constraints) { + // Fit from what the row really renders: the numeral, avatar and gaps are + // non-shrinkable, the name already ellipsises, so the count stays inline + // exactly as before while it fits beside them and drops to its own + // end-aligned line only when it cannot. + final fixed = + rankExtent + + 8 + + 36 + + 12 + + _singleLineWidth(context, countLabel, countStyle); + final fitsInline = fixed <= constraints.maxWidth; + + if (fitsInline) { + return Row( + children: [ + rankBox(), + const SizedBox(width: 8), + avatar(), + const SizedBox(width: 12), + Expanded(child: Text(name, style: theme.textTheme.bodyMedium)), + Text(countLabel, style: countStyle), + ], + ); + } + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + rankBox(), + const SizedBox(width: 8), + avatar(), + const SizedBox(width: 12), + Expanded( + child: Text( + name, + style: theme.textTheme.bodyMedium, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ], ), - ), - ), - const SizedBox(width: 8), - MemberAvatar( - emoji: emoji, - memberName: member?.effectiveName(preferDisplayName: prefer), - avatarImageData: member?.avatarImageData, - customColorEnabled: member?.customColorEnabled ?? false, - customColorHex: member?.customColorHex, - size: 36, - ), - const SizedBox(width: 12), - Expanded(child: Text(name, style: theme.textTheme.bodyMedium)), - Text( - context.l10n.statisticsSessions(sessionCount), - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ), - ], + const SizedBox(height: 4), + Align( + alignment: AlignmentDirectional.centerEnd, + child: Text(countLabel, style: countStyle), + ), + ], + ); + }, ), ); } diff --git a/lib/features/settings/widgets/member_ranking_chart.dart b/lib/features/settings/widgets/member_ranking_chart.dart index a109bb14d..f7b56ff73 100644 --- a/lib/features/settings/widgets/member_ranking_chart.dart +++ b/lib/features/settings/widgets/member_ranking_chart.dart @@ -10,6 +10,7 @@ import 'package:prism_plurality/shared/extensions/duration_extensions.dart'; import 'package:prism_plurality/shared/theme/app_colors.dart'; import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:prism_plurality/shared/widgets/member_avatar.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_surface.dart'; /// Hero chart showing per-member fronting time as vertical bars sorted @@ -33,9 +34,11 @@ class MemberRankingChart extends ConsumerStatefulWidget { static const double _gapPctToBar = 4; static const double _gapBarToAvatar = 8; static const double _gapAvatarToName = 4; - // Slot bounds: floor keeps the avatar (24px) plus minimal breathing room - // visible; ceiling stops a single very long name from inflating every - // column. Anything beyond the ceiling ellipsises rather than bloats. + // Slot bounds, expressed at the default text size and scaled by the label's own + // measured scale at build time: the floor keeps the avatar (24px) plus minimal + // breathing room visible and the "%"/time readout whole, and the ceiling stops + // one very long name from inflating every column. Anything beyond the ceiling + // still ellipsises rather than bloats. static const double _minSlotWidth = 40; static const double _maxSlotWidth = 88; // Horizontal padding inside each slot, applied to both sides of the @@ -43,8 +46,7 @@ class MemberRankingChart extends ConsumerStatefulWidget { static const double _slotHorizontalPadding = 3; @override - ConsumerState createState() => - _MemberRankingChartState(); + ConsumerState createState() => _MemberRankingChartState(); } class _MemberRankingChartState extends ConsumerState { @@ -67,13 +69,25 @@ class _MemberRankingChartState extends ConsumerState { // subscriptions — fewer rebuilds, single network/db pass, and the same // map drives both name measurement and bar rendering. final ids = memberStats.map((s) => s.memberId).toList(); - final memberMapAsync = - ref.watch(membersByIdsProvider(memberIdsKey(ids))); - final memberMap = - memberMapAsync.value ?? const {}; + final memberMapAsync = ref.watch(membersByIdsProvider(memberIdsKey(ids))); + final memberMap = memberMapAsync.value ?? const {}; final textScaler = MediaQuery.textScalerOf(context); final labelStyle = theme.textTheme.labelSmall; + final labelFontSize = labelStyle?.fontSize ?? 11; + // The label's own scale, measured through the ambient scaler (a nonlinear + // platform scaler does not scale every font size by one ratio), so the slot + // bounds follow the glyphs the chart actually paints instead of a constant. + final labelScale = labelFontSize > 0 + ? textScaler.scale(labelFontSize) / labelFontSize + : 1.0; + // Bounds only, and never below the original geometry: the avatar inside a slot is + // a fixed 24dp and the readouts are the chart's smallest type, so a sub-1x text + // preference must not squeeze the columns under their 40/88dp bounds. The label + // text itself still paints at the requested 0.5x. + final boundsScale = labelScale < 1 ? 1.0 : labelScale; + final minSlotWidth = MemberRankingChart._minSlotWidth * boundsScale; + final maxSlotWidth = MemberRankingChart._maxSlotWidth * boundsScale; // Slot width: measure each visible name with the actual label style and // ambient text scaler, take the widest, then add side padding. Names @@ -82,32 +96,35 @@ class _MemberRankingChartState extends ConsumerState { double widestName = 0; for (final stat in memberStats) { final name = _displayName(memberMap[stat.memberId]); - final width = _measureTextWidth(name, labelStyle, textScaler); + final width = _measureTextWidth(context, name, labelStyle); if (width > widestName) widestName = width; } - final slotWidth = (widestName + - MemberRankingChart._slotHorizontalPadding * 2) - .clamp(MemberRankingChart._minSlotWidth, - MemberRankingChart._maxSlotWidth); + final slotWidth = + (widestName + MemberRankingChart._slotHorizontalPadding * 2).clamp( + minSlotWidth, + maxSlotWidth, + ); // Compute the chart row height precisely from the scaled text + fixed // pieces, so the ListView is exactly as tall as one bar slot. No // outer cardHeight, no Expanded → no dead space above the bars when // bottom-anchored. - final labelFontSize = labelStyle?.fontSize ?? 11; final labelLineMult = labelStyle?.height ?? 1.4; final scaledLabelHeight = textScaler.scale(labelFontSize) * labelLineMult; // 4px slack absorbs leading/baseline rounding so the column never // overflows the ListView; rendered text varies slightly by font. const overflowSlack = 4.0; - final rowHeight = scaledLabelHeight // % label - + MemberRankingChart._gapPctToBar - + MemberRankingChart._barHeight - + MemberRankingChart._gapBarToAvatar - + MemberRankingChart._avatarSize - + MemberRankingChart._gapAvatarToName - + scaledLabelHeight // member name - + overflowSlack; + final rowHeight = + scaledLabelHeight // % label + + + MemberRankingChart._gapPctToBar + + MemberRankingChart._barHeight + + MemberRankingChart._gapBarToAvatar + + MemberRankingChart._avatarSize + + MemberRankingChart._gapAvatarToName + + scaledLabelHeight // member name + + + overflowSlack; return PrismSurface( padding: const EdgeInsets.fromLTRB(16, 12, 0, 12), @@ -125,8 +142,7 @@ class _MemberRankingChartState extends ConsumerState { // "Per-{term} Colors" pattern in appearance settings. // Axis hint below stays `singularLower` because that's // the inline noun-modifier pattern. - context.l10n - .statisticsFrontingTimeByMember(terms.singular), + context.l10n.statisticsFrontingTimeByMember(terms.singular), style: theme.textTheme.titleSmall?.copyWith( fontWeight: FontWeight.bold, // Drop built-in line-height padding so the title sits as @@ -139,8 +155,9 @@ class _MemberRankingChartState extends ConsumerState { // system {term}-minutes, not wall-clock fronting time. // See §4.3 of fronting-per-member-sessions.md. Text( - context.l10n - .statisticsMemberMinutesAxisHint(terms.singularLower), + context.l10n.statisticsMemberMinutesAxisHint( + terms.singularLower, + ), style: theme.textTheme.labelSmall?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), @@ -183,18 +200,27 @@ String _displayName(Member? m) { return m.name; } -double _measureTextWidth( - String text, - TextStyle? style, - TextScaler scaler, -) { +/// Width one line of [text] needs, measured the way the chart paints it. +/// +/// The style goes through [prismTextStyleForMeasurement] so the ambient +/// [DefaultTextStyle] merge and the bold-text accessibility flag are applied exactly as +/// `Text` applies them, and the painter receives the inherited locale and height +/// behaviour, so the measurement and the painted label resolve the same face. +double _measureTextWidth(BuildContext context, String text, TextStyle? style) { final painter = TextPainter( - text: TextSpan(text: text, style: style), - textDirection: TextDirection.ltr, + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), maxLines: 1, - textScaler: scaler, )..layout(); - return painter.width; + final width = painter.width; + painter.dispose(); + return width; } class _MemberBar extends StatelessWidget { @@ -224,14 +250,18 @@ class _MemberBar extends StatelessWidget { final brightness = theme.brightness; final name = _displayName(member); - final color = (member?.customColorEnabled ?? false) && - member?.customColorHex != null + final color = + (member?.customColorEnabled ?? false) && member?.customColorHex != null ? AppColors.fromHex(member!.customColorHex!) : AppColors.generatedColor( - rowIndex, theme.colorScheme.primary, brightness); + rowIndex, + theme.colorScheme.primary, + brightness, + ); - final fraction = - peakMinutes > 0 ? stat.totalTime.inMinutes / peakMinutes : 0.0; + final fraction = peakMinutes > 0 + ? stat.totalTime.inMinutes / peakMinutes + : 0.0; final filledHeight = (barHeight * fraction).clamp(2.0, barHeight); // Bar width scales with the slot so a wider column doesn't leave the // bar looking lonely in the middle. Floor + ceiling keep the geometry @@ -288,7 +318,8 @@ class _MemberBar extends StatelessWidget { color: theme.colorScheme.surfaceContainerHighest .withValues(alpha: 0.4), borderRadius: BorderRadius.circular( - PrismShapes.of(context).radius(2)), + PrismShapes.of(context).radius(2), + ), ), ), Container( @@ -296,7 +327,8 @@ class _MemberBar extends StatelessWidget { decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular( - PrismShapes.of(context).radius(2)), + PrismShapes.of(context).radius(2), + ), ), ), ], diff --git a/lib/features/settings/widgets/navigation_layout_editor.dart b/lib/features/settings/widgets/navigation_layout_editor.dart index 1850d7f5b..6e2b182b8 100644 --- a/lib/features/settings/widgets/navigation_layout_editor.dart +++ b/lib/features/settings/widgets/navigation_layout_editor.dart @@ -22,6 +22,7 @@ import 'package:prism_plurality/shared/utils/nav_bar_layout.dart' import 'package:prism_plurality/shared/widgets/app_shell.dart'; import 'package:prism_plurality/shared/widgets/prism_inline_icon_button.dart'; import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_section.dart'; import 'package:prism_plurality/shared/widgets/prism_section_card.dart'; @@ -590,6 +591,56 @@ class _AvailableItem extends StatelessWidget { } } +/// Width [text] needs on one line at the ambient scaler with [style]. +/// +/// Used to decide from the row's real width whether two static texts still fit +/// side by side; it reads the same scaler the texts paint with, so no ratio or +/// scale threshold is guessed. +double _singleLineWidth(BuildContext context, String text, TextStyle? style) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final width = painter.width; + painter.dispose(); + return width; +} + +/// Whether [text] is painted in full inside [maxWidth] within [maxLines] lines. +/// +/// Mirrors the ellipsis policy of the widget it stands in for: the answer is false +/// when a `maxLines`/ellipsis box of that size would have to truncate the text. +bool _fitsWithin( + BuildContext context, + String text, + TextStyle? style, { + required double maxWidth, + required int maxLines, +}) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: maxLines, + ellipsis: '\u2026', + )..layout(maxWidth: maxWidth); + final fits = !painter.didExceedMaxLines; + painter.dispose(); + return fits; +} + class _DisabledItem extends StatelessWidget { const _DisabledItem({ required this.tab, @@ -601,34 +652,98 @@ class _DisabledItem extends StatelessWidget { final String terminologyPlural; final VoidCallback? onTap; + /// Horizontal padding of this row (`PrismListRow.padding` below). + static const double _rowPadding = 16; + + /// Leading slot plus its trailing gap, as `PrismListRow` lays it out. + static const double _leadingSlot = 40 + 12; + + /// The gap `PrismListRow` inserts before a trailing child. It is part of the row's + /// fixed budget, so the inline fit has to subtract it too - without it the decision was + /// 12dp too generous and could keep the hint inline where the row then clips it. + static const double _trailingGap = 12; + + /// Widest the hint is allowed to be while it stays beside the label, and the + /// line budget it has there - unchanged from the previous layout. + static const double _inlineHintMaxWidth = 104; + static const int _inlineHintMaxLines = 2; + @override Widget build(BuildContext context) { final theme = Theme.of(context); - return PrismListRow( - padding: const EdgeInsets.symmetric(horizontal: 16), - leading: Icon( - tab.icon, - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.3), - ), - title: Text( - tab.localizedLabel(context, terminologyPlural: terminologyPlural), - style: TextStyle( - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), - ), - ), - trailing: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 104), - child: Text( - context.l10n.navigationEnableInFeatures, - maxLines: 2, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.end, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.primary.withValues(alpha: 0.7), + final label = tab.localizedLabel( + context, + terminologyPlural: terminologyPlural, + ); + final hint = context.l10n.navigationEnableInFeatures; + // PrismListRow paints its title in bodyLarge with w600 and height 1.2, so the + // measurement has to use that base weight rather than the bare theme style. + final labelStyle = theme.textTheme.bodyLarge?.copyWith( + fontWeight: FontWeight.w600, + height: 1.2, + ); + final hintStyle = theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.primary.withValues(alpha: 0.7), + ); + + return LayoutBuilder( + builder: (context, constraints) { + // Natural fit, from the row's real width: the hint stays in the trailing + // slot, exactly as before, while a 104dp two-line box would paint it in + // full beside the destination name; otherwise it takes its own line under + // the name, where it has the whole row and wraps instead of being + // ellipsised into a fragment. The row is a fixed-width settings list, so + // the measurement is exact - no text-scale threshold is guessed. + final availableForContent = + constraints.maxWidth - + (_rowPadding * 2) - + _leadingSlot - + _trailingGap; + // Boundary guard: a degenerate row (no room left for content at all) can never + // hold the hint inline, whatever the measured widths say. + final hasRoomForContent = availableForContent > 0; + final labelWidth = _singleLineWidth(context, label, labelStyle); + final hintFitsInline = + hasRoomForContent && + _fitsWithin( + context, + hint, + hintStyle, + maxWidth: _inlineHintMaxWidth, + maxLines: _inlineHintMaxLines, + ) && + labelWidth + _inlineHintMaxWidth <= availableForContent; + + return PrismListRow( + padding: const EdgeInsets.symmetric(horizontal: _rowPadding), + leading: Icon( + tab.icon, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.3), ), - ), - ), - onTap: onTap, + title: Text( + label, + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.5), + ), + ), + trailing: hintFitsInline + ? ConstrainedBox( + constraints: const BoxConstraints( + maxWidth: _inlineHintMaxWidth, + ), + child: Text( + hint, + maxLines: _inlineHintMaxLines, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.end, + style: hintStyle, + ), + ) + : null, + subtitle: hintFitsInline ? null : Text(hint, style: hintStyle), + onTap: onTap, + ); + }, ); } } diff --git a/lib/features/sharing/views/accept_invite_sheet.dart b/lib/features/sharing/views/accept_invite_sheet.dart index d6f1f024f..d7d30d3da 100644 --- a/lib/features/sharing/views/accept_invite_sheet.dart +++ b/lib/features/sharing/views/accept_invite_sheet.dart @@ -15,7 +15,13 @@ import 'package:prism_plurality/shared/widgets/unsaved_changes_guard.dart'; /// Bottom sheet for sending a sharing request from someone else's sharing code. class AcceptInviteSheet extends ConsumerStatefulWidget { - const AcceptInviteSheet({super.key}); + const AcceptInviteSheet({super.key, this.scrollController}); + + /// Scroll controller handed over by `PrismSheet.showFullScreen`. + /// + /// Passing it keeps drag-to-dismiss coordinated with the body scroll view; + /// without it the sheet still scrolls, it just uses its own controller. + final ScrollController? scrollController; @override ConsumerState createState() => _AcceptInviteSheetState(); @@ -53,105 +59,123 @@ class _AcceptInviteSheetState extends ConsumerState { builder: (context, _) => UnsavedChangesGuard( hasUnsavedChanges: _isDirty, child: SafeArea( - child: Padding( - padding: EdgeInsets.only( - left: 24, - right: 24, - top: 24, - bottom: MediaQuery.of(context).viewInsets.bottom + 24, - ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - context.l10n.sharingUseSharingCode, - style: theme.textTheme.titleLarge, - ), - const SizedBox(height: 16), - if (_error != null) ...[ - PrismSurface( - padding: const EdgeInsets.all(12), - fillColor: theme.colorScheme.errorContainer, - borderColor: theme.colorScheme.error.withValues(alpha: 0.2), - child: Text( - _error!, - style: TextStyle( - color: theme.colorScheme.onErrorContainer, - ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // The sheet is mounted by PrismSheet.showFullScreen, whose body is + // height-tight: a plain Column put the Cancel / Send Request row + // below the sheet bottom as soon as the text grew (263dp of + // overflow at default text on a 320x568 phone, 859dp at 1.5x), so + // the body scrolls and the actions stay pinned where they can + // always be reached. + Expanded( + child: ListView( + controller: widget.scrollController, + padding: const EdgeInsets.fromLTRB(24, 24, 24, 12), + children: [ + Text( + context.l10n.sharingUseSharingCode, + style: theme.textTheme.titleLarge, ), - ), - const SizedBox(height: 12), - ], - PrismTextField( - controller: _inviteController, - labelText: context.l10n.sharingSharingCodeLabel, - hintText: context.l10n.sharingSharingCodeHint, - maxLines: 4, - minLines: 3, - textInputAction: TextInputAction.newline, - onChanged: (_) => _parseInvite(), - ), - const SizedBox(height: 12), - if (_parsedInvite != null) - PrismSurface( - padding: const EdgeInsets.all(12), - child: Row( - children: [ - Icon(AppIcons.link, size: 20), - const SizedBox(width: 8), - Expanded( - child: Text( - _parsedInvite!.displayName != null - ? context.l10n.sharingConnectingWith( - _parsedInvite!.displayName!, - ) - : context.l10n.sharingReadyToSend, - style: theme.textTheme.bodyMedium, + const SizedBox(height: 16), + if (_error != null) ...[ + PrismSurface( + padding: const EdgeInsets.all(12), + fillColor: theme.colorScheme.errorContainer, + borderColor: theme.colorScheme.error.withValues( + alpha: 0.2, + ), + child: Text( + _error!, + style: TextStyle( + color: theme.colorScheme.onErrorContainer, ), ), - ], + ), + const SizedBox(height: 12), + ], + PrismTextField( + controller: _inviteController, + labelText: context.l10n.sharingSharingCodeLabel, + hintText: context.l10n.sharingSharingCodeHint, + maxLines: 4, + minLines: 3, + textInputAction: TextInputAction.newline, + onChanged: (_) => _parseInvite(), ), - ), - const SizedBox(height: 16), - PrismTextField( - controller: _nameController, - labelText: context.l10n.sharingYourDisplayName, - hintText: context.l10n.sharingDisplayNameHint, - textInputAction: TextInputAction.done, - onChanged: (_) => setState(() {}), - ), - const SizedBox(height: 16), - Text( - context.l10n.sharingWhatToShare, - style: theme.textTheme.titleSmall?.copyWith( - color: theme.colorScheme.primary, - fontWeight: FontWeight.w600, - ), - ), - const SizedBox(height: 8), - ...ShareScope.values.map( - (scope) => PrismCheckboxRow( - dense: true, - leading: Icon(scope.icon, size: 20), - title: Text(scope.displayNameFor(termPlural: terms.plural)), - subtitle: Text( - scope.descriptionFor(termSingular: terms.singular), + const SizedBox(height: 12), + if (_parsedInvite != null) + PrismSurface( + padding: const EdgeInsets.all(12), + child: Row( + children: [ + Icon(AppIcons.link, size: 20), + const SizedBox(width: 8), + Expanded( + child: Text( + _parsedInvite!.displayName != null + ? context.l10n.sharingConnectingWith( + _parsedInvite!.displayName!, + ) + : context.l10n.sharingReadyToSend, + style: theme.textTheme.bodyMedium, + ), + ), + ], + ), + ), + const SizedBox(height: 16), + PrismTextField( + controller: _nameController, + labelText: context.l10n.sharingYourDisplayName, + hintText: context.l10n.sharingDisplayNameHint, + textInputAction: TextInputAction.done, + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 16), + Text( + context.l10n.sharingWhatToShare, + style: theme.textTheme.titleSmall?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w600, + ), ), - value: _selectedScopes.contains(scope), - onChanged: (checked) { - setState(() { - if (checked) { - _selectedScopes.add(scope); - } else { - _selectedScopes.remove(scope); - } - }); - }, - ), + const SizedBox(height: 8), + ...ShareScope.values.map( + (scope) => PrismCheckboxRow( + dense: true, + leading: Icon(scope.icon, size: 20), + title: Text( + scope.displayNameFor(termPlural: terms.plural), + ), + subtitle: Text( + scope.descriptionFor(termSingular: terms.singular), + ), + value: _selectedScopes.contains(scope), + onChanged: (checked) { + setState(() { + if (checked) { + _selectedScopes.add(scope); + } else { + _selectedScopes.remove(scope); + } + }); + }, + ), + ), + ], + ), + ), + // Pinned: the only way to send, and the only way out without + // sending. It never scrolls away. + Padding( + padding: EdgeInsets.fromLTRB( + 24, + 4, + 24, + MediaQuery.of(context).viewInsets.bottom + 24, ), - const SizedBox(height: 16), - Row( + child: Row( children: [ Expanded( child: PrismButton( @@ -178,8 +202,8 @@ class _AcceptInviteSheetState extends ConsumerState { ), ], ), - ], - ), + ), + ], ), ), ), diff --git a/lib/features/sharing/views/sharing_screen.dart b/lib/features/sharing/views/sharing_screen.dart index a5e50473e..a3d49918b 100644 --- a/lib/features/sharing/views/sharing_screen.dart +++ b/lib/features/sharing/views/sharing_screen.dart @@ -170,7 +170,8 @@ class _SharingScreenState extends ConsumerState { Future _showUseInvite(BuildContext context) async { final result = await PrismSheet.showFullScreen( context: context, - builder: (context, _) => const AcceptInviteSheet(), + builder: (context, scrollController) => + AcceptInviteSheet(scrollController: scrollController), ); if (result == true && context.mounted) { PrismToast.show(context, message: context.l10n.sharingRequestSent); diff --git a/lib/shared/utils/nav_bar_layout.dart b/lib/shared/utils/nav_bar_layout.dart index fe2dcff5c..7b3948405 100644 --- a/lib/shared/utils/nav_bar_layout.dart +++ b/lib/shared/utils/nav_bar_layout.dart @@ -49,6 +49,36 @@ const double _kLabelWidthSafetyPadding = 8.0; /// labels. const double _kMinimumCollapsedItemWidth = 44.0; +/// Height of one nav-bar label line at [textScaler]. +/// +/// The bar's row height, the label's offset below the row centre and the icon +/// lift all have to agree on this value; a constant tuned for 1x text drifts +/// apart from the real line box as soon as the label scales. +double navBarLabelLineHeight({ + required String label, + required TextStyle style, + required TextScaler textScaler, + required TextDirection textDirection, + Locale? locale, + TextHeightBehavior? textHeightBehavior, +}) { + // [style] is the style the painted label is handed and must already be resolved for + // measurement by the context-bearing caller (ambient DefaultTextStyle merged, bold + // text applied); this helper stays context-free so the layout maths can run without + // one. + final painter = TextPainter( + text: TextSpan(text: label, style: style), + textDirection: textDirection, + textScaler: textScaler, + locale: locale, + textHeightBehavior: textHeightBehavior, + maxLines: 1, + )..layout(); + final height = painter.height; + painter.dispose(); + return height; +} + TextStyle navBarLabelTextStyle( BuildContext context, { required bool isSelected, diff --git a/lib/shared/widgets/app_shell.dart b/lib/shared/widgets/app_shell.dart index 747f70275..ecd9de2ba 100644 --- a/lib/shared/widgets/app_shell.dart +++ b/lib/shared/widgets/app_shell.dart @@ -41,6 +41,7 @@ import 'package:prism_plurality/shared/utils/haptics.dart'; import 'package:prism_plurality/shared/utils/nav_bar_layout.dart'; import 'package:prism_plurality/shared/utils/pin_lock_decision.dart'; import 'package:prism_plurality/shared/widgets/floating_nav_bar_backdrop.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; /// Gap between overflow row and primary row when the nav bar is expanded. const _kNavBarRowGap = 6.0; @@ -55,6 +56,10 @@ const _kNavBarSelectedItemPillHeight = 32.0; const _kNavBarSelectedItemPillTop = 8.0; const _kNavBarPrimaryPillHorizontalInset = 8.0; const _kNavBarIconOnlyIconOpticalOffsetY = 1.0; + +/// Legacy slot height for the label reveal lift. Only used as the default of +/// [navBarLabelRevealLiftY] when a caller has no measured label line box; the +/// live bar always passes the real measured height. const _kNavBarLabelRevealSlotHeight = kNavBarLabelFontSize + 4.0; /// Extra vertical breathing room around the icon + label stack so scaled text @@ -190,26 +195,30 @@ class FrontingUpgradeSheetDecision { 'shouldShow: $shouldShow, isDismissible: $isDismissible)'; } +/// Tallest single-line label box among [labels] at [textScaler]. Labels render +/// with `maxLines: 1`, so the height does not depend on the slot width. double _measureNavBarLabelHeight({ required List labels, - required double slotWidth, required TextStyle labelStyle, required TextScaler textScaler, required TextDirection textDirection, + Locale? locale, + TextHeightBehavior? textHeightBehavior, }) { if (labels.isEmpty) return 0; var maxLabelHeight = 0.0; - final maxWidth = math.max(0.0, slotWidth); for (final label in labels) { - final painter = TextPainter( - text: TextSpan(text: label, style: labelStyle), - textDirection: textDirection, + final lineHeight = navBarLabelLineHeight( + label: label, + style: labelStyle, textScaler: textScaler, - maxLines: 1, - )..layout(maxWidth: maxWidth); - maxLabelHeight = math.max(maxLabelHeight, painter.height); + textDirection: textDirection, + locale: locale, + textHeightBehavior: textHeightBehavior, + ); + maxLabelHeight = math.max(maxLabelHeight, lineHeight); } return maxLabelHeight; @@ -217,26 +226,22 @@ double _measureNavBarLabelHeight({ double _measurePrimaryNavBarRowHeight({ required List primaryLabels, - required double barWidth, - required bool usesOverflowMenu, required int primaryCount, required TextStyle labelStyle, required TextScaler textScaler, required TextDirection textDirection, + Locale? locale, + TextHeightBehavior? textHeightBehavior, }) { if (primaryCount <= 0) return kFloatingNavBarHeight; - final primarySlotWidth = math.max( - 0.0, - (barWidth - (usesOverflowMenu ? 16.0 + _kMoreButtonWidth : 24.0)) / - primaryCount, - ); final maxPrimaryLabelHeight = _measureNavBarLabelHeight( labels: primaryLabels, - slotWidth: primarySlotWidth, labelStyle: labelStyle, textScaler: textScaler, textDirection: textDirection, + locale: locale, + textHeightBehavior: textHeightBehavior, ); return math.max( @@ -283,11 +288,36 @@ double navBarPrimaryPillScaleY({ layoutHeight; } +/// Vertical space a measured row leaves for its label, i.e. what +/// `_measurePrimaryNavBarRowHeight` reserved beyond the icon and the item +/// padding. Rows measured without labels (label visibility `whenExpanded` or +/// `never`) reserve none, and the item then keeps its icon where it was +/// instead of lifting it out of the row. @visibleForTesting -double navBarLabelRevealLiftY({required double labelVisibility}) { - return labelVisibility.clamp(0.0, 1.0).toDouble() * - _kNavBarLabelRevealSlotHeight / - 2; +double navBarReservedLabelHeight({ + required double rowHeight, + required double iconHeight, +}) { + final reserved = + rowHeight - + iconHeight - + _kNavBarItemVerticalPadding - + (_kNavBarBorderWidth * 2); + return math.max(0.0, reserved); +} + +/// How far the icon cluster lifts to make room for a revealed label. +/// +/// [labelHeight] is the label's measured line box. When omitted the historical +/// 16dp slot constant is used, which keeps older call sites behaving exactly as +/// before. +@visibleForTesting +double navBarLabelRevealLiftY({ + required double labelVisibility, + double? labelHeight, +}) { + final slotHeight = labelHeight ?? _kNavBarLabelRevealSlotHeight; + return labelVisibility.clamp(0.0, 1.0).toDouble() * slotHeight / 2; } @visibleForTesting @@ -307,6 +337,7 @@ double navBarPrimaryPillTop({ required double rowHeight, required bool prominentIcons, required double labelVisibility, + double? labelHeight, }) { if (!prominentIcons) return _kNavBarSelectedItemPillTop; final visibility = labelVisibility.clamp(0.0, 1.0).toDouble(); @@ -315,7 +346,11 @@ double navBarPrimaryPillTop({ labelVisibility: visibility, ); final centerY = - (rowHeight / 2) - navBarLabelRevealLiftY(labelVisibility: visibility); + (rowHeight / 2) - + navBarLabelRevealLiftY( + labelVisibility: visibility, + labelHeight: labelHeight, + ); return (centerY - (pillHeight / 2)).clamp(0.0, rowHeight); } @@ -324,6 +359,7 @@ double navBarPrimaryPillPaintOffsetY({ required double rowHeight, required bool prominentIcons, required double labelVisibility, + double? labelHeight, }) { final layoutHeight = navBarPrimaryPillLayoutHeight( prominentIcons: prominentIcons, @@ -336,6 +372,7 @@ double navBarPrimaryPillPaintOffsetY({ rowHeight: rowHeight, prominentIcons: prominentIcons, labelVisibility: labelVisibility, + labelHeight: labelHeight, ) - navBarPrimaryPillLayoutTop( rowHeight: rowHeight, @@ -376,23 +413,24 @@ double navBarEffectiveLabelVisibility({ double _measureOverflowNavBarRowHeight({ required List overflowLabels, - required double barWidth, required int overflowColumns, required TextStyle labelStyle, required TextScaler textScaler, required TextDirection textDirection, + Locale? locale, + TextHeightBehavior? textHeightBehavior, }) { if (overflowLabels.isEmpty || overflowColumns <= 0) { return kFloatingNavBarHeight; } - final overflowSlotWidth = math.max(0.0, (barWidth - 24.0) / overflowColumns); final maxOverflowLabelHeight = _measureNavBarLabelHeight( labels: overflowLabels, - slotWidth: overflowSlotWidth, labelStyle: labelStyle, textScaler: textScaler, textDirection: textDirection, + locale: locale, + textHeightBehavior: textHeightBehavior, ); return math.max( @@ -443,6 +481,10 @@ class _NavLayoutSignature { required this.fontWeight, required this.labelVisibility, required this.labelStyleMode, + required this.boldText, + required this.locale, + required this.styleHash, + required this.textHeightBehaviorHash, }); final double barWidth; @@ -455,6 +497,14 @@ class _NavLayoutSignature { final NavBarLabelVisibility labelVisibility; final NavBarLabelStyle labelStyleMode; + /// Bold text and locale change the measured label height (the bold weight is + /// merged into the style, and the locale selects the face for some scripts), so + /// they belong in the key: without them a cached layout survives a toggle. + final bool boldText; + final Locale? locale; + final int styleHash; + final int textHeightBehaviorHash; + @override bool operator ==(Object other) { if (identical(this, other)) return true; @@ -466,6 +516,10 @@ class _NavLayoutSignature { other.fontWeight == fontWeight && other.labelVisibility == labelVisibility && other.labelStyleMode == labelStyleMode && + other.boldText == boldText && + other.locale == locale && + other.styleHash == styleHash && + other.textHeightBehaviorHash == textHeightBehaviorHash && _listEquals(other.primaryLabels, primaryLabels) && _listEquals(other.overflowLabels, overflowLabels); } @@ -479,6 +533,10 @@ class _NavLayoutSignature { fontWeight, labelVisibility, labelStyleMode, + boldText, + locale, + styleHash, + textHeightBehaviorHash, Object.hashAll(primaryLabels), Object.hashAll(overflowLabels), ); @@ -509,6 +567,8 @@ AppShellMobileNavLayout computeAdaptiveMobileNavLayout({ required TextDirection textDirection, NavBarLabelVisibility labelVisibility = NavBarLabelVisibility.always, NavBarLabelStyle labelStyleMode = NavBarLabelStyle.full, + Locale? locale, + TextHeightBehavior? textHeightBehavior, }) { assert(primaryTabs.length == primaryLabels.length); assert(overflowTabs.length == overflowLabels.length); @@ -542,20 +602,21 @@ AppShellMobileNavLayout computeAdaptiveMobileNavLayout({ : const []; final rowHeight = _measurePrimaryNavBarRowHeight( primaryLabels: visualPrimaryLabels, - barWidth: barWidth, - usesOverflowMenu: spec.usesOverflowMenu, primaryCount: split.primary.length, labelStyle: labelStyle, textScaler: textScaler, textDirection: textDirection, + locale: locale, + textHeightBehavior: textHeightBehavior, ); final overflowRowHeight = _measureOverflowNavBarRowHeight( overflowLabels: visualOverflowLabels, - barWidth: barWidth, overflowColumns: spec.overflowColumns, labelStyle: labelStyle, textScaler: textScaler, textDirection: textDirection, + locale: locale, + textHeightBehavior: textHeightBehavior, ); return AppShellMobileNavLayout( @@ -875,6 +936,9 @@ class _AppShellState extends ConsumerState required TextDirection textDirection, required NavBarLabelVisibility labelVisibility, required NavBarLabelStyle labelStyleMode, + required Locale? locale, + required TextHeightBehavior? textHeightBehavior, + required bool boldText, }) { final signature = _NavLayoutSignature( barWidth: barWidth, @@ -886,6 +950,10 @@ class _AppShellState extends ConsumerState fontWeight: labelStyle.fontWeight ?? FontWeight.w500, labelVisibility: labelVisibility, labelStyleMode: labelStyleMode, + boldText: boldText, + locale: locale, + styleHash: labelStyle.hashCode, + textHeightBehaviorHash: textHeightBehavior.hashCode, ); final cached = _cachedNavLayout; if (cached != null && _cachedNavLayoutSignature == signature) { @@ -902,6 +970,8 @@ class _AppShellState extends ConsumerState textDirection: textDirection, labelVisibility: labelVisibility, labelStyleMode: labelStyleMode, + locale: locale, + textHeightBehavior: textHeightBehavior, ); _cachedNavLayoutSignature = signature; _cachedNavLayout = layout; @@ -1305,11 +1375,19 @@ class _AppShellState extends ConsumerState overflowTabs: configuredOverflowTabs, primaryLabels: primaryLabels, overflowLabels: overflowLabels, - labelStyle: navBarLabelTextStyle(context, isSelected: true), + // Resolved here, where the context exists, with the same helper the painted + // Text uses; the layout maths downstream stays context-free. + labelStyle: prismTextStyleForMeasurement( + context, + navBarLabelTextStyle(context, isSelected: true), + ), textScaler: MediaQuery.textScalerOf(context), textDirection: Directionality.of(context), labelVisibility: labelVisibility, labelStyleMode: labelStyleMode, + locale: Localizations.maybeLocaleOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + boldText: MediaQuery.boldTextOf(context), ); final currentVisibleIndex = mobileLayout.allTabs.indexWhere( (t) => t.branchIndex == widget.navigationShell.currentIndex, @@ -1842,11 +1920,19 @@ class _FloatingNavBarState extends State<_FloatingNavBar> rowHeight: widget.rowHeight, prominentIcons: prominentIcons, ); + // The pill tracks the icon centre, so it needs the + // same measured label box the item lifts against. + final reservedLabelHeight = + navBarReservedLabelHeight( + rowHeight: widget.rowHeight, + iconHeight: kNavBarItemIconHeight, + ); final pillPaintOffsetY = navBarPrimaryPillPaintOffsetY( rowHeight: widget.rowHeight, prominentIcons: prominentIcons, labelVisibility: labelVisibility, + labelHeight: reservedLabelHeight, ); final pillScaleY = navBarPrimaryPillScaleY( prominentIcons: prominentIcons, @@ -2169,10 +2255,15 @@ class _FloatingNavBarState extends State<_FloatingNavBar> rowHeight: widget.rowHeight, prominentIcons: prominentIcons, ); + final reservedLabelHeight = navBarReservedLabelHeight( + rowHeight: widget.rowHeight, + iconHeight: kNavBarItemIconHeight, + ); final pillPaintOffsetY = navBarPrimaryPillPaintOffsetY( rowHeight: widget.rowHeight, prominentIcons: prominentIcons, labelVisibility: simpleLabelVisibility, + labelHeight: reservedLabelHeight, ); final pillScaleY = navBarPrimaryPillScaleY( prominentIcons: prominentIcons, @@ -2396,11 +2487,40 @@ class _NavBarItem extends StatelessWidget { final restingIconWidth = prominentIcon ? kNavBarIconOnlyItemIconHeight : kNavBarItemWidth; + // Measure the label's real line box: its offset and the icon lift have to + // agree with it, otherwise the constant 16dp slot drifts as text scales and + // the label is painted over the icon (or the icon out of the row). + final labelStyle = navBarLabelTextStyle( + context, + isSelected: isSelected, + color: isSelected + ? theme.colorScheme.onSurface + : _navInactiveLabelColor(theme), + ); + final measuredLabelHeight = navBarLabelLineHeight( + label: label, + style: prismTextStyleForMeasurement(context, labelStyle), + textScaler: MediaQuery.textScalerOf(context), + textDirection: Directionality.of(context), + locale: Localizations.maybeLocaleOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + ); + final labelHeight = math.min( + measuredLabelHeight, + // Both row measurers reserve space above the 32dp icon box, including + // for icon-only overflow slots, so the reservation is read the same way. + navBarReservedLabelHeight( + rowHeight: rowHeight, + iconHeight: kNavBarItemIconHeight, + ), + ); final iconLift = navBarLabelRevealLiftY( labelVisibility: visibleLabelFactor, + labelHeight: labelHeight, ); - final labelOffsetY = - (iconHeight / 2) + (_kNavBarLabelRevealSlotHeight / 2) - iconLift; + // Icon cluster sits directly above the label, both centred in the row, so + // the label's own offset below the row centre is half the icon box. + final labelOffsetY = (iconHeight / 2) + (labelHeight / 2) - iconLift; Widget iconWidget = Icon( itemIcon, @@ -2443,13 +2563,7 @@ class _NavBarItem extends StatelessWidget { child: _NavBarLabel( key: ValueKey('nav_label_${tab.id.name}'), label: label, - style: navBarLabelTextStyle( - context, - isSelected: isSelected, - color: isSelected - ? theme.colorScheme.onSurface - : _navInactiveLabelColor(theme), - ), + style: labelStyle, opacity: visibleLabelFactor, ), ); @@ -2569,7 +2683,22 @@ class _FloatingSidebar extends ConsumerWidget { child: Padding( padding: const EdgeInsets.only(left: 12, top: 12, bottom: 12), child: Container( - width: _kSidebarWidth, + // Grow with the actual label scaler, but keep most of the + // window available to the current screen. + width: math.min( + _kSidebarWidth * + math.max( + 1.0, + MediaQuery.textScalerOf(context).scale(13) / 13, + ), + math.min( + 320.0, + math.max( + _kSidebarWidth, + MediaQuery.sizeOf(context).width * 0.40, + ), + ), + ), height: double.infinity, decoration: BoxDecoration( color: Color.alphaBlend( @@ -2702,8 +2831,8 @@ class _SidebarItemState extends State<_SidebarItem> { // Colors.transparent (a transparent black) flashed a dark tint // mid-fade and lagged the highlight onto adjacent rows on hover. child: Container( - height: _kSidebarItemHeight, - padding: const EdgeInsets.symmetric(horizontal: 12), + constraints: const BoxConstraints(minHeight: _kSidebarItemHeight), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( color: fillColor, borderRadius: BorderRadius.circular( @@ -2725,17 +2854,20 @@ class _SidebarItemState extends State<_SidebarItem> { ), ), const SizedBox(width: 10), - Text( - widget.tab.localizedLabel( - context, - terminologyPlural: widget.terminologyPlural, - ), - style: TextStyle( - fontSize: 13, - fontWeight: widget.isSelected - ? FontWeight.w600 - : FontWeight.w400, - color: labelColor, + Flexible( + child: Text( + widget.tab.localizedLabel( + context, + terminologyPlural: widget.terminologyPlural, + ), + softWrap: true, + style: TextStyle( + fontSize: 13, + fontWeight: widget.isSelected + ? FontWeight.w600 + : FontWeight.w400, + color: labelColor, + ), ), ), ], diff --git a/lib/shared/widgets/member_mention_text_field.dart b/lib/shared/widgets/member_mention_text_field.dart index 435bc89c9..936135563 100644 --- a/lib/shared/widgets/member_mention_text_field.dart +++ b/lib/shared/widgets/member_mention_text_field.dart @@ -617,10 +617,15 @@ class _MemberMentionOverlayState extends ConsumerState<_MemberMentionOverlay> { child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => widget.onSelect(member), - child: SizedBox( - height: 48, + // Grow with the member name's line box: a fixed 48dp row + // clipped the glyphs once the composed scale passed 3x. + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: 48), child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 12), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), child: Row( children: [ MemberAvatar( diff --git a/lib/shared/widgets/member_search_sheet.dart b/lib/shared/widgets/member_search_sheet.dart index a9dbc5f99..32851d6a1 100644 --- a/lib/shared/widgets/member_search_sheet.dart +++ b/lib/shared/widgets/member_search_sheet.dart @@ -6,7 +6,6 @@ import 'package:prism_plurality/shared/extensions/app_localizations_extension.da import 'package:prism_plurality/shared/theme/accent_legibility.dart'; import 'package:prism_plurality/shared/theme/app_colors.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; -import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/utils/member_filter.dart'; import 'package:prism_plurality/shared/utils/member_picker_order.dart'; import 'package:prism_plurality/shared/utils/modal_insets.dart'; @@ -17,6 +16,7 @@ import 'package:prism_plurality/shared/widgets/prism_chip.dart'; import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; import 'package:prism_plurality/shared/widgets/prism_text_field.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; /// Typed result returned by [MemberSearchSheet.showSingle]. /// @@ -441,7 +441,14 @@ class _MemberSearchSheetState extends ConsumerState { return LayoutBuilder( builder: (context, constraints) { - if (constraints.maxHeight < PrismTokens.topBarHeight) { + // The bar grows with the ambient text scale; compare against what it + // needs rather than the fixed 66dp. + final barHeight = prismScaledHeightOf( + context, + topBar, + availableWidth: constraints.maxWidth, + ); + if (constraints.maxHeight < barHeight) { return CustomScrollView( controller: widget.scrollController, primary: widget.scrollController == null, diff --git a/lib/shared/widgets/pin_numpad_button.dart b/lib/shared/widgets/pin_numpad_button.dart index affcc2e4a..e952aa722 100644 --- a/lib/shared/widgets/pin_numpad_button.dart +++ b/lib/shared/widgets/pin_numpad_button.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:prism_plurality/shared/providers/visual_effects_provider.dart'; import 'package:prism_plurality/shared/theme/prism_shapes.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_metrics.dart'; import 'package:prism_plurality/shared/widgets/tinted_glass_surface.dart'; /// A glass numpad key with two-phase spring press feedback. @@ -56,20 +57,25 @@ class _PinNumpadButtonState extends ConsumerState { final mode = VisualEffectsModeX.of(context, ref); final useAnim = mode.useAnimations; + // Digits keep headlineMedium at the requested text size; the key grows to + // hold that glyph box on both axes instead of clipping it. Icon-only keys + // keep the square geometry (the icon is decorative and does not scale). + final digitStyle = + theme.textTheme.headlineMedium?.copyWith(fontWeight: FontWeight.w500) ?? + const TextStyle(fontSize: 28, fontWeight: FontWeight.w500); + final keyExtent = widget.label == null + ? (width: widget.size, height: widget.size) + : pinNumpadKeyExtent(context, size: widget.size, style: digitStyle); + final Widget surface = TintedGlassSurface( - width: widget.size, - height: widget.size, + width: keyExtent.width, + height: keyExtent.height, borderRadius: BorderRadius.circular( - PrismShapes.of(context).radius(widget.size / 2), + PrismShapes.of(context).radius(keyExtent.width / 2), ), tint: _pressed ? Colors.white.withValues(alpha: 0.08) : null, child: widget.label != null - ? Text( - widget.label!, - style: theme.textTheme.headlineMedium?.copyWith( - fontWeight: FontWeight.w500, - ), - ) + ? Text(widget.label!, style: digitStyle) : Icon( widget.icon, size: widget.size * 0.33, @@ -117,8 +123,8 @@ class _PinNumpadButtonState extends ConsumerState { onPointerUp: (_) => _release(), onPointerCancel: (_) => _release(), child: SizedBox( - width: widget.size, - height: widget.size, + width: keyExtent.width, + height: keyExtent.height, child: animated, ), ), diff --git a/lib/shared/widgets/pin_numpad_cell.dart b/lib/shared/widgets/pin_numpad_cell.dart index 3cfbc1bde..1a335e6af 100644 --- a/lib/shared/widgets/pin_numpad_cell.dart +++ b/lib/shared/widgets/pin_numpad_cell.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_metrics.dart'; /// Flat circular numpad cell for PIN entry sheets. Icon-only cells (backspace) /// get a [Semantics] + [Tooltip] wrapper automatically. @@ -21,32 +22,43 @@ class PinNumpadCell extends StatelessWidget { final VoidCallback onTap; final ThemeData theme; + /// Requested key width; the painted size follows the digit and only ever grows + /// past it (see [pinNumpadKeyExtent]). + static const double _keyWidth = 72; + @override Widget build(BuildContext context) { final isIconOnly = icon != null && label == null; - final backspaceLabel = - isIconOnly ? context.l10n.syncSetupNumpadBackspaceLabel : null; + final backspaceLabel = isIconOnly + ? context.l10n.syncSetupNumpadBackspaceLabel + : null; + + final digitStyle = TextStyle( + color: theme.colorScheme.onSurface, + fontSize: 24, + fontWeight: FontWeight.w500, + ); + // Keep the 24pt digit at the requested scale and let the key grow; a fixed + // 72dp box clipped it above ~2.1x. Square keys still render as a circle + // because the radius is half the width. + final keyExtent = label != null + ? pinNumpadKeyExtent(context, size: _keyWidth, style: digitStyle) + : (width: _keyWidth, height: _keyWidth); Widget button = GestureDetector( onTap: onTap, behavior: HitTestBehavior.opaque, child: Container( - width: 72, - height: 72, + width: keyExtent.width, + height: keyExtent.height, alignment: Alignment.center, decoration: BoxDecoration( - shape: BoxShape.circle, + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(keyExtent.width / 2), color: theme.colorScheme.primary.withValues(alpha: 0.08), ), child: label != null - ? Text( - label!, - style: TextStyle( - color: theme.colorScheme.onSurface, - fontSize: 24, - fontWeight: FontWeight.w500, - ), - ) + ? Text(label!, style: digitStyle) : Icon(icon, size: 24, color: theme.colorScheme.onSurface), ), ); @@ -55,10 +67,7 @@ class PinNumpadCell extends StatelessWidget { button = Semantics( label: backspaceLabel, button: true, - child: Tooltip( - message: backspaceLabel!, - child: button, - ), + child: Tooltip(message: backspaceLabel!, child: button), ); } diff --git a/lib/shared/widgets/pin_numpad_metrics.dart b/lib/shared/widgets/pin_numpad_metrics.dart new file mode 100644 index 000000000..3aa283743 --- /dev/null +++ b/lib/shared/widgets/pin_numpad_metrics.dart @@ -0,0 +1,98 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; + +/// Digits measured for every key so the pad uses one consistent extent. +const kPinNumpadDigits = [ + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + '9', +]; + +/// Breathing room kept above, below and beside a PIN key's digit so the glyph +/// never touches the key's rounded edge. +const double kPinNumpadKeyVerticalPadding = 8.0; +const double kPinNumpadKeyHorizontalPadding = 8.0; + +Size _digitSize( + BuildContext context, + TextStyle style, + String digit, { + double? maxWidth, +}) { + final painter = TextPainter( + text: TextSpan( + text: digit, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + locale: Localizations.maybeLocaleOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + maxLines: 1, + )..layout(maxWidth: maxWidth ?? double.infinity); + final size = Size(painter.width, painter.height); + painter.dispose(); + return size; +} + +/// Height of one line of [style] at the ambient text scale, for the tallest digit. +double pinNumpadDigitLineHeight(BuildContext context, TextStyle style) { + var height = 0.0; + for (final digit in kPinNumpadDigits) { + height = math.max(height, _digitSize(context, style, digit).height); + } + return height; +} + +/// Natural (unwrapped) advance of the widest digit in [style] at the ambient +/// text scale. +double pinNumpadDigitWidth(BuildContext context, TextStyle style) { + var width = 0.0; + for (final digit in kPinNumpadDigits) { + width = math.max(width, _digitSize(context, style, digit).width); + } + return width; +} + +/// Painted size of one PIN numpad key for a caller asking for [size]. +/// +/// Default geometry is preserved: while every digit's line box and advance still +/// fit inside [size] the key stays square at [size] (up to ~1.8x on the 64dp +/// keys and ~2x on the 72dp ones). Past that the key grows to hold the digit at +/// the requested font size - vertically by the line box plus padding, and +/// horizontally only if a glyph ever gets wider than the caller's key, which a +/// digit does not at the bundled faces but a substituted font could. Every key in +/// a pad resolves to the same extent because the measurement covers 0-9. +({double width, double height}) pinNumpadKeyExtent( + BuildContext context, { + required double size, + required TextStyle style, +}) { + final digitHeight = pinNumpadDigitLineHeight(context, style); + final digitWidth = pinNumpadDigitWidth(context, style); + // TintedGlassSurface's decoration consumes one hairline on EACH edge. + // Compare with its usable interior, not the outer key: a 71.82dp digit does + // not fit in the 71dp interior of a 72dp glass key. The flat cell uses this + // same conservative envelope, so all shared callers size consistently. + const borderExtent = PrismTokens.hairlineBorderWidth * 2; + final minimum = math.max(44.0, size); + return ( + width: digitWidth + borderExtent <= minimum + ? minimum + : digitWidth + borderExtent + kPinNumpadKeyHorizontalPadding * 2, + height: digitHeight + borderExtent <= minimum + ? minimum + : digitHeight + borderExtent + kPinNumpadKeyVerticalPadding, + ); +} diff --git a/lib/shared/widgets/prism_glass_app_bar.dart b/lib/shared/widgets/prism_glass_app_bar.dart index 41217238c..218a11d2d 100644 --- a/lib/shared/widgets/prism_glass_app_bar.dart +++ b/lib/shared/widgets/prism_glass_app_bar.dart @@ -1,9 +1,17 @@ import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; /// A centered app bar layout intended to pair with Prism glass controls. -class PrismGlassAppBar extends StatelessWidget implements PreferredSizeWidget { +/// +/// [height] is the minimum (66dp by default). Callers that place this bar in a +/// slot which reserves a fixed extent — `Scaffold.appBar` is the only such slot in +/// Prism — must declare the height they want with [preferredHeightFor]; inside a +/// [SliverPinnedTopBar] the sliver asks for it instead and no caller wiring is +/// needed. +class PrismGlassAppBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const PrismGlassAppBar({ super.key, required this.title, @@ -25,7 +33,11 @@ class PrismGlassAppBar extends StatelessWidget implements PreferredSizeWidget { Size get preferredSize => Size.fromHeight(height); @override - Widget build(BuildContext context) { + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + return _bar().preferredHeightFor(context, availableWidth: availableWidth); + } + + PrismTopBar _bar() { return PrismTopBar( title: title, subtitle: subtitle, @@ -35,4 +47,7 @@ class PrismGlassAppBar extends StatelessWidget implements PreferredSizeWidget { horizontalPadding: EdgeInsets.symmetric(horizontal: horizontalPadding), ); } + + @override + Widget build(BuildContext context) => _bar(); } diff --git a/lib/shared/widgets/prism_list_row.dart b/lib/shared/widgets/prism_list_row.dart index 9281a767f..3d1766123 100644 --- a/lib/shared/widgets/prism_list_row.dart +++ b/lib/shared/widgets/prism_list_row.dart @@ -12,6 +12,7 @@ class PrismListRow extends StatefulWidget { required this.title, this.subtitle, this.leading, + this.leadingWidth, this.trailing, this.onTap, this.onLongPress, @@ -27,6 +28,10 @@ class PrismListRow extends StatefulWidget { final Widget title; final Widget? subtitle; final Widget? leading; + + /// Optional extent for leading content that grows with accessibility text. + /// Null preserves the normal 40dp (36dp dense) slot for existing callers. + final double? leadingWidth; final Widget? trailing; final VoidCallback? onTap; final VoidCallback? onLongPress; @@ -69,7 +74,7 @@ class _PrismListRowState extends State { children: [ if (widget.leading != null) ...[ SizedBox( - width: widget.dense ? 36 : 40, + width: widget.leadingWidth ?? (widget.dense ? 36 : 40), child: Center(child: widget.leading), ), const SizedBox(width: 12), @@ -120,7 +125,9 @@ class _PrismListRowState extends State { ), ); - if (!canPress && widget.onLongPress == null && widget.onSecondaryTap == null) { + if (!canPress && + widget.onLongPress == null && + widget.onSecondaryTap == null) { return child; } diff --git a/lib/shared/widgets/prism_mnemonic_field.dart b/lib/shared/widgets/prism_mnemonic_field.dart index bdae5f80c..39e5be086 100644 --- a/lib/shared/widgets/prism_mnemonic_field.dart +++ b/lib/shared/widgets/prism_mnemonic_field.dart @@ -16,6 +16,7 @@ import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/utils/haptics.dart'; import 'package:prism_plurality/shared/widgets/glass_surface.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/secure_scope.dart'; /// Outcome of a pre-scan camera permission probe. @@ -404,12 +405,127 @@ class _PrismMnemonicFieldState extends State { _applyMnemonic(scannedMnemonic); } + /// One numbered word slot; [index] is 0-based, the label is 1-based. + Widget _buildWordSlot(int index, double ordinalWidth) { + return _WordSlotInput( + slotNumber: index + 1, + ordinalWidth: ordinalWidth, + controller: _slotControllers[index], + focusNode: _slotFocusNodes[index], + obscureText: _obscure, + wordSet: _wordSet, + enabled: widget.enabled, + autofocus: widget.autofocus && index == 0, + isLast: index == 11, + onChanged: (v) => _onSlotChanged(index, v), + onSubmitted: index < 11 + ? (_) => _moveFocusToSlot(index + 1) + : (_) => widget.onSubmitted?.call(widget.controller.text), + ); + } + + /// A painter configured exactly like the text this field paints: the shared + /// measurement style (ambient DefaultTextStyle merged per `Text`'s rules, + /// `inherit: false` respected, the platform bold weight applied), the ambient + /// text scaler, the ambient direction, the locale and the inherited text-height + /// behaviour. + /// + /// Every extent in this file is measured through here, so a reserved height and + /// the glyphs it holds can never come from different faces. + /// + /// The painter is returned **owned by the caller**: it holds native layout state, + /// so every call site releases it in a `finally` as soon as the height or width it + /// was built for has been read. + static TextPainter _measurementPainter( + BuildContext context, + InlineSpan text, { + int? maxLines, + double maxWidth = double.infinity, + }) { + return TextPainter( + text: text, + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: maxLines, + textHeightBehavior: prismTextHeightBehaviorFor(context), + )..layout(maxWidth: maxWidth); + } + + /// Height the word-suggestion band reserves for one chip line. + /// + /// Unlike a hint, this value becomes the band's actual height, so it is measured + /// from the style the chips paint with - the same base style, resolved through + /// the shared contract - plus the band's 4dp list padding and the chip's 8dp + /// vertical padding on each side and the GlassSurface border dimensions. The + /// original 48dp band stays the floor. + static double _suggestionStripHeight(BuildContext context, TextStyle? style) { + final painter = _measurementPainter( + context, + TextSpan(text: 'Hg', style: prismTextStyleForMeasurement(context, style)), + maxLines: 1, + ); + try { + // Container includes its decoration border in addition to explicit padding. + final borderInsets = Border.all( + width: PrismTokens.hairlineBorderWidth, + ).dimensions; + return math.max(48.0, painter.height + 24 + borderInsets.vertical); + } finally { + // The painter is owned by this call: it holds native layout state, so it is + // released as soon as the one number it was built for has been read. + painter.dispose(); + } + } + + /// Width the ordinal column needs for whichever label 1..12 is widest. + /// + /// Measured once per field build, for every label, with the style, direction + /// and inherited scaler the slots paint with - not from an assumed widest + /// "12", which a different font could beat, and not per slot. One fixed + /// budget keeps the twelve numbers in a single column, and it never touches a + /// controller, focus node or IME connection. Twelve short literals are the + /// whole cost, so no vocabulary or history is scanned. The original 18dp + /// column stays the floor for small text. + static double _measuredSlotOrdinalWidth( + BuildContext context, + TextStyle? style, + ) { + final resolved = prismTextStyleForMeasurement(context, style); + var widest = 0.0; + for (var slot = 1; slot <= 12; slot++) { + final painter = _measurementPainter( + context, + TextSpan(text: '$slot', style: resolved), + maxLines: 1, + ); + try { + if (painter.width > widest) widest = painter.width; + } finally { + // Each iteration owns its painter; twelve of them would otherwise keep + // native layout state alive until the frame's garbage collection. + painter.dispose(); + } + } + return math.max(18.0, widest + 2); + } + // ── Build ───────────────────────────────────────────────────────────────── @override Widget build(BuildContext context) { final theme = Theme.of(context); final l10n = context.l10n; + // One ordinal column width for the whole grid, measured once per build for + // every label 1..12 (never an assumed widest digit) with the style, scaler + // and direction the slots paint with. One fixed budget keeps the numbers in + // a single column; it is a pass over twelve literals, so no vocabulary or + // history is touched, and changing it never rebuilds a controller, focus + // node or IME connection. + final slotOrdinalWidth = _measuredSlotOrdinalWidth( + context, + _slotOrdinalTextStyle(theme), + ); final validCount = _slotControllers .where((c) => _wordSet.contains(c.text.trim())) .length; @@ -434,7 +550,18 @@ class _PrismMnemonicFieldState extends State { child: Material( color: Colors.transparent, child: SizedBox( - height: 48, + // The strip must fit one chip line at the inherited scale: a + // fixed 48dp band clipped the suggestion word at large text. The + // floor keeps the original band at default and small text. + height: _suggestionStripHeight( + context, + // The same base style the chips paint with (labelLarge plus the + // chip's own weight), so the reserved height belongs to the face + // and weight that are actually drawn. + Theme.of( + context, + ).textTheme.labelLarge?.copyWith(fontWeight: FontWeight.w600), + ), child: ListView.separated( scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric( @@ -534,31 +661,21 @@ class _PrismMnemonicFieldState extends State { const SizedBox(height: 10), // ── 2×6 word input grid ──────────────────────────────────────────── - GridView.builder( - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - mainAxisExtent: 40, - crossAxisSpacing: 6, - mainAxisSpacing: 6, - ), - itemCount: 12, - itemBuilder: (_, i) => _WordSlotInput( - slotNumber: i + 1, - controller: _slotControllers[i], - focusNode: _slotFocusNodes[i], - obscureText: _obscure, - wordSet: _wordSet, - enabled: widget.enabled, - autofocus: widget.autofocus && i == 0, - isLast: i == 11, - onChanged: (v) => _onSlotChanged(i, v), - onSubmitted: i < 11 - ? (_) => _moveFocusToSlot(i + 1) - : (_) => widget.onSubmitted?.call(widget.controller.text), + // Six rows of two self-sizing slots rather than a GridView with a + // fixed 40dp row extent: the word line box grows with the text scale, + // and a fixed extent sliced the word the user has to transcribe. The + // slot keeps a 40dp minimum, so default geometry is unchanged. + for (var row = 0; row < 6; row++) ...[ + if (row > 0) const SizedBox(height: 6), + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: _buildWordSlot(row * 2, slotOrdinalWidth)), + const SizedBox(width: 6), + Expanded(child: _buildWordSlot(row * 2 + 1, slotOrdinalWidth)), + ], ), - ), + ], if (hasError) ...[ const SizedBox(height: 6), @@ -844,9 +961,20 @@ class _CameraPermissionDialog extends StatelessWidget { // ───────────────────────────────────────────────────────────────────────────── /// Single numbered word slot: slot label + single-line TextField. +/// The label style every slot ordinal renders with. +/// +/// Shared so the column width is measured with exactly the style the number is +/// painted in. +TextStyle? _slotOrdinalTextStyle(ThemeData theme) => + theme.textTheme.labelSmall?.copyWith( + color: theme.colorScheme.onSurface.withValues(alpha: 0.4), + fontFeatures: const [FontFeature.tabularFigures()], + ); + class _WordSlotInput extends StatelessWidget { const _WordSlotInput({ required this.slotNumber, + required this.ordinalWidth, required this.controller, required this.focusNode, required this.obscureText, @@ -859,6 +987,10 @@ class _WordSlotInput extends StatelessWidget { }); final int slotNumber; + + /// Fixed width of the ordinal column for the whole grid, measured once by the + /// field for every label 1..12 at the inherited text scale. + final double ordinalWidth; final TextEditingController controller; final FocusNode focusNode; final bool obscureText; @@ -899,57 +1031,63 @@ class _WordSlotInput extends StatelessWidget { ), ); - return Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - SizedBox( - width: 18, - child: Text( - '$slotNumber', - textAlign: TextAlign.right, - style: theme.textTheme.labelSmall?.copyWith( - color: theme.colorScheme.onSurface.withValues(alpha: 0.4), - fontFeatures: const [FontFeature.tabularFigures()], + // The ordinal keeps its own glyph width: at 3.375x a fixed 18dp column + // clipped two-digit numbers, and the number is the only way to tell which + // word of the phrase you are typing. The width comes from the field's single + // measured budget for labels 1..12. + final slotLabelStyle = _slotOrdinalTextStyle(theme); + + return ConstrainedBox( + constraints: const BoxConstraints(minHeight: 40), + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: ordinalWidth, + child: Text( + '$slotNumber', + textAlign: TextAlign.right, + style: slotLabelStyle, ), ), - ), - const SizedBox(width: 6), - Expanded( - child: TextField( - controller: controller, - focusNode: focusNode, - enabled: enabled, - autofocus: autofocus, - obscureText: obscureText, - keyboardType: TextInputType.visiblePassword, - autocorrect: false, - enableSuggestions: false, - enableIMEPersonalizedLearning: false, - textCapitalization: TextCapitalization.none, - maxLines: 1, - onChanged: onChanged, - onSubmitted: onSubmitted, - textInputAction: isLast - ? TextInputAction.done - : TextInputAction.next, - style: theme.textTheme.bodyMedium, - cursorColor: theme.colorScheme.primary, - inputFormatters: [_WordInputFormatter()], - decoration: InputDecoration( - isDense: true, - contentPadding: const EdgeInsets.symmetric( - horizontal: 8, - vertical: 6, + const SizedBox(width: 6), + Expanded( + child: TextField( + controller: controller, + focusNode: focusNode, + enabled: enabled, + autofocus: autofocus, + obscureText: obscureText, + keyboardType: TextInputType.visiblePassword, + autocorrect: false, + enableSuggestions: false, + enableIMEPersonalizedLearning: false, + textCapitalization: TextCapitalization.none, + maxLines: 1, + onChanged: onChanged, + onSubmitted: onSubmitted, + textInputAction: isLast + ? TextInputAction.done + : TextInputAction.next, + style: theme.textTheme.bodyMedium, + cursorColor: theme.colorScheme.primary, + inputFormatters: [_WordInputFormatter()], + decoration: InputDecoration( + isDense: true, + contentPadding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 6, + ), + filled: true, + fillColor: fillColor, + border: baseBorder, + enabledBorder: baseBorder, + focusedBorder: focusedBorder, ), - filled: true, - fillColor: fillColor, - border: baseBorder, - enabledBorder: baseBorder, - focusedBorder: focusedBorder, ), ), - ), - ], + ], + ), ); } } diff --git a/lib/shared/widgets/prism_page_scaffold.dart b/lib/shared/widgets/prism_page_scaffold.dart index f334ea3db..659e252b5 100644 --- a/lib/shared/widgets/prism_page_scaffold.dart +++ b/lib/shared/widgets/prism_page_scaffold.dart @@ -21,6 +21,7 @@ class PrismPageScaffold extends StatelessWidget { this.resizeToAvoidBottomInset, this.safeAreaBottom = true, this.topBarMaxWidth = double.infinity, + this.topBarMinBodyExtent = 0.0, }); final Widget body; @@ -38,6 +39,13 @@ class PrismPageScaffold extends StatelessWidget { /// clamped, so the bar lines up with the content column. final double topBarMaxWidth; + /// Body height that must remain visible for [topBar] to stay pinned. Defaults + /// to zero, i.e. the bar is pinned whenever it fits at all (unchanged + /// behaviour). A composite header whose measured content can outgrow a short + /// viewport (keyboard up) passes the room it needs here; the header then + /// scrolls with the content instead of squeezing the body away. + final double topBarMinBodyExtent; + @override Widget build(BuildContext context) { final paddedBody = Padding( @@ -48,7 +56,11 @@ class PrismPageScaffold extends StatelessWidget { final scaffoldBody = topBar != null ? NestedScrollView( headerSliverBuilder: (_, _) => [ - SliverPinnedTopBar(maxWidth: topBarMaxWidth, child: topBar!), + SliverPinnedTopBar( + maxWidth: topBarMaxWidth, + minBodyExtent: topBarMinBodyExtent, + child: topBar!, + ), ], body: paddedBody, ) diff --git a/lib/shared/widgets/prism_scaled_height.dart b/lib/shared/widgets/prism_scaled_height.dart new file mode 100644 index 000000000..9feba61d1 --- /dev/null +++ b/lib/shared/widgets/prism_scaled_height.dart @@ -0,0 +1,191 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; + +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; + +/// A chrome widget that can report the height it needs at the ambient text +/// scale — the user's system accessibility scaler composed with Prism's own +/// font-size preference (`PrismTextScaler` in `app.dart`), never clamped and +/// never rounded to a constant. +/// +/// A pinned header has to know its extent before its child is laid out, so a bar +/// that can grow exposes this instead of relying on a fixed +/// [PreferredSizeWidget] size. [preferredHeightFor] returns the height at the +/// ambient text scale; the returned value excludes system padding (the safe-area +/// top), which the sliver adds once for every bar. +abstract interface class PrismScaledHeight { + /// Height this widget needs, at the text scale in [context]. + /// + /// [availableWidth] is the cross-axis space the widget will actually be given, + /// when the caller knows it. Content that wraps or that sizes itself from its + /// own width (filter rows, segmented tracks, chip strips) must measure against + /// this width instead of guessing from the window; content that is a single + /// ellipsised line is width-independent and may ignore it. + double preferredHeightFor(BuildContext context, {double? availableWidth}); +} + +/// The effective [TextStyle] a [Text] with [style] paints in, at [context]. +/// +/// Mirrors `Text.build` in `flutter/lib/src/widgets/text.dart`: the ambient +/// [DefaultTextStyle] is merged **only** when [style] is null or `style.inherit`, +/// and `MediaQuery.boldText` is applied last as [FontWeight.bold] (w700). A +/// measurement that skips either step measures a different face or weight from the +/// one that is painted, which is exactly how a bar ends up a few dp short. +/// +/// This is the style every measurement painter in this file starts from; callers +/// pass the style they hand to [Text] (theme style, or a caller override), not a +/// pre-merged one. +TextStyle prismTextStyleForMeasurement(BuildContext context, TextStyle? style) { + final defaultTextStyle = DefaultTextStyle.of(context); + TextStyle effective; + if (style == null || style.inherit) { + effective = defaultTextStyle.style.merge(style); + } else { + effective = style; + } + if (MediaQuery.boldTextOf(context)) { + effective = effective.merge(const TextStyle(fontWeight: FontWeight.bold)); + } + return effective; +} + +/// [TextHeightBehavior] the painted text inherits, for measurement painters. +TextHeightBehavior? prismTextHeightBehaviorFor(BuildContext context) => + DefaultTextStyle.of(context).textHeightBehavior; + +/// Height one line of [text] occupies at the text scale in [context], measured +/// by laying the paragraph out with the resolved style, scaler and text +/// direction. +/// +/// Deliberately not `fontSize * textScaleFactor`: the composed scaler is +/// nonlinear on platforms that expose one, and a face's line box is not its em +/// square. The text itself is measured, not a representative glyph, because a +/// run resolved to a fallback face (emoji, CJK, Arabic) can report a taller line +/// box than the primary face — laying out `'M'` alone would under-measure +/// exactly those titles. +/// +/// This is the paragraph's line box, i.e. the box the text paints in and the box +/// a bar can reserve. A fallback face can still draw ink a little outside its +/// own line box, which is why the bars keep breathing space above and below the +/// block when they grow (see [PrismTopBar]'s grown padding) and why the +/// regressions assert glyph-run ink boxes, not only the paragraph box (the same +/// allowance the timeline header uses). +double prismLineHeight( + BuildContext context, + TextStyle? style, { + String text = 'M', +}) { + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final height = painter.height; + painter.dispose(); + return height; +} + +/// Height [bar] needs at the text scale in [context]. +/// +/// A [PrismScaledHeight] bar reports its own measured height; any other +/// [PreferredSizeWidget] keeps its declared `preferredSize` (so a bar that has +/// not opted in behaves exactly as before); anything else falls back to the +/// [PrismTokens.topBarHeight] minimum. +double prismScaledHeightOf( + BuildContext context, + Widget bar, { + double? availableWidth, +}) { + // A typed pattern, not an `is` promotion: [Widget] and the two interfaces are + // unrelated types, so Dart does not promote across the test. + if (bar case final PrismScaledHeight scaled) { + return scaled.preferredHeightFor(context, availableWidth: availableWidth); + } + if (bar case final PreferredSizeWidget sized) { + return sized.preferredSize.height; + } + return PrismTokens.topBarHeight; +} + +/// Resolves [bar]'s height for a slot that reserves a fixed extent. +/// +/// `Scaffold.appBar` is the only such slot in Prism: it caps its child at +/// `AppBar.preferredHeightFor(context, appBar.preferredSize) + +/// MediaQuery.padding.top` (`scaffold.dart`, `_ScaffoldSlot.appBar`), so a bar +/// whose [PreferredSizeWidget.preferredSize] is a constant cannot grow there — +/// `preferredSize` is a getter without a `BuildContext`. +/// +/// Use this adapter where a context exists, and pass the *content* height: the +/// returned size excludes the status bar, because `Scaffold` adds +/// `MediaQuery.padding.top` to the cap itself and the bar's own `SafeArea` +/// consumes it. Adding the inset here as well would reserve a status bar of +/// empty space above the bar. +/// +/// ```dart +/// final bar = PrismGlassAppBar(title: title); +/// return Scaffold(appBar: prismScaledPreferredSize(context, bar)); +/// ``` +/// +/// Bars that do not implement [PrismScaledHeight] fall back to their declared +/// `preferredSize` (see [prismScaledHeightOf]), i.e. exactly today's behaviour. +PreferredSizeWidget prismScaledPreferredSize( + BuildContext context, + Widget bar, { + double? availableWidth, +}) { + return PreferredSize( + preferredSize: Size.fromHeight( + prismScaledHeightOf(context, bar, availableWidth: availableWidth), + ), + child: bar, + ); +} + +/// How far [text]'s glyph ink escapes its own line box, vertically. +/// +/// A paragraph's height is its line box; a run resolved to a fallback face can +/// still paint above the first line's top or below its bottom (emoji, CJK, and +/// faces with unusual ascenders — the same allowance the timeline header makes). +/// Returns the larger of the two escapes, so a bar that keeps this much space +/// above *and* below a block of height [prismLineHeight] contains the ink at the +/// requested text size without shrinking anything. +/// +/// Measured from the same paragraph the text will paint (style, scaler and +/// direction), via the laid-out run boxes; additive helper, no existing +/// signature or behaviour is changed by it. +double prismTextInkEscape( + BuildContext context, + TextStyle? style, { + required String text, +}) { + if (text.isEmpty) return 0; + final painter = TextPainter( + text: TextSpan( + text: text, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + textHeightBehavior: prismTextHeightBehaviorFor(context), + locale: Localizations.maybeLocaleOf(context), + maxLines: 1, + )..layout(); + final boxes = painter.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: text.length), + ); + final lineHeight = painter.height; + var escape = 0.0; + for (final box in boxes) { + escape = math.max(escape, -box.top); + escape = math.max(escape, box.bottom - lineHeight); + } + painter.dispose(); + return math.max(0.0, escape); +} diff --git a/lib/shared/widgets/prism_segmented_control.dart b/lib/shared/widgets/prism_segmented_control.dart index c4f574a4a..51813b81c 100644 --- a/lib/shared/widgets/prism_segmented_control.dart +++ b/lib/shared/widgets/prism_segmented_control.dart @@ -1,8 +1,24 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/theme/prism_shapes.dart'; import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; + +/// Minimum painted height of the track at normal text. Preserved exactly: the +/// outer box is this tall when the labels fit on one line. +const double kPrismSegmentedControlMinHeight = 44.0; + +/// Hairline around the track. The border insets the labels by this much on each +/// side, so the track's painted height is its content height plus twice this. +const double _kTrackBorderWidth = 0.5; + +/// Gap between a segment label and its badge. +const double _kBadgeGap = 6.0; +const double _kBadgeMinSize = 18.0; +const double _kBadgeHorizontalPadding = 6.0; /// A segment within a [PrismSegmentedControl]. class PrismSegment { @@ -96,7 +112,8 @@ class PrismSegmentedControlColors { /// /// Replaces [SegmentedButton] with Prism's warm, glassy design language. /// All segments are single-select. -class PrismSegmentedControl extends StatefulWidget { +class PrismSegmentedControl extends StatefulWidget + implements PrismScaledHeight { const PrismSegmentedControl({ super.key, required this.segments, @@ -108,11 +125,139 @@ class PrismSegmentedControl extends StatefulWidget { final T selected; final ValueChanged onChanged; + /// Painted height of the track at the text scale in [context]. + /// + /// Exactly what the widget renders: labels wrap at the width they really get + /// (two lines are allowed, then they ellipsise), badges keep their own line + /// box, and the track never goes below [kPrismSegmentedControlMinHeight] or + /// below its content plus the hairline border. Pass [availableWidth] when the + /// caller knows the cross-axis space; without it labels are measured as single + /// lines, which is the same result only when they do not wrap. + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + if (segments.isEmpty) return kPrismSegmentedControlMinHeight; + + final theme = Theme.of(context); + final textScaler = MediaQuery.textScalerOf(context); + final textDirection = Directionality.of(context); + final locale = Localizations.maybeLocaleOf(context); + final baseStyle = theme.textTheme.labelLarge ?? const TextStyle(); + // The hairline is painted on top (foregroundDecoration), so it takes no space + // and each segment gets exactly its share of the caller's width. + final slotWidth = availableWidth == null + ? double.infinity + : math.max(0.0, availableWidth) / segments.length; + + var contentHeight = 0.0; + for (final segment in segments) { + final badge = _measureBadge( + context, + theme, + segment, + textScaler, + textDirection, + locale, + ); + final labelMaxWidth = slotWidth.isFinite + ? math.max( + 1.0, + slotWidth - (badge == null ? 0.0 : badge.width + _kBadgeGap), + ) + : double.infinity; + final labelHeight = _measureLabelHeight( + context, + label: segment.label, + style: baseStyle.copyWith( + fontWeight: segment.value == selected + ? FontWeight.w600 + : FontWeight.w500, + ), + textScaler: textScaler, + textDirection: textDirection, + locale: locale, + maxWidth: labelMaxWidth, + ); + contentHeight = math.max( + contentHeight, + badge == null ? labelHeight : math.max(labelHeight, badge.height), + ); + } + + return math.max(kPrismSegmentedControlMinHeight, contentHeight); + } + @override State> createState() => _PrismSegmentedControlState(); } +Size? _measureBadge( + BuildContext context, + ThemeData theme, + PrismSegment segment, + TextScaler textScaler, + TextDirection textDirection, + Locale? locale, +) { + final count = segment.badgeCount ?? 0; + if (count <= 0) return null; + final label = count <= 9 ? '$count' : '9+'; + // The badge is painted at w600 with height 1.0; the prediction has to use the + // same style or its width - and the room it leaves the label - comes out wrong. + // The painted badge is labelSmall at w600 with height 1.0; the prediction has to + // start from the same style or the width it takes - and the room it leaves the + // label - comes out wrong. + final style = prismTextStyleForMeasurement( + context, + (theme.textTheme.labelSmall ?? const TextStyle()).merge( + const TextStyle(fontWeight: FontWeight.w600, height: 1.0), + ), + ); + final painter = TextPainter( + text: TextSpan(text: label, style: style), + textDirection: textDirection, + textScaler: textScaler, + locale: locale, + textHeightBehavior: prismTextHeightBehaviorFor(context), + maxLines: 1, + )..layout(); + final size = Size( + painter.width + _kBadgeHorizontalPadding * 2, + painter.height, + ); + painter.dispose(); + return Size( + math.max(_kBadgeMinSize, size.width), + math.max(_kBadgeMinSize, size.height), + ); +} + +double _measureLabelHeight( + BuildContext context, { + required String label, + required TextStyle style, + required TextScaler textScaler, + required TextDirection textDirection, + required Locale? locale, + required double maxWidth, +}) { + final painter = TextPainter( + text: TextSpan( + text: label, + style: prismTextStyleForMeasurement(context, style), + ), + textDirection: textDirection, + textScaler: textScaler, + locale: locale, + textHeightBehavior: prismTextHeightBehaviorFor(context), + textAlign: TextAlign.center, + maxLines: 2, + )..layout(maxWidth: maxWidth); + final height = painter.height; + painter.dispose(); + return height; +} + class _PrismSegmentedControlState extends State> with SingleTickerProviderStateMixin { late AnimationController _controller; @@ -182,13 +327,25 @@ class _PrismSegmentedControlState extends State> return Semantics( label: context.l10n.segmentedControl, child: Container( - height: 44, + // Sizes to its labels: the border insets them, so the painted height is + // exactly max(44, content + border) - the same value preferredHeightFor + // reports to callers that reserve space for this track. decoration: BoxDecoration( color: controlColors.trackColor, borderRadius: BorderRadius.circular( PrismShapes.of(context).radius(999), ), - border: Border.all(color: controlColors.trackBorderColor, width: 0.5), + ), + // Painted on top so the hairline does not inset the segments: the track's + // full height is tappable, and its painted height stays 44dp at normal text. + foregroundDecoration: BoxDecoration( + borderRadius: BorderRadius.circular( + PrismShapes.of(context).radius(999), + ), + border: Border.all( + color: controlColors.trackBorderColor, + width: _kTrackBorderWidth, + ), ), child: LayoutBuilder( builder: (context, constraints) { @@ -245,43 +402,59 @@ class _PrismSegmentedControlState extends State> selected: widget.segments[i].value == widget.selected, button: true, - child: Center( - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: Text( - widget.segments[i].label, - style: theme.textTheme.labelLarge - ?.copyWith( - color: - widget.segments[i].value == - widget.selected - ? theme.colorScheme.onSurface - : theme - .colorScheme - .onSurfaceVariant, - fontWeight: - widget.segments[i].value == - widget.selected - ? FontWeight.w600 - : FontWeight.w500, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - if ((widget.segments[i].badgeCount ?? 0) > - 0) ...[ - const SizedBox(width: 6), - _SegmentBadge( - count: widget.segments[i].badgeCount!, - semanticLabel: - widget.segments[i].badgeSemanticLabel, - theme: theme, + // The segment itself is the tap target, so it holds + // the track's full minimum height while the label is + // short, and grows when the label does. + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: kPrismSegmentedControlMinHeight, + ), + // heightFactor: 1 makes the segment take its own + // content height even when the parent hands down a + // finite max height (a Scaffold body, a pinned band, a + // sheet column). Without it the Center fills that + // parent and the track grows to the parent's height. + child: Center( + heightFactor: 1, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + widget.segments[i].label, + style: theme.textTheme.labelLarge + ?.copyWith( + color: + widget.segments[i].value == + widget.selected + ? theme.colorScheme.onSurface + : theme + .colorScheme + .onSurfaceVariant, + fontWeight: + widget.segments[i].value == + widget.selected + ? FontWeight.w600 + : FontWeight.w500, + ), + maxLines: 2, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + ), ), + if ((widget.segments[i].badgeCount ?? 0) > + 0) ...[ + const SizedBox(width: 6), + _SegmentBadge( + count: widget.segments[i].badgeCount!, + semanticLabel: widget + .segments[i] + .badgeSemanticLabel, + theme: theme, + ), + ], ], - ], + ), ), ), ), @@ -340,7 +513,6 @@ class _SegmentBadge extends StatelessWidget { final pill = ConstrainedBox( constraints: const BoxConstraints(minWidth: 18, minHeight: 18), child: Container( - height: 18, padding: const EdgeInsets.symmetric(horizontal: 6), alignment: Alignment.center, decoration: BoxDecoration( diff --git a/lib/shared/widgets/prism_sheet.dart b/lib/shared/widgets/prism_sheet.dart index 26692b98a..a28b6d30b 100644 --- a/lib/shared/widgets/prism_sheet.dart +++ b/lib/shared/widgets/prism_sheet.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; @@ -8,6 +9,7 @@ import 'package:prism_plurality/shared/extensions/app_localizations_extension.da import 'package:prism_plurality/shared/utils/modal_insets.dart'; import 'package:prism_plurality/shared/widgets/detail_side_sheet.dart'; import 'package:prism_plurality/shared/widgets/prism_glass_icon_button.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/sheet_presentation.dart'; import 'package:prism_plurality/shared/widgets/unsaved_changes_guard.dart'; @@ -593,12 +595,19 @@ class _SheetChromeState extends State<_SheetChrome> { /// A top bar for full-screen sheets with close button, centered title, and /// an optional trailing widget (typically a [PrismGlassIconButton]). /// -/// Matches [PrismTopBar] sizing: 44pt action slots, titleLarge at 22/w700. +/// Matches [PrismTopBar] sizing: 44pt action slots, titleLarge at 22/w700, and a +/// 66dp minimum. The bar grows with the ambient text scale instead of clamping +/// its title: [preferredHeightFor] reports the height it needs and the bar is laid +/// out at that height, keeping the title at the size the user asked for (one +/// line, ellipsised, full string in semantics). /// -/// When [titleWidget] is provided it replaces the text title in the center -/// area, automatically inset by [PrismTokens.topBarActionSize] on each side. +/// [titleWidget] replaces the text title in the middle slot. It gets the real +/// width between the action slots (no fixed ceiling) and, when it implements +/// [PrismScaledHeight], its height is measured with that same width so the bar +/// contains it instead of clipping it. A widget that cannot report a height keeps +/// sizing the bar by its own content. /// -class PrismSheetTopBar extends StatelessWidget { +class PrismSheetTopBar extends StatelessWidget implements PrismScaledHeight { const PrismSheetTopBar({ super.key, required this.title, @@ -612,55 +621,165 @@ class PrismSheetTopBar extends StatelessWidget { /// Optional trailing widget (e.g. a done/confirm button). final Widget? trailing; - /// When set, replaces the text title. Automatically inset by - /// [PrismTokens.topBarActionSize] on each side so it never overlaps the - /// leading/trailing action buttons. + /// When set, replaces the text title. Laid out between the action slots. final Widget? titleWidget; /// Replaces the default close button. Size to [PrismTokens.topBarActionSize]. final Widget? leading; + /// Space above and below the title once the bar has to grow past + /// [PrismTokens.topBarHeight]. Also absorbs sub-pixel differences between the + /// measured line box and the painted one. + static const double _grownVerticalPadding = 12; + + /// `NavigationToolbar`'s default spacing around the middle slot. + static const double _middleSpacing = 16; + + TextStyle _titleStyle(BuildContext context) { + return Theme.of(context).textTheme.titleLarge?.copyWith( + fontSize: 22, + fontWeight: FontWeight.w700, + ) ?? + const TextStyle(fontSize: 22, fontWeight: FontWeight.w700); + } + + /// Width the middle slot gets between the action slots. + /// + /// Computed from the action-slot geometry (`PrismGlassIconButton` at + /// [PrismTokens.topBarActionSize]) rather than from layout, because the height + /// has to be known before layout. It is the same arithmetic + /// `NavigationToolbar` applies to its middle child, and the middle is also + /// constrained to it, so measurement and layout cannot disagree. + double _middleWidth(BuildContext context, double? availableWidth) { + final width = availableWidth ?? MediaQuery.sizeOf(context).width; + final slots = + (leading == null ? 0.0 : PrismTokens.topBarActionSize) + + (trailing == null ? 0.0 : PrismTokens.topBarActionSize); + final reserved = + PrismTokens.topBarPadding.horizontal + slots + _middleSpacing * 2; + return math.max(0.0, width - reserved); + } + + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + final minimum = math.max( + PrismTokens.topBarHeight, + PrismTokens.topBarActionSize, + ); + final widget = titleWidget; + if (widget == null) { + final style = _titleStyle(context); + final line = prismLineHeight(context, style, text: title); + // Reserve a fallback face's measured ink escape above and below; ordinary + // Latin text escapes by nothing and keeps the 12dp default breathing. + final inkEscape = prismTextInkEscape(context, style, text: title); + return math.max( + minimum, + line + math.max(_grownVerticalPadding, inkEscape * 2 + 2), + ); + } + // Typed pattern: the widget is only known as a [Widget], so an `is` test + // cannot promote it to the interface. + if (widget case final PrismScaledHeight scaled) { + return math.max( + minimum, + scaled.preferredHeightFor( + context, + availableWidth: _middleWidth(context, availableWidth), + ) + + _grownVerticalPadding, + ); + } + // An arbitrary widget sizes the middle slot by itself, so no taller + // prediction is possible; the layout below lets it. + return minimum; + } + + Widget _leading(BuildContext context) { + return leading ?? + PrismGlassIconButton( + icon: AppIcons.close, + size: PrismTokens.topBarActionSize, + onPressed: () => Navigator.of(context).maybePop(), + tooltip: context.l10n.close, + semanticLabel: context.l10n.close, + ); + } + + Widget _slotted(Widget child, double barHeight) { + return SizedBox( + height: barHeight, + child: Center(widthFactor: 1, child: child), + ); + } + @override Widget build(BuildContext context) { - final theme = Theme.of(context); + // Content-driven height, measured against the width the bar is actually + // given (a sheet may be narrower than the window). + return LayoutBuilder( + builder: (context, constraints) => _buildBar( + context, + preferredHeightFor(context, availableWidth: constraints.maxWidth), + constraints.maxWidth, + ), + ); + } + + Widget _buildBar( + BuildContext context, + double barHeight, + double availableWidth, + ) { + final widget = titleWidget; + final measurableWidget = widget is PrismScaledHeight; + + if (widget != null && !measurableWidget) { + // Content-driven: the caller's widget decides the middle slot's height, so + // nothing here may clamp it to a text-derived height. + return ConstrainedBox( + constraints: const BoxConstraints(minHeight: PrismTokens.topBarHeight), + child: Padding( + padding: PrismTokens.topBarPadding, + child: Row( + children: [ + _leading(context), + const SizedBox(width: _middleSpacing), + Expanded( + child: Align(alignment: Alignment.center, child: widget), + ), + const SizedBox(width: _middleSpacing), + if (trailing != null) + trailing! + else + const SizedBox.square(dimension: PrismTokens.topBarActionSize), + ], + ), + ), + ); + } return SizedBox( - height: PrismTokens.topBarHeight, + height: barHeight, child: Padding( padding: PrismTokens.topBarPadding, - child: Stack( - alignment: Alignment.center, - children: [ - if (titleWidget != null) - Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 180), - child: titleWidget, - ), - ) - else - Text( - title, - style: theme.textTheme.titleLarge?.copyWith( - fontSize: 22, - fontWeight: FontWeight.w700, - ), - ), - Align( - alignment: Alignment.centerLeft, - child: - leading ?? - PrismGlassIconButton( - icon: AppIcons.close, - size: PrismTokens.topBarActionSize, - onPressed: () => Navigator.of(context).maybePop(), - tooltip: context.l10n.close, - semanticLabel: context.l10n.close, + child: NavigationToolbar( + leading: _slotted(_leading(context), barHeight), + middle: widget != null + ? ConstrainedBox( + constraints: BoxConstraints( + maxWidth: _middleWidth(context, availableWidth), ), - ), - if (trailing != null) - Align(alignment: Alignment.centerRight, child: trailing!), - ], + child: widget, + ) + : Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: _titleStyle(context), + ), + trailing: trailing == null ? null : _slotted(trailing!, barHeight), ), ), ); diff --git a/lib/shared/widgets/prism_top_bar.dart b/lib/shared/widgets/prism_top_bar.dart index 8ae9019c9..d3b4d1bd6 100644 --- a/lib/shared/widgets/prism_top_bar.dart +++ b/lib/shared/widgets/prism_top_bar.dart @@ -1,3 +1,5 @@ +import 'dart:math' as math; + import 'package:flutter/material.dart'; import 'package:prism_plurality/shared/extensions/app_localizations_extension.dart'; import 'package:prism_plurality/shared/theme/app_icons.dart'; @@ -5,14 +7,35 @@ import 'package:prism_plurality/shared/theme/prism_tokens.dart'; import 'package:prism_plurality/shared/widgets/embedded_pane_marker.dart'; import 'package:prism_plurality/shared/widgets/list_detail_layout.dart'; import 'package:prism_plurality/shared/widgets/modal_side_sheet_marker.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; /// Shared top-bar layout for standard Prism pages. /// -/// The title is always centered on screen (not between leading/trailing) when -/// [centerTitle] is true. Use [actions] for multiple trailing buttons — they -/// are automatically spaced. -class PrismTopBar extends StatelessWidget implements PreferredSizeWidget { +/// The title is centered on screen (not between leading/trailing) when +/// [centerTitle] is true; `NavigationToolbar` measures the real action widths +/// and only moves the title when centering it would run underneath them. Use +/// [actions] for multiple trailing buttons — they are automatically spaced. +/// +/// The bar is [height] tall whenever its content fits there, and grows with the +/// ambient text scale when it does not: the title is always laid out at the size +/// the user asked for (one line, ellipsised, with the full string in its +/// semantics) instead of being shrunk to fit. +/// +/// Two heights exist and they are not interchangeable: +/// * [preferredSize] is a constant minimum ([height], 66dp by default). It is +/// what a `PreferredSizeWidget` getter can report without a `BuildContext`. +/// * [preferredHeightFor] is the height this bar actually needs at the ambient +/// text scale (content height, excluding the safe-area top). +/// +/// A parent that reserves an extent must use the second one: [SliverPinnedTopBar] +/// (and therefore every [PrismPageScaffold] screen) asks it while building, and a +/// fixed slot such as `Scaffold.appBar` needs +/// `prismScaledPreferredSize(context, bar)`. Mounting this widget directly in +/// `Scaffold.appBar` reserves only the minimum and clips at large text — that is +/// the limitation the adapter exists for, not something a getter can fix. +class PrismTopBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { const PrismTopBar({ super.key, required this.title, @@ -37,12 +60,13 @@ class PrismTopBar extends StatelessWidget implements PreferredSizeWidget { /// Single trailing widget. For multiple actions prefer [actions]. final Widget? trailing; - /// Multiple trailing action widgets, automatically spaced 8px apart. + /// Multiple trailing action widgets, automatically spaced. final List? actions; /// Optional override for the title text style. final TextStyle? titleStyle; + /// Minimum bar height. Preserved exactly whenever the content fits here. final double height; final EdgeInsets horizontalPadding; final bool centerTitle; @@ -52,9 +76,81 @@ class PrismTopBar extends StatelessWidget implements PreferredSizeWidget { /// side sheets. final bool showBackButton; + /// Space above and below the title block once the bar has to grow past + /// [height]. It also absorbs sub-pixel differences between the measured line + /// box and the painted one, so the bar never clamps its own title. + static const double _grownVerticalPadding = 12; + @override Size get preferredSize => Size.fromHeight(height); + TextStyle _resolvedTitleStyle(BuildContext context) { + final theme = Theme.of(context); + final isDesktop = + MediaQuery.sizeOf(context).width >= PrismTokens.desktopBreakpoint; + return titleStyle ?? + theme.textTheme.headlineLarge?.copyWith( + fontSize: isDesktop ? 18 : 22, + height: 1, + ) ?? + const TextStyle(); + } + + TextStyle _resolvedSubtitleStyle(BuildContext context) { + final theme = Theme.of(context); + return theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.82), + fontWeight: FontWeight.w500, + fontSize: 11, + height: 1, + ) ?? + const TextStyle(); + } + + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + // Measure the strings this bar will really paint: a title resolved to a + // fallback face (emoji, CJK, Arabic) can have a taller line box than the + // primary face, and reserving less would clip it. + final titleLine = prismLineHeight( + context, + _resolvedTitleStyle(context), + text: title, + ); + final subtitleLine = subtitle == null + ? 0.0 + : 3 + + prismLineHeight( + context, + _resolvedSubtitleStyle(context), + text: subtitle!, + ); + // Width does not enter: the title is a single ellipsised line, so its height + // depends only on the scaler and the style. + // Fallback faces (emoji, CJK, Arabic) can paint outside their line box; the + // bars reserve that measured escape above and below instead of shrinking the + // text or clipping it. Ordinary Latin text escapes by nothing, so the 12dp + // default breathing is what applies then. + final inkEscape = math.max( + prismTextInkEscape(context, _resolvedTitleStyle(context), text: title), + subtitle == null + ? 0.0 + : prismTextInkEscape( + context, + _resolvedSubtitleStyle(context), + text: subtitle!, + ), + ); + final breathing = math.max(_grownVerticalPadding, inkEscape * 2 + 2); + return math.max( + height, + math.max( + PrismTokens.topBarActionSize, + titleLine + subtitleLine + breathing, + ), + ); + } + @override Widget build(BuildContext context) { // Embedded panes close the selection instead of popping a route. @@ -84,63 +180,29 @@ class PrismTopBar extends StatelessWidget implements PreferredSizeWidget { : null); final effectiveTrailing = trailing ?? _buildActions(); - - final titleBlock = _TitleBlock( - title: title, - subtitle: subtitle, - centerTitle: centerTitle, - titleStyle: titleStyle, - ); + final barHeight = preferredHeightFor(context); return SafeArea( bottom: false, child: SizedBox( - height: height, + height: barHeight, child: Padding( padding: horizontalPadding, - child: Align( - alignment: Alignment.center, - child: centerTitle - ? Stack( - alignment: Alignment.center, - children: [ - // Title centered on the full bar width. - titleBlock, - // Leading and trailing positioned at edges. - Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - if (effectiveLeading != null) - effectiveLeading - else - _slot(null), - const Spacer(), - if (effectiveTrailing != null) - effectiveTrailing - else - _slot(null), - ], - ), - ], - ) - : Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - _slot(effectiveLeading), - const SizedBox(width: 12), - Expanded( - child: Align( - alignment: Alignment.centerLeft, - child: titleBlock, - ), - ), - const SizedBox(width: 12), - if (effectiveTrailing != null) - effectiveTrailing - else - _slot(null), - ], - ), + child: NavigationToolbar( + centerMiddle: centerTitle, + leading: effectiveLeading == null + ? null + : _slot(effectiveLeading, barHeight), + middle: _TitleBlock( + title: title, + subtitle: subtitle, + centerTitle: centerTitle, + titleStyle: _resolvedTitleStyle(context), + subtitleStyle: _resolvedSubtitleStyle(context), + ), + trailing: effectiveTrailing == null + ? null + : _slot(effectiveTrailing, barHeight), ), ), ), @@ -161,10 +223,15 @@ class PrismTopBar extends StatelessWidget implements PreferredSizeWidget { ); } - Widget _slot(Widget? child) { - return SizedBox.square( - dimension: PrismTokens.topBarActionSize, - child: child ?? const SizedBox.shrink(), + /// A toolbar slot: as wide as [child], as tall as the bar, child centered. + /// + /// `NavigationToolbar` lays its leading child out with the bar's exact height; + /// the inner `Center` keeps the 44dp action at its real size and vertically + /// centered, which is where it has always been. + Widget _slot(Widget child, double barHeight) { + return SizedBox( + height: barHeight, + child: Center(widthFactor: 1, child: child), ); } } @@ -174,20 +241,19 @@ class _TitleBlock extends StatelessWidget { required this.title, required this.subtitle, required this.centerTitle, - this.titleStyle, + required this.titleStyle, + required this.subtitleStyle, }); final String title; final String? subtitle; final bool centerTitle; - final TextStyle? titleStyle; + final TextStyle titleStyle; + final TextStyle subtitleStyle; @override Widget build(BuildContext context) { - final theme = Theme.of(context); final alignment = centerTitle ? TextAlign.center : TextAlign.left; - final isDesktop = - MediaQuery.sizeOf(context).width >= PrismTokens.desktopBreakpoint; return Column( mainAxisAlignment: MainAxisAlignment.center, @@ -195,20 +261,14 @@ class _TitleBlock extends StatelessWidget { ? CrossAxisAlignment.center : CrossAxisAlignment.start, children: [ - FittedBox( - fit: BoxFit.scaleDown, - child: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: alignment, - style: - titleStyle ?? - theme.textTheme.headlineLarge?.copyWith( - fontSize: isDesktop ? 18 : 22, - height: 1, - ), - ), + // Full size, one line, ellipsised: the paragraph keeps the whole string + // in its semantics, and nothing scales the user's text size down. + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: alignment, + style: titleStyle, ), if (subtitle != null) ...[ const SizedBox(height: 3), @@ -217,12 +277,7 @@ class _TitleBlock extends StatelessWidget { maxLines: 1, overflow: TextOverflow.ellipsis, textAlign: alignment, - style: theme.textTheme.labelMedium?.copyWith( - color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.82), - fontWeight: FontWeight.w500, - fontSize: 11, - height: 1, - ), + style: subtitleStyle, ), ], ], diff --git a/lib/shared/widgets/sliver_pinned_top_bar.dart b/lib/shared/widgets/sliver_pinned_top_bar.dart index c34dcd71b..13b885b74 100644 --- a/lib/shared/widgets/sliver_pinned_top_bar.dart +++ b/lib/shared/widgets/sliver_pinned_top_bar.dart @@ -1,16 +1,42 @@ import 'package:flutter/material.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; + /// A sliver that pins a [PrismTopBar] at the top of a [CustomScrollView], /// with a subtle gradient fade below it (mirroring the bottom nav bar style). /// /// The gradient overlaps the scrolling content rather than pushing it down, /// creating a smooth fade from the bar into the list. -class SliverPinnedTopBar extends StatelessWidget { +/// +/// The pinned extent comes from the bar itself: a [PrismScaledHeight] child is +/// asked for its height at the ambient text scale, measured against the real +/// cross-axis width of this sliver, so a bar that grows for large text grows the +/// band it sits in. Any other [PreferredSizeWidget] keeps its declared +/// `preferredSize` (nothing changes for it). +/// +/// Measurement is cached for the current inputs only — the child widget instance, +/// the cross-axis width, the text scaler, direction, locale, theme and the bold / +/// high-contrast flags — and dropped when the platform font set changes +/// (`PaintingBinding.systemFonts`). `SliverLayoutBuilder` re-runs its builder on +/// every layout (scroll offset is part of [SliverConstraints]), so without this +/// cache a bar would re-shape its text on every scroll frame. +/// +/// Asset faces are registered through `FontLoader` before the first frame and the +/// app never swaps them at runtime; a font *preference* change arrives as a new +/// `ThemeData`, which is already a cache key. +/// +/// [minBodyExtent] is opt-in and defaults to zero, which is exactly the previous +/// behaviour: a plain bar stays pinned. A composite header whose own content can +/// outgrow a short window (keyboard up) passes the body height it needs there; +/// when the viewport cannot give the bar that much room the header is laid out +/// unpinned, so it scrolls away instead of squeezing the body to nothing. +class SliverPinnedTopBar extends StatefulWidget { const SliverPinnedTopBar({ super.key, required this.child, this.gradientHeight = 24.0, this.maxWidth = double.infinity, + this.minBodyExtent = 0.0, }); /// The top bar widget to pin. @@ -23,23 +49,154 @@ class SliverPinnedTopBar extends StatelessWidget { /// on content-primary screens so the bar lines up with the clamped body. final double maxWidth; + /// Body height that must remain visible for this bar to stay pinned. Zero (the + /// default) pins the bar whenever it fits at all, i.e. unchanged behaviour for + /// ordinary bars; a composite header that grows for large text opts in. + final double minBodyExtent; + + @override + State createState() => _SliverPinnedTopBarState(); +} + +class _SliverPinnedTopBarState extends State { + _BarExtentCache? _cache; + + @override + void initState() { + super.initState(); + // The platform's font set can change while the app runs; a measurement taken + // with the old set is no longer trustworthy. + PaintingBinding.instance.systemFonts.addListener(_handleSystemFontsChanged); + } + + @override + void dispose() { + PaintingBinding.instance.systemFonts.removeListener( + _handleSystemFontsChanged, + ); + super.dispose(); + } + + void _handleSystemFontsChanged() { + if (!mounted) return; + setState(() => _cache = null); + } + + /// Height the bar needs at [width], reusing the last measurement only while + /// every input that can change it is unchanged. + double _barHeightFor(BuildContext context, double width) { + final child = widget.child; + // `PrismTopBar` chooses its title size from the *window* width + // (desktopBreakpoint), which is not the same value as this sliver's + // cross-axis width inside a fixed-width pane. Both are keys. + final windowWidth = MediaQuery.sizeOf(context).width; + final scaler = MediaQuery.textScalerOf(context); + // Measurements resolve their style through `DefaultTextStyle` (and honour its + // height behaviour), so an inherited style change is a cache input too. + final defaultTextStyle = DefaultTextStyle.of(context); + final baseStyle = defaultTextStyle.style; + final textHeightBehavior = defaultTextStyle.textHeightBehavior; + final direction = Directionality.of(context); + final theme = Theme.of(context); + final locale = Localizations.maybeLocaleOf(context); + final boldText = MediaQuery.boldTextOf(context); + final highContrast = MediaQuery.highContrastOf(context); + + final cached = _cache; + if (cached != null && + identical(cached.child, child) && + cached.width == width && + cached.windowWidth == windowWidth && + cached.scaler == scaler && + cached.direction == direction && + identical(cached.theme, theme) && + cached.locale == locale && + cached.boldText == boldText && + cached.highContrast == highContrast && + cached.baseStyle == baseStyle && + cached.textHeightBehavior == textHeightBehavior) { + return cached.height; + } + + final height = prismScaledHeightOf(context, child, availableWidth: width); + _cache = _BarExtentCache( + child: child, + width: width, + windowWidth: windowWidth, + scaler: scaler, + direction: direction, + theme: theme, + locale: locale, + boldText: boldText, + highContrast: highContrast, + baseStyle: baseStyle, + textHeightBehavior: textHeightBehavior, + height: height, + ); + return height; + } + @override Widget build(BuildContext context) { final topPadding = MediaQuery.of(context).viewPadding.top; - final barHeight = child.preferredSize.height + topPadding; - - return SliverPersistentHeader( - pinned: true, - delegate: _PinnedTopBarDelegate( - child: child, - barHeight: barHeight, - gradientHeight: gradientHeight, - maxWidth: maxWidth, - ), + + return SliverLayoutBuilder( + builder: (context, constraints) { + final barHeight = + _barHeightFor(context, constraints.crossAxisExtent) + topPadding; + final pinned = + barHeight + widget.minBodyExtent <= + constraints.viewportMainAxisExtent; + + return SliverPersistentHeader( + pinned: pinned, + delegate: _PinnedTopBarDelegate( + child: widget.child, + barHeight: barHeight, + gradientHeight: widget.gradientHeight, + maxWidth: widget.maxWidth, + ), + ); + }, ); } } +/// One resolved extent, valid only for the inputs recorded with it. +class _BarExtentCache { + const _BarExtentCache({ + required this.child, + required this.width, + required this.windowWidth, + required this.scaler, + required this.direction, + required this.theme, + required this.locale, + required this.boldText, + required this.highContrast, + required this.baseStyle, + required this.textHeightBehavior, + required this.height, + }); + + final Widget child; + + /// Cross-axis extent of this sliver. + final double width; + + /// Window width, the input `PrismTopBar` uses to pick 22pt vs 18pt. + final double windowWidth; + final TextScaler scaler; + final TextDirection direction; + final ThemeData theme; + final Locale? locale; + final bool boldText; + final bool highContrast; + final TextStyle baseStyle; + final TextHeightBehavior? textHeightBehavior; + final double height; +} + class _PinnedTopBarDelegate extends SliverPersistentHeaderDelegate { const _PinnedTopBarDelegate({ required this.child, diff --git a/pubspec.yaml b/pubspec.yaml index 0341be982..faca48f85 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: prism_plurality description: "Prism — plural system management app" publish_to: 'none' -version: 0.16.0+16004 +version: 0.17.0+17001 environment: sdk: ^3.11.1 diff --git a/test/features/chat/emoji/emoji_code_context_grammar_test.dart b/test/features/chat/emoji/emoji_code_context_grammar_test.dart new file mode 100644 index 000000000..7383bbb5c --- /dev/null +++ b/test/features/chat/emoji/emoji_code_context_grammar_test.dart @@ -0,0 +1,137 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:markdown/markdown.dart' as md; + +import 'package:prism_plurality/features/chat/emoji/emoji_name_completion.dart'; +import 'package:prism_plurality/features/chat/utils/chat_markdown_syntax.dart'; + +/// One synthetic draft from the renderer-differential corpus. +/// +/// Each case pins a block or inline construct where the composer's +/// `isInsideCodeContext` predicate and the chat renderer's own Markdown grammar +/// could disagree. The drafts are synthetic Markdown only: no user data, no +/// member or message content, and nothing is read from disk. +class _GrammarCase { + const _GrammarCase( + this.id, + this.draft, + this.colonIndex, + this.caretOffset, + this.rendererIsCode, + ); + + /// Stable case id from the corpus (blockquote, list, multiline, tab cases). + final String id; + + /// The complete synthetic draft. + final String draft; + + /// Offset of the `:` that introduces the `:sun` token. + final int colonIndex; + + /// Caret offset the composer sees when completion would be offered. + final int caretOffset; + + /// Whether the chat renderer places this token inside a code span or block. + final bool rendererIsCode; +} + +const List<_GrammarCase> _cases = <_GrammarCase>[ + // Blockquote containers: the `>` marker is stripped before the child lines + // are parsed, so a fence or an indented block inside a quote is still code. + _GrammarCase('BQ1', '> ```\n> :sun\n> ```', 8, 12, true), + _GrammarCase('BQ2', '> :sun', 6, 10, true), + // Control: an indented line lazily continues the paragraph, so it is text. + _GrammarCase('BQ3', '> hi\n> :sun', 11, 15, false), + // List containers: a four-space body under a list item is a paragraph, not + // code, while a fence nested in the item is code. + _GrammarCase('L1', '- item\n\n :sun', 12, 16, false), + _GrammarCase('L5', ' - item\n ```\n :sun', 25, 29, true), + // Multiline inline spans: the span state carries across the line break. + _GrammarCase('ML1', '`code\n:sun`', 6, 10, true), + _GrammarCase('ML2', 'a `code\nmore` :sun', 14, 18, false), + // Tab-indented blocks: a tab is an indent unit at container start and after + // a container marker, but not a code block when continuing a paragraph. + _GrammarCase('TB1', '\t:sun', 1, 5, true), + _GrammarCase('TB2', '\tcode\n\t:sun', 7, 11, true), + _GrammarCase('TB3', 'hi\n\t:sun', 4, 8, false), +]; + +/// Inserted at the token's colon so the parsed tree can be searched for it. +const String _marker = 'PrismGrammarProbeMarker'; + +/// Whether the chat renderer parses the token at [offset] as code. +/// +/// This is the reference oracle, not the product predicate: it parses the draft +/// with the same extension set the message bubble uses and looks for the marker +/// inside a `code` or `pre` element. +bool _rendererTreatsAsCode(String draft, int offset) { + expect( + draft.contains(_marker), + isFalse, + reason: 'The synthetic marker must not already occur in the draft.', + ); + final marked = draft.replaceRange(offset, offset, _marker); + final nodes = md.Document( + extensionSet: chatExtensionSet, + ).parseLines(marked.split('\n')); + expect( + nodes.any((node) => node.textContent.contains(_marker)), + isTrue, + reason: + 'The renderer AST must retain the marker, or this reference ' + 'answers a different question than the one being asked.', + ); + + bool insideCode(md.Node node) { + if (node is! md.Element) return false; + if ((node.tag == 'code' || node.tag == 'pre') && + node.textContent.contains(_marker)) { + return true; + } + return (node.children ?? const []).any(insideCode); + } + + return nodes.any(insideCode); +} + +void main() { + group('code-context grammar differential', () { + for (final grammarCase in _cases) { + test( + '${grammarCase.id}: composer suppression matches the chat renderer', + () { + final reference = _rendererTreatsAsCode( + grammarCase.draft, + grammarCase.colonIndex, + ); + expect( + reference, + grammarCase.rendererIsCode, + reason: + '${grammarCase.id}: the recorded corpus expectation must ' + 'still match the pinned Markdown grammar. If this fails the ' + 'grammar changed, not the composer.', + ); + expect( + isInsideCodeContext(grammarCase.draft, grammarCase.colonIndex), + reference, + reason: + '${grammarCase.id}: the composer predicate must agree with ' + 'the renderer for the same draft instead of approximating it.', + ); + expect( + detectEmojiCompletionTriggerAt( + grammarCase.draft, + grammarCase.caretOffset, + ) != + null, + !reference, + reason: + '${grammarCase.id}: completion is offered only outside a ' + 'code span or block.', + ); + }, + ); + } + }); +} diff --git a/test/features/chat/emoji/emoji_name_completion_test.dart b/test/features/chat/emoji/emoji_name_completion_test.dart new file mode 100644 index 000000000..64e61c333 --- /dev/null +++ b/test/features/chat/emoji/emoji_name_completion_test.dart @@ -0,0 +1,631 @@ +import 'dart:convert'; + +import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:markdown/markdown.dart' as md; + +import 'package:prism_plurality/features/chat/emoji/emoji_name_completion.dart'; +import 'package:prism_plurality/features/chat/utils/chat_markdown_syntax.dart'; + +/// Flatten a Markdown parse into tags, text and attributes so two parses can be +/// compared without depending on object identity. +String _flattenParse(String text) { + final document = md.Document( + extensionSet: chatExtensionSet, + encodeHtml: false, + ); + final nodes = document.parseLines(const LineSplitter().convert(text)); + final buffer = StringBuffer(); + + void visit(md.Node node) { + if (node is md.Text) { + buffer.write('T(${node.text})'); + return; + } + if (node is! md.Element) return; + final keys = node.attributes.keys.toList()..sort(); + buffer.write('E(${node.tag}'); + for (final key in keys) { + buffer.write(',$key=${node.attributes[key]}'); + } + buffer.write(')['); + for (final child in node.children ?? const []) { + visit(child); + } + buffer.write(']'); + } + + for (final node in nodes) { + visit(node); + } + return buffer.toString(); +} + +/// The single analysis marker inside a probe string, if any. +String _markerIn(String probe) { + for (var i = 0; i < probe.length; i++) { + final unit = probe.codeUnitAt(i); + if (unit >= 0xFDD0 && unit <= 0xFDEF) return probe[i]; + } + return ''; +} + +void main() { + EmojiCompletionTrigger? detect(String text, int caret) => + detectEmojiCompletionTriggerAt(text, caret); + + group('detectEmojiCompletionTrigger', () { + test('finds a token at the start of the draft', () { + final trigger = detect(':sun', 4); + + expect(trigger, isNotNull); + expect(trigger!.start, 0); + expect(trigger.end, 4); + expect(trigger.prefix, 'sun'); + }); + + test('finds a token later in the draft and lowercases the prefix', () { + final trigger = detect('hello :Sunflower', 16); + + expect(trigger, isNotNull); + expect(trigger!.start, 6); + expect(trigger.end, 16); + expect(trigger.prefix, 'sunflower'); + }); + + test('accepts a token after a newline and after an opening delimiter', () { + expect(detect('hi\n:sun', 7)?.start, 3); + expect(detect('(:sun', 5)?.start, 1); + expect(detect('":sun', 5)?.start, 1); + }); + + test('accepts underscores, digits, plus and hyphen in the prefix', () { + expect(detect(':grinning_face', 14)?.prefix, 'grinning_face'); + expect(detect(':upside-down', 12)?.prefix, 'upside-down'); + expect(detect(':1st_place', 10)?.prefix, '1st_place'); + }); + + test('a bare colon does not open', () { + expect(detect(':', 1), isNull); + expect(detect('note:', 5), isNull); + }); + + test('a space in the token body does not open', () { + expect(detect(': sun', 5), isNull); + expect(detect(':sun flower', 11), isNull); + }); + + test('does not trigger on URL schemes', () { + const url = 'see https://example.com/sun'; + expect(detect(url, url.length), isNull); + // A colon-triggered token after the URL still works. + expect(detect('$url :sun', url.length + 5)?.start, url.length + 1); + }); + + test('does not trigger on clock times', () { + expect(detect('meet at 12:30', 13), isNull); + expect(detect('10:30', 5), isNull); + }); + + test('does not trigger on a colon after a letter or another colon', () { + expect(detect('a:sun', 5), isNull); + expect(detect('::sun', 5), isNull); + }); + + test('does not trigger inside an inline code span', () { + expect(detect('`:sun', 5), isNull); + expect(detect('x `:sun`', 7), isNull); + expect(detect('x ``:sun``', 8), isNull); + }); + + test('does not trigger inside a fenced code block', () { + const block = '```\n:sun'; + expect(detect(block, block.length), isNull); + const dartBlock = '```dart\ncode\n:sun'; + expect(detect(dartBlock, dartBlock.length), isNull); + }); + + test('triggers again after a fenced code block closes', () { + final trigger = detect('```\nx\n```\n:sun', 14); + + expect(trigger, isNotNull); + expect(trigger!.prefix, 'sun'); + }); + + test('code spans and fences only look at the draft, not other text', () { + // A closed span earlier in the line does not block a later token. + final trigger = detect('use `code` then :sun', 20); + + expect(trigger, isNotNull); + expect(trigger!.prefix, 'sun'); + }); + + test('does not trigger when the caret is inside the token', () { + expect(detect('a :sun b', 5), isNull); + expect(detect(':sun', 2), isNull); + }); + + test('does not trigger with a non-collapsed selection', () { + const selection = TextSelection(baseOffset: 0, extentOffset: 4); + + expect(detectEmojiCompletionTrigger(':sun', selection), isNull); + + const collapsed = TextSelection.collapsed(offset: 4); + expect(detectEmojiCompletionTrigger(':sun', collapsed), isNotNull); + }); + + test('does not trigger for an over-long token', () { + final longToken = ':${'a' * (emojiCompletionMaxPrefixLength + 1)}'; + + expect(detect(longToken, longToken.length), isNull); + + final atLimit = ':${'a' * emojiCompletionMaxPrefixLength}'; + expect(detect(atLimit, atLimit.length), isNotNull); + }); + + test('does not split a grapheme cluster at the caret', () { + // Caret sits directly before the emoji variation selector. + expect(detect(':sun\uFE0F', 4), isNull); + // Caret sits directly before a combining mark. + expect(detect(':sun\u0301', 4), isNull); + // Caret sits inside a ZWJ sequence. + expect(detect(':sun\u200D\u{1F525}', 4), isNull); + }); + + test( + 'insertion point after an unrelated emoji is not part of a cluster', + () { + // `sun` ends the token and the next code point starts a new cluster. + final trigger = detect(':sun😊', 4); + + expect(trigger, isNotNull); + expect(trigger!.end, 4); + }, + ); + + test('equality is value based for the composer diff check', () { + expect(detect(':sun', 4), detect(':sun', 4)); + expect(detect(':sun', 4), isNot(detect('hi :sun', 7))); + expect(detect(':sun', 4)!.hashCode, detect(':sun', 4)!.hashCode); + }); + }); + + group('isInsideCodeContext', () { + test('reports code spans and fences around an offset', () { + expect(isInsideCodeContext('`:sun', 1), isTrue); + expect(isInsideCodeContext('```\n:sun', 4), isTrue); + expect(isInsideCodeContext('plain :sun', 6), isFalse); + }); + }); + + group('searchEmojiNames', () { + test('finds an exact annotation from the shipped catalog', () { + final results = searchEmojiNames('sunflower'); + + expect(results, isNotEmpty); + expect(results.first.emoji, '🌻'); + expect(results.first.keywords.first, 'sunflower'); + }); + + test('finds keywords and ranks the exact keyword first', () { + final results = searchEmojiNames('rocket'); + + expect(results.first.emoji, '🚀'); + expect(results.length, lessThanOrEqualTo(emojiCompletionMaxResults)); + }); + + test('matches hyphenated annotations', () { + expect(searchEmojiNames('upside-down').first.emoji, '🙃'); + }); + + test('is case insensitive and trims the query', () { + final lower = searchEmojiNames('sunflower'); + final upper = searchEmojiNames(' SUNFLOWER '); + + expect( + upper.map((emoji) => emoji.emoji).toList(), + lower.map((emoji) => emoji.emoji).toList(), + ); + }); + + test('is bounded even for a broad prefix', () { + final results = searchEmojiNames('sun'); + + expect(results.length, emojiCompletionMaxResults); + expect(results.first.emoji, '☀️'); + expect(searchEmojiNames('sun', limit: 3).length, 3); + }); + + test('returns nothing for empty or unmatched prefixes', () { + expect(searchEmojiNames(''), isEmpty); + expect(searchEmojiNames(' '), isEmpty); + expect(searchEmojiNames('zzzznotanemoji'), isEmpty); + }); + + test('is deterministic across calls', () { + final first = searchEmojiNames('heart').map((e) => e.emoji).toList(); + final second = searchEmojiNames('heart').map((e) => e.emoji).toList(); + + expect(second, first); + }); + + test('ranks annotation and keyword matches in a documented order', () { + final index = EmojiNameIndex.fromCategories(const [ + CategoryEmoji(Category.SMILEYS, [ + Emoji('🥇', 'alpha thing | alpha | first'), + Emoji('🥈', 'beta alpha | beta | second'), + Emoji('🥉', 'gamma | contains alpha inside'), + ]), + ]); + + expect(index.search('alpha thing').first.emoji, '🥇'); + expect(index.search('alpha').first.emoji, '🥇'); + expect(index.search('beta').first.emoji, '🥈'); + expect(index.search('beta').length, 1); + expect(index.search('alpha', limit: 1).length, 1); + expect(index.search('alpha').length, 3); + }); + + test('drops duplicate glyphs from a catalog', () { + final index = EmojiNameIndex.fromCategories(const [ + CategoryEmoji(Category.SMILEYS, [Emoji('🌻', 'sunflower | flower')]), + CategoryEmoji(Category.ANIMALS, [ + Emoji('🌻', 'sunflower duplicate | flower'), + ]), + ]); + + expect(index.search('sunflower').length, 1); + }); + }); + + // These pin the completion trigger to what the chat renderer actually treats + // as code, so issue #20's "do not trigger in code" is measured against the + // renderer rather than against a hand-written fence rule. + // + // Renderer boundary, read from the pinned packages: + // - markdown 7.3.1 `FencedCodeBlockSyntax` (`codeFencePattern` in + // `lib/src/patterns.dart`): a fence is a run of 3+ backticks or 3+ tildes + // indented at most 3 spaces. Its `parseChildLines` only closes on a line + // whose marker `startsWith(openingMarker)` and that has no info string, so + // a 3-backtick line cannot close a 4-backtick fence. + // - markdown 7.3.1 `CodeBlockSyntax` (`indentPattern` = 4 spaces or a tab): + // a 4+ space indented line at block start is an indented code block, and a + // fence indented 4+ spaces never matches `codeFencePattern`, so it is not a + // fence. + // - flutter_markdown_plus 1.0.7 builds `md.Document(...)` without + // `withDefaultBlockSyntaxes: false`, so those default syntaxes stay enabled + // next to `chatExtensionSet` (`lib/features/chat/utils/chat_markdown_syntax.dart`). + group('code fences follow the renderer boundary', () { + test('a tilde fence opens a code block', () { + const draft = '~~~\n:sun\n~~~'; + + // Caret at the end of `:sun`, inside the tilde-fenced block. + expect(detect(draft, 8), isNull); + }); + + test('a token after a closed tilde fence completes normally', () { + const draft = '~~~\nx\n~~~\n:sun'; + + expect(detect(draft, draft.length), isNotNull); + }); + + test('a 3-backtick line inside a 4-backtick fence does not close it', () { + // The opening marker is four backticks, so a three-backtick line is + // content and the block is still open at `:sun` — nothing closes it here. + const draft = '````\n```\n:sun'; + + expect(detect(draft, draft.length), isNull); + }); + + test('a matching 4-backtick fence closes and reopens completion', () { + const inside = '````\n:sun\n````'; + expect(detect(inside, 9), isNull); + + const afterClose = '````\nx\n````\n:sun'; + expect(detect(afterClose, afterClose.length), isNotNull); + }); + + test('a fence indented three spaces still opens a code block', () { + const draft = ' ```\n:sun'; + + expect(detect(draft, draft.length), isNull); + }); + + test('a fence indented four spaces is not a fence', () { + // Four spaces then a fence line is an indented code block, so the + // unindented `:sun` after it starts a paragraph and completion opens. + const draft = ' ```\n:sun'; + + expect(detect(draft, draft.length), isNotNull); + }); + + test('a four-space indented code block suppresses completion', () { + // Indented code is code: `:sun` inside it must not open a popup, even + // though there is no fence character on the line. + const draft = ' :sun'; + + expect(detect(draft, draft.length), isNull); + }); + + test('indented code continues on a following indented line', () { + const draft = ' a\n :sun'; + + expect(detect(draft, draft.length), isNull); + }); + + test('an indented line after a paragraph is not indented code', () { + // CommonMark lazy continuation: the indented line continues the + // paragraph, so `:sun` is text and completion opens. + const draft = 'hi\n :sun'; + + expect(detect(draft, draft.length), isNotNull); + }); + + test('a backtick fence with a backtick in its info is not a fence', () { + // The renderer's backtick info string is `[^`]*`, so this line is text. + const draft = '```x`y\n:sun'; + + expect(detect(draft, draft.length), isNotNull); + }); + }); + + group('result limit contract', () { + /// Three `alpha` matches, ranked 🥇 (prefix) then 🥉/🥈 (substring). + EmojiNameIndex alphaIndex() => EmojiNameIndex.fromCategories(const [ + CategoryEmoji(Category.SMILEYS, [ + Emoji('🥇', 'alpha thing | alpha | first'), + Emoji('🥈', 'beta alpha | beta | second'), + Emoji('🥉', 'gamma | contains alpha inside'), + ]), + ]); + + test('a smaller limit after a larger one recomputes', () { + final index = alphaIndex(); + + expect(index.search('alpha').length, 3); + expect(index.search('alpha', limit: 1).length, 1); + expect(index.search('alpha', limit: 2).length, 2); + expect(index.search('alpha').length, 3); + }); + + test('a larger limit after a smaller one recomputes', () { + final index = alphaIndex(); + + expect(index.search('alpha', limit: 1).length, 1); + expect(index.search('alpha').length, 3); + }); + + test('the real catalog also recomputes when the limit changes', () { + expect(searchEmojiNames('sun').length, emojiCompletionMaxResults); + expect(searchEmojiNames('sun', limit: 3).length, 3); + expect(searchEmojiNames('sun').length, emojiCompletionMaxResults); + }); + + test( + 'a non-positive limit returns nothing and leaves the cache intact', + () { + expect(searchEmojiNames('sun').length, emojiCompletionMaxResults); + + expect(searchEmojiNames('sun', limit: 0), isEmpty); + expect(searchEmojiNames('sun', limit: -5), isEmpty); + + // The previous entry is still valid for the same request. + expect(searchEmojiNames('sun').length, emojiCompletionMaxResults); + }, + ); + + test('a limit above the cap is clamped to the popup maximum', () { + final capped = searchEmojiNames('sun', limit: 1000); + + expect(capped.length, emojiCompletionMaxResults); + expect( + capped.map((emoji) => emoji.emoji).toList(), + searchEmojiNames('sun').map((emoji) => emoji.emoji).toList(), + ); + }); + }); + + // Measured against `md.Document(extensionSet: chatExtensionSet)` by the parent + // probe (verification/emoji-corpus-probe). These expectations are the + // renderer's; the checker now borrows that grammar instead of guessing. + group('renderer corpus (measured)', () { + final cases = <({String id, String draft, bool isCode})>[ + ( + id: 'BQ1 fence inside a blockquote', + draft: '> ```\n> :sun\n> ```', + isCode: true, + ), + ( + id: 'BQ2 indented code in a blockquote', + draft: '> :sun', + isCode: true, + ), + ( + id: 'BQ3 lazy continuation in a blockquote', + draft: '> hi\n> :sun', + isCode: false, + ), + ( + id: 'L1 four-space continuation in a list item', + draft: '- item\n\n :sun', + isCode: false, + ), + ( + id: 'L5 fence inside an indented list item', + draft: ' - item\n ```\n :sun', + isCode: true, + ), + ( + id: 'ML1 span closing after the caret', + draft: '`code\n:sun`', + isCode: true, + ), + ( + id: 'ML2 span closed before the token', + draft: 'a `code\nmore` :sun', + isCode: false, + ), + (id: 'TB1 tab-indented code', draft: '\t:sun', isCode: true), + ( + id: 'TB2 tab-indented code continuation', + draft: '\tcode\n\t:sun', + isCode: true, + ), + ( + id: 'TB3 tab line after a paragraph', + draft: 'hi\n\t:sun', + isCode: false, + ), + ]; + + for (final testCase in cases) { + test('${testCase.id} is ${testCase.isCode ? 'code' : 'not code'}', () { + final colon = testCase.draft.indexOf(':'); + + expect( + isInsideCodeContext(testCase.draft, colon), + testCase.isCode, + reason: testCase.draft, + ); + }); + } + + test('the analysis marker does not change the parsed tree', () { + for (final testCase in cases) { + final colon = testCase.draft.indexOf(':'); + final probe = emojiCodeContextProbe(testCase.draft, colon); + final marker = _markerIn(probe); + + expect(probe, isNot(testCase.draft), reason: testCase.id); + expect(marker, isNotEmpty, reason: testCase.id); + expect( + _flattenParse(probe).replaceAll(marker, ':'), + _flattenParse(escapeLeadingHeadings(testCase.draft)), + reason: testCase.id, + ); + } + }); + }); + + group('analysis marker safety', () { + test('a noncharacter already in the draft is skipped', () { + // `_markerIn` would find the source's own U+FDD0 first, so assert the + // substituted code unit at the colon instead: the next candidate is used + // and the source noncharacter survives untouched. + const draft = '\uFDD0 :sun'; + final probe = emojiCodeContextProbe(draft, 2); + + expect(probe.codeUnitAt(2), 0xFDD1); + expect(probe.codeUnitAt(0), 0xFDD0); + // No code starter, so the cheap no-code path answers here. + expect(isInsideCodeContext(draft, 2), isFalse); + }); + + test('an existing noncharacter is skipped inside the parsed path too', () { + // A closed span elsewhere keeps this draft on the parsing path while the + // source still contains U+FDD0. + const draft = '\uFDD0 `x` :sun'; + final colon = draft.lastIndexOf(':'); + final probe = emojiCodeContextProbe(draft, colon); + + expect(probe.codeUnitAt(colon), 0xFDD1); + expect(probe.codeUnitAt(0), 0xFDD0); + expect(isInsideCodeContext(draft, colon), isFalse); + }); + + test('using up all 32 candidates fails closed', () { + final buffer = StringBuffer(); + for (var i = 0; i < 0x20; i++) { + buffer.write(String.fromCharCode(0xFDD0 + i)); + } + // A backtick keeps the draft in the "could contain code" path. + final draft = '`$buffer :sun'; + + expect(isInsideCodeContext(draft, draft.lastIndexOf(':')), isTrue); + }); + + test('a marker lost to a link title fails closed', () { + // A closed span earlier keeps the draft on the parsing path; the marker is + // then consumed by the link title, which is an attribute, not text. + const parsed = '`x` [y](/u ":sun")'; + expect(isInsideCodeContext(parsed, parsed.lastIndexOf(':')), isTrue); + + // Without any code starter the cheap bypass answers instead, and the + // draft is ordinary text. + const plain = '[x](/u ":sun")'; + expect(isInsideCodeContext(plain, plain.indexOf(':')), isFalse); + }); + + test('a marker lost to a fence info string fails closed', () { + const draft = '``` :sun'; + + expect(isInsideCodeContext(draft, 4), isTrue); + }); + + test('an offset that is not a colon fails closed', () { + // The checker only marks validated token colons; substituting any other + // character could change the structure the probe relies on. + expect(isInsideCodeContext('a:b', 0), isTrue); + expect(isInsideCodeContext('abc', 1), isTrue); + }); + }); + + group('unfinished span guard', () { + test('an unclosed span on the caret line suppresses', () { + expect(isInsideCodeContext('`:sun', 1), isTrue); + expect(isInsideCodeContext('x `:sun', 3), isTrue); + }); + + test('an escaped backtick does not suppress', () { + // Directly after the tick the colon is not a valid token colon (a backtick + // is not a trigger-preceding character), so it is text either way. + const adjacent = 'x \\`:sun'; + expect(isInsideCodeContext(adjacent, adjacent.indexOf(':')), isFalse); + expect(detect(adjacent, adjacent.length), isNull); + + // Spaced out the token is valid and completes: the escaped tick is text, + // not an open code span. + const spaced = 'x \\` :sun'; + expect(isInsideCodeContext(spaced, spaced.indexOf(':')), isFalse); + expect(detect(spaced, spaced.length), isNotNull); + }); + + test('a span after an earlier closed fence still suppresses', () { + const draft = '```\nx\n```\n`:sun'; + + expect(isInsideCodeContext(draft, draft.indexOf(':')), isTrue); + }); + + test('stray runs on an earlier line do not suppress', () { + // The control from the fence work: this line is a paragraph, so the + // opener on line 1 must not make the token "code". + const draft = '```x`y\n:sun'; + + expect(isInsideCodeContext(draft, draft.indexOf(':')), isFalse); + }); + }); + + group('renderer budget', () { + test('a long plain draft still completes without a parse', () { + final draft = '${'a' * 3000} :sun'; + + expect(isInsideCodeContext(draft, draft.indexOf(':')), isFalse); + expect(detect(draft, draft.length), isNotNull); + }); + + test('an over-budget draft that could contain code hides suggestions', () { + final draft = '`x\n${'a' * 3000} :sun'; + + expect(isInsideCodeContext(draft, draft.indexOf(':')), isTrue); + }); + + test('exactly at the budget the draft is still parsed', () { + final padding = 'a' * (chatMarkdownParseLimit - ' :sun'.length); + final draft = '$padding :sun'; + + expect(draft.length, chatMarkdownParseLimit); + expect(isInsideCodeContext(draft, draft.length - 4), isFalse); + }); + }); +} diff --git a/test/features/chat/widgets/emoji_name_completion_overlay_test.dart b/test/features/chat/widgets/emoji_name_completion_overlay_test.dart new file mode 100644 index 000000000..d8a7546cc --- /dev/null +++ b/test/features/chat/widgets/emoji_name_completion_overlay_test.dart @@ -0,0 +1,473 @@ +import 'package:emoji_picker_flutter/emoji_picker_flutter.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/chat/widgets/emoji_name_completion_overlay.dart'; + +/// Physical counterpart of a logical key used in these tests. +/// +/// `KeyDownEvent`/`KeyUpEvent` require a real [PhysicalKeyboardKey] and the SDK +/// has no `PhysicalKeyboardKey.none`, so every key a test synthesises is mapped +/// to its actual physical key. An unmapped key is a test bug and throws instead +/// of silently standing in a placeholder. +PhysicalKeyboardKey _physicalKeyFor(LogicalKeyboardKey key) { + return switch (key) { + LogicalKeyboardKey.arrowDown => PhysicalKeyboardKey.arrowDown, + LogicalKeyboardKey.arrowUp => PhysicalKeyboardKey.arrowUp, + LogicalKeyboardKey.enter => PhysicalKeyboardKey.enter, + LogicalKeyboardKey.tab => PhysicalKeyboardKey.tab, + LogicalKeyboardKey.escape => PhysicalKeyboardKey.escape, + LogicalKeyboardKey.keyA => PhysicalKeyboardKey.keyA, + _ => throw ArgumentError.value( + key, + 'key', + 'No physical key mapped for this logical key in the completion tests', + ), + }; +} + +/// Key events also need a timestamp; the overlay reads the logical key and the +/// event type. +KeyDownEvent _keyDown(LogicalKeyboardKey key) => KeyDownEvent( + physicalKey: _physicalKeyFor(key), + logicalKey: key, + timeStamp: Duration.zero, +); + +KeyUpEvent _keyUp(LogicalKeyboardKey key) => KeyUpEvent( + physicalKey: _physicalKeyFor(key), + logicalKey: key, + timeStamp: Duration.zero, +); + +const _matches = [ + Emoji('🌻', 'sunflower | flower'), + Emoji('🌞', 'sun with face | sun'), + Emoji('☀️', 'sun'), +]; + +void main() { + Widget buildSubject({ + List emojis = _matches, + ValueChanged? onSelect, + double availableWidth = 320, + double availableHeight = 240, + double textScale = 1, + }) { + return MaterialApp( + home: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: EmojiNameCompletionOverlay( + matches: emojis, + onSelect: onSelect ?? (emoji) {}, + availableWidth: availableWidth, + availableHeight: availableHeight, + ), + ), + ), + ), + ), + ); + } + + Finder rowText(String label) => find.descendant( + of: find.byKey(EmojiNameCompletionOverlay.surfaceKey), + matching: find.text(label), + ); + + testWidgets('renders one glyph and annotation row per match', (tester) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsOneWidget); + expect(rowText('sunflower'), findsOneWidget); + expect(rowText('sun with face'), findsOneWidget); + expect(rowText('sun'), findsOneWidget); + expect(find.text('🌻'), findsOneWidget); + expect(find.text('☀️'), findsOneWidget); + }); + + testWidgets('empty matches render nothing at all', (tester) async { + await tester.pumpWidget(buildSubject(emojis: const [])); + await tester.pumpAndSettle(); + + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsNothing); + }); + + testWidgets('no room above the field renders nothing', (tester) async { + await tester.pumpWidget(buildSubject(availableHeight: 0)); + await tester.pumpAndSettle(); + + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsNothing); + }); + + testWidgets('a popup too narrow to read is not shown', (tester) async { + await tester.pumpWidget(buildSubject(availableWidth: 100)); + await tester.pumpAndSettle(); + + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsNothing); + }); + + testWidgets('rows carry glyph and annotation as their accessible name', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + expect(find.bySemanticsLabel('🌻 sunflower'), findsOneWidget); + expect(find.bySemanticsLabel('☀️ sun'), findsOneWidget); + final data = tester + .getSemantics(find.bySemanticsLabel('🌻 sunflower')) + .getSemanticsData(); + expect(data.label, '🌻 sunflower'); + expect(data.hasAction(SemanticsAction.tap), isTrue); + semantics.dispose(); + }); + + testWidgets('tapping a row selects that emoji', (tester) async { + Emoji? selected; + await tester.pumpWidget( + buildSubject(onSelect: (emoji) => selected = emoji), + ); + await tester.pumpAndSettle(); + + await tester.tap(rowText('sun with face')); + await tester.pumpAndSettle(); + + expect(selected?.emoji, '🌞'); + }); + + testWidgets('rows are at least a 44 logical pixel touch target', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + final row = find + .ancestor( + of: rowText('sunflower'), + matching: find.byType(GestureDetector), + ) + .first; + expect(tester.getSize(row).height, greaterThanOrEqualTo(44)); + expect(tester.getSize(row).width, greaterThanOrEqualTo(100)); + }); + + testWidgets('keyboard down and enter select the second match', ( + tester, + ) async { + Emoji? selected; + await tester.pumpWidget( + buildSubject(onSelect: (emoji) => selected = emoji), + ); + await tester.pumpAndSettle(); + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + + expect( + state.handleKeyEvent(_keyDown(LogicalKeyboardKey.arrowDown)), + isTrue, + ); + await tester.pump(); + expect(state.handleKeyEvent(_keyDown(LogicalKeyboardKey.enter)), isTrue); + await tester.pumpAndSettle(); + + expect(selected?.emoji, '🌞'); + }); + + testWidgets('arrow up wraps to the last match', (tester) async { + Emoji? selected; + await tester.pumpWidget( + buildSubject(onSelect: (emoji) => selected = emoji), + ); + await tester.pumpAndSettle(); + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + + state.handleKeyEvent(_keyDown(LogicalKeyboardKey.arrowUp)); + await tester.pump(); + state.handleKeyEvent(_keyDown(LogicalKeyboardKey.tab)); + await tester.pumpAndSettle(); + + expect(selected?.emoji, '☀️'); + }); + + testWidgets('escape is consumed but selects nothing', (tester) async { + var selections = 0; + await tester.pumpWidget(buildSubject(onSelect: (_) => selections++)); + await tester.pumpAndSettle(); + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + + expect(state.handleKeyEvent(_keyDown(LogicalKeyboardKey.escape)), isTrue); + await tester.pumpAndSettle(); + + expect(selections, 0); + }); + + testWidgets('unrelated keys are not consumed', (tester) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + + expect(state.handleKeyEvent(_keyDown(LogicalKeyboardKey.keyA)), isFalse); + expect(state.handleKeyEvent(_keyUp(LogicalKeyboardKey.arrowDown)), isFalse); + }); + + testWidgets('large text scale keeps rows readable without overflow', ( + tester, + ) async { + tester.view.physicalSize = const Size(360, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + buildSubject(availableWidth: 240, availableHeight: 160, textScale: 2), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsOneWidget); + expect( + tester.getSize(find.byKey(EmojiNameCompletionOverlay.surfaceKey)).height, + lessThanOrEqualTo(160), + ); + await tester.tap(rowText('sunflower')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + + // Regression for the measured B1 defect: a hidden popup (no room, or an + // anchored width too narrow for a row) must not consume navigation or + // selection keys, and must never call onSelect for a row nobody can see. + group('hidden popup does not consume keys', () { + for (final entry in <({String name, double height, double width})>[ + (name: 'no room above the field', height: 0, width: 320), + (name: 'too narrow to read', height: 240, width: 100), + ]) { + for (final key in [ + LogicalKeyboardKey.enter, + LogicalKeyboardKey.tab, + LogicalKeyboardKey.arrowDown, + LogicalKeyboardKey.arrowUp, + ]) { + testWidgets('${entry.name}: ${key.keyLabel} is not consumed', ( + tester, + ) async { + var selections = 0; + await tester.pumpWidget( + buildSubject( + availableHeight: entry.height, + availableWidth: entry.width, + onSelect: (_) => selections++, + ), + ); + await tester.pumpAndSettle(); + + expect( + find.byKey(EmojiNameCompletionOverlay.surfaceKey), + findsNothing, + ); + + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + expect(state.handleKeyEvent(_keyDown(key)), isFalse); + await tester.pumpAndSettle(); + + expect(selections, 0); + expect( + find.byKey(EmojiNameCompletionOverlay.surfaceKey), + findsNothing, + ); + }); + } + } + + testWidgets('a visible popup still consumes and selects exactly once', ( + tester, + ) async { + var selections = 0; + Emoji? selected; + await tester.pumpWidget( + buildSubject( + onSelect: (emoji) { + selections++; + selected = emoji; + }, + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(EmojiNameCompletionOverlay.surfaceKey), findsOneWidget); + + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + expect(state.handleKeyEvent(_keyDown(LogicalKeyboardKey.enter)), isTrue); + await tester.pumpAndSettle(); + + expect(selections, 1); + expect(selected?.emoji, '🌻'); + }); + }); + + testWidgets('a shrinking match list resets the highlight to the best row', ( + tester, + ) async { + Emoji? selected; + await tester.pumpWidget( + buildSubject(onSelect: (emoji) => selected = emoji), + ); + await tester.pumpAndSettle(); + final state = tester.state( + find.byType(EmojiNameCompletionOverlay), + ); + + // Highlight the second row, then narrow the catalog to one match. + state.handleKeyEvent(_keyDown(LogicalKeyboardKey.arrowDown)); + await tester.pump(); + await tester.pumpWidget( + buildSubject( + emojis: const [Emoji('☀️', 'sun')], + onSelect: (emoji) => selected = emoji, + ), + ); + await tester.pumpAndSettle(); + + tester + .state( + find.byType(EmojiNameCompletionOverlay), + ) + .handleKeyEvent(_keyDown(LogicalKeyboardKey.enter)); + await tester.pumpAndSettle(); + + expect(selected?.emoji, '☀️'); + }); + + group('3.375x bounds', () { + testWidgets('3.375x scrolls each row into view and keeps it hittable', ( + tester, + ) async { + tester.view.physicalSize = const Size(360, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + final selections = []; + await tester.pumpWidget( + buildSubject( + availableWidth: 240, + availableHeight: 200, + textScale: 3.375, + onSelect: selections.add, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + final surfaceFinder = find.byKey(EmojiNameCompletionOverlay.surfaceKey); + expect(surfaceFinder, findsOneWidget); + + final surface = tester.getRect(surfaceFinder); + expect(surface.left, greaterThanOrEqualTo(0)); + expect(surface.top, greaterThanOrEqualTo(0)); + expect(surface.right, lessThanOrEqualTo(360)); + expect(surface.bottom, lessThanOrEqualTo(640)); + expect( + surface.height, + lessThanOrEqualTo(200), + reason: 'The surface may never grow past the height it was offered.', + ); + + const fixtures = <({String label, String glyph})>[ + (label: 'sunflower | flower', glyph: '🌻'), + (label: 'sun with face | sun', glyph: '🌞'), + (label: 'sun', glyph: '☀️'), + ]; + + for (final fixture in fixtures) { + final row = find + .ancestor( + of: rowText(fixture.label), + matching: find.byType(GestureDetector), + ) + .first; + expect( + tester.getSize(row).height, + greaterThanOrEqualTo(44), + reason: + 'Every row at 3.375x is a 44dp touch target, on or off ' + 'screen.', + ); + + final glyph = find.descendant( + of: row, + matching: find.text(fixture.glyph), + ); + expect(glyph, findsOneWidget); + + // The overlay builds every row eagerly inside a capped, scrollable + // viewport, so a row below the fold is legitimate scroll content and + // not overflow. Bring this row's glyph into view before asserting. + await tester.ensureVisible(glyph); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + + final viewport = tester.getRect(surfaceFinder); + final rowRect = tester.getRect(row); + final glyphRect = tester.getRect(glyph); + + // The glyph stays inside the row it was laid out in. + expect(glyphRect.left, greaterThanOrEqualTo(rowRect.left)); + expect(glyphRect.top, greaterThanOrEqualTo(rowRect.top)); + expect(glyphRect.right, lessThanOrEqualTo(rowRect.right)); + expect( + glyphRect.bottom, + lessThanOrEqualTo(rowRect.bottom), + reason: 'The glyph must not be clipped by its own row.', + ); + + // After scrolling, the glyph itself is visible inside the viewport. + expect(glyphRect.left, greaterThanOrEqualTo(viewport.left)); + expect(glyphRect.top, greaterThanOrEqualTo(viewport.top)); + expect(glyphRect.right, lessThanOrEqualTo(viewport.right)); + expect( + glyphRect.bottom, + lessThanOrEqualTo(viewport.bottom), + reason: + 'A scrolled row glyph must paint inside the surface ' + 'viewport.', + ); + expect( + viewport.contains(tester.getCenter(glyph)), + isTrue, + reason: 'The glyph centre must be hittable inside the surface.', + ); + + final before = selections.length; + await tester.tapAt(tester.getCenter(glyph)); + await tester.pumpAndSettle(); + expect( + selections.length, + before + 1, + reason: 'Tapping the glyph centre selects exactly once.', + ); + expect(selections.last.emoji, fixture.glyph); + } + }); + }); +} diff --git a/test/features/chat/widgets/message_input_emoji_completion_test.dart b/test/features/chat/widgets/message_input_emoji_completion_test.dart new file mode 100644 index 000000000..bba272a91 --- /dev/null +++ b/test/features/chat/widgets/message_input_emoji_completion_test.dart @@ -0,0 +1,674 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/conversation.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/member_group.dart'; +import 'package:prism_plurality/domain/models/member_group_entry.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/chat/providers/chat_providers.dart'; +import 'package:prism_plurality/features/chat/providers/klipy_providers.dart'; +import 'package:prism_plurality/features/chat/services/klipy_service.dart'; +import 'package:prism_plurality/features/chat/widgets/emoji_name_completion_overlay.dart'; +import 'package:prism_plurality/features/chat/widgets/mention_overlay.dart'; +import 'package:prism_plurality/features/chat/widgets/message_input.dart'; +import 'package:prism_plurality/features/members/providers/member_groups_providers.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; + +class _FixedSpeakingAsNotifier extends SpeakingAsNotifier { + _FixedSpeakingAsNotifier(this.memberId); + + final String? memberId; + + @override + String? build() => memberId; +} + +/// Records what the composer sent without touching repositories. +class _RecordingChatNotifier extends ChatNotifier { + final sentContents = []; + + @override + Future sendMessage({ + required String conversationId, + required String content, + required String authorId, + String? messageId, + String? replyToId, + String? replyToAuthorId, + String? replyToContent, + }) async { + sentContents.add(content); + return 'message-id-${sentContents.length}'; + } +} + +/// Keeps one send in flight so the composer's busy state can be observed. +class _PendingChatNotifier extends ChatNotifier { + final sentContents = []; + final release = Completer(); + + @override + Future sendMessage({ + required String conversationId, + required String content, + required String authorId, + String? messageId, + String? replyToId, + String? replyToAuthorId, + String? replyToContent, + }) async { + sentContents.add(content); + await release.future; + return 'message-id-${sentContents.length}'; + } +} + +void main() { + const aliceId = '00000000-0000-0000-0000-000000000001'; + const bobId = '00000000-0000-0000-0000-000000000002'; + + final alice = Member( + id: aliceId, + name: 'Alice', + createdAt: DateTime(2025, 1, 1), + isActive: true, + ); + final bob = Member( + id: bobId, + name: 'Bob', + createdAt: DateTime(2025, 1, 1), + isActive: true, + ); + final conversation = Conversation( + id: 'conv-1', + participantIds: const [aliceId, bobId], + createdAt: DateTime(2025, 1, 1), + lastActivityAt: DateTime(2025, 1, 1), + isDirectMessage: false, + ); + + Widget buildSubject({ + ChatNotifier Function()? chatNotifierFactory, + double textScale = 1, + ComposerDraftCache? draftCache, + }) { + return ProviderScope( + overrides: [ + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + gifServiceConfigProvider.overrideWith( + (ref) async => const GifServiceConfig.disabled(), + ), + speakingAsProvider.overrideWith( + () => _FixedSpeakingAsNotifier(aliceId), + ), + activeMembersProvider.overrideWith((ref) => Stream.value([alice, bob])), + allGroupsProvider.overrideWith( + (ref) => Stream.value(const []), + ), + allGroupEntriesProvider.overrideWith( + (ref) => Stream.value(const []), + ), + conversationByIdProvider( + 'conv-1', + ).overrideWith((ref) => Stream.value(conversation)), + if (chatNotifierFactory != null) + chatNotifierProvider.overrideWith(chatNotifierFactory), + if (draftCache != null) + composerDraftCacheProvider.overrideWithValue(draftCache), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + // MaterialApp.builder is above Navigator and its Overlay, so popup + // content sees the same text scale as the composer itself. + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ), + home: const Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: MessageInput(conversationId: 'conv-1'), + ), + ), + ), + ); + } + + final emojiSurface = find.byKey(EmojiNameCompletionOverlay.surfaceKey); + + Finder emojiRow(String label) => + find.descendant(of: emojiSurface, matching: find.text(label)); + + TextEditingController controllerOf(WidgetTester tester) => + tester.widget(find.byType(TextField)).controller!; + + String composerText(WidgetTester tester) => controllerOf(tester).text; + + Future setCaret(WidgetTester tester, int offset) async { + controllerOf(tester).selection = TextSelection.collapsed(offset: offset); + await tester.pumpAndSettle(); + } + + testWidgets('typing a colon prefix opens matches and a tap inserts one', ( + tester, + ) async { + final notifier = _RecordingChatNotifier(); + + await tester.pumpWidget(buildSubject(chatNotifierFactory: () => notifier)); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), 'hi :sunflower'); + await tester.pumpAndSettle(); + + expect(emojiSurface, findsOneWidget); + expect(emojiRow('sunflower'), findsOneWidget); + expect(find.text('🌻'), findsOneWidget); + + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + + expect(composerText(tester), 'hi 🌻'); + expect(emojiSurface, findsNothing); + expect(notifier.sentContents, isEmpty); + }); + + testWidgets('a bare colon and an unmatched prefix leave no overlay', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), ':'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + + await tester.enterText(find.byType(TextField), ':zzzznotanemoji'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + }); + + testWidgets('URL schemes, clock times and code do not open the popup', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + for (final draft in [ + 'https://example.com/sun', + 'meet at 12:30', + 'a:sun', + '::sun', + ]) { + await tester.enterText(find.byType(TextField), draft); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing, reason: draft); + } + + // Inside an inline code span, even with the caret at the token end. + await tester.enterText(find.byType(TextField), '`:sun`'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + await setCaret(tester, 5); + expect(emojiSurface, findsNothing); + + // Inside a fenced block. + await tester.enterText(find.byType(TextField), '```\n:sun'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + }); + + testWidgets('editing the prefix updates the matches and closes cleanly', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + expect(emojiRow('sunflower'), findsOneWidget); + expect(emojiRow('sunset'), findsOneWidget); + + // Deleting the last character narrows the list. + await tester.enterText(find.byType(TextField), ':sunf'); + await tester.pumpAndSettle(); + expect(emojiRow('sunflower'), findsOneWidget); + expect(emojiRow('sunset'), findsNothing); + + // A terminator closes the token. + await tester.enterText(find.byType(TextField), ':sunf '); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + + // Deleting the whole token closes it too. + await tester.enterText(find.byType(TextField), ''); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + }); + + testWidgets('insertion in the middle of the draft keeps the rest of it', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), 'hello :sunflower world'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + + await setCaret(tester, 16); + expect(emojiSurface, findsOneWidget); + + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + + expect(composerText(tester), 'hello 🌻 world'); + expect(controllerOf(tester).selection.baseOffset, 8); + expect(emojiSurface, findsNothing); + }); + + testWidgets('a caret inside the token does not open the popup', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), 'hi :sunflower'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + + await setCaret(tester, 8); + expect(emojiSurface, findsNothing); + }); + + testWidgets('mention completion keeps priority over emoji completion', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), '@A'); + await tester.pumpAndSettle(); + expect(find.byType(MentionOverlay), findsOneWidget); + expect(emojiSurface, findsNothing); + + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + expect(find.byType(MentionOverlay), findsNothing); + expect(emojiSurface, findsOneWidget); + + await tester.tap(emojiRow('sun')); + await tester.pumpAndSettle(); + expect(composerText(tester), '☀️'); + }); + + testWidgets('an active IME composition does not open the popup', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + + controllerOf(tester).value = const TextEditingValue( + text: ':sun', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 0, end: 4), + ); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + + // The same text without a composition opens normally. + controllerOf(tester).value = const TextEditingValue( + text: ':sun', + selection: TextSelection.collapsed(offset: 4), + ); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + }); + + testWidgets('member mentions and formatting survive an emoji insertion', ( + tester, + ) async { + final notifier = _RecordingChatNotifier(); + + await tester.pumpWidget(buildSubject(chatNotifierFactory: () => notifier)); + await tester.pumpAndSettle(); + + await tester.enterText( + find.byType(TextField), + '@[$aliceId] **hi** :sunflower', + ); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + + expect(composerText(tester), '@[$aliceId] **hi** 🌻'); + + await tester.tap(find.bySemanticsLabel('Send message')); + await tester.pumpAndSettle(); + + expect(notifier.sentContents, ['@[$aliceId] **hi** 🌻']); + expect(composerText(tester), ''); + }); + + testWidgets('the popup stays hidden and sends stay single while busy', ( + tester, + ) async { + final notifier = _PendingChatNotifier(); + + await tester.pumpWidget(buildSubject(chatNotifierFactory: () => notifier)); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), ':sunflower'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + + await tester.tap(find.bySemanticsLabel('Send message')); + await tester.pump(); + + // One send is in flight; typing another token must not open the popup. + expect(notifier.sentContents, [':sunflower']); + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + + notifier.release.complete(); + await tester.pumpAndSettle(); + + expect(notifier.sentContents, [':sunflower']); + }); + + testWidgets('large text scale on a narrow window keeps the popup usable', ( + tester, + ) async { + tester.view.physicalSize = const Size(360, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget(buildSubject(textScale: 2)); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(emojiSurface, findsOneWidget); + + expect( + MediaQuery.textScalerOf(tester.element(emojiSurface)).scale(14), + 28, + reason: 'The actual popup, not only the route, must see 2x scaling', + ); + final surface = tester.getRect(emojiSurface); + final screenWidth = + tester.view.physicalSize.width / tester.view.devicePixelRatio; + expect(surface.width, lessThanOrEqualTo(screenWidth)); + expect(surface.left, greaterThanOrEqualTo(0)); + expect(surface.right, lessThanOrEqualTo(screenWidth)); + // The popup sits above the field, never over it. + expect( + surface.bottom, + lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy), + ); + + await tester.tap(emojiRow('sun')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(composerText(tester), '☀️'); + }); + + testWidgets('insertion preserves surrounding flag and ZWJ sequences', ( + tester, + ) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + const prefix = '👩🏽‍💻 🇨🇦'; + const suffix = ' 🇳🇿 👩‍👩‍👧‍👦'; + const token = ':sunflower'; + const draft = '$prefix $token$suffix'; + await tester.enterText(find.byType(TextField), draft); + await setCaret(tester, prefix.length + 1 + token.length); + expect(emojiSurface, findsOneWidget); + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(composerText(tester), '$prefix 🌻$suffix'); + expect( + controllerOf(tester).selection, + const TextSelection.collapsed(offset: prefix.length + 1 + '🌻'.length), + ); + }); + + testWidgets('inserted emoji and cursor survive the draft cache round trip', ( + tester, + ) async { + final cache = ComposerDraftCache(); + await tester.pumpWidget(buildSubject(draftCache: cache)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi :sunflower'); + await tester.pumpAndSettle(); + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + final inserted = controllerOf(tester).value; + expect(inserted.text, 'hi 🌻'); + expect(cache.read('conv-1'), inserted); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + await tester.pumpWidget(buildSubject(draftCache: cache)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(controllerOf(tester).value, inserted); + expect(emojiSurface, findsNothing); + expect(cache.read('conv-1'), inserted); + }); + + testWidgets('a restored unfinished token keeps its text and selection', ( + tester, + ) async { + const saved = TextEditingValue( + text: 'unsent :sun', + selection: TextSelection.collapsed(offset: 11), + ); + final cache = ComposerDraftCache()..write('conv-1', saved); + await tester.pumpWidget(buildSubject(draftCache: cache)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(controllerOf(tester).value, saved); + expect(cache.read('conv-1'), saved); + }); + + testWidgets( + 'parse budget hides only suggestions and long plain text completes', + (tester) async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + final sensitive = '` ${'x' * 2200} :sunflower'; + await tester.enterText(find.byType(TextField), sensitive); + await tester.pumpAndSettle(); + expect(emojiSurface, findsNothing); + expect(composerText(tester), sensitive); + expect(controllerOf(tester).selection.baseOffset, sensitive.length); + final plain = '${'x' * 2200} :sunflower'; + await tester.enterText(find.byType(TextField), plain); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + await tester.tap(emojiRow('sunflower')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(composerText(tester), '${'x' * 2200} 🌻'); + }, + ); + + group('desktop keyboard', () { + testWidgets('Enter selects the highlighted emoji and does not send', ( + tester, + ) async { + final notifier = _RecordingChatNotifier(); + + await _withDesktopPlatform(() async { + await tester.pumpWidget( + buildSubject(chatNotifierFactory: () => notifier), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), ':sunflower'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(composerText(tester), '🌻'); + expect(emojiSurface, findsNothing); + expect(notifier.sentContents, isEmpty); + }); + }); + + testWidgets('arrow keys move the highlight before Enter selects', ( + tester, + ) async { + await _withDesktopPlatform(() async { + await tester.pumpWidget(buildSubject()); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + expect(emojiRow('sun'), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + // The second match for `sun` is sunset, not the exact `sun` row. + expect(composerText(tester), '🌇'); + }); + }); + + testWidgets('Escape closes the popup and keeps the typed token', ( + tester, + ) async { + final notifier = _RecordingChatNotifier(); + + await _withDesktopPlatform(() async { + await tester.pumpWidget( + buildSubject(chatNotifierFactory: () => notifier), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'hi :sunflower'); + await tester.pumpAndSettle(); + expect(emojiSurface, findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + + expect(emojiSurface, findsNothing); + expect(composerText(tester), 'hi :sunflower'); + expect(notifier.sentContents, isEmpty); + + // With the popup closed, Enter is the normal send path again. + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + + expect(notifier.sentContents, ['hi :sunflower']); + }); + }); + }); + + group('3.375x narrow composer', () { + testWidgets('keeps the popup usable and inserts the chosen emoji', ( + tester, + ) async { + tester.view.physicalSize = const Size(360, 640); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget(buildSubject(textScale: 3.375)); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), ':sun'); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(emojiSurface, findsOneWidget); + + expect( + MediaQuery.textScalerOf(tester.element(emojiSurface)).scale(14), + 47.25, + reason: 'The real popup, not only the route, must see 3.375x scaling.', + ); + + final surface = tester.getRect(emojiSurface); + final screenWidth = + tester.view.physicalSize.width / tester.view.devicePixelRatio; + final screenHeight = + tester.view.physicalSize.height / tester.view.devicePixelRatio; + expect(surface.left, greaterThanOrEqualTo(0)); + expect(surface.right, lessThanOrEqualTo(screenWidth)); + expect(surface.top, greaterThanOrEqualTo(0)); + expect( + surface.bottom, + lessThanOrEqualTo(screenHeight), + reason: 'A 3.375x popup must not paint past the bottom of the window.', + ); + expect( + surface.bottom, + lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy), + reason: 'The popup sits above the field, never over it.', + ); + + // The popup scrolls its own rows, so the chosen row can be below the + // fold at this scale; bring it into view before tapping. + await tester.ensureVisible(emojiRow('sun')); + await tester.pumpAndSettle(); + final scrolledSurface = tester.getRect(emojiSurface); + expect( + scrolledSurface.bottom, + lessThanOrEqualTo(tester.getTopLeft(find.byType(TextField)).dy), + reason: 'Scrolling inside the popup must not move it over the field.', + ); + + await tester.tap(emojiRow('sun')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(composerText(tester), '☀️'); + }); + }); +} + +/// Run [body] with the desktop platform override in place. +/// +/// The override has to be cleared **inside** the test body: the binding's +/// `debugAssertAllFoundationVarsUnset` invariant runs when the body returns, so +/// resetting it in `tearDown` is too late and fails the test. +Future _withDesktopPlatform(Future Function() body) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + try { + await body(); + } finally { + debugDefaultTargetPlatformOverride = null; + } +} diff --git a/test/features/fronting/widgets/timeline_large_text_layout_test.dart b/test/features/fronting/widgets/timeline_large_text_layout_test.dart new file mode 100644 index 000000000..6109e0268 --- /dev/null +++ b/test/features/fronting/widgets/timeline_large_text_layout_test.dart @@ -0,0 +1,987 @@ +// Simulated large-text layout tests for the timeline member header row. +// +// Scenario: 225% system text size x 150% Prism font-size preference, composed +// the way app.dart does it with PrismTextScaler, so header labels scale by +// 3.375. These are simulated layout tests - they do not reproduce the reporter's +// captured settings and they do not qualify any native Windows build. They +// render the real TimelineView with real bundled faces (OpenDyslexic plus an +// emoji fallback, not the square test font) and assert observable layout, not +// implementation: the sticky header grows instead of clipping its names, +// ordinary names stay readable instead of collapsing to one initial, header +// columns stay aligned with the painted grid after horizontal scrolling, and a +// tap still opens the intended member's session. + +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/domain/models/fronting_session.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/features/fronting/providers/sleep_providers.dart'; +import 'package:prism_plurality/features/fronting/providers/timeline_providers.dart'; +import 'package:prism_plurality/features/fronting/widgets/timeline_painter.dart'; +import 'package:prism_plurality/features/fronting/widgets/timeline_view.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/member_avatar.dart'; + +import '../../../helpers/fake_repositories.dart'; +import '../../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// The scenario's system text-size factor: Windows accessibility text size at +/// its maximum, 225%. +const TextScaler _windowsMaxSystemScaler = TextScaler.linear(2.25); + +/// The scenario's Prism font-size factor: the app clamps its preference to +/// 150% (`FontFamily.maximumScale`). +const double _appMaxFontScale = 1.5; + +/// Today's compact header band; default text size must keep it. +const double _defaultHeaderBandHeight = 56; + +/// A nonlinear accessibility scaler, like the platform-provided ones that +/// PrismTextScaler delegates each size to instead of assuming a linear factor. +class _NonlinearTextScaler extends TextScaler { + const _NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize <= 14 ? fontSize * 2.5 : 35 + (fontSize - 14) * 0.4; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 2.5; +} + +Finder _timelineCanvasFinder() => find.byWidgetPredicate( + (widget) => widget is CustomPaint && widget.painter is TimelinePainter, +); + +TimelinePainter _timelinePainter(WidgetTester tester) => + tester.widget(_timelineCanvasFinder()).painter! + as TimelinePainter; + +Rect _timelineCanvasRect(WidgetTester tester) => + tester.getRect(_timelineCanvasFinder()); + +/// The vertical scroller holding the grid, i.e. everything below the sticky +/// header band and its one-pixel divider. Its top edge is the band's bottom. +/// Anchored on the canvas so a header that has to scroll vertically in a short +/// window can never be mistaken for it. +Finder _gridScrollViewFinder() => find + .ancestor( + of: _timelineCanvasFinder(), + matching: find.byWidgetPredicate( + (widget) => + widget is SingleChildScrollView && + widget.scrollDirection == Axis.vertical, + ), + ) + .first; + +double _headerBandHeight(WidgetTester tester) { + final viewTop = tester.getTopLeft(find.byType(TimelineView)).dy; + final gridTop = tester.getTopLeft(_gridScrollViewFinder()).dy; + return gridTop - viewTop - 1; +} + +/// Laid-out glyph boxes for the visible part of a header name. +List _nameBoxes(RenderParagraph paragraph, String name) => + paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: name.length), + ); + +/// Number of rendered text lines, from the laid-out glyph boxes. +int _nameLineCount(RenderParagraph paragraph, String name) => + {for (final box in _nameBoxes(paragraph, name)) box.top.round()}.length; + +/// Asserts a header label is laid out at the full composed scale of the +/// scenario, so a font cap, a forced strut or a reduced scaler cannot pass. +void _expectComposedScale( + RenderParagraph paragraph, + double expectedScale, { + required int expectedLines, +}) { + final style = paragraph.text.style!; + final fontSize = style.fontSize!; + expect(style.height, isNotNull); + expect( + paragraph.textScaler.scale(fontSize), + closeTo(fontSize * expectedScale, 1e-6), + reason: 'the header must inherit the composed system x Prism text scaler', + ); + expect( + paragraph.size.height, + closeTo(fontSize * style.height! * expectedScale * expectedLines, 0.5), + reason: 'laid-out lines must use the full scaled size, not a capped one', + ); +} + +RenderParagraph _nameParagraph(WidgetTester tester, String name) { + final finder = find.text(name); + expect( + finder, + findsOneWidget, + reason: 'the header must render exactly one label for "$name"', + ); + return tester.renderObject(finder); +} + +List _members(List names) => [ + for (var i = 0; i < names.length; i++) + Member( + id: 'member-$i', + name: names[i], + createdAt: DateTime(2026, 1, 1), + displayOrder: i, + ), +]; + +/// One active session per member, so every column has a bar that spans "now". +FakeFrontingSessionRepository _repoFor(List members) { + final repo = FakeFrontingSessionRepository(); + final now = DateTime.now(); + for (final member in members) { + repo.sessions.add( + FrontingSession( + id: '${member.id}-session', + memberId: member.id, + startTime: now.subtract(const Duration(hours: 2)), + ), + ); + } + return repo; +} + +ProviderContainer _container( + FakeFrontingSessionRepository repo, + List members, +) { + final memberRepo = FakeMemberRepository()..seed(members); + return ProviderContainer( + overrides: [ + frontingSessionRepositoryProvider.overrideWithValue(repo), + memberRepositoryProvider.overrideWithValue(memberRepo), + allMembersProvider.overrideWith((ref) => Stream.value(members)), + recentSleepSessionsPaginatedProvider.overrideWith( + (ref, limit) => Stream.value(const []), + ), + ], + ); +} + +/// Real bundled faces, loaded once in `setUpAll` through the repository's +/// platform-gated loader (rootBundle first, on-disk asset as fallback). +/// OpenDyslexic has production-like advances and line metrics that the square +/// test font hides; the emoji fallback covers emoji inside member names. +ThemeData _timelineTheme() => ThemeData( + fontFamily: 'OpenDyslexic', + fontFamilyFallback: const ['NotoColorEmoji'], +); + +Widget _buildSubject( + ProviderContainer container, { + TextScaler? systemScaler, + double appFontScale = 1.0, +}) { + return UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: _timelineTheme(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) { + final content = child ?? const SizedBox.shrink(); + if (systemScaler == null) return content; + // Mirrors app.dart: the app factor is applied on top of the system + // accessibility scaler through PrismTextScaler, per size. + return MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: PrismTextScaler(systemScaler, appFontScale)), + child: content, + ); + }, + home: const Scaffold(body: TimelineView()), + ), + ); +} + +void _useWindow(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +Future _pumpTimeline( + WidgetTester tester, + ProviderContainer container, { + TextScaler? systemScaler, + double appFontScale = 1.0, +}) async { + await tester.pumpWidget( + _buildSubject( + container, + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + testWidgets('large text keeps fitting columns to the changing window width', ( + tester, + ) async { + final members = _members(['Wren', 'Nico', 'Ash', 'Ivy']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + final widths = []; + for (final window in [600.0, 800.0, 900.0, 1100.0]) { + _useWindow(tester, Size(window, 700)); + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + expect(tester.takeException(), isNull); + final expected = + ((window - 52) / 4).clamp( + 40 * 3.375, + (window >= 900 ? 68 : 52) * 3.375, + ) - + 4; + final width = _timelinePainter(tester).columnWidth; + expect( + width, + closeTo(expected, .01), + reason: + 'Large text must retain distinct scaled minimum and maximum bounds.', + ); + widths.add(width); + _expectComposedScale( + _nameParagraph(tester, 'Nico'), + 3.375, + expectedLines: 1, + ); + } + expect( + widths.toSet().length, + 4, + reason: 'Resizing must not leave every column locked to one width.', + ); + }); + + testWidgets('large text keeps fitting columns to the member count', ( + tester, + ) async { + _useWindow(tester, const Size(800, 700)); + final widths = []; + for (final count in [2, 5, 20]) { + final members = _members([for (var i = 0; i < count; i++) 'Nico $i']); + final container = _container(_repoFor(members), members); + try { + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + expect(tester.takeException(), isNull); + final width = _timelinePainter(tester).columnWidth; + expect( + width, + closeTo(((800 - 52) / count).clamp(40 * 3.375, 52 * 3.375) - 4, .01), + ); + widths.add(width); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + container.dispose(); + await tester.pump(); + } + } + expect(widths[0], greaterThan(widths[1])); + expect(widths[1], greaterThan(widths[2])); + }); + + testWidgets('short names at large text reserve only the line they need', ( + tester, + ) async { + _useWindow(tester, const Size(1200, 700)); + final members = _members(['Nico', 'Ash']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + final name = _nameParagraph(tester, 'Nico'); + expect( + name.maxLines, + 1, + reason: + 'Larger type alone is not a reason to reserve an empty second line.', + ); + _expectComposedScale(name, 3.375, expectedLines: 1); + final style = name.text.style!; + final lineHeight = style.fontSize! * style.height! * 3.375; + expect(_headerBandHeight(tester), lessThan(28 + 2 + 2 * lineHeight)); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'widening the timeline releases an unnecessary wrapped name line', + (tester) async { + final members = _members(['Nico Nico', 'Nico']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + _useWindow(tester, const Size(600, 700)); + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + expect( + _nameLineCount(_nameParagraph(tester, 'Nico Nico'), 'Nico Nico'), + 2, + ); + final narrowBand = _headerBandHeight(tester); + tester.view.physicalSize = const Size(1200, 700); + await tester.pumpAndSettle(); + final name = _nameParagraph(tester, 'Nico Nico'); + expect(name.maxLines, 1); + expect(name.didExceedMaxLines, isFalse); + expect(_headerBandHeight(tester), lessThan(narrowBand)); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('small text keeps avatar-safe columns and the compact band', ( + tester, + ) async { + _useWindow(tester, const Size(800, 700)); + final members = _members([for (var i = 0; i < 40; i++) 'Nico $i']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + await _pumpTimeline( + tester, + container, + systemScaler: const TextScaler.linear(1), + appFontScale: .5, + ); + expect(_timelinePainter(tester).columnWidth, 36); + expect(_headerBandHeight(tester), 56); + _expectComposedScale( + _nameParagraph(tester, 'Nico 0'), + .5, + expectedLines: 1, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'default text size (100% x 100%) keeps the compact 56 px band and narrow ' + 'columns', + (tester) async { + _useWindow(tester, const Size(800, 700)); + final members = _members([for (var i = 0; i < 40; i++) 'Member $i']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline(tester, container); + + expect(tester.takeException(), isNull); + expect( + _headerBandHeight(tester), + closeTo(_defaultHeaderBandHeight, 0.01), + ); + final painter = _timelinePainter(tester); + expect( + painter.columnWidth, + closeTo(36, 0.01), + reason: 'default text size keeps the existing 36 px column floor', + ); + + final canvasRect = _timelineCanvasRect(tester); + final zones = painter.computeHitZones(canvasRect.size); + final firstZone = zones.firstWhere( + (zone) => zone.session.memberId == 'member-0', + ); + expect(firstZone.rect.width, closeTo(painter.columnWidth, 0.01)); + expect( + tester.getCenter(find.text('Member 0')).dx, + closeTo(canvasRect.left + firstZone.rect.center.dx, 1), + reason: 'header columns must stay centered over their grid columns', + ); + }, + ); + + testWidgets( + '225% system x 150% Prism scaling grows the header instead of clipping ' + 'names', + (tester) async { + _useWindow(tester, const Size(800, 700)); + final members = _members([ + 'Alexandria', + 'Bartholomew Thistlewood', + 'Wren', + 'Ash', + 'Moth', + 'Sable', + 'Ivy', + 'Rowan', + 'Juniper', + 'Caspian', + 'Thistle', + 'Vesper', + 'Ember', + 'Dandelion', + ]); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect( + tester.takeException(), + isNull, + reason: 'names must not overflow the sticky header band', + ); + final band = _headerBandHeight(tester); + expect( + band, + greaterThan(_defaultHeaderBandHeight), + reason: 'the header band has to grow with the scaled name text', + ); + + expect( + tester.getSize(_gridScrollViewFinder()).height, + closeTo(700 - band - 1, 0.5), + reason: + 'the taller header must reduce the grid viewport, not overlap it', + ); + + final viewTop = tester.getTopLeft(find.byType(TimelineView)).dy; + final bandBottom = tester.getTopLeft(_gridScrollViewFinder()).dy - 1; + for (final name in ['Alexandria', 'Bartholomew Thistlewood', 'Wren']) { + final rect = tester.getRect(find.text(name)); + expect(rect.top, greaterThanOrEqualTo(viewTop)); + expect( + rect.bottom, + lessThanOrEqualTo(bandBottom), + reason: + '"$name" must be laid out inside the header band, not clipped', + ); + } + + final ordinary = _nameParagraph(tester, 'Alexandria'); + expect( + ordinary.didExceedMaxLines, + isFalse, + reason: + 'a 10-character name must stay fully readable at maximum text ' + 'size, not collapse to a single initial', + ); + expect( + _nameLineCount(ordinary, 'Alexandria'), + greaterThanOrEqualTo(2), + reason: 'large text wraps names over two lines instead of truncating', + ); + _expectComposedScale( + ordinary, + _windowsMaxSystemScaler.scale(1) * _appMaxFontScale, + expectedLines: 2, + ); + + final long = _nameParagraph(tester, 'Bartholomew Thistlewood'); + expect( + long.didExceedMaxLines, + isTrue, + reason: 'unbounded names still ellipsize rather than widen forever', + ); + expect( + find.byTooltip('Bartholomew Thistlewood'), + findsOneWidget, + reason: 'an ellipsized name keeps its full text as an accessible label', + ); + + final painter = _timelinePainter(tester); + expect( + painter.columnWidth, + greaterThan(48), + reason: + 'columns widen past the default 48 px cap so names stay readable ' + 'instead of squeezing every member into the window', + ); + final canvasRect = _timelineCanvasRect(tester); + final zones = painter.computeHitZones(canvasRect.size); + final firstZone = zones.firstWhere( + (zone) => zone.session.memberId == 'member-0', + ); + expect( + tester.getCenter(find.text('Alexandria')).dx, + closeTo(canvasRect.left + firstZone.rect.center.dx, 1), + reason: 'widened columns stay aligned between header and grid', + ); + }, + ); + + testWidgets( + 'short window at 225% x 150% falls back to a scrollable header without ' + 'shrinking text', + (tester) async { + _useWindow(tester, const Size(420, 180)); + final members = _members(['Wren', 'Bartholomew Thistlewood', 'Moth']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect( + tester.takeException(), + isNull, + reason: 'a short window must not overflow the header or the grid', + ); + final band = _headerBandHeight(tester); + expect(band, greaterThan(0)); + expect( + band, + lessThanOrEqualTo(180 - 1), + reason: 'the header band cannot take more than the window height', + ); + expect( + tester.getSize(_gridScrollViewFinder()).height, + greaterThan(0), + reason: 'the grid keeps a usable viewport, never a negative one', + ); + + // This case must still reach the capped-header fallback after short + // names have become eligible for a compact, single-line header. + final headerScroll = find.ancestor( + of: find.text('Wren'), + matching: find.byWidgetPredicate( + (widget) => + widget is SingleChildScrollView && + widget.scrollDirection == Axis.vertical, + ), + ); + expect(headerScroll, findsOneWidget); + await tester.drag(headerScroll, const Offset(0, -100)); + await tester.pumpAndSettle(); + expect( + tester.getBottomLeft(find.text('Bartholomew Thistlewood')).dy, + lessThanOrEqualTo(tester.getTopLeft(_gridScrollViewFinder()).dy), + ); + + // The inherited scaler and the laid-out line height are both exact, so a + // reduced scale cannot pass this by accident. + _expectComposedScale( + _nameParagraph(tester, 'Wren'), + _windowsMaxSystemScaler.scale(1) * _appMaxFontScale, + expectedLines: 1, + ); + }, + ); + + testWidgets( + 'default text size keeps the band, the name row and the avatar row aligned', + (tester) async { + _useWindow(tester, const Size(900, 700)); + final members = _members(['Alexandria', 'Nico']); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline(tester, container); + + expect(tester.takeException(), isNull); + expect( + _headerBandHeight(tester), + closeTo(_defaultHeaderBandHeight, 0.01), + ); + expect( + _timelinePainter(tester).columnWidth, + closeTo(64, 0.01), + reason: 'a 900 px window keeps the wide column maximum', + ); + final avatars = find.byType(MemberAvatar); + expect(avatars, findsNWidgets(2)); + expect( + tester.getRect(avatars.at(0)).top, + closeTo(tester.getRect(avatars.at(1)).top, 0.5), + ); + expect( + tester.getRect(find.text('Alexandria')).top, + closeTo(tester.getRect(find.text('Nico')).top, 0.5), + ); + }, + ); + + testWidgets( + 'emoji, RTL and unbounded names stay inside the grown header band at ' + '225% x 150%', + (tester) async { + _useWindow(tester, const Size(900, 700)); + final names = ['🜁 Wren', 'نور', 'Alexandria', 'Bartholomew Thistlewood']; + final members = _members(names); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect(tester.takeException(), isNull); + final viewTop = tester.getTopLeft(find.byType(TimelineView)).dy; + final bandBottom = tester.getTopLeft(_gridScrollViewFinder()).dy - 1; + for (final name in names) { + final finder = find.text(name); + if (finder.evaluate().isEmpty) continue; // column scrolled out of view + final rect = tester.getRect(finder); + expect(rect.top, greaterThanOrEqualTo(viewTop)); + expect( + rect.bottom, + lessThanOrEqualTo(bandBottom), + reason: '"$name" must fit inside the header band', + ); + expect( + find.byTooltip(name), + findsOneWidget, + reason: '"$name" keeps a full-name accessible label', + ); + // Fallback faces (emoji) can draw taller ink than the primary face, so + // check the glyph boxes, not only the paragraph box. + final paragraph = _nameParagraph(tester, name); + final boxes = _nameBoxes(paragraph, name); + expect( + boxes, + isNotEmpty, + reason: '"$name" must render glyphs, including fallback ink', + ); + for (final box in boxes) { + expect( + rect.top + box.top, + greaterThanOrEqualTo(viewTop), + reason: '"$name" fallback ink must not clip at the band top', + ); + expect( + rect.top + box.bottom, + lessThanOrEqualTo(bandBottom), + reason: '"$name" fallback ink must not clip at the band bottom', + ); + } + } + + final rtl = _nameParagraph(tester, 'نور'); + expect(_nameBoxes(rtl, 'نور'), isNotEmpty); + expect(rtl.size.width, greaterThan(0)); + }, + ); + + testWidgets( + 'one-line and two-line names keep avatars and first baselines level at ' + '225% x 150%', + (tester) async { + _useWindow(tester, const Size(900, 700)); + final names = ['Alexandria', 'Nico', 'Ash', 'Bartholomew Thistlewood']; + final members = _members(names); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect(tester.takeException(), isNull); + // The case is only meaningful with genuinely mixed name heights. + expect( + _nameLineCount(_nameParagraph(tester, 'Alexandria'), 'Alexandria'), + 2, + ); + expect(_nameLineCount(_nameParagraph(tester, 'Nico'), 'Nico'), 1); + + final avatars = find.byType(MemberAvatar); + final avatarCount = avatars.evaluate().length; + expect(avatarCount, greaterThanOrEqualTo(3)); + final avatarTops = [ + for (var i = 0; i < avatarCount; i++) tester.getRect(avatars.at(i)).top, + ]; + for (final top in avatarTops) { + expect( + top, + closeTo(avatarTops.first, 0.5), + reason: + 'avatar rows must stay level whether a name takes one line or ' + 'two; a short name must not drag its avatar down', + ); + } + for (var i = 0; i < avatarCount; i++) { + expect(tester.getRect(avatars.at(i)).height, closeTo(28, 0.5)); + } + + final nameTops = {}; + for (final name in names) { + final finder = find.text(name); + if (finder.evaluate().isEmpty) continue; // column scrolled out of view + nameTops[name] = tester.getRect(finder).top; + } + expect(nameTops.length, greaterThanOrEqualTo(3)); + final referenceTop = nameTops['Alexandria']!; + for (final entry in nameTops.entries) { + expect( + entry.value, + closeTo(referenceTop, 0.5), + reason: + '"${entry.key}" must start on the same first-name baseline as ' + 'the two-line names', + ); + } + }, + ); + + testWidgets( + 'accented and descending names keep their glyph ink inside the band at ' + '225% x 150%', + (tester) async { + _useWindow(tester, const Size(900, 700)); + final names = ['ÉÅgjpq', 'Éowyn Åse', 'gjpqy ģ', 'Wren']; + final members = _members(names); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect(tester.takeException(), isNull); + final viewTop = tester.getTopLeft(find.byType(TimelineView)).dy; + final bandBottom = tester.getTopLeft(_gridScrollViewFinder()).dy - 1; + + var checked = 0; + for (final name in names) { + final finder = find.text(name); + if (finder.evaluate().isEmpty) continue; // column scrolled out of view + final paragraph = _nameParagraph(tester, name); + final origin = tester.getTopLeft(finder); + final boxes = _nameBoxes(paragraph, name); + expect(boxes, isNotEmpty, reason: '"$name" must render glyphs'); + for (final box in boxes) { + expect( + origin.dy + box.top, + greaterThanOrEqualTo(viewTop), + reason: '"$name" ink must not be clipped at the band top', + ); + expect( + origin.dy + box.bottom, + lessThanOrEqualTo(bandBottom), + reason: '"$name" ink must not be clipped at the band bottom', + ); + } + checked++; + } + expect( + checked, + greaterThanOrEqualTo(3), + reason: 'the accented/descender columns must actually be rendered', + ); + _expectComposedScale( + _nameParagraph(tester, 'ÉÅgjpq'), + _windowsMaxSystemScaler.scale(1) * _appMaxFontScale, + expectedLines: 1, + ); + }, + ); + + testWidgets( + 'scrolling to the last member keeps header and grid aligned and taps it', + (tester) async { + _useWindow(tester, const Size(500, 800)); + final members = _members([ + 'Wren', + 'Ash', + 'Moth', + 'Juniper', + 'Rowan', + 'Vesper', + ]); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + // Scenario variant at system 150% x Prism 150%: still a combined + // large-text layout, but the preview sheet itself stays out of the + // extreme range that other tests cover. + await _pumpTimeline( + tester, + container, + systemScaler: const TextScaler.linear(1.5), + appFontScale: 1.5, + ); + + expect( + _timelinePainter(tester).columnWidth, + greaterThan(48), + reason: 'large text widens columns instead of squeezing every member', + ); + + // The canvas center is far below the viewport, so scroll from the grid + // viewport itself: the inner horizontal scroller claims the drag. + await tester.drag(_gridScrollViewFinder(), const Offset(-4000, 0)); + await tester.pumpAndSettle(); + + expect( + find.byTooltip('Vesper'), + findsOneWidget, + reason: 'the last member header scrolls into view with the grid', + ); + + final painter = _timelinePainter(tester); + final canvasRect = _timelineCanvasRect(tester); + final zones = painter.computeHitZones(canvasRect.size); + final lastZone = zones.firstWhere( + (zone) => zone.session.memberId == 'member-5', + ); + expect( + tester.getCenter(find.text('Vesper')).dx, + closeTo(canvasRect.left + lastZone.rect.center.dx, 1), + reason: + 'after horizontal scrolling the header column is still centered ' + 'over its grid column', + ); + + await tester.tapAt(canvasRect.topLeft + lastZone.rect.center); + await tester.pumpAndSettle(); + + expect(find.text('View Details'), findsOneWidget); + expect( + find.descendant( + of: find.byType(BottomSheet), + matching: find.text('Vesper'), + ), + findsOneWidget, + reason: 'the tap opens the session of the column that was tapped', + ); + }, + ); + + testWidgets( + 'zooming out at 225% x 150% keeps the culling offset inside the canvas', + (tester) async { + _useWindow(tester, const Size(800, 700)); + final members = _members(['Wren']); + final repo = FakeFrontingSessionRepository(); + final now = DateTime.now(); + repo.sessions.add( + FrontingSession( + id: 'long-session', + memberId: 'member-0', + startTime: now.subtract(const Duration(days: 21)), + endTime: now, + ), + ); + final container = _container(repo, members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: _windowsMaxSystemScaler, + appFontScale: _appMaxFontScale, + ); + + expect(_headerBandHeight(tester), greaterThan(_defaultHeaderBandHeight)); + expect( + _timelinePainter(tester).scrollOffsetNotifier!.value, + lessThanOrEqualTo(tester.getSize(_timelineCanvasFinder()).height), + ); + + final notifier = container.read(timelineStateProvider.notifier); + while (container.read(timelineStateProvider).pixelsPerHour > + TimelineState.minPixelsPerHour) { + notifier.zoomOut(); + await tester.pump(); + } + + expect( + _timelinePainter(tester).scrollOffsetNotifier!.value, + lessThanOrEqualTo(tester.getSize(_timelineCanvasFinder()).height), + reason: 'a taller header must not leave a stale culling offset', + ); + }, + ); + + testWidgets('nonlinear system scaling composes with the Prism font scale', ( + tester, + ) async { + _useWindow(tester, const Size(800, 700)); + final members = _members([ + 'Alexandria', + 'Wren', + 'Ash', + 'Moth', + 'Sable', + 'Ivy', + 'Rowan', + 'Juniper', + ]); + final container = _container(_repoFor(members), members); + addTearDown(container.dispose); + + await _pumpTimeline( + tester, + container, + systemScaler: const _NonlinearTextScaler(), + appFontScale: _appMaxFontScale, + ); + + expect(tester.takeException(), isNull); + expect(_headerBandHeight(tester), greaterThan(_defaultHeaderBandHeight)); + final paragraph = _nameParagraph(tester, 'Alexandria'); + expect(paragraph.didExceedMaxLines, isFalse); + final bandBottom = tester.getTopLeft(_gridScrollViewFinder()).dy - 1; + expect( + tester.getRect(find.text('Alexandria')).bottom, + lessThanOrEqualTo(bandBottom), + ); + expect( + _timelinePainter(tester).columnWidth, + greaterThan(48), + reason: 'the nonlinear scaler still widens columns past the default cap', + ); + }); +} diff --git a/test/features/habits/services/habit_notification_reset_orphan_test.dart b/test/features/habits/services/habit_notification_reset_orphan_test.dart new file mode 100644 index 000000000..54c5e99e9 --- /dev/null +++ b/test/features/habits/services/habit_notification_reset_orphan_test.dart @@ -0,0 +1,738 @@ +// Regression: resetting habit data must retract that habit's pending reminders. +// +// The reset path deletes habit rows (`_resetHabits` in +// lib/features/settings/providers/reset_data_provider.dart) without telling the +// notification scheduler, and `HabitNotificationService.rescheduleAll` only +// visits habits that still exist. So the deleted habit's pending one-shots stay +// scheduled and fire later; tapping one opens an empty habits screen. +// +// This test drives the real reset provider, the real HabitNotificationService +// and the real LocalNotificationService. Only the platform notification channel +// (`dexterous.com/flutter/local_notifications`) is faked, so cancellation must +// come from the production code path rather than a stubbed `cancelRange`. +// Fixtures are synthetic: no member, message, token or user data is involved. + +import 'dart:async'; + +import 'package:drift/drift.dart' show Value; +import 'package:drift/native.dart'; +import 'package:flutter/foundation.dart' + show debugDefaultTargetPlatformOverride, TargetPlatform; +import 'package:flutter/services.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:prism_plurality/core/database/app_database.dart' hide Habit; +import 'package:prism_plurality/core/database/database_provider.dart'; +import 'package:prism_plurality/core/services/local_notification_service.dart'; +import 'package:prism_plurality/domain/models/habit.dart'; +import 'package:prism_plurality/features/habits/services/habit_notification_service.dart'; +import 'package:prism_plurality/features/settings/providers/reset_data_provider.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:timezone/data/latest_all.dart' as tzdata; +import 'package:timezone/timezone.dart' as tz; + +/// Habit scheduling namespace, mirroring `HabitNotificationService`: +/// `3_000_000 + id.hashCode.abs() % 100_000`. +/// +/// Owned IDs are not the bare base: the service schedules and cancels +/// `base..base + _habitSeriesWidth - 1`, so the top base (3_099_999) owns IDs +/// through 3_100_028. Attribution must therefore use a habit's owned series, +/// never a 3_000_000..3_099_999 hard bound. +const _habitIdBase = 3000000; +const _habitIdMod = 100000; +const _habitSeriesWidth = LocalNotificationService.maxIntervalOccurrences; + +int _habitBaseId(String habitId) => + _habitIdBase + (habitId.hashCode.abs() % _habitIdMod); + +/// Every notification ID the service may use for one habit base. +Set _ownedSeries(int baseId) => { + for (var i = 0; i < _habitSeriesWidth; i++) baseId + i, +}; + +/// Every notification ID the service may use for [habitId]. +Set _habitSeriesIds(String habitId) => _ownedSeries(_habitBaseId(habitId)); + +/// Notification ID ranges owned by other subsystems. A habit reset must leave +/// them alone: fronting notifications use 1000-1999, reminders 20_000_000+. +const _frontingId = 1500; +const _reminderId = 20000005; + +/// Bounded waits for the interleaving gate: how long to wait for the batch to +/// reach the gated one-shot, and how long to drain it after release. +const _gateHoldTimeout = Duration(seconds: 10); +const _batchDrainTimeout = Duration(seconds: 10); + +/// Stateful fake of the flutter_local_notifications platform channel: it holds +/// the pending-request table the OS would hold, so `cancel`/`zonedSchedule` +/// effects are observable through [LocalNotificationService]. +class _FakeNotificationPlatform { + final Map> pending = {}; + final List calls = []; + + /// One-shot gate for interleaving tests: the fake records the pending entry + /// for [gatedScheduleId], then holds that `zonedSchedule` until + /// [gateReleased] completes, so a test can act while a scheduling pass is + /// suspended at a chosen one-shot. Only scheduling is gated — cancellation is + /// never held, so work run inside the gate cannot deadlock. + int? gatedScheduleId; + Completer? gateEntered; + Completer? gateReleased; + + /// IDs whose cancellation is attempted, recorded, and then fails — the + /// pending entry survives, standing for a reminder that may still fire. + Set failCancelIds = {}; + + Future handle(MethodCall call) async { + calls.add(call); + switch (call.method) { + case 'initialize': + return true; + case 'zonedSchedule': + final args = (call.arguments as Map).cast(); + final id = args['id']! as int; + pending[id] = { + 'id': id, + 'title': args['title'] ?? '', + 'body': args['body'] ?? '', + 'payload': args['payload'] ?? '', + }; + if (id == gatedScheduleId) { + if (gateEntered != null && !gateEntered!.isCompleted) { + gateEntered!.complete(); + } + await gateReleased!.future; + } + return null; + case 'cancel': + // The iOS implementation passes the raw ID as the argument. + final id = call.arguments as int; + if (failCancelIds.contains(id)) { + throw PlatformException( + code: 'cancel_failed', + message: 'synthetic cancel failure', + ); + } + pending.remove(id); + return null; + case 'pendingNotificationRequests': + return pending.values.toList(); + default: + return null; + } + } + + List get pendingIds => pending.keys.toList()..sort(); + + List get cancelledIds => [ + for (final call in calls) + if (call.method == 'cancel') call.arguments as int, + ]; + + List get methods => [for (final call in calls) call.method]; + + /// Seeds a pending notification owned by another subsystem, as the OS would + /// already hold after that subsystem scheduled it. + void seedForeignPending(int id, String payload) { + pending[id] = { + 'id': id, + 'title': 'fixture', + 'body': 'fixture', + 'payload': payload, + }; + } +} + +Habit _habitFixture(String id) { + final now = DateTime(2026, 1, 1, 9); + return Habit( + id: id, + name: 'Fixture habit $id', + frequency: HabitFrequency.daily, + isActive: true, + notificationsEnabled: true, + reminderTime: '09:00', + createdAt: now, + modifiedAt: now, + ); +} + +/// Database whose transactions always fail, so a reset's capture/delete step +/// throws before anything is captured or cancelled. +class _FailingTransactionDatabase extends AppDatabase { + _FailingTransactionDatabase() : super(NativeDatabase.memory()); + + @override + Future transaction( + Future Function() action, { + bool requireNew = false, + }) async { + throw StateError('synthetic transaction failure'); + } +} + +Future _insertHabitRow( + AppDatabase db, + String id, { + bool softDeleted = false, + bool active = true, +}) { + final now = DateTime.utc(2026, 3, 18, 12); + return db + .into(db.habits) + .insert( + HabitsCompanion.insert( + id: id, + name: 'Fixture habit $id', + createdAt: now, + modifiedAt: now, + reminderTime: const Value('09:00'), + notificationsEnabled: const Value(true), + isActive: Value(active), + isDeleted: Value(softDeleted), + ), + ); +} + +Future _countRows(AppDatabase db, String table) async { + final row = await db + .customSelect('SELECT COUNT(*) AS c FROM $table') + .getSingle(); + return row.read('c'); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const channel = MethodChannel('dexterous.com/flutter/local_notifications'); + + late _FakeNotificationPlatform platform; + late AppDatabase db; + late ProviderContainer container; + + setUpAll(() { + tzdata.initializeTimeZones(); + tz.setLocalLocation(tz.getLocation('UTC')); + // The plugin resolves its implementation through the registered platform + // instance; each test pins defaultTargetPlatform to iOS inside setUp. + IOSFlutterLocalNotificationsPlugin.registerWith(); + }); + + tearDownAll(() { + debugDefaultTargetPlatformOverride = null; + }); + + setUp(() async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + platform = _FakeNotificationPlatform(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, platform.handle); + db = AppDatabase(NativeDatabase.memory()); + container = ProviderContainer( + overrides: [ + databaseProvider.overrideWithValue(db), + // Locale only affects notification copy; pin it so the habit service + // does not pull the settings stream into this test's provider graph. + localeOverrideProvider.overrideWithValue(null), + ], + ); + // Build the reset notifier before the assertion so `reset()` reports a + // failure through its state instead of a not-yet-built provider. + await container.read(resetDataNotifierProvider.future); + }); + + tearDown(() async { + container.dispose(); + await db.close(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + debugDefaultTargetPlatformOverride = null; + }); + + test('resetting habit data leaves no pending habit reminder', () async { + final habit = _habitFixture('habit-reset-1'); + await _insertHabitRow(db, habit.id); + + final service = container.read(habitNotificationServiceProvider); + final local = container.read(localNotificationServiceProvider); + await service.scheduleForHabit(habit); + + // Guard against a vacuous pass: the fixture must really be on the OS-side + // pending table, in the habit namespace only, and visible through the + // service's own read path. + final seriesIds = _habitSeriesIds(habit.id); + expect( + platform.pendingIds.where(seriesIds.contains), + hasLength(7), + reason: + 'a daily habit schedules 7 one-shots (HabitNotificationService.' + '_dailyOccurrences); pending=${platform.pendingIds}', + ); + expect( + (await local.pendingNotificationRequests()) + .map((request) => request.id) + .where(seriesIds.contains), + hasLength(7), + ); + + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect(await _countRows(db, 'habits'), 0); + expect(await _countRows(db, 'habit_completions'), 0); + + final orphaned = (await local.pendingNotificationRequests()) + .map((request) => request.id) + .where(seriesIds.contains) + .toList(); + expect( + orphaned, + isEmpty, + reason: + 'resetting habit data deleted the habit rows, so its reminder IDs ' + 'must be cancelled before this point; they are now orphans that fire ' + 'against an empty habits screen. Still pending: $orphaned ' + '(namespace ${_habitBaseId(habit.id)}..' + '${_habitBaseId(habit.id) + _habitSeriesWidth - 1}).', + ); + }); + + test('resetting habit data also retracts a soft-deleted habit row', () async { + // A habit soft-deleted by a sync-inbound change keeps its already + // scheduled reminders; the reset deletes that row too, so its IDs must be + // retracted as well (a capture that filters `is_deleted = 0` leaks them). + final habit = _habitFixture('habit-reset-soft-deleted'); + await _insertHabitRow(db, habit.id, softDeleted: true); + + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(habit); + + final seriesIds = _habitSeriesIds(habit.id); + expect(platform.pendingIds.where(seriesIds.contains), isNotEmpty); + + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect(await _countRows(db, 'habits'), 0); + expect( + platform.pendingIds.where(seriesIds.contains), + isEmpty, + reason: 'soft-deleted habit rows are deleted by the reset as well', + ); + }); + + test('resetting habit data also retracts an inactive habit row', () async { + // A habit deactivated by a sync-inbound change keeps the reminders that were + // scheduled while it was active; the reset deletes that row too, so a + // capture filtering `is_active = 1` would leak those IDs. + final habit = _habitFixture('habit-reset-inactive'); + await _insertHabitRow(db, habit.id, active: false); + + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(habit); + + final seriesIds = _habitSeriesIds(habit.id); + expect(platform.pendingIds.where(seriesIds.contains), isNotEmpty); + + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect(await _countRows(db, 'habits'), 0); + expect( + platform.pendingIds.where(seriesIds.contains), + isEmpty, + reason: 'inactive habit rows are deleted by the reset as well', + ); + }); + + test('a stale reschedule batch cannot re-arm a habit the reset deleted', () async { + // Interleaving: rescheduleAll([A, B]) is already inside A when the reset + // deletes and cancels both habits. When A finishes, the batch advances to + // B; without a batch-epoch bump at bulk cancellation, scheduleForHabit(B) + // starts AFTER cancel(B), takes a fresh per-habit generation, and arms + // seven IDs for a habit that no longer exists (handoff addenda 2-3). + // + // B is pinned to zero pending IDs before the batch, while the batch is + // suspended, and after release, so a failure here identifies NEWLY ARMED B + // rather than A's already-proven reset orphan. The gate sits after the fake + // records A's final one-shot and before that call completes, and never + // holds a cancellation. + final habitA = _habitFixture('batch-stale-a'); + final habitB = _habitFixture('batch-stale-b'); + await _insertHabitRow(db, habitA.id); + await _insertHabitRow(db, habitB.id); + + final seriesA = _habitSeriesIds(habitA.id); + final seriesB = _habitSeriesIds(habitB.id); + expect( + seriesA.intersection(seriesB), + isEmpty, + reason: 'fixture habit IDs must not share a notification series', + ); + expect(platform.pendingIds.where(seriesA.contains), isEmpty); + expect(platform.pendingIds.where(seriesB.contains), isEmpty); + + final service = container.read(habitNotificationServiceProvider); + + // Gate on the last of A's seven daily one-shots (_dailyOccurrences - 1). + platform.gatedScheduleId = _habitBaseId(habitA.id) + 6; + platform.gateEntered = Completer(); + platform.gateReleased = Completer(); + + Object? drainFailure; + final batch = service.rescheduleAll([habitA, habitB]); + try { + try { + await platform.gateEntered!.future.timeout(_gateHoldTimeout); + } on TimeoutException { + fail( + 'the batch never reached the gated one-shot, so the interleaving ' + 'fixture is broken (not a fix result)', + ); + } + + // Suspended inside A: A armed, B has never been scheduled by anyone. + expect(platform.pendingIds.where(seriesA.contains), isNotEmpty); + expect(platform.pendingIds.where(seriesB.contains), isEmpty); + + // The real reset deletes both rows and cancels both series while the batch + // is still suspended inside A. + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect(await _countRows(db, 'habits'), 0); + expect( + platform.pendingIds.where(seriesB.contains), + isEmpty, + reason: 'reset-during-gate must leave B with no pending reminder', + ); + } finally { + // Always release the held platform call — even after a gate timeout, a + // throwing reset or a failed assertion — so no scheduled call stays + // suspended, then drain the batch under the bounded timeout. A drain + // failure is recorded and surfaced after the assertions below instead of + // masking an earlier one. + final released = platform.gateReleased; + if (released != null && !released.isCompleted) released.complete(); + try { + await batch.timeout(_batchDrainTimeout); + } catch (error) { + drainFailure = error; + } + } + + // Released in the finally block; the stale batch has now had its chance to + // advance into the deleted B. + + final armedB = platform.pendingIds + .where(seriesB.contains) + .toList() + .toString(); + expect( + platform.pendingIds.where(seriesB.contains), + isEmpty, + reason: + 'the stale batch armed B after the reset deleted and cancelled it: ' + 'pending=$armedB (series ${_habitBaseId(habitB.id)}..' + '${_habitBaseId(habitB.id) + _habitSeriesWidth - 1}). Bulk ' + 'cancellation must bump the batch epoch before any await, so a stale ' + 'list cannot start a later habit.', + ); + // Only meaningful once B's assertion passes: A is cancelled too. + expect(platform.pendingIds.where(seriesA.contains), isEmpty); + expect( + drainFailure, + isNull, + reason: + 'the stale batch did not finish cleanly within the drain timeout ' + 'after the gate was released: $drainFailure', + ); + }); + + test('habit reset leaves other notification namespaces pending', () async { + platform.seedForeignPending(_frontingId, 'prism:fronting:fixture'); + platform.seedForeignPending(_reminderId, 'prism:reminder:fixture'); + + final habit = _habitFixture('habit-reset-2'); + // Created up front so the attribution guard can include its owned series; + // the replacement is deliberately scheduled only after the reset. + final replacement = _habitFixture('habit-after-reset'); + await _insertHabitRow(db, habit.id); + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(habit); + + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect( + platform.pendingIds, + contains(_frontingId), + reason: 'fronting notifications are not habit-owned', + ); + expect( + platform.pendingIds, + contains(_reminderId), + reason: 'reminder notifications are not habit-owned', + ); + // No app-wide wipe, and no hard-bounded range: every cancellation must be + // attributable to the owned series of a habit this reset deleted (or of the + // replacement, which is the only habit scheduled after it). A series + // reaches base+29, so the top base legitimately owns IDs past 3_099_999. + final ownedSeries = { + ..._habitSeriesIds(habit.id), + ..._habitSeriesIds(replacement.id), + }; + for (final id in platform.cancelledIds) { + expect( + ownedSeries, + contains(id), + reason: + 'reset cancelled notification ID $id, which belongs to no habit ' + 'row this reset deleted; habit cleanup must be scoped to the owned ' + 'series of the captured habit IDs', + ); + } + expect( + platform.methods, + isNot( + anyOf(contains('cancelAll'), contains('cancelAllPendingNotifications')), + ), + ); + + // Active habits must keep scheduling normally after a habit reset. + await _insertHabitRow(db, replacement.id); + await service.scheduleForHabit(replacement); + expect( + platform.pendingIds.where(_habitSeriesIds(replacement.id).contains), + isNotEmpty, + reason: 'habit scheduling must still work after a reset', + ); + }); + + test('owned-ID attribution admits the real namespace upper edge', () { + // Review finding this guards: the service owns base..base+29, so an + // upper-edge habit is cancelled above 3_099_999. A hard + // 3_000_000..3_099_999 bound would reject that correct cancellation (and + // mask an over-cancel in the same 29-ID tail), so attribution is by owned + // series. This is pure arithmetic: no hashing, no scan, no unbounded loop. + const topBase = _habitIdBase + _habitIdMod - 1; // 3_099_999 + final owned = _ownedSeries(topBase); + + expect(owned, hasLength(_habitSeriesWidth)); + expect(owned, contains(3_100_028)); + expect( + owned.where((id) => id > topBase), + isNotEmpty, + reason: 'a hard 3_099_999 bound would reject IDs this habit really owns', + ); + // The tail still stays clear of the other subsystems' namespaces. + expect(owned, isNot(contains(_frontingId))); + expect(owned, isNot(contains(_reminderId))); + }); + + test('a failed reminder cancel reports the delete truthfully', () async { + final habitA = _habitFixture('cancel-failure-a'); + final habitB = _habitFixture('cancel-failure-b'); + await _insertHabitRow(db, habitA.id); + await _insertHabitRow(db, habitB.id); + + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(habitA); + await service.scheduleForHabit(habitB); + + final seriesA = _habitSeriesIds(habitA.id); + final seriesB = _habitSeriesIds(habitB.id); + expect( + seriesA.intersection(seriesB), + isEmpty, + reason: 'fixture habit IDs must not share a notification series', + ); + expect(platform.pendingIds.where(seriesA.contains), hasLength(7)); + expect(platform.pendingIds.where(seriesB.contains), hasLength(7)); + + // Observers must still be told about the committed delete, even though the + // reminder cleanup below fails. + final emptied = Completer(); + final subscription = db.select(db.habits).watch().listen((rows) { + if (rows.isEmpty && !emptied.isCompleted) emptied.complete(); + }); + addTearDown(subscription.cancel); + + // Every cancellation for A fails; B's succeed. + platform.failCancelIds = seriesA; + platform.calls.clear(); + + Object? resetError; + try { + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + } catch (error) { + resetError = error; + } + + // Truthful non-success, with no habit names or IDs in the message. + expect( + resetError, + isNotNull, + reason: 'a failed reminder cancel must not report a clean success', + ); + final message = resetError.toString(); + expect(message.toLowerCase(), contains('deleted')); + expect(message.toLowerCase(), contains('may still fire')); + expect(message, isNot(contains(habitA.id))); + expect(message, isNot(contains(habitB.id))); + expect(message, isNot(contains('${_habitBaseId(habitA.id)}'))); + expect(message, isNot(contains('${_habitBaseId(habitB.id)}'))); + // The existing AsyncError route carries the failure as well. + expect(container.read(resetDataNotifierProvider).hasError, isTrue); + + // The delete is committed and observers saw it. + expect(await _countRows(db, 'habits'), 0); + await emptied.future.timeout(const Duration(seconds: 5)); + + // Every ID was attempted: B's series is gone, A's could not be retracted. + expect( + platform.cancelledIds.where(seriesA.contains).toSet(), + hasLength(_habitSeriesWidth), + reason: 'every ID of the failing habit must be attempted', + ); + expect( + platform.cancelledIds.where(seriesB.contains).toSet(), + hasLength(_habitSeriesWidth), + reason: 'a failure on one habit must not strand another', + ); + expect( + platform.pendingIds.where(seriesB.contains), + isEmpty, + reason: 'B was cancelled successfully and must not linger', + ); + expect( + platform.pendingIds.where(seriesA.contains), + isNotEmpty, + reason: 'A could not be cancelled, which is why the error must say so', + ); + }); + + test( + 'a failed reset transaction cancels nothing and loses no data', + () async { + final failingDb = _FailingTransactionDatabase(); + addTearDown(failingDb.close); + final failingContainer = ProviderContainer( + overrides: [ + databaseProvider.overrideWithValue(failingDb), + localeOverrideProvider.overrideWithValue(null), + ], + ); + addTearDown(failingContainer.dispose); + await failingContainer.read(resetDataNotifierProvider.future); + + final habit = _habitFixture('transaction-failure'); + await _insertHabitRow(failingDb, habit.id); + final seriesIds = _habitSeriesIds(habit.id); + await failingContainer + .read(habitNotificationServiceProvider) + .scheduleForHabit(habit); + expect(platform.pendingIds.where(seriesIds.contains), hasLength(7)); + + platform.calls.clear(); + Object? resetError; + try { + await failingContainer + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + } catch (error) { + resetError = error; + } + + // The transaction failure surfaces as itself, is not masked by a cancel + // failure, and nothing was cancelled or deleted. + expect(resetError, isA()); + expect(resetError.toString(), contains('synthetic transaction failure')); + expect( + platform.cancelledIds, + isEmpty, + reason: 'a transaction that never committed must cancel nothing', + ); + expect(platform.pendingIds.where(seriesIds.contains), hasLength(7)); + expect(await _countRows(failingDb, 'habits'), 1); + }, + ); + + test( + 'ordinary per-habit cancellation leaves another habit scheduled', + () async { + final habitA = _habitFixture('per-habit-a'); + final habitB = _habitFixture('per-habit-b'); + await _insertHabitRow(db, habitA.id); + await _insertHabitRow(db, habitB.id); + + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(habitA); + await service.scheduleForHabit(habitB); + expect( + _habitSeriesIds(habitA.id).intersection(_habitSeriesIds(habitB.id)), + isEmpty, + reason: 'fixture habit IDs must not share a notification series', + ); + + // The cancellation the ordinary per-habit delete route performs before it + // removes the row (habit_providers.dart `deleteHabit`). + await service.cancelForHabit(habitA.id); + + expect( + platform.pendingIds.where(_habitSeriesIds(habitA.id).contains), + isEmpty, + ); + expect( + platform.pendingIds.where(_habitSeriesIds(habitB.id).contains), + hasLength(7), + reason: 'cancelling one habit must not touch another active habit', + ); + }, + ); + + test('habit scheduling still works after a successful reset', () async { + final removed = _habitFixture('post-reset-removed'); + await _insertHabitRow(db, removed.id); + + final service = container.read(habitNotificationServiceProvider); + await service.scheduleForHabit(removed); + expect( + platform.pendingIds.where(_habitSeriesIds(removed.id).contains), + hasLength(7), + ); + + await container + .read(resetDataNotifierProvider.notifier) + .reset(ResetCategory.habits); + + expect(await _countRows(db, 'habits'), 0); + expect( + platform.pendingIds.where(_habitSeriesIds(removed.id).contains), + isEmpty, + reason: 'a successful reset retracts the removed habit reminders', + ); + + final fresh = _habitFixture('post-reset-fresh'); + expect( + _habitSeriesIds(removed.id).intersection(_habitSeriesIds(fresh.id)), + isEmpty, + reason: 'fixture habit IDs must not share a notification series', + ); + await _insertHabitRow(db, fresh.id); + await service.scheduleForHabit(fresh); + expect( + platform.pendingIds.where(_habitSeriesIds(fresh.id).contains), + hasLength(7), + reason: 'a successful reset must not disable habit scheduling', + ); + }); +} diff --git a/test/features/habits/widgets/habit_chip_compact_scale_test.dart b/test/features/habits/widgets/habit_chip_compact_scale_test.dart new file mode 100644 index 000000000..ab49afd22 --- /dev/null +++ b/test/features/habits/widgets/habit_chip_compact_scale_test.dart @@ -0,0 +1,435 @@ +// Compact HabitChip at a 320px window with a weekly-progress pill, a positive +// multi-digit streak pill and a ZWJ family icon, at the maximum and a nonlinear text +// scale, in both bundled faces. +// +// Desired behaviour (nothing here assumes the icon is several ems wide - the font +// decides that): +// * no layout error, i.e. the chip row does not overflow; +// * the glyph is painted at the requested size (no clamp, no ancestor shrink) and +// inside its completion target; +// * the completion target stays >= 44dp; +// * both pills are still painted, un-ellipsised, inside the chip; +// * the completion tap still fires onQuickComplete and the body tap onTap. +// +// Geometry note: the chip is pumped inside the padding chain it really lives in - +// the due container's 16dp horizontal padding and `_FullDueContent`'s 12dp +// (`today_habits_container.dart:238-239`, `:333-334`) - so at a 320dp window the chip +// has 264dp, not 320dp. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/habit.dart'; +import 'package:prism_plurality/domain/models/habit_completion.dart'; +import 'package:prism_plurality/features/habits/widgets/habit_chip.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_shapes.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/prism_pill.dart'; + +import '../../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// A ZWJ family sequence; how wide it renders is the font's decision. +const String _familyIcon = + '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'; + +final DateTime _baseDate = DateTime(2026, 4, 11); + +/// Monday 2026-04-06 and Wednesday 2026-04-08 fall inside `weeklyDays` below, so the +/// progress pill reads 2/3. +Habit _habit() => Habit( + id: 'h1', + name: 'Walk together', + icon: _familyIcon, + createdAt: _baseDate, + modifiedAt: _baseDate, + frequency: HabitFrequency.weekly, + weeklyDays: const [1, 3, 5], + currentStreak: 12, +); + +HabitCompletion _completion(DateTime at) => HabitCompletion( + id: 'c-${at.millisecondsSinceEpoch}', + habitId: 'h1', + completedAt: at, + createdAt: at, + modifiedAt: at, +); + +List _weeklyCompletions() => [ + _completion(DateTime(2026, 4, 6, 9)), + _completion(DateTime(2026, 4, 8, 9)), +]; + +/// A scaler that does not scale every size by one ratio. +class _NonlinearTextScaler extends TextScaler { + const _NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize <= 14 ? fontSize * 3.0 : fontSize * 1.6; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.0; + + @override + bool operator ==(Object other) => other is _NonlinearTextScaler; + + @override + int get hashCode => 0x68616231; // 'hab1' +} + +Widget _scope({ + required double system, + required double app, + required String fontFamily, + TextScaler? scalerOverride, + VoidCallback? onTap, + VoidCallback? onComplete, +}) { + final scaler = + scalerOverride ?? PrismTextScaler(TextScaler.linear(system), app); + return ProviderScope( + child: MaterialApp( + theme: ThemeData( + fontFamily: fontFamily, + fontFamilyFallback: const ['NotoColorEmoji'], + extensions: const [PrismShapes.rounded], + ), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: scaler), + child: child ?? const SizedBox.shrink(), + ), + home: Scaffold( + body: Padding( + // Production nesting: the due container's padding, then the full-due + // content's padding, so the chip has the width it really gets. + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: HabitChip( + habit: _habit(), + todayCompletions: const [], + weeklyCompletions: _weeklyCompletions(), + completed: false, + onTap: onTap, + onQuickComplete: onComplete == null + ? null + : () async => onComplete(), + ), + ), + ), + ), + ), + ); +} + +void useWindow(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +/// Asserts [inner] paints inside [outer]. +void expectPaintedInside( + WidgetTester tester, + Finder inner, + Finder outer, { + required String label, +}) { + final outerRect = tester.getRect(outer); + final innerRect = tester.getRect(inner); + expect( + innerRect.left, + greaterThanOrEqualTo(outerRect.left - 0.5), + reason: '$label: left edge ${innerRect.left} < ${outerRect.left}', + ); + expect( + innerRect.right, + lessThanOrEqualTo(outerRect.right + 0.5), + reason: '$label: right edge ${innerRect.right} > ${outerRect.right}', + ); + expect( + innerRect.top, + greaterThanOrEqualTo(outerRect.top - 0.5), + reason: '$label: top edge ${innerRect.top} < ${outerRect.top}', + ); + expect( + innerRect.bottom, + lessThanOrEqualTo(outerRect.bottom + 0.5), + reason: '$label: bottom edge ${innerRect.bottom} > ${outerRect.bottom}', + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + for (final (label, system, app, scalerOverride) + in <(String, double, double, TextScaler?)>[ + ('system 225% x Prism 150% = 3.375x', 2.25, 1.5, null), + ('nonlinear scaler', 1, 1, const _NonlinearTextScaler()), + ]) { + for (final fontFamily in ['Lexend', 'OpenDyslexic']) { + testWidgets( + 'compact chip keeps glyph, target and pills intact - $label / $fontFamily', + (tester) async { + useWindow(tester, const Size(320, 800)); + await tester.pumpWidget( + _scope( + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); + await tester.pumpAndSettle(); + + // No RenderFlex overflow anywhere in the chip. + final error = tester.takeException(); + expect( + error, + isNull, + reason: '$label / $fontFamily: layout reported "$error"', + ); + + final chip = find.byType(HabitChip); + final circle = find.byType(HabitLeadingCircle); + expect(chip, findsOneWidget); + expect(circle, findsOneWidget); + final target = tester.getSize(circle); + + // An accessible completion target, independent of the font's glyph width. + expect( + target.width, + greaterThanOrEqualTo(44), + reason: '$label / $fontFamily: completion target too narrow', + ); + expect( + target.height, + greaterThanOrEqualTo(44), + reason: '$label / $fontFamily: completion target too short', + ); + + // The glyph is the icon subtree's paragraph. + final icon = find.byKey( + const ValueKey('habit-chip-icon-$_familyIcon'), + ); + expect(icon, findsOneWidget); + final glyphFinder = find.descendant( + of: icon, + matching: find.byType(RichText), + ); + expect(glyphFinder, findsOneWidget); + final glyph = tester.renderObject(glyphFinder); + + // Painted at the requested size: not clamped, not ellipsised, and no + // ancestor (FittedBox and friends) shrinking the paint. + expect( + glyph.didExceedMaxLines, + isFalse, + reason: '$label / $fontFamily: the glyph was ellipsised', + ); + expect( + glyph.size.height, + greaterThanOrEqualTo( + glyph.getMaxIntrinsicHeight(glyph.size.width) - 0.5, + ), + reason: '$label / $fontFamily: the glyph was vertically clamped', + ); + expect( + glyph.getTransformTo(null).getMaxScaleOnAxis(), + closeTo(1.0, 0.02), + reason: '$label / $fontFamily: an ancestor scaled the glyph', + ); + // ...and it sits inside the completion target it belongs to. + expectPaintedInside( + tester, + glyphFinder, + circle, + label: 'glyph ($label / $fontFamily)', + ); + + // The metadata pills are still painted in full, inside the chip. + for (final text in ['2/3', '12']) { + final finder = find.text(text); + expect( + finder, + findsWidgets, + reason: '$text ($label / $fontFamily)', + ); + final paragraph = tester.renderObject( + find + .descendant( + of: find + .ancestor(of: finder, matching: find.byType(PrismPill)) + .first, + matching: find.byType(RichText), + ) + .first, + ); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: '$label / $fontFamily: "$text" was ellipsised', + ); + expectPaintedInside( + tester, + finder, + chip, + label: '$text ($label / $fontFamily)', + ); + } + }, + ); + } + } + + testWidgets('the metadata gap is the same inline and stacked (6dp)', ( + tester, + ) async { + // Inline at the default size: the two pills sit on the title's line. + useWindow(tester, const Size(320, 800)); + await tester.pumpWidget(_scope(system: 1, app: 1, fontFamily: 'Lexend')); + await tester.pumpAndSettle(); + + final pills = find.byType(PrismPill); + expect(pills, findsNWidgets(2)); + var gap = + tester.getRect(pills.at(1)).left - tester.getRect(pills.at(0)).right; + expect(gap, closeTo(6, 0.6), reason: 'inline gap between the two pills'); + expect( + tester.getCenter(pills.at(0)).dy, + closeTo(tester.getCenter(pills.at(1)).dy, 0.6), + reason: 'inline: both pills share one line', + ); + + // Stacked at the maximum scale: the wrap owns the gap, and it must be the same 6dp + // (the old build interleaved a 6dp spacer *and* asked the wrap for 6dp, so this read + // 18dp). + await tester.pumpWidget( + _scope(system: 2.25, app: 1.5, fontFamily: 'Lexend'), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: 'stacked layout must not overflow', + ); + final stacked = find.byType(PrismPill); + expect(stacked, findsNWidgets(2)); + final stacked0 = tester.getRect(stacked.at(0)); + final stacked1 = tester.getRect(stacked.at(1)); + if ((stacked1.left - stacked0.right).abs() < 100 && + (stacked1.top - stacked0.top).abs() < 0.6) { + gap = stacked1.left - stacked0.right; + expect(gap, closeTo(6, 0.6), reason: 'stacked gap between the two pills'); + } else { + // A very narrow wrap may put the second pill on its own run; the vertical gap is + // then the run spacing (2dp) and the horizontal gap is the same 6dp constant. + expect(stacked1.left, closeTo(stacked0.left, 0.6)); + } + }); + + testWidgets( + 'the pills are never shrunk to make them fit at the inline boundary', + (tester) async { + // Widths at and just under the point where the pills stop fitting beside the title at + // 1.5x: the layout may switch from inline to stacked between them, but the pill labels + // must never be shrunk, ellipsised or clipped to buy the fit. + for (final width in [320.0, 300.0, 280.0]) { + useWindow(tester, Size(width, 800)); + await tester.pumpWidget( + _scope(system: 1.5, app: 1, fontFamily: 'Lexend'), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$width: the chip must not overflow at the boundary', + ); + + final chipRect = tester.getRect(find.byType(HabitChip)); + for (final label in ['2/3', '12']) { + final paragraph = tester.renderObject( + find + .descendant( + of: find + .ancestor( + of: find.text(label), + matching: find.byType(PrismPill), + ) + .first, + matching: find.byType(RichText), + ) + .first, + ); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: '$width: "$label" was ellipsised to fit', + ); + expect( + paragraph.getTransformTo(null).getMaxScaleOnAxis(), + closeTo(1.0, 0.02), + reason: '$width: "$label" was scaled down to fit', + ); + final rect = tester.getRect(find.text(label)); + expect( + rect.right, + lessThanOrEqualTo(chipRect.right + 0.5), + reason: '$width: "$label" paints past the chip', + ); + } + } + }, + ); + + testWidgets('completion and detail taps still reach their own callbacks', ( + tester, + ) async { + useWindow(tester, const Size(320, 800)); + var completions = 0; + var details = 0; + await tester.pumpWidget( + _scope( + system: 2.25, + app: 1.5, + fontFamily: 'Lexend', + onTap: () => details++, + onComplete: () => completions++, + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(HabitLeadingCircle)); + await tester.pumpAndSettle(); + expect( + completions, + 1, + reason: 'the completion tap must fire onQuickComplete', + ); + expect( + details, + 0, + reason: 'the completion tap must not open the detail view', + ); + + await tester.tap(find.text('Walk together')); + await tester.pumpAndSettle(); + expect(details, 1, reason: 'the body tap must still open the detail view'); + expect(completions, 1, reason: 'the body tap must not toggle completion'); + }); +} diff --git a/test/features/members/views/member_detail_navigation_test.dart b/test/features/members/views/member_detail_navigation_test.dart index 78e3222bf..01fbda7f1 100644 --- a/test/features/members/views/member_detail_navigation_test.dart +++ b/test/features/members/views/member_detail_navigation_test.dart @@ -442,14 +442,27 @@ void main() { expect(resolved, isA>()); expect(resolved.value, alice); expect(find.byType(MemberProfileHeader), findsOneWidget); - expect(find.text('Pronouns'), findsOneWidget); - final detail = find.byWidgetPredicate( - (widget) => - widget is FieldInlineMarkdownText && widget.data == pronouns, + // Exactly one pronoun display: the header capsule. The separate + // "Pronouns" label block under the header is gone. + expect(find.text('Pronouns'), findsNothing); + final capsule = find.byKey(memberProfilePronounsCapsuleKey); + expect(capsule, findsOneWidget); + final detail = find.descendant( + of: capsule, + matching: find.byWidgetPredicate( + (widget) => + widget is FieldInlineMarkdownText && widget.data == pronouns, + ), ); expect(detail, findsOneWidget); + // Nothing outside the capsule renders the field renderer for pronouns. + expect( + find.byType(FieldInlineMarkdownText), + findsOneWidget, + reason: 'the header capsule must be the only pronoun display', + ); final texts = tester.widgetList( - find.descendant(of: detail, matching: find.byType(RichText)), + find.descendant(of: capsule, matching: find.byType(RichText)), ); expect(texts, isNotEmpty); final rendered = texts.map((text) => text.text.toPlainText()).join(); diff --git a/test/features/members/widgets/field_inline_markdown_text_test.dart b/test/features/members/widgets/field_inline_markdown_text_test.dart index 105290f67..ccec66cc0 100644 --- a/test/features/members/widgets/field_inline_markdown_text_test.dart +++ b/test/features/members/widgets/field_inline_markdown_text_test.dart @@ -1,12 +1,24 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:prism_plurality/core/router/app_routes.dart'; +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/database/database_providers.dart'; +import '../../../helpers/fake_repositories.dart'; import 'package:prism_plurality/domain/models/member.dart'; import 'package:prism_plurality/features/members/providers/members_providers.dart'; import 'package:prism_plurality/features/members/widgets/custom_field_display_widgets.dart'; import 'package:prism_plurality/shared/markdown/spoiler_syntax.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/domain/preferences/member_name_presentation.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; void main() { const urlLauncherChannel = MethodChannel('plugins.flutter.io/url_launcher'); @@ -25,6 +37,19 @@ void main() { child: MaterialApp(home: Scaffold(body: FieldInlineMarkdownText(data))), ); + /// Same host, but with an explicit block alignment so a `null` opt-in can be + /// compared against the widget's default. + Widget hostWithAlignment(String data, TextAlign? textAlign) => ProviderScope( + overrides: [ + activeMemberListProvider.overrideWith( + (ref) => Stream.value(const []), + ), + ], + child: MaterialApp( + home: Scaffold(body: FieldInlineMarkdownText(data, textAlign: textAlign)), + ), + ); + List spoilerOpacities(WidgetTester tester) => tester .widgetList(find.byType(AnimatedOpacity)) .map((w) => w.opacity) @@ -369,4 +394,390 @@ void main() { ); }, ); + + // ------------------------------------------------------------------------- + // Block alignment (fit-content opt-in) tests + // ------------------------------------------------------------------------- + + testWidgets('default alignment keeps blocks at the available width', ( + tester, + ) async { + const data = '# heading\n\nthey/them'; + await tester.pumpWidget(host(data)); + + final field = tester.widget( + find.byType(FieldInlineMarkdownText), + ); + // Existing callers keep the start alignment and full-width block layout. + expect(field.textAlign, TextAlign.start); + expect(tester.getSize(find.byType(Wrap).first).width, greaterThan(700)); + }); + + testWidgets('null alignment opts into fit-content so blocks hug', ( + tester, + ) async { + const data = '# heading\n\nthey/them'; + await tester.pumpWidget(hostWithAlignment(data, null)); + + final field = tester.widget( + find.byType(FieldInlineMarkdownText), + ); + expect(field.textAlign, isNull); + // Opt-in: the block container hugs its text instead of filling the width. + expect(tester.getSize(find.byType(Wrap).first).width, lessThan(400)); + }); + + group('custom field value at extreme text scale', () { + testWidgets('grows at 3.375x and keeps its mention tappable', ( + tester, + ) async { + const bobId = '99999999-8888-7777-6666-555555555555'; + final bob = Member(id: bobId, name: 'Bob', createdAt: DateTime(2026)); + const data = 'we met @[$bobId] at the market and talked for a while'; + + // A 1x baseline in the same host, so growth is measured against this + // value rather than against a hard-coded line height. + await _pumpFieldInRouter(tester, data, members: [bob]); + final baseHeight = tester + .getSize(find.byType(FieldInlineMarkdownText)) + .height; + final baseRect = _mentionSelectionRect( + tester, + find.textContaining('@Bob'), + '@Bob', + ); + + // Direct linear 3.375x is equivalent at every size to the production + // composition PrismTextScaler(TextScaler.linear(2.25), 1.5). The separate + // nonlinear case checks that composition cannot generally be reduced + // to one scale factor when the platform curve varies per font size. + final pushedMemberIds = await _pumpFieldInRouter( + tester, + data, + members: [bob], + textScaler: const TextScaler.linear(3.375), + ); + + final field = find.byType(FieldInlineMarkdownText); + final bodySize = + Theme.of(tester.element(field)).textTheme.bodyMedium?.fontSize ?? 14; + final scaler = MediaQuery.textScalerOf(tester.element(field)); + expect( + scaler.scale(bodySize), + closeTo(bodySize * 3.375, 0.001), + reason: 'the field itself, not an ancestor wrapper, sees 3.375x', + ); + + // The value grows onto several lines instead of clipping to one. + final scaledHeight = tester.getSize(field).height; + expect(scaledHeight, greaterThan(baseHeight)); + expect( + scaledHeight, + greaterThan(scaler.scale(bodySize) * 2), + reason: 'a 3.375x value must occupy several lines of the field', + ); + + // The authored text survives and the raw mention token never leaks. + final richTexts = tester + .widgetList( + find.descendant(of: field, matching: find.byType(RichText)), + ) + .toList(); + final rendered = richTexts + .map((richText) => richText.text.toPlainText()) + .join(); + expect(rendered, contains('we met')); + expect(rendered, contains('talked for a while')); + expect(rendered, contains('@Bob')); + expect(rendered, isNot(contains('@[$bobId]'))); + for (final richText in richTexts) { + expect(richText.maxLines, isNull); + expect(richText.overflow, isNot(TextOverflow.ellipsis)); + } + + final mention = find.textContaining('@Bob'); + expect(mention, findsOneWidget); + expect( + tester + .renderObject(mention) + .textScaler + .scale(bodySize), + closeTo(bodySize * 3.375, 0.001), + reason: 'the mention paragraph layout uses the same scaler', + ); + final rect = _mentionSelectionRect(tester, mention, '@Bob'); + expect( + rect.height / baseRect.height, + closeTo(3.375, 3.375 * 0.1), + reason: + 'the mention selection-run box layout box must scale, not just its parent', + ); + final fieldRect = tester.getRect(field); + expect( + fieldRect.contains(rect.center), + isTrue, + reason: 'the mention selection-run point must be inside the field', + ); + expect(rect.right, lessThanOrEqualTo(fieldRect.right + 0.5)); + + await _tapMentionSelection(tester, mention, '@Bob'); + + expect(pushedMemberIds, [bobId]); + expect(find.text('member-$bobId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('taps the second mention of a wrapped value, not the first', ( + tester, + ) async { + const bobId = '99999999-8888-7777-6666-555555555555'; + const caraId = '77777777-1111-2222-3333-444444444444'; + final bob = Member(id: bobId, name: 'Bob', createdAt: DateTime(2026)); + final cara = Member(id: caraId, name: 'Cara', createdAt: DateTime(2026)); + const data = '@[$bobId] and @[$caraId] were both at the market'; + + final pushedMemberIds = await _pumpFieldInRouter( + tester, + data, + members: [bob, cara], + textScaler: const TextScaler.linear(3.375), + ); + + // Both labels resolve from the real member list, so neither tap can pass + // through an unresolved 'Unknown' mention. + expect(find.text('@Bob'), findsOneWidget); + expect(find.text('@Cara'), findsOneWidget); + final bobRect = _mentionSelectionRect(tester, find.text('@Bob'), '@Bob'); + final caraRect = _mentionSelectionRect( + tester, + find.text('@Cara'), + '@Cara', + ); + expect(caraRect.center, isNot(bobRect.center)); + expect( + caraRect.top, + greaterThan(bobRect.top + 0.5), + reason: 'this second-mention case must exercise distinct wrapped runs', + ); + + await _tapMentionSelection(tester, find.text('@Cara'), '@Cara'); + + expect(pushedMemberIds, [caraId]); + expect(find.text('member-$caraId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('grows and stays tappable under the composed scaler', ( + tester, + ) async { + const bobId = '99999999-8888-7777-6666-555555555555'; + final bob = Member(id: bobId, name: 'Bob', createdAt: DateTime(2026)); + const data = 'we met @[$bobId] at the market and talked for a while'; + // PrismTextScaler(platform scaler, font-size factor) is what app.dart + // installs; with a nonlinear platform curve the composition is not a + // single factor: 3x at 14 pt and 2.1x at 24 pt. + const composedScaler = PrismTextScaler(_StepNonlinearTextScaler(), 1.5); + + await _pumpFieldInRouter(tester, data, members: [bob]); + final baseHeight = tester + .getSize(find.byType(FieldInlineMarkdownText)) + .height; + + final pushedMemberIds = await _pumpFieldInRouter( + tester, + data, + members: [bob], + textScaler: composedScaler, + ); + + final field = find.byType(FieldInlineMarkdownText); + final scaler = MediaQuery.textScalerOf(tester.element(field)); + expect(scaler, composedScaler); + expect(scaler.scale(14), closeTo(42, 0.001)); + expect(scaler.scale(24), closeTo(50.4, 0.001)); + expect( + scaler.scale(24), + lessThan(24 * scaler.scale(14) / 14), + reason: 'the composed provider scaler is nonlinear, not a flat ratio', + ); + + final scaledHeight = tester.getSize(field).height; + expect(scaledHeight, greaterThan(baseHeight)); + expect( + scaledHeight, + greaterThan(scaler.scale(14) * 2), + reason: 'the composed 42 pt body role must wrap onto several lines', + ); + + final mention = find.textContaining('@Bob'); + expect(mention, findsOneWidget); + expect( + tester.renderObject(mention).textScaler, + composedScaler, + ); + + await _tapMentionSelection(tester, mention, '@Bob'); + + expect(pushedMemberIds, [bobId]); + expect(find.text('member-$bobId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + }); +} + +/// The selection-run layout box of [label] inside the mention matched by [mention], in +/// global coordinates. +/// These are selection/layout bounds, not raster glyph-ink measurements. +/// Bundled-font painting is not covered by this default-test-font fixture. +/// +/// The mention builder emits its label as its own `Text.rich`, so that +/// paragraph holds exactly the label and its selection boxes locate a point for a real pointer +/// tap. The enclosing paragraph's centre would land on other text in the +/// value. +Rect _mentionSelectionRect(WidgetTester tester, Finder mention, String label) { + final paragraph = tester.renderObject(mention); + final start = paragraph.text.toPlainText().indexOf(label); + expect( + start, + isNonNegative, + reason: '$label must belong to its mention paragraph', + ); + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: start, extentOffset: start + label.length), + ); + expect(boxes, isNotEmpty, reason: '$label must have selection boxes'); + final local = boxes.first.toRect(); + return Rect.fromPoints( + paragraph.localToGlobal(local.topLeft), + paragraph.localToGlobal(local.bottomRight), + ); +} + +/// Scrolls [mention] into view and taps the centre of its [label] selection-run box. +Future _tapMentionSelection( + WidgetTester tester, + Finder mention, + String label, +) async { + await tester.ensureVisible(mention); + await tester.pump(); + final point = _mentionSelectionRect(tester, mention, label).center; + final paragraph = tester.renderObject(mention); + expect( + tester + .hitTestOnBinding(point) + .path + .any((entry) => identical(entry.target, paragraph)), + isTrue, + reason: 'the selected mention layout point must hit its real paragraph', + ); + await tester.tapAt(point); + await tester.pumpAndSettle(); +} + +/// Pumps a custom field value the way the member detail page shows it — +/// inside a real router and a scrollable column, at [textScaler] — and returns +/// the member ids its mention taps pushed. +Future> _pumpFieldInRouter( + WidgetTester tester, + String data, { + List members = const [], + TextScaler textScaler = TextScaler.noScaling, + double width = 390, +}) async { + final pushedMemberIds = []; + final router = GoRouter( + initialLocation: '/', + routes: [ + GoRoute( + path: '/', + builder: (_, _) => Scaffold( + body: SingleChildScrollView( + child: SizedBox(width: width, child: FieldInlineMarkdownText(data)), + ), + ), + ), + GoRoute( + path: AppRoutePaths.members, + builder: (_, _) => const Scaffold(body: Text('members')), + routes: [ + GoRoute( + path: ':id', + builder: (_, state) { + final id = state.pathParameters['id']!; + pushedMemberIds.add(id); + return Scaffold(body: Text('member-$id')); + }, + ), + ], + ), + ], + ); + final appPrefs = FakeAppPreferenceRepository(); + var databaseReads = 0; + addTearDown(() async { + // ProviderScope owns its container: unmounting cancels its subscriptions + // before the router and the fake preference stream controllers are closed. + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + router.dispose(); + await tester.runAsync( + () => appPrefs.close().timeout(const Duration(seconds: 5)), + ); + // AsyncValue fallback must not mask an accidental DB-provider read. + expect( + databaseReads, + 0, + reason: 'this fixture must never read the real DB', + ); + }); + + await tester.pumpWidget( + ProviderScope( + // A fresh owned container for each baseline/scaled pump, not an override + // update on the previous fixture's container. + key: UniqueKey(), + overrides: [ + memberNamePreferDisplayProvider.overrideWithValue(true), + memberNamePresentationProvider.overrideWithValue( + MemberNamePresentation.fullName, + ), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + frontingTermsSettingProvider.overrideWithValue(null), + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + databaseProvider.overrideWith((ref) { + databaseReads += 1; + throw StateError( + 'Pronoun regression fixtures must not open a database', + ); + }), + activeMemberListProvider.overrideWith((ref) => Stream.value(members)), + ], + child: MaterialApp.router( + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + routerConfig: router, + ), + ), + ); + await tester.pumpAndSettle(); + return pushedMemberIds; +} + +/// A platform-like nonlinear scaler: it reports 1.5, doubles body sizes and +/// grows larger sizes by 1.4, the way a nonlinear accessibility curve does. +class _StepNonlinearTextScaler extends TextScaler { + const _StepNonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 2 : fontSize * 1.4; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.5; } diff --git a/test/features/members/widgets/member_profile_header_pronouns_test.dart b/test/features/members/widgets/member_profile_header_pronouns_test.dart new file mode 100644 index 000000000..22102f411 --- /dev/null +++ b/test/features/members/widgets/member_profile_header_pronouns_test.dart @@ -0,0 +1,1082 @@ +import 'dart:convert'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/core/router/app_routes.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/members/widgets/custom_field_display_widgets.dart'; +import 'package:prism_plurality/features/members/widgets/member_profile_header.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/theme/prism_shapes.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/domain/preferences/member_name_presentation.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; +import 'package:prism_plurality/shared/widgets/member_avatar.dart'; + +import '../../../helpers/fake_repositories.dart'; + +final Uint8List _pngBytes = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lB0Q9wAAAABJRU5ErkJggg==', +); + +const String _aliceId = '11111111-2222-3333-4444-555555555555'; +const String _bobId = '99999999-8888-7777-6666-555555555555'; + +// Text sizes used by the layout policy tests: the phone body-medium role is +// 14, so 15 em is 210 pt at 1x, 315 pt at 1.5x and 420 pt at 2x. +const double _wideHeader = 390; // 390 pt phone minus the 24 pt page padding +const double _narrowHeader = 272; // 320 pt phone minus the page padding + +Member _member({ + String id = _aliceId, + String name = 'Alice', + String? displayName, + String? pronouns, + String? age, + String? birthday, + Uint8List? headerImage, + Uint8List? avatarImage, + MemberProfileHeaderLayout layout = + MemberProfileHeaderLayout.compactBackground, + MemberProfileHeaderSource source = MemberProfileHeaderSource.prism, + bool headerVisible = true, + bool isAdmin = false, + bool isActive = true, + MemberNameFont nameStyleFont = MemberNameFont.standard, + bool nameStyleItalic = false, +}) => Member( + id: id, + name: name, + displayName: displayName, + emoji: '*', + age: age, + birthday: birthday, + pronouns: pronouns, + createdAt: DateTime(2026, 4, 1), + avatarImageData: avatarImage, + isAdmin: isAdmin, + isActive: isActive, + nameStyleFont: nameStyleFont, + nameStyleItalic: nameStyleItalic, + profileHeaderSource: source, + profileHeaderLayout: layout, + profileHeaderVisible: headerVisible, + profileHeaderImageData: headerImage, +); + +/// A scaler that behaves like Android's nonlinear scaling: reported factor 1.5, +/// but the body role (14) really scales to 2x while larger sizes scale less. +class _NonlinearTextScaler extends TextScaler { + const _NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 2 : fontSize * 1.4; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.5; +} + +/// Pumps a header inside a fixed-width column so layout assertions do not depend +/// on the test surface size. +Future _pumpHeader( + WidgetTester tester, + Member member, { + double width = _wideHeader, + TextScaler textScaler = TextScaler.noScaling, + TextDirection textDirection = TextDirection.ltr, + ThemeData? theme, + bool isFronting = false, + List mentionMembers = const [], + VoidCallback? onAvatarTap, + VoidCallback? onAvatarRemove, + VoidCallback? onNameStyleTap, +}) async { + final appPrefs = FakeAppPreferenceRepository(); + addTearDown(() async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + await tester.runAsync( + () => appPrefs.close().timeout(const Duration(seconds: 5)), + ); + }); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + databaseProvider.overrideWith((ref) { + throw StateError('Pronoun header tests must not open a database'); + }), + if (mentionMembers.isNotEmpty) + activeMemberListProvider.overrideWith( + (ref) => Stream.value(mentionMembers), + ), + ], + child: MaterialApp( + theme: theme, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + home: Directionality( + textDirection: textDirection, + child: Scaffold( + body: SingleChildScrollView( + child: SizedBox( + width: width, + child: MemberProfileHeader( + member: member, + isFronting: isFronting, + onAvatarTap: onAvatarTap, + onAvatarRemove: onAvatarRemove, + onNameStyleTap: onNameStyleTap, + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); +} + +final Finder _capsule = find.byKey(memberProfilePronounsCapsuleKey); + +Finder _insideCapsule(Finder matching) => + find.descendant(of: _capsule, matching: matching); + +/// Every RichText painted inside [root], so assertions read what the header +/// really renders rather than the raw markdown source. +List _richTexts(WidgetTester tester, Finder root) => tester + .widgetList( + find.descendant(of: root, matching: find.byType(RichText)), + ) + .toList(); + +List _textSpans(WidgetTester tester, Finder root) { + final spans = []; + for (final richText in _richTexts(tester, root)) { + richText.text.visitChildren((span) { + if (span is TextSpan && (span.text?.isNotEmpty ?? false)) { + spans.add(span); + } + return true; + }); + } + return spans; +} + +String _renderedText(WidgetTester tester, Finder root) => _richTexts( + tester, + root, +).map((richText) => richText.text.toPlainText()).join(); + +String _collapsed(String value) => value.replaceAll(RegExp(r'\s+'), ' ').trim(); + +double _bodyMediumSize(WidgetTester tester) => + Theme.of( + tester.element(find.byType(MemberProfileHeader)), + ).textTheme.bodyMedium?.fontSize ?? + 14; + +/// The header's title role size, resolved the way the widget resolves it, so a +/// scaler assertion reads the role the name uses for layout. +double _titleSize(WidgetTester tester) => + Theme.of( + tester.element(find.byType(MemberProfileHeader)), + ).textTheme.headlineSmall?.fontSize ?? + 24; + +/// The selection-run layout box of [label] inside the mention matched by [mention], in +/// global coordinates. +/// These are selection/layout bounds, not raster glyph-ink measurements. +/// Bundled-font painting is not covered by this default-test-font fixture. +/// +/// The mention builder emits its label as its own `Text.rich`, so that paragraph +/// holds exactly the label and its selection boxes locate a point for a real pointer tap. The +/// enclosing paragraph's centre lands on the pronoun text instead, which never +/// reaches the mention's recognizer. +Rect _mentionSelectionRect(WidgetTester tester, Finder mention, String label) { + final paragraph = tester.renderObject(mention); + final start = paragraph.text.toPlainText().indexOf(label); + expect( + start, + isNonNegative, + reason: '$label must belong to its mention paragraph', + ); + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: start, extentOffset: start + label.length), + ); + expect(boxes, isNotEmpty, reason: '$label must have selection boxes'); + final local = boxes.first.toRect(); + return Rect.fromPoints( + paragraph.localToGlobal(local.topLeft), + paragraph.localToGlobal(local.bottomRight), + ); +} + +/// Scrolls [mention] into view and taps the centre of its [label] selection-run box. +Future _tapMentionSelection( + WidgetTester tester, + Finder mention, + String label, +) async { + await tester.ensureVisible(mention); + await tester.pump(); + final point = _mentionSelectionRect(tester, mention, label).center; + final paragraph = tester.renderObject(mention); + expect( + tester + .hitTestOnBinding(point) + .path + .any((entry) => identical(entry.target, paragraph)), + isTrue, + reason: 'the selected mention layout point must hit its real paragraph', + ); + await tester.tapAt(point); + await tester.pumpAndSettle(); +} + +/// Pumps a header the way the member profile page hosts it — behind a real +/// router, in a scrollable column, at [textScaler] — and returns the member ids +/// its mention taps pushed. +Future> _pumpHeaderInRouter( + WidgetTester tester, + Member member, { + required List mentionMembers, + TextScaler textScaler = TextScaler.noScaling, + double width = _wideHeader, +}) async { + final pushedMemberIds = []; + final router = GoRouter( + initialLocation: '/', + routes: [ + GoRoute( + path: '/', + builder: (_, _) => Scaffold( + body: SingleChildScrollView( + child: SizedBox( + width: width, + child: MemberProfileHeader(member: member), + ), + ), + ), + ), + GoRoute( + path: AppRoutePaths.members, + builder: (_, _) => const Scaffold(body: Text('members')), + routes: [ + GoRoute( + path: ':id', + builder: (_, state) { + final id = state.pathParameters['id']!; + pushedMemberIds.add(id); + return Scaffold(body: Text('member-$id')); + }, + ), + ], + ), + ], + ); + final appPrefs = FakeAppPreferenceRepository(); + var databaseReads = 0; + addTearDown(() async { + // ProviderScope owns its container: unmounting cancels its subscriptions + // before the router and the fake preference stream controllers are closed. + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + router.dispose(); + await tester.runAsync( + () => appPrefs.close().timeout(const Duration(seconds: 5)), + ); + // AsyncValue fallback must not mask an accidental DB-provider read. + expect( + databaseReads, + 0, + reason: 'this fixture must never read the real DB', + ); + }); + + await tester.pumpWidget( + ProviderScope( + // A fresh owned container for each baseline/scaled pump, not an override + // update on the previous fixture's container. + key: UniqueKey(), + overrides: [ + memberNamePreferDisplayProvider.overrideWithValue(true), + memberNamePresentationProvider.overrideWithValue( + MemberNamePresentation.fullName, + ), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + frontingTermsSettingProvider.overrideWithValue(null), + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + databaseProvider.overrideWith((ref) { + databaseReads += 1; + throw StateError( + 'Pronoun regression fixtures must not open a database', + ); + }), + activeMemberListProvider.overrideWith( + (ref) => Stream.value(mentionMembers), + ), + ], + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + routerConfig: router, + ), + ), + ); + await tester.pumpAndSettle(); + return pushedMemberIds; +} + +void main() { + group('pronoun capsule', () { + testWidgets('shows the string once at body-medium under the name', ( + tester, + ) async { + const pronouns = 'they/them'; + await _pumpHeader(tester, _member(pronouns: pronouns)); + + expect(_capsule, findsOneWidget); + // Rendered text is the pronoun string itself, not raw markdown. + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect(find.text(pronouns), findsOneWidget); + // The name line keeps the name only: no inline `` · pronouns`` suffix. + expect(find.text('Alice'), findsOneWidget); + + final spans = _textSpans(tester, _capsule); + expect(spans, isNotEmpty); + expect(spans.first.style?.fontSize, _bodyMediumSize(tester)); + expect(spans.first.style?.fontWeight, FontWeight.w500); + + for (final richText in _richTexts(tester, _capsule)) { + expect(richText.maxLines, isNull); + expect(richText.overflow, isNot(TextOverflow.ellipsis)); + } + expect(_insideCapsule(find.byType(FittedBox)), findsNothing); + + // The capsule sits under the name, not on the name line. + expect( + tester.getRect(_capsule).top, + greaterThanOrEqualTo(tester.getRect(find.text('Alice')).bottom), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'keeps short pronouns beside the avatar as a single-line pill', + (tester) async { + await _pumpHeader(tester, _member(pronouns: 'she/her')); + + final avatar = tester.getRect(find.byType(MemberAvatar)); + final capsule = tester.getRect(_capsule); + expect(capsule.left, greaterThanOrEqualTo(avatar.right + 15)); + // Still inside the avatar column, so narrower than the column itself. + expect(capsule.width, lessThan(_wideHeader - 80 - 16)); + // One line of body-medium plus the 6 pt vertical padding on each side. + expect(capsule.height, lessThan(_bodyMediumSize(tester) * 2 + 14)); + }, + ); + + testWidgets('grows a long list beside the avatar without truncation', ( + tester, + ) async { + const pronouns = + 'She/Her, Sae/Saers, Lace/Laces, Bliss/Blissful, Pure/Pures'; + await _pumpHeader(tester, _member(pronouns: 'she/her')); + final shortHeight = tester.getSize(_capsule).height; + + await _pumpHeader(tester, _member(pronouns: pronouns)); + + final avatar = tester.getRect(find.byType(MemberAvatar)); + final capsule = tester.getRect(_capsule); + expect(capsule.left, greaterThanOrEqualTo(avatar.right + 15)); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + expect(capsule.height, greaterThan(shortHeight)); + for (final richText in _richTexts(tester, _capsule)) { + expect(richText.maxLines, isNull); + expect(richText.overflow, isNot(TextOverflow.ellipsis)); + } + expect(tester.takeException(), isNull); + }); + + testWidgets('grows a very long list instead of clipping it', ( + tester, + ) async { + const pronouns = + 'she/her, they/them, xe/xem, ze/zir, fae/faer, it/its, ae/aer, ' + 'co/cos, ve/ver, e/em, per/per, thy/thym, hu/hum, ne/nem, ' + 'vi/vim, ey/em, sie/hir, he/him, one/ones, any/all'; + await _pumpHeader(tester, _member(pronouns: pronouns)); + + expect(_capsule, findsOneWidget); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + final size = tester.getSize(_capsule); + expect(size.width, lessThanOrEqualTo(_wideHeader + 0.01)); + // Many wrapped lines, not one clipped line. + expect(size.height, greaterThan(_bodyMediumSize(tester) * 4)); + expect(tester.takeException(), isNull); + }); + + testWidgets('preserves emoji, ZWJ sequences and authored order', ( + tester, + ) async { + const pronouns = 'they/them 🧑🏽‍🚀 🏳️‍🌈 ze/zie'; + await _pumpHeader(tester, _member(pronouns: pronouns)); + + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + expect(tester.takeException(), isNull); + }); + + testWidgets('reuses the field renderer for formatting and mentions', ( + tester, + ) async { + final bob = _member(id: _bobId, name: 'Bob'); + const pronouns = 'they/them **bold** @[$_bobId]'; + await _pumpHeader( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + ); + // Let the member stream deliver so the mention resolves to its label. + await tester.pumpAndSettle(); + + // One shared renderer, inside the capsule, reading the stored string. + final fieldText = _insideCapsule( + find.byWidgetPredicate( + (widget) => + widget is FieldInlineMarkdownText && widget.data == pronouns, + ), + ); + expect(fieldText, findsOneWidget); + + final spans = _textSpans(tester, _capsule); + final boldSpan = spans.where((span) => span.text == 'bold').toList(); + expect(boldSpan, isNotEmpty); + expect(boldSpan.first.style?.fontWeight, FontWeight.bold); + + final rendered = _renderedText(tester, _capsule); + expect(rendered, contains('@Bob')); + expect(rendered, isNot(contains('@[$_bobId]'))); + expect(rendered, isNot(contains('**'))); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'uses the full header width when text scale outgrows the column', + (tester) async { + const pronouns = 'they/them/ze/zie'; + await _pumpHeader(tester, _member(pronouns: pronouns)); + final beside = tester.getRect(_capsule); + final avatar = tester.getRect(find.byType(MemberAvatar)); + expect(beside.left, greaterThanOrEqualTo(avatar.right + 15)); + + // 390 pt header at 2x: 15 em of 28 pt is 420 pt, wider than the header. + await _pumpHeader( + tester, + _member(pronouns: pronouns), + textScaler: const TextScaler.linear(2), + ); + + final dropped = tester.getRect(_capsule); + expect( + dropped.left, + lessThanOrEqualTo( + tester.getRect(find.byType(MemberAvatar)).left + 0.5, + ), + ); + expect(dropped.width, greaterThan(beside.width)); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('drops under the avatar on a narrow phone at 1.5x', ( + tester, + ) async { + const pronouns = 'they/them/ze/zie'; + await _pumpHeader( + tester, + _member(pronouns: pronouns), + width: _narrowHeader, + textScaler: const TextScaler.linear(1.5), + ); + + final avatar = tester.getRect(find.byType(MemberAvatar)); + final capsule = tester.getRect(_capsule); + // 15 em of 21 pt is 315 pt, wider than the 272 pt header. + expect(capsule.left, lessThanOrEqualTo(avatar.left + 0.5)); + expect(capsule.width, greaterThan(_narrowHeader - 80 - 16)); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + expect(tester.takeException(), isNull); + }); + + testWidgets('follows a nonlinear scaler at the capsule font size', ( + tester, + ) async { + const pronouns = 'they/them/ze/zie'; + await _pumpHeader(tester, _member(pronouns: pronouns)); + final avatar = tester.getRect(find.byType(MemberAvatar)); + expect( + tester.getRect(_capsule).left, + greaterThanOrEqualTo(avatar.right + 15), + ); + + // Reported factor 1.5 would keep 15 em at 315 pt (still narrower than + // 390), but the body role really scales to 28 pt, so the capsule moves. + await _pumpHeader( + tester, + _member(pronouns: pronouns), + textScaler: const _NonlinearTextScaler(), + ); + + expect( + tester.getRect(_capsule).left, + lessThanOrEqualTo(tester.getRect(find.byType(MemberAvatar)).left + 0.5), + ); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + expect(tester.takeException(), isNull); + }); + + testWidgets('renders fully and grows at 3.375x without clipping', ( + tester, + ) async { + const pronouns = 'she/her, they/them, xe/xem'; + await _pumpHeader( + tester, + _member(pronouns: pronouns), + textScaler: const TextScaler.linear(3.375), + ); + + final capsule = tester.getRect(_capsule); + expect(capsule.width, lessThanOrEqualTo(_wideHeader + 0.01)); + expect(_collapsed(_renderedText(tester, _capsule)), pronouns); + for (final richText in _richTexts(tester, _capsule)) { + expect(richText.maxLines, isNull); + } + expect( + tester.getSize(_insideCapsule(find.byType(RichText)).first).height, + greaterThan(_bodyMediumSize(tester) * 3), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('renders nothing and leaves no gap when pronouns are empty', ( + tester, + ) async { + await _pumpHeader(tester, _member()); + final withoutPronouns = tester.getSize(find.byType(MemberProfileHeader)); + expect(_capsule, findsNothing); + + await _pumpHeader(tester, _member(pronouns: '')); + expect(_capsule, findsNothing); + expect(tester.getSize(find.byType(MemberProfileHeader)), withoutPronouns); + + await _pumpHeader(tester, _member(pronouns: ' ')); + expect(_capsule, findsNothing); + expect(tester.getSize(find.byType(MemberProfileHeader)), withoutPronouns); + expect(tester.takeException(), isNull); + }); + + testWidgets('lays the capsule out from the start edge in right-to-left', ( + tester, + ) async { + const pronouns = 'هي/لها they/them'; + await _pumpHeader( + tester, + _member(pronouns: pronouns), + textDirection: TextDirection.rtl, + ); + + // In RTL the avatar is on the right and the capsule starts at the + // identity column's inline start edge, i.e. flush with the avatar gap. + final avatar = tester.getRect(find.byType(MemberAvatar)); + final capsule = tester.getRect(_capsule); + expect(capsule.right, closeTo(avatar.left - 16, 0.5)); + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect(tester.takeException(), isNull); + }); + + testWidgets('renders in compact, image-behind and classic headers', ( + tester, + ) async { + const pronouns = 'they/them 🦊'; + + await _pumpHeader(tester, _member(pronouns: pronouns)); + expect(_capsule, findsOneWidget); + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect(tester.takeException(), isNull); + + await _pumpHeader( + tester, + _member(pronouns: pronouns, headerImage: _pngBytes), + ); + expect(_capsule, findsOneWidget); + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect(tester.takeException(), isNull); + + await _pumpHeader( + tester, + _member( + pronouns: pronouns, + headerImage: _pngBytes, + layout: MemberProfileHeaderLayout.classicOverlap, + ), + ); + expect(_capsule, findsOneWidget); + expect(_renderedText(tester, _capsule).trim(), pronouns); + expect( + tester.widget(find.byType(AspectRatio)).aspectRatio, + 3, + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('keeps status chips separate from the pronoun capsule', ( + tester, + ) async { + const pronouns = 'they/them'; + await _pumpHeader( + tester, + _member( + pronouns: pronouns, + birthday: '2011-06-15', + age: '25', + isAdmin: true, + isActive: false, + ), + isFronting: true, + ); + + expect(find.text('Fronting'), findsOneWidget); + expect(_insideCapsule(find.text('Fronting')), findsNothing); + expect(_insideCapsule(find.textContaining('25')), findsNothing); + expect(_renderedText(tester, _capsule).trim(), pronouns); + // Chips stay below the capsule rather than above it. + expect( + tester.getRect(find.text('Fronting')).top, + greaterThan(tester.getRect(_capsule).bottom), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('keeps avatar, remove and name-style callbacks', ( + tester, + ) async { + var avatarTapped = 0; + var avatarRemoved = 0; + var nameStyleTapped = 0; + await _pumpHeader( + tester, + _member(pronouns: 'they/them', avatarImage: _pngBytes), + onAvatarTap: () => avatarTapped++, + onAvatarRemove: () => avatarRemoved++, + onNameStyleTap: () => nameStyleTapped++, + ); + + expect(_capsule, findsOneWidget); + + await tester.tap(find.byIcon(AppIcons.textFields)); + await tester.pump(); + expect(nameStyleTapped, 1); + + await tester.tap(find.byType(MemberAvatar)); + await tester.pump(); + expect(avatarTapped, 1); + + await tester.tap(find.byIcon(AppIcons.close)); + await tester.pump(); + expect(avatarRemoved, 1); + expect(tester.takeException(), isNull); + }); + + testWidgets('hugs a short capsule instead of filling the avatar column', ( + tester, + ) async { + await _pumpHeader(tester, _member(pronouns: 'she/her')); + + final capsule = tester.getSize(_capsule); + // The avatar column is 390 - 80 - 16 = 294 wide; a hugged capsule stays + // well inside it instead of taking the whole column. + expect(capsule.width, lessThan((_wideHeader - 96) * 0.8)); + final textWidth = tester + .getSize(_insideCapsule(find.byType(RichText)).first) + .width; + expect(textWidth, greaterThan(0)); + // The capsule is the rendered text plus the 12 pt padding on each side. + expect(capsule.width, closeTo(textWidth + 24, 1)); + expect(_renderedText(tester, _capsule).trim(), 'she/her'); + expect(tester.takeException(), isNull); + }); + + testWidgets('labels the capsule and keeps mentions reachable', ( + tester, + ) async { + final bob = _member(id: _bobId, name: 'Bob'); + const pronouns = 'they/them @[$_bobId]'; + // The active handle must be disposed inside the test body: the widget + // tester verifies handles before addTearDown callbacks run. + final handle = tester.ensureSemantics(); + try { + await _pumpHeader( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + ); + await tester.pumpAndSettle(); + + final labels = []; + void collect(SemanticsNode node) { + if (node.label.isNotEmpty) labels.add(node.label); + node.visitChildren((child) { + collect(child); + return true; + }); + } + + collect(tester.getSemantics(_capsule)); + final announced = labels.join(' '); + // The pronoun role is announced, but nothing is excluded or flattened: + // the rendered text and the mention are still in the semantics subtree. + expect(announced, contains('Pronouns')); + expect(announced, contains('they/them')); + expect(announced, contains('@Bob')); + + // The mention keeps its tap recognizer under the label. + var mentionHasRecognizer = false; + for (final richText in _richTexts(tester, _capsule)) { + richText.text.visitChildren((span) { + if (span is TextSpan && + (span.text ?? '').contains('@Bob') && + span.recognizer is TapGestureRecognizer) { + mentionHasRecognizer = true; + } + return true; + }); + } + expect(mentionHasRecognizer, isTrue); + expect(tester.takeException(), isNull); + } finally { + handle.dispose(); + } + }); + + testWidgets('opens a mentioned member from inside the capsule', ( + tester, + ) async { + final bob = _member(id: _bobId, name: 'Bob'); + const pronouns = 'they/them @[$_bobId]'; + final appPrefs = FakeAppPreferenceRepository(); + final router = GoRouter( + initialLocation: '/', + routes: [ + GoRoute( + path: '/', + builder: (_, _) => Scaffold( + body: SingleChildScrollView( + child: SizedBox( + width: _wideHeader, + child: MemberProfileHeader( + member: _member(pronouns: pronouns), + ), + ), + ), + ), + ), + GoRoute( + path: AppRoutePaths.members, + builder: (_, _) => const Scaffold(body: Text('members')), + routes: [ + GoRoute( + path: ':id', + builder: (_, state) => Scaffold( + body: Text('member-${state.pathParameters['id']}'), + ), + ), + ], + ), + ], + ); + // Unmount before disposing the router, then close the preference fake. + addTearDown(() async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + router.dispose(); + await tester.runAsync( + () => appPrefs.close().timeout(const Duration(seconds: 5)), + ); + }); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + databaseProvider.overrideWith((ref) { + throw StateError('Pronoun header tests must not open a database'); + }), + activeMemberListProvider.overrideWith((ref) => Stream.value([bob])), + ], + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + routerConfig: router, + ), + ), + ); + await tester.pumpAndSettle(); + + // Tap the mention span itself. The paragraph's own centre sits on + // "they/them", and a paragraph forwards a pointer only to the span under + // it, so resolve the "@Bob" glyph box and tap its centre. + final mentionFinder = find.textContaining('@Bob'); + expect(mentionFinder, findsOneWidget); + final paragraph = tester.renderObject(mentionFinder); + final mentionStart = paragraph.text.toPlainText().indexOf('@Bob'); + expect(mentionStart, isNonNegative); + final mentionBoxes = paragraph.getBoxesForSelection( + TextSelection( + baseOffset: mentionStart, + extentOffset: mentionStart + '@Bob'.length, + ), + ); + expect(mentionBoxes, isNotEmpty); + await tester.tapAt( + paragraph.localToGlobal(mentionBoxes.first.toRect().center), + ); + await tester.pumpAndSettle(); + + expect(find.text('member-$_bobId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('keeps square corners when PrismShapes is angular', ( + tester, + ) async { + await _pumpHeader( + tester, + _member(pronouns: 'they/them'), + theme: ThemeData( + useMaterial3: true, + extensions: const [PrismShapes.angular], + ), + ); + + expect(_capsule, findsOneWidget); + final decoration = tester.widget(_capsule).decoration; + expect(decoration, isA()); + expect((decoration! as BoxDecoration).borderRadius, BorderRadius.zero); + expect(_renderedText(tester, _capsule).trim(), 'they/them'); + expect(tester.takeException(), isNull); + }); + + testWidgets('keeps the display-name preference and name styling', ( + tester, + ) async { + await _pumpHeader( + tester, + _member( + name: 'North Star', + displayName: 'Navigator', + pronouns: 'xe/xem', + nameStyleFont: MemberNameFont.display, + nameStyleItalic: true, + ), + ); + + final nameSpans = _textSpans( + tester, + find.byType(MemberProfileHeader), + ).where((span) => (span.text ?? '').contains('Navigator')).toList(); + expect(nameSpans, isNotEmpty); + // The chosen name style still applies to the primary or alternate name. + expect(nameSpans.first.style?.fontFamily, 'Unbounded'); + expect(nameSpans.first.style?.fontStyle, FontStyle.italic); + // Pronouns stay out of the name line and keep their own capsule. + expect(_renderedText(tester, _capsule).trim(), 'xe/xem'); + expect(tester.takeException(), isNull); + }); + }); + + group('pronoun capsule mention at extreme text scale', () { + testWidgets('opens the mentioned member at a selection-run point at 3.375x', ( + tester, + ) async { + final bob = _member(id: _bobId, name: 'Bob'); + const pronouns = 'she/her @[$_bobId]'; + + // A 1x baseline from the same widget tree, so the scaled selection-run box is + // compared against what this very mention lays out. + await _pumpHeaderInRouter( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + ); + final baseMention = _insideCapsule(find.textContaining('@Bob')); + expect(baseMention, findsOneWidget); + final baseRect = _mentionSelectionRect(tester, baseMention, '@Bob'); + expect( + tester.getRect(_capsule).contains(baseRect.center), + isTrue, + reason: 'the 1x baseline must be a real mention inside the capsule', + ); + + // Direct linear 3.375x is equivalent at every size to the production + // composition PrismTextScaler(TextScaler.linear(2.25), 1.5). The separate + // nonlinear case checks that composition cannot generally be reduced + // to one scale factor when the platform curve varies per font size. + final pushedMemberIds = await _pumpHeaderInRouter( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + textScaler: const TextScaler.linear(3.375), + ); + + final bodySize = _bodyMediumSize(tester); + final scaler = MediaQuery.textScalerOf(tester.element(_capsule)); + expect( + scaler.scale(bodySize), + closeTo(bodySize * 3.375, 0.001), + reason: 'the capsule itself, not an ancestor wrapper, sees 3.375x', + ); + + // 15 em of the scaled body role is 708.75 pt, wider than the 390 pt + // header, so the capsule leaves the avatar column. + expect( + tester.getRect(_capsule).left, + lessThanOrEqualTo(tester.getRect(find.byType(MemberAvatar)).left + 0.5), + ); + + final mention = _insideCapsule(find.textContaining('@Bob')); + expect(mention, findsOneWidget); + final paragraph = tester.renderObject(mention); + expect( + paragraph.textScaler.scale(bodySize), + closeTo(bodySize * 3.375, 0.001), + reason: 'the mention paragraph layout uses the same scaler', + ); + expect(paragraph.maxLines, isNull); + expect(paragraph.overflow, isNot(TextOverflow.ellipsis)); + + final rect = _mentionSelectionRect(tester, mention, '@Bob'); + expect(rect.width, greaterThan(0)); + expect( + rect.height / baseRect.height, + closeTo(3.375, 3.375 * 0.1), + reason: + 'the mention selection-run box layout box must scale, not just its parent', + ); + expect( + tester.getRect(_capsule).contains(rect.center), + isTrue, + reason: 'the mention selection-run point must be inside the capsule', + ); + + await _tapMentionSelection(tester, mention, '@Bob'); + + expect(pushedMemberIds, [_bobId]); + expect(find.text('member-$_bobId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('opens the mentioned member under nonlinear composed scaling', ( + tester, + ) async { + final bob = _member(id: _bobId, name: 'Bob'); + const pronouns = 'she/her @[$_bobId]'; + // What the app really builds: PrismTextScaler delegates to the platform + // scaler, then multiplies its result by the user's font-size factor + // (capped at 1.5 by FontFamily.maximumScale). With a nonlinear platform + // curve the composition is nonlinear too: 3x at the 14 pt body role and + // 2.1x at the 24 pt title role, so no single factor describes it. + const composedScaler = PrismTextScaler(_NonlinearTextScaler(), 1.5); + + await _pumpHeaderInRouter( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + ); + final baseRect = _mentionSelectionRect( + tester, + _insideCapsule(find.textContaining('@Bob')), + '@Bob', + ); + + final pushedMemberIds = await _pumpHeaderInRouter( + tester, + _member(pronouns: pronouns), + mentionMembers: [bob], + textScaler: composedScaler, + ); + + final bodySize = _bodyMediumSize(tester); + final titleSize = _titleSize(tester); + final scaler = MediaQuery.textScalerOf(tester.element(_capsule)); + expect(scaler, composedScaler); + expect(scaler.scale(bodySize), closeTo(bodySize * 3, 0.001)); + expect( + scaler.scale(titleSize), + closeTo(titleSize * 1.4 * 1.5, 0.001), + reason: 'the composed provider scaler is nonlinear per size', + ); + expect( + scaler.scale(titleSize), + lessThan(titleSize * scaler.scale(bodySize) / bodySize), + reason: 'a uniform 3.375x would scale the title role as far as body', + ); + + // 15 em of the 42 pt body role is 630 pt, still wider than the 390 pt + // header, so the capsule and its mention move under the avatar. + expect( + tester.getRect(_capsule).left, + lessThanOrEqualTo(tester.getRect(find.byType(MemberAvatar)).left + 0.5), + ); + + final mention = _insideCapsule(find.textContaining('@Bob')); + expect(mention, findsOneWidget); + final rect = _mentionSelectionRect(tester, mention, '@Bob'); + expect( + rect.height / baseRect.height, + closeTo(3, 3 * 0.1), + reason: 'the mention layout must use the scaler measured at 14 pt', + ); + expect( + tester.getRect(_capsule).contains(rect.center), + isTrue, + reason: 'the mention selection-run point must be inside the capsule', + ); + + await _tapMentionSelection(tester, mention, '@Bob'); + + expect(pushedMemberIds, [_bobId]); + expect(find.text('member-$_bobId'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/test/features/members/widgets/member_profile_header_test.dart b/test/features/members/widgets/member_profile_header_test.dart index 0b3764dec..de3f5b71a 100644 --- a/test/features/members/widgets/member_profile_header_test.dart +++ b/test/features/members/widgets/member_profile_header_test.dart @@ -124,28 +124,30 @@ void main() { }, ); - testWidgets('short multiline pronouns do not become part of the title', ( + testWidgets('multiline pronouns stay out of the title in one capsule', ( tester, ) async { const pronouns = 'elle\nshe\nthey'; await _pumpIsolatedPronounHeader(tester, pronouns); final title = tester.widget(find.text('Alice')); expect(title.textSpan!.toPlainText(), 'Alice'); - final preview = tester.widget(find.text(pronouns)); - expect(preview.maxLines, 2); - expect(preview.overflow, TextOverflow.ellipsis); + // One integrated capsule under the name, shown in full: no line limit and + // no ellipsis (this replaces the old two-line chip preview). + expect(find.byKey(memberProfilePronounsCapsuleKey), findsOneWidget); + final rendered = tester.widget(find.text(pronouns)); + expect(rendered.maxLines, isNull); + expect(rendered.overflow, isNot(TextOverflow.ellipsis)); expect(tester.takeException(), isNull); }); - testWidgets('multiline header pronoun preview remains capped at two lines', ( - tester, - ) async { + testWidgets('multiline header pronouns render in full', (tester) async { const pronouns = 'elle / accords féminins\nshe / her\nthey / them\nother terms'; await _pumpIsolatedPronounHeader(tester, pronouns); - final preview = tester.widget(find.text(pronouns)); - expect(preview.maxLines, 2); - expect(preview.overflow, TextOverflow.ellipsis); + expect(find.byKey(memberProfilePronounsCapsuleKey), findsOneWidget); + final rendered = tester.widget(find.text(pronouns)); + expect(rendered.maxLines, isNull); + expect(rendered.overflow, isNot(TextOverflow.ellipsis)); expect(tester.takeException(), isNull); }); @@ -212,7 +214,9 @@ void main() { expect(aspectRatio.aspectRatio, 3); }); - testWidgets('long pronoun chip wraps in the profile header', (tester) async { + testWidgets('long pronouns wrap in the classic header capsule', ( + tester, + ) async { addTearDown(() => tester.view.resetPhysicalSize()); tester.view.physicalSize = const Size(360, 640); tester.view.devicePixelRatio = 1; @@ -238,9 +242,10 @@ void main() { expect(tester.takeException(), isNull); + expect(find.byKey(memberProfilePronounsCapsuleKey), findsOneWidget); final pronounText = tester.widget(find.text(pronouns)); - expect(pronounText.maxLines, 2); - expect(pronounText.overflow, TextOverflow.ellipsis); + expect(pronounText.maxLines, isNull); + expect(pronounText.overflow, isNot(TextOverflow.ellipsis)); expect(tester.getSize(find.text(pronouns)).height, greaterThan(16)); }); diff --git a/test/features/settings/providers/reset_data_provider_test.dart b/test/features/settings/providers/reset_data_provider_test.dart index 587d2c759..a201d9bde 100644 --- a/test/features/settings/providers/reset_data_provider_test.dart +++ b/test/features/settings/providers/reset_data_provider_test.dart @@ -5,8 +5,11 @@ import 'dart:io'; import 'package:drift/drift.dart' hide isNull, isNotNull; import 'package:drift/native.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/foundation.dart' + show TargetPlatform, debugDefaultTargetPlatformOverride; import 'package:flutter_riverpod/misc.dart' show ProviderException; import 'package:flutter/services.dart'; +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; import 'package:prism_plurality/core/database/app_database.dart'; @@ -17,6 +20,7 @@ import 'package:prism_plurality/core/reset/native_reset_keys.dart'; import 'package:prism_plurality/core/services/files/prism_file_dialog_service.dart'; import 'package:prism_plurality/core/services/media/download_manager.dart'; import 'package:prism_plurality/core/services/media/media_encryption_service.dart'; +import 'package:prism_plurality/core/services/local_notification_service.dart'; import 'package:prism_plurality/core/services/media/media_providers.dart'; import 'package:prism_plurality/core/sync/pk_front_orphan_projection_repair.dart'; import 'package:prism_plurality/core/sync/prism_sync_providers.dart' as sync; @@ -175,6 +179,51 @@ const _memberRefAllowlist = <(String, String)>{ ('pk_identity_sync_aliases', 'member_id'), }; +/// Fake of the flutter_local_notifications platform channel for reset tests. +/// +/// The habits reset now retracts the reminder series of every habit row it +/// deletes, through the real habit notification service and the real local +/// notification service. Without a platform those cancellations fail and the +/// reset reports that truthfully, so a reset test needs the channel faked — not +/// the service. +class _NotificationChannelFake { + static const _channel = MethodChannel( + 'dexterous.com/flutter/local_notifications', + ); + + /// Notification IDs the reset actually cancelled. + final List cancelledIds = []; + + /// Installs the fake and pins the platform to iOS so the plugin resolves its + /// iOS implementation, as it would on a phone. + void install() { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + IOSFlutterLocalNotificationsPlugin.registerWith(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, _handle); + } + + /// Removes the handler and the platform override, so later tests in this file + /// see no fake notification platform. + void uninstall() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, null); + debugDefaultTargetPlatformOverride = null; + } + + Future _handle(MethodCall call) async { + switch (call.method) { + case 'initialize': + return true; + case 'cancel': + cancelledIds.add(call.arguments as int); + return null; + default: + return null; + } + } +} + class _PausedNotificationResetDatabase extends AppDatabase { _PausedNotificationResetDatabase() : super(NativeDatabase.memory()); final pending = Completer(); @@ -872,9 +921,35 @@ void main() { final harness = await _ResetHarness.create(); addTearDown(harness.dispose); + // The reset retracts the deleted rows' reminders through the real + // notification service, so the platform channel must exist; nothing about + // the reset or the notification services is mocked. + final notifications = _NotificationChannelFake(); + notifications.install(); + addTearDown(notifications.uninstall); + await harness.seedAllData(); await harness.reset(ResetCategory.habits); + // The seeded habit's owned series (base..base+N-1) must be cancelled even + // though its row never had notifications enabled: the reset captures every + // row it deletes. + const habitIdBase = 3000000; + const habitIdMod = 100000; + final habitBase = habitIdBase + ('habit-1'.hashCode.abs() % habitIdMod); + expect( + notifications.cancelledIds.toSet(), + { + for ( + var i = 0; + i < LocalNotificationService.maxIntervalOccurrences; + i++ + ) + habitBase + i, + }, + reason: 'the reset must retract the seeded habit reminder series', + ); + final reopened = await harness.reopenDatabase(); addTearDown(reopened.close); diff --git a/test/goldens/members/goldens/member_profile_header_matrix.png b/test/goldens/members/goldens/member_profile_header_matrix.png index 745ed1176..1ea717d30 100644 Binary files a/test/goldens/members/goldens/member_profile_header_matrix.png and b/test/goldens/members/goldens/member_profile_header_matrix.png differ diff --git a/test/shared/widgets/app_shell_adaptive_nav_layout_test.dart b/test/shared/widgets/app_shell_adaptive_nav_layout_test.dart index 11f6805b0..28e7eeed7 100644 --- a/test/shared/widgets/app_shell_adaptive_nav_layout_test.dart +++ b/test/shared/widgets/app_shell_adaptive_nav_layout_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -23,6 +24,7 @@ import 'package:prism_plurality/features/members/providers/members_providers.dar import 'package:prism_plurality/l10n/app_localizations.dart'; import 'package:prism_plurality/shared/theme/app_colors.dart'; import 'package:prism_plurality/shared/theme/app_theme.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; import 'package:prism_plurality/shared/utils/nav_bar_layout.dart'; import '../../helpers/fake_repositories.dart' show FakeAppPreferenceRepository; import 'package:prism_plurality/shared/widgets/app_shell.dart'; @@ -1215,6 +1217,711 @@ void main() { semantics.dispose(); } }); + + // --------------------------------------------------------------------- + // Desktop sidebar at Windows accessibility text sizes: + // labels were laid out on one unconstrained line and clipped by a fixed + // 38pt row height, so the panel showed cut-off text. These are real + // AppShell tests: they measure the actual RenderParagraph boxes of the + // sidebar labels at the combined system + app text scale. + // --------------------------------------------------------------------- + + testWidgets( + 'desktop sidebar keeps its default panel and row metrics at scale 1', + variant: TargetPlatformVariant.only(TargetPlatform.windows), + (tester) async { + final semantics = tester.ensureSemantics(); + try { + final shell = await _pumpDesktopSidebarShell( + tester, + windowSize: const Size(1280, 900), + textScaler: const TextScaler.linear(1), + ); + + // Default-size design is unchanged: 200pt panel, 38pt rows. + expect(_sidebarPanelRect(tester).width, 200.0); + + final viewportRect = _sidebarViewportRect(tester); + for (final label in shell.labels) { + _expectSidebarLabelFits( + tester, + label, + viewportRect: viewportRect, + scaleDescription: '1x', + expectedTextScaler: const TextScaler.linear(1), + ); + expect( + _sidebarTextMetrics(_sidebarLabelParagraph(tester, label)).lines, + 1, + reason: '"$label" fits on one line at the default text size.', + ); + expect( + _sidebarItemRect(tester, label).height, + 38.0, + reason: 'Sidebar rows keep their 38pt default height at 1x.', + ); + } + + // Tab order and localized labels are unchanged. + final renderedLabels = [ + for (final element + in find + .descendant( + of: _sidebarScrollView(), + matching: find.byType(Text), + ) + .evaluate()) + (element.widget as Text).data, + ]; + expect(renderedLabels, shell.labels); + } finally { + semantics.dispose(); + } + }, + ); + + testWidgets( + 'desktop sidebar wraps labels and grows rows at 3.375x text scale', + variant: TargetPlatformVariant.only(TargetPlatform.windows), + (tester) async { + final semantics = tester.ensureSemantics(); + try { + final shell = await _pumpDesktopSidebarShell( + tester, + windowSize: const Size(1280, 900), + // Windows 225% accessibility scaling times the app's 1.5 font + // preference, composed the way lib/app.dart composes it. + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + chatUnreadCount: 2, + ); + + final viewportRect = _sidebarViewportRect(tester); + for (final label in shell.labels) { + _expectSidebarLabelFits( + tester, + label, + viewportRect: viewportRect, + scaleDescription: '3.375x', + expectedTextScaler: const PrismTextScaler( + TextScaler.linear(2.25), + 1.5, + ), + ); + final paragraph = _sidebarLabelParagraph(tester, label); + expect( + paragraph.size.height, + greaterThan(30.0), + reason: + '"$label" still renders at the scaled text size; there is no ' + 'shrink-to-fit cap on sidebar labels.', + ); + expect( + _sidebarItemRect(tester, label).height, + greaterThanOrEqualTo(38.0), + reason: 'Rows never shrink below their default 38pt height.', + ); + } + + final panelRect = _sidebarPanelRect(tester); + expect( + panelRect.width, + greaterThan(200.0), + reason: + 'The panel grows with the label text scale so scaled labels ' + 'need fewer mid-word wraps.', + ); + expect( + panelRect.width, + lessThanOrEqualTo(320.5), + reason: 'The panel width stays bounded at large text sizes.', + ); + + final contentRect = tester.getRect( + find.byKey(const ValueKey('route_body_home')), + ); + expect( + contentRect.left, + greaterThanOrEqualTo(panelRect.right - 0.5), + reason: 'Sidebar and content must not overlap.', + ); + expect( + contentRect.width, + greaterThanOrEqualTo(1280 * 0.5), + reason: 'A wider panel must not starve the main content column.', + ); + + // Badge presence and the declared accessibility contract survive the + // layout change; asserted separately from the geometry above. + final chatLabel = _shellLabel(shell, AppShellTabId.chat); + final chatItem = _sidebarItemFinder(chatLabel); + expect( + find.descendant(of: chatItem, matching: find.text('2')), + findsOneWidget, + reason: 'The unread chat badge still renders inside the row.', + ); + + final groupSemantics = _sidebarGroupSemantics(tester); + expect( + groupSemantics.container, + isTrue, + reason: 'The sidebar is still a semantics container.', + ); + expect( + groupSemantics.properties.label, + AppLocalizations.of( + tester.element(find.byType(AppShell)), + ).mainNavigation, + reason: 'The sidebar still announces itself as the main navigation.', + ); + for (var index = 0; index < shell.labels.length; index++) { + final label = shell.labels[index]; + final itemSemantics = _sidebarItemSemantics(tester, label); + expect( + itemSemantics.properties.label, + label, + reason: 'The "$label" row still exposes its localized label.', + ); + expect( + itemSemantics.properties.button, + isTrue, + reason: 'The "$label" row is still a button.', + ); + expect( + itemSemantics.properties.selected, + index == 0, + reason: 'Only the current destination is announced as selected.', + ); + } + } finally { + semantics.dispose(); + } + }, + ); + + testWidgets( + 'desktop sidebar wraps a long custom terminology label at 4.5x scale', + variant: TargetPlatformVariant.only(TargetPlatform.windows), + (tester) async { + final semantics = tester.ensureSemantics(); + try { + final shell = await _pumpDesktopSidebarShell( + tester, + windowSize: const Size(1280, 900), + // Beyond the app's 1.5 cap on purpose: a stress case for future + // scalers and narrow panels. + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 2.0), + settings: const SystemSettings( + terminology: SystemTerminology.custom, + customTerminology: 'Systemmitglied', + customPluralTerminology: 'Systemmitglieder', + ), + ); + + final membersLabel = _shellLabel(shell, AppShellTabId.members); + expect(membersLabel, 'Systemmitglieder'); + + final viewportRect = _sidebarViewportRect(tester); + for (final label in shell.labels) { + _expectSidebarLabelFits( + tester, + label, + viewportRect: viewportRect, + scaleDescription: '4.5x', + expectedTextScaler: const PrismTextScaler( + TextScaler.linear(2.25), + 2.0, + ), + ); + } + + // A long word has to break across lines instead of painting past the + // panel edge. + expect( + _sidebarTextMetrics( + _sidebarLabelParagraph(tester, membersLabel), + ).lines, + greaterThanOrEqualTo(2), + reason: + 'A 16-character custom terminology label cannot fit on one line ' + 'at 4.5x in a bounded panel, so it must wrap.', + ); + + final panelRect = _sidebarPanelRect(tester); + expect(panelRect.width, lessThanOrEqualTo(320.5)); + expect( + tester.getRect(find.byKey(const ValueKey('route_body_home'))).width, + greaterThanOrEqualTo(1280 * 0.5), + reason: 'The main content column stays usable at the stress scale.', + ); + } finally { + semantics.dispose(); + } + }, + ); + + testWidgets( + 'desktop sidebar keeps Settings reachable on a short narrow window at 3.375x', + variant: TargetPlatformVariant.only(TargetPlatform.windows), + (tester) async { + final semantics = tester.ensureSemantics(); + try { + final shell = await _pumpDesktopSidebarShell( + tester, + windowSize: const Size(768, 480), + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + // The order from the report, with Settings at the bottom of the + // list, so the last row is the one that has to stay reachable. + displayOrder: const [ + AppShellTabId.members, + AppShellTabId.home, + AppShellTabId.notes, + AppShellTabId.chat, + AppShellTabId.boards, + AppShellTabId.sleep, + AppShellTabId.media, + AppShellTabId.polls, + AppShellTabId.statistics, + AppShellTabId.timeline, + AppShellTabId.groups, + AppShellTabId.settings, + ], + ); + + final panelRect = _sidebarPanelRect(tester); + expect(panelRect.width, greaterThanOrEqualTo(200.0)); + expect( + panelRect.width, + lessThanOrEqualTo(768 * 0.45), + reason: 'The panel stays bounded on a narrow desktop window.', + ); + expect( + tester.getRect(find.byKey(const ValueKey('route_body_home'))).width, + greaterThanOrEqualTo(768 * 0.55), + reason: 'Main content keeps the majority of a narrow desktop window.', + ); + + final viewportRect = _sidebarViewportRect(tester); + for (final label in shell.labels) { + _expectSidebarLabelFits( + tester, + label, + viewportRect: viewportRect, + scaleDescription: '3.375x on a 768pt window', + expectedTextScaler: const PrismTextScaler( + TextScaler.linear(2.25), + 1.5, + ), + ); + } + + // The list is taller than the panel here, so Settings starts clipped + // below the fold and must be reachable by scrolling. + final settingsLabel = _shellLabel(shell, AppShellTabId.settings); + expect( + _sidebarItemRect(tester, settingsLabel).bottom, + greaterThan(viewportRect.bottom), + reason: 'At this scale the sidebar content overflows its panel.', + ); + + expect(find.byType(SingleChildScrollView), findsOneWidget); + await tester.drag( + find.byType(SingleChildScrollView), + const Offset(0, -4000), + ); + await tester.pumpAndSettle(); + + final scrolledViewport = _sidebarViewportRect(tester); + final settingsRect = _sidebarItemRect(tester, settingsLabel); + expect( + settingsRect.top, + greaterThanOrEqualTo(scrolledViewport.top - 0.5), + reason: 'Scrolling reaches the bottom of the sidebar.', + ); + expect( + settingsRect.bottom, + lessThanOrEqualTo(scrolledViewport.bottom + 0.5), + reason: 'The Settings row is fully visible after scrolling.', + ); + + await tester.tap(find.text(settingsLabel)); + await tester.pumpAndSettle(); + + expect( + shell.router.routeInformationProvider.value.uri.path, + AppRoutePaths.settings, + reason: 'Tapping Settings navigates to the settings branch.', + ); + expect( + find.byKey(const ValueKey('route_body_settings')), + findsOneWidget, + reason: 'The settings branch renders its own content.', + ); + + // Selection moved to Settings and away from Home. + final theme = Theme.of(tester.element(find.byType(AppShell))); + expect( + _sidebarItemIconColor(tester, settingsLabel), + theme.colorScheme.primary, + reason: 'The selected destination is tinted with the accent color.', + ); + expect( + _sidebarItemIconColor(tester, _shellLabel(shell, AppShellTabId.home)), + isNot(theme.colorScheme.primary), + reason: 'The previously selected destination is no longer selected.', + ); + expect( + _sidebarItemSemantics(tester, settingsLabel).properties.selected, + isTrue, + reason: 'The Settings destination is announced as selected.', + ); + expect( + _sidebarItemSemantics( + tester, + _shellLabel(shell, AppShellTabId.home), + ).properties.selected, + isFalse, + reason: 'Home is announced as not selected after navigating away.', + ); + } finally { + semantics.dispose(); + } + }, + ); +} + +typedef _DesktopSidebarShell = ({ + List tabs, + List labels, + GoRouter router, +}); + +/// Pumps the real [AppShell] on a desktop-sized Windows window with the app's +/// composed text scaler, and returns the tab list, the rendered labels and the +/// router so tests can assert navigation. +Future<_DesktopSidebarShell> _pumpDesktopSidebarShell( + WidgetTester tester, { + required Size windowSize, + required TextScaler textScaler, + SystemSettings settings = const SystemSettings(), + int chatUnreadCount = 0, + List? displayOrder, +}) async { + tester.view.physicalSize = windowSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + // Branches follow branchIndex, like the real router; the sidebar renders + // the configured tab order, which is user-reorderable. + final displayIds = displayOrder ?? [for (final tab in appShellTabs) tab.id]; + final tabs = [ + for (final id in displayIds) appShellTabs.firstWhere((tab) => tab.id == id), + ]; + final router = GoRouter( + initialLocation: AppRoutePaths.home, + routes: [ + StatefulShellRoute.indexedStack( + builder: (context, state, navigationShell) => AppShell( + navigationShell: navigationShell, + routePath: state.uri.path, + ), + branches: [ + for (final tab in appShellTabs) + StatefulShellBranch( + routes: [ + GoRoute( + path: tab.rootLocation, + builder: (context, state) => Scaffold( + body: Container(key: ValueKey('route_body_${tab.id.name}')), + ), + ), + ], + ), + ], + ), + ], + ); + addTearDown(router.dispose); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + activeNavBarTabsProvider.overrideWithValue(tabs), + appPreferenceRepositoryProvider.overrideWithValue( + FakeAppPreferenceRepository(), + ), + navBarOverflowTabsProvider.overrideWithValue(const []), + systemSettingsProvider.overrideWith((ref) => Stream.value(settings)), + isPinSetProvider.overrideWith((ref) async => false), + syncStatusProvider.overrideWith(_FakeSyncStatusNotifier.new), + pkAutoPollProvider.overrideWith(_FakePkAutoPollNotifier.new), + pluralKitSyncProvider.overrideWith(_FakePluralKitSyncNotifier.new), + habitsBadgeEnabledProvider.overrideWith((ref) => false), + activeSessionsProvider.overrideWith((ref) => Stream.value(const [])), + allMembersProvider.overrideWith((ref) => Stream.value(const [])), + unreadConversationCountProvider.overrideWith((ref) => chatUnreadCount), + frontingMigrationGateProvider.overrideWith( + (ref) => FrontingMigrationGateStatus.complete, + ), + ], + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData(fontFamily: 'OpenDyslexic'), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + routerConfig: router, + ), + ), + ); + await tester.pumpAndSettle(); + + final appShellContext = tester.element(find.byType(AppShell)); + final terminology = resolveTerminology( + AppLocalizations.of(appShellContext), + settings.terminology, + customSingular: settings.customTerminology, + customPlural: settings.customPluralTerminology, + useEnglish: settings.terminologyUseEnglish, + ); + final labels = [ + for (final tab in tabs) + tab.localizedLabel( + appShellContext, + terminologyPlural: terminology.plural, + ), + ]; + return (tabs: tabs, labels: labels, router: router); +} + +/// The desktop sidebar's scroll view. +/// +/// It is the only [SingleChildScrollView] inside [AppShell], so structural +/// lookups scoped to the app shell cannot reach the content beside the panel. +/// Deliberately not keyed off the "Main navigation" semantics label: this +/// harness does not surface that group node through `find.bySemanticsLabel` +/// even though the nav bar's equivalent node is found, so scoping must not +/// depend on the semantics tree. +Finder _sidebarScrollView() { + final scrollView = find.descendant( + of: find.byType(AppShell), + matching: find.byType(SingleChildScrollView), + ); + expect( + scrollView, + findsOneWidget, + reason: 'The desktop shell renders exactly one sidebar scroll view.', + ); + return scrollView; +} + +/// The floating panel: the [Container] that wraps the sidebar scroll view. +Rect _sidebarPanelRect(WidgetTester tester) { + final panel = find + .ancestor(of: _sidebarScrollView(), matching: find.byType(Container)) + .first; + expect( + panel, + findsOneWidget, + reason: 'The sidebar panel wraps its scroll view.', + ); + return tester.getRect(panel); +} + +/// The sidebar scroll viewport; this is the rectangle that clips the panel. +Rect _sidebarViewportRect(WidgetTester tester) => + tester.getRect(_sidebarScrollView()); + +/// The sidebar's declared accessibility group. +/// +/// The contract is read from the widget that publishes it, not from the +/// semantics tree, for the reason in [_sidebarScrollView]. +Semantics _sidebarGroupSemantics(WidgetTester tester) { + final finder = find + .ancestor(of: _sidebarScrollView(), matching: find.byType(Semantics)) + .first; + expect( + finder, + findsOneWidget, + reason: 'The sidebar publishes a semantics group.', + ); + return tester.widget(finder); +} + +/// The declared accessibility contract of one sidebar destination. +Semantics _sidebarItemSemantics(WidgetTester tester, String label) { + final finder = find + .ancestor(of: find.text(label), matching: find.byType(Semantics)) + .first; + expect( + finder, + findsOneWidget, + reason: 'The "$label" row publishes semantics.', + ); + return tester.widget(finder); +} + +Finder _sidebarItemFinder(String label) { + final item = find + .ancestor(of: find.text(label), matching: find.byType(GestureDetector)) + .first; + expect(item, findsOneWidget, reason: 'Expected a sidebar row for "$label".'); + return item; +} + +Rect _sidebarItemRect(WidgetTester tester, String label) => + tester.getRect(_sidebarItemFinder(label)); + +RenderParagraph _sidebarLabelParagraph(WidgetTester tester, String label) { + final finder = find.text(label); + expect( + finder, + findsOneWidget, + reason: 'Expected one sidebar label "$label".', + ); + return tester.renderObject(finder); +} + +Color? _sidebarItemIconColor(WidgetTester tester, String label) { + final icon = find + .descendant(of: _sidebarItemFinder(label), matching: find.byType(Icon)) + .first; + expect(icon, findsOneWidget); + return tester.widget(icon).color; +} + +String _shellLabel(_DesktopSidebarShell shell, AppShellTabId id) { + final index = shell.tabs.indexWhere((tab) => tab.id == id); + expect(index, isNonNegative, reason: 'Tab $id belongs to the shell.'); + return shell.labels[index]; +} + +/// Re-lays out a sidebar label's paragraph at the width it was given, so the +/// height and line count it *needs* can be compared with the box it got. +({double height, int lines}) _sidebarTextMetrics(RenderParagraph paragraph) { + final maxWidth = paragraph.constraints.maxWidth; + final layoutWidth = maxWidth.isFinite ? maxWidth : paragraph.size.width; + final painter = TextPainter( + text: paragraph.text, + textAlign: paragraph.textAlign, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + maxLines: paragraph.maxLines, + locale: paragraph.locale, + strutStyle: paragraph.strutStyle, + textHeightBehavior: paragraph.textHeightBehavior, + textWidthBasis: paragraph.textWidthBasis, + )..layout(maxWidth: layoutWidth); + final metrics = ( + height: painter.height, + lines: painter.computeLineMetrics().length, + ); + painter.dispose(); + return metrics; +} + +/// Asserts one sidebar label is fully painted inside its row and the panel. +void _expectSidebarLabelFits( + WidgetTester tester, + String label, { + required Rect viewportRect, + required String scaleDescription, + required TextScaler expectedTextScaler, +}) { + final paragraph = _sidebarLabelParagraph(tester, label); + final labelRect = tester.getRect(find.text(label)); + final itemRect = _sidebarItemRect(tester, label); + final metrics = _sidebarTextMetrics(paragraph); + expect(paragraph.text.style?.fontSize, 13); + expect( + paragraph.textScaler.scale(13), + expectedTextScaler.scale(13), + reason: 'The sidebar must keep the requested system and Prism text scale.', + ); + + // Nav labels may use as many lines as they need: no ellipsis, no line cap + // and no clipping overflow hiding the problem. + expect( + paragraph.maxLines, + isNull, + reason: '"$label" at $scaleDescription must not cap its line count.', + ); + expect( + paragraph.overflow, + isNot(TextOverflow.ellipsis), + reason: '"$label" at $scaleDescription must not be truncated.', + ); + expect( + paragraph.softWrap, + isTrue, + reason: '"$label" at $scaleDescription must wrap instead of clipping.', + ); + + // The row has to be as tall as the text needs; a fixed height clips glyphs. + expect( + paragraph.size.height, + greaterThanOrEqualTo(metrics.height - 0.5), + reason: + '"$label" at $scaleDescription is laid out in ' + '${paragraph.size.height}px but its text needs ${metrics.height}px, ' + 'so the row clips its glyphs.', + ); + + // The label box stays inside its row... + expect( + labelRect.left, + greaterThanOrEqualTo(itemRect.left - 0.5), + reason: '"$label" at $scaleDescription paints past the left of its row.', + ); + expect( + labelRect.right, + lessThanOrEqualTo(itemRect.right + 0.5), + reason: '"$label" at $scaleDescription paints past the right of its row.', + ); + expect( + labelRect.top, + greaterThanOrEqualTo(itemRect.top - 0.5), + reason: '"$label" at $scaleDescription paints above its row.', + ); + expect( + labelRect.bottom, + lessThanOrEqualTo(itemRect.bottom + 0.5), + reason: '"$label" at $scaleDescription paints below its row.', + ); + + // ...and inside the scroll viewport, whose edge clips it against the panel. + expect( + labelRect.left, + greaterThanOrEqualTo(viewportRect.left - 0.5), + reason: '"$label" at $scaleDescription is clipped at the panel edge.', + ); + expect( + labelRect.right, + lessThanOrEqualTo(viewportRect.right + 0.5), + reason: '"$label" at $scaleDescription is clipped at the panel edge.', + ); + + // Every glyph box stays inside the paragraph, so no word runs past the panel. + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: label.length), + ); + expect( + boxes, + isNotEmpty, + reason: 'No glyph boxes were reported for "$label".', + ); + final widestGlyphRight = boxes + .map((box) => box.right) + .fold(0, (widest, right) => right > widest ? right : widest); + expect( + widestGlyphRight, + lessThanOrEqualTo(paragraph.size.width + 0.5), + reason: + '"$label" at $scaleDescription paints glyphs outside its own box, so ' + 'they are clipped.', + ); } Color _floatingNavBarDecorationColor(WidgetTester tester) { diff --git a/test/text_scale_fixes/access/accept_invite_access_text_scale_test.dart b/test/text_scale_fixes/access/accept_invite_access_text_scale_test.dart new file mode 100644 index 000000000..fa31656af --- /dev/null +++ b/test/text_scale_fixes/access/accept_invite_access_text_scale_test.dart @@ -0,0 +1,280 @@ +// Accept-invite sheet: the Cancel / Send Request row belongs to the sheet at +// every text scale, with the keyboard up, and with long input. +// +// The sheet is mounted by PrismSheet.showFullScreen, whose body is tight to the +// viewport, so its content has to scroll: the actions are pinned below the +// scrolling body, which carries the title, both fields, the preview and the scope +// rows. The assertions below describe that behaviour - every action stays inside +// the sheet, and cancelling sends nothing. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/sharing/views/accept_invite_sheet.dart'; +import 'package:prism_plurality/shared/widgets/prism_button.dart'; +import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; +import 'package:prism_plurality/shared/widgets/prism_text_field.dart'; + +import 'access_text_scale_harness.dart'; + +/// Opens the real full-screen accept-invite sheet exactly like the sharing +/// screen does and keeps the value the route returns. +class _InviteHost extends StatelessWidget { + const _InviteHost({required this.onResult}); + + final void Function(bool?) onResult; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Builder( + builder: (buttonContext) => TextButton( + onPressed: () async { + final result = await PrismSheet.showFullScreen( + context: buttonContext, + builder: (context, _) => const AcceptInviteSheet(), + ); + onResult(result); + }, + child: const Text('open invite sheet'), + ), + ), + ), + ); + } +} + +Future _pumpSheet( + WidgetTester tester, { + required Size size, + TextScaler? systemScaler, + double appFontScale = 1.0, + double keyboardInset = 0, + void Function(bool?)? onResult, +}) async { + useWindow(tester, size, keyboardInset: keyboardInset); + await tester.pumpWidget( + ProviderScope( + child: accessApp( + _InviteHost(onResult: onResult ?? (_) {}), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ), + ); + await tester.tap(find.text('open invite sheet')); + await tester.pumpAndSettle(); + expect(find.byType(AcceptInviteSheet), findsOneWidget); +} + +void _expectActionRowOnSheet( + WidgetTester tester, + Size size, { + double? maxBottom, +}) { + final bottomLimit = maxBottom ?? size.height; + for (final label in ['Cancel', 'Send Request']) { + final button = find.widgetWithText(PrismButton, label); + expect(button, findsOneWidget, reason: '$label must be on the sheet'); + final rect = tester.getRect(button); + expect( + rect.top, + greaterThanOrEqualTo(0), + reason: '$label is above the sheet top: $rect', + ); + expect( + rect.bottom, + lessThanOrEqualTo(bottomLimit), + reason: + '$label must stay on the sheet: it is at $rect on a ' + '${size.height}dp viewport (limit $bottomLimit).', + ); + final labelRect = tester.getRect(find.text(label)); + expect(labelRect.bottom, lessThanOrEqualTo(bottomLimit)); + expect(labelRect.top, greaterThanOrEqualTo(0)); + } +} + +void main() { + setUpAll(loadAccessFonts); + + testWidgets('default text: Cancel and Send Request are on the sheet and ' + 'Cancel dismisses without sending', (tester) async { + bool? result; + var closed = false; + await _pumpSheet( + tester, + size: compactPhone, + onResult: (value) { + result = value; + closed = true; + }, + ); + + expect(tester.takeException(), isNull); + _expectActionRowOnSheet(tester, compactPhone); + + await tester.tap(find.widgetWithText(PrismButton, 'Cancel')); + await tester.pumpAndSettle(); + + expect(closed, isTrue); + expect(result, isNull, reason: 'cancelling sends nothing'); + expect(find.byType(AcceptInviteSheet), findsNothing); + }); + + testWidgets('Send Request is inert until the sheet has something to send', ( + tester, + ) async { + await _pumpSheet(tester, size: compactPhone); + + final sendButton = tester.widget( + find.widgetWithText(PrismButton, 'Send Request'), + ); + expect(sendButton.enabled, isFalse); + + await tester.tap(find.widgetWithText(PrismButton, 'Send Request')); + await tester.pumpAndSettle(); + + // The tap does nothing: the sheet is still there and nothing was sent. + expect(find.byType(AcceptInviteSheet), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets('${scenario.name}: the action row stays on a compact phone and ' + 'Cancel still dismisses', (tester) async { + bool? result; + var closed = false; + await _pumpSheet( + tester, + size: compactPhone, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + onResult: (value) { + result = value; + closed = true; + }, + ); + + expect( + tester.takeException(), + isNull, + reason: + 'the sheet body must fit the space it is given: it is tight to the ' + 'viewport, so its content scrolls instead of overflowing.', + ); + _expectActionRowOnSheet(tester, compactPhone); + + await tester.tap(find.widgetWithText(PrismButton, 'Cancel')); + await tester.pumpAndSettle(); + expect(closed, isTrue); + expect(result, isNull); + }); + + testWidgets('${scenario.name} with long input: nothing is pushed off the ' + 'sheet', (tester) async { + await _pumpSheet( + tester, + size: compactPhone, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ); + + // A long display name and a long, invalid sharing code: the error + // surface and the preview row both grow, and the action row must still + // be on the sheet. + const longName = 'Wren and Nico of the Long-Named System'; + final longCode = 'prism-share:${'ab' * 120}'; + // The body is a lazy ListView: a field below the fold is not built, so it is + // scrolled to by its own label (never indexed among "all fields", which + // would count only the ones that happen to exist). + final body = find.byType(Scrollable).first; + await tester.scrollUntilVisible( + find.text('Sharing code'), + 120, + scrollable: body, + ); + await tester.pumpAndSettle(); + final codeField = find.descendant( + of: find.byWidgetPredicate( + (widget) => + widget is PrismTextField && widget.labelText == 'Sharing code', + ), + matching: find.byType(TextField), + ); + expect(codeField, findsOneWidget); + await tester.enterText(codeField, longCode); + await tester.pumpAndSettle(); + + await tester.scrollUntilVisible( + find.text('Your display name'), + 120, + scrollable: body, + ); + await tester.pumpAndSettle(); + final nameField = find.descendant( + of: find.byWidgetPredicate( + (widget) => + widget is PrismTextField && + widget.labelText == 'Your display name', + ), + matching: find.byType(TextField), + ); + expect(nameField, findsOneWidget); + await tester.enterText(nameField, longName); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + _expectActionRowOnSheet(tester, compactPhone); + }); + } + + testWidgets('composed 3.375x with the keyboard up on a compact phone: the ' + 'action row is still reachable', (tester) async { + await _pumpSheet( + tester, + size: compactPhone, + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + keyboardInset: 260, + ); + + expect(tester.takeException(), isNull); + // The sheet is padded above the keyboard, so the actions must clear it. + _expectActionRowOnSheet( + tester, + compactPhone, + maxBottom: compactPhone.height - 260, + ); + + // Typing into the code field keeps the sheet usable: the field is on the + // sheet and the actions do not move off it. + final body = find.byType(Scrollable).first; + await tester.scrollUntilVisible( + find.text('Sharing code'), + 120, + scrollable: body, + ); + await tester.pumpAndSettle(); + final codeField = find.descendant( + of: find.byWidgetPredicate( + (widget) => + widget is PrismTextField && widget.labelText == 'Sharing code', + ), + matching: find.byType(TextField), + ); + expect(codeField, findsOneWidget); + await tester.enterText(codeField, 'prism-share:abc'); + await tester.pumpAndSettle(); + _expectActionRowOnSheet( + tester, + compactPhone, + maxBottom: compactPhone.height - 260, + ); + }); +} diff --git a/test/text_scale_fixes/access/access_text_scale_harness.dart b/test/text_scale_fixes/access/access_text_scale_harness.dart new file mode 100644 index 000000000..fad3253da --- /dev/null +++ b/test/text_scale_fixes/access/access_text_scale_harness.dart @@ -0,0 +1,226 @@ +// Shared harness for the onboarding, recovery-word and invite text-scale +// regressions. +// +// Mirrors how `lib/app.dart` composes text size: the user's system +// accessibility scaler, then Prism's own font-size preference, delegated per +// font size through [PrismTextScaler] (no global clamp anywhere). Real bundled +// faces (Lexend/OpenDyslexic + the emoji fallback) are loaded so measurements +// come from the glyphs the app actually paints, not the square test font. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// Compact phone the scenario is measured on. +const Size compactPhone = Size(320, 568); + +/// Desktop/tablet width used for the "wide" controls. +const Size wideDesktop = Size(1440, 900); + +/// Platform accessibility ceiling used by the stress scenarios (225%). +const TextScaler maxSystemScaler = TextScaler.linear(2.25); + +/// Prism's own font-size ceiling (150%). +const double maxAppFontScale = 1.5; + +/// A long, narrow window: same 320dp width as the compact phone but enough +/// height for the shared onboarding header. Used only where a case measures a +/// horizontal defect and must not also exercise the separate header/body +/// vertical squeeze on short windows. +const Size narrowTallPhone = Size(320, 1800); + +Future loadAccessFonts() => loadPrismGoldenFonts(); + +/// Deterministic window size, with an optional software-keyboard inset. +void useWindow(WidgetTester tester, Size size, {double keyboardInset = 0}) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + if (keyboardInset > 0) { + tester.view.viewInsets = FakeViewPadding(bottom: keyboardInset); + } + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + tester.view.resetViewInsets(); + }); +} + +/// Theme with the bundled faces the app ships; [family] selects which one. +ThemeData accessTheme({String family = 'OpenDyslexic'}) => + ThemeData(fontFamily: family, fontFamilyFallback: const ['NotoColorEmoji']); + +/// MaterialApp that composes the system scaler with Prism's preference exactly +/// like `app.dart`, so measurements see the same text size the user chose. +Widget accessApp( + Widget home, { + TextScaler? systemScaler, + double appFontScale = 1.0, + ThemeData? theme, +}) { + return MaterialApp( + theme: theme ?? accessTheme(), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) { + final content = child ?? const SizedBox.shrink(); + if (systemScaler == null) return content; + return MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: PrismTextScaler(systemScaler, appFontScale)), + child: content, + ); + }, + home: home, + ); +} + +/// A deliberately nonlinear scaler: no case may assume a single scale ratio or +/// derive one length from another by multiplication. +class NonlinearTextScaler extends TextScaler { + const NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 3.0 : fontSize * 1.6; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.0; + + @override + bool operator ==(Object other) => other is NonlinearTextScaler; + + @override + int get hashCode => 0x4e0a; +} + +/// The scaler in effect inside the widget under test. +TextScaler effectiveScaler(WidgetTester tester, Finder finder) => + MediaQuery.textScalerOf(tester.element(finder)); + +/// The paragraph a [Text] really rendered: its resolved span (family, height, +/// leading included), scaler, direction, locale and the width it was given. +/// +/// Measuring from this - never from `Text.style` - is what makes a height +/// assertion describe the glyphs on screen. `Text.style` carries only the +/// explicit part of the style, so a painter built from it silently drops the +/// ambient DefaultTextStyle and the app's font family. +RenderParagraph paragraphOf(WidgetTester tester, Finder textFinder) { + return tester.renderObject( + find.descendant(of: textFinder, matching: find.byType(RichText)).first, + ); +} + +double _layoutWidth(RenderParagraph paragraph) { + final width = paragraph.constraints.hasBoundedWidth + ? paragraph.constraints.maxWidth + : paragraph.size.width; + // RenderParagraph widens the layout to infinity when the text neither wraps + // nor ellipsises (`softWrap || overflow == ellipsis ? maxWidth : infinity`). + // TextPainter has no softWrap/overflow parameters, so mirror that decision + // here instead of inventing constructor fields. + return paragraph.softWrap || paragraph.overflow == TextOverflow.ellipsis + ? width + : double.infinity; +} + +double _layoutMinWidth(RenderParagraph paragraph) => + paragraph.constraints.hasBoundedWidth ? paragraph.constraints.minWidth : 0; + +/// A painter configured exactly like the paragraph's own, so heights and line +/// counts describe the same glyphs. +TextPainter _mirrorPainter( + RenderParagraph paragraph, { + bool unboundedLines = false, +}) { + return TextPainter( + text: paragraph.text, + textAlign: paragraph.textAlign, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + maxLines: unboundedLines ? null : paragraph.maxLines, + ellipsis: paragraph.overflow == TextOverflow.ellipsis ? '\u2026' : null, + locale: paragraph.locale, + textWidthBasis: paragraph.textWidthBasis, + textHeightBehavior: paragraph.textHeightBehavior, + ); +} + +/// Height [paragraph]'s own span needs at the width it was given. +/// +/// [unboundedLines] drops the widget's own line cap so a case can ask for the +/// full natural height; the default keeps the cap the widget renders with, +/// which is what "not squeezed" means. +double paragraphHeight( + RenderParagraph paragraph, { + bool unboundedLines = false, + double? atWidth, +}) { + final painter = _mirrorPainter(paragraph, unboundedLines: unboundedLines) + ..layout( + minWidth: atWidth == null ? _layoutMinWidth(paragraph) : 0, + maxWidth: atWidth ?? _layoutWidth(paragraph), + ); + return painter.height; +} + +/// Number of lines [paragraph]'s span needs at the width it was given. +int paragraphLineCount(RenderParagraph paragraph) { + final painter = _mirrorPainter(paragraph) + ..layout( + minWidth: _layoutMinWidth(paragraph), + maxWidth: _layoutWidth(paragraph), + ); + return painter.computeLineMetrics().length; +} + +/// Upper bound: the tallest [paragraph]'s own span can be at the width it was +/// given, computed by the paragraph itself. +/// +/// `getMaxIntrinsicHeight` is the SDK's own answer for "how tall would this +/// paragraph be at this width with the line cap lifted", so the bound cannot +/// disagree with the text on screen. Rebuilding a painter at an unbounded one-line +/// width was wrong: at large text it reported a single line (32dp) for a label +/// that legitimately wraps to two (64dp) and turned a correct layout into a +/// failure. +double paragraphMaxIntrinsicHeight(RenderParagraph paragraph) => + paragraph.getMaxIntrinsicHeight(_layoutWidth(paragraph)); + +/// Width [paragraph]'s span needs on one line at its own size. +double paragraphIntrinsicWidth(RenderParagraph paragraph) { + final painter = _mirrorPainter(paragraph)..layout(); + return painter.width; +} + +/// The editable text render object inside a text field. +RenderEditable editableOf(WidgetTester tester, Finder fieldFinder) { + final fieldRect = tester.getRect(fieldFinder); + for (final candidate in tester.allRenderObjects.whereType()) { + if (!candidate.attached || !candidate.hasSize) continue; + final rect = candidate.localToGlobal(Offset.zero) & candidate.size; + if (fieldRect.contains(rect.center)) return candidate; + } + throw StateError('no RenderEditable inside $fieldFinder'); +} + +/// Height one line of [editable]'s own span needs. +/// +/// `RenderEditable.preferredLineHeight` is the SDK's own measurement of a +/// typical line in that editable's style, scaler and locale, so it needs no +/// re-created painter and cannot disagree with the glyphs on screen. +double editableLineHeight(RenderEditable editable) => + editable.preferredLineHeight; + +/// True when [inner] sits inside [outer] (with a half-pixel of slack): the +/// no-shrink check - a laid-out box that paints outside its container has been +/// clipped or displaced. +bool rectInside(Rect inner, Rect outer, {double slack = 0.5}) => + inner.top >= outer.top - slack && + inner.bottom <= outer.bottom + slack && + inner.left >= outer.left - slack && + inner.right <= outer.right + slack; diff --git a/test/text_scale_fixes/access/onboarding_action_pill_text_scale_test.dart b/test/text_scale_fixes/access/onboarding_action_pill_text_scale_test.dart new file mode 100644 index 000000000..3368e84f2 --- /dev/null +++ b/test/text_scale_fixes/access/onboarding_action_pill_text_scale_test.dart @@ -0,0 +1,202 @@ +// Onboarding action pills: PrismButton sits in a 52dp minimum, so the label +// keeps its requested size and the pill grows with it. +// +// `onboarding_data_ready_view.dart` is the public instance of that wrapper; the +// `_ActionButton` in `sync_device_step.dart` and `import_data_step.dart` uses the +// same shape inside its own flow. At default text the pill is exactly 52dp; once +// the label needs more than 12dp of padding plus its lines, the pill has to grow +// rather than clip. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/onboarding/models/onboarding_data_counts.dart'; +import 'package:prism_plurality/features/onboarding/widgets/onboarding_data_ready_view.dart'; +import 'package:prism_plurality/shared/widgets/prism_button.dart'; + +import 'access_text_scale_harness.dart'; + +const _counts = OnboardingDataCounts( + members: 3, + frontingSessions: 41, + conversations: 2, + messages: 120, + habits: 1, + notes: 7, +); + +Widget _view({ + String actionLabel = 'Get started', + VoidCallback? onAction, + TextScaler? systemScaler, + double appFontScale = 1.0, +}) { + return ProviderScope( + child: accessApp( + Scaffold( + body: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: OnboardingDataReadyView( + title: 'Import complete', + description: 'Your data is ready.', + summaryLabel: 'Imported', + counts: _counts, + actionLabel: actionLabel, + onAction: onAction ?? () {}, + ), + ), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); +} + +/// The label is laid out at the size its own glyphs need and stays inside its +/// pill. +/// +/// Everything here is measured from the paragraph that is actually on screen +/// (its resolved span, scaler, width, text-height behaviour), not from a style +/// rebuilt in the test: a rebuilt style silently loses the ambient +/// DefaultTextStyle and the app font, and then the "needed" height belongs to a +/// different font than the one being read. +void _expectLabelFitsPill(WidgetTester tester) { + final button = find.byType(PrismButton); + expect(button, findsOneWidget); + final buttonRect = tester.getRect(button); + final label = find.descendant(of: button, matching: find.byType(Text)).first; + final paragraph = paragraphOf(tester, label); + final labelRect = paragraph.localToGlobal(Offset.zero) & paragraph.size; + + expect( + rectInside(labelRect, buttonRect), + isTrue, + reason: 'the label rect $labelRect must sit inside its pill $buttonRect', + ); + + // What the span needs at the width it was given, with the label's own line + // cap (PrismButton: two lines) and, for the diagnostic, with no cap at all. + final needed = paragraphHeight(paragraph); + final natural = paragraphMaxIntrinsicHeight(paragraph); + final lines = paragraphLineCount(paragraph); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + 'the label needs ${needed.toStringAsFixed(1)}dp for its $lines natural ' + 'line(s) but is laid out at ' + '${paragraph.size.height.toStringAsFixed(1)}dp', + ); + expect( + paragraph.size.height, + lessThanOrEqualTo(natural + 0.5), + reason: 'the label is laid out no taller than its own span needs', + ); +} + +void main() { + setUpAll(loadAccessFonts); + + testWidgets('default text: the action keeps its 52dp pill and fires its ' + 'callback', (tester) async { + useWindow(tester, compactPhone); + var taps = 0; + await tester.pumpWidget(_view(onAction: () => taps += 1)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(tester.getSize(find.byType(PrismButton)).height, closeTo(52, 0.5)); + _expectLabelFitsPill(tester); + + await tester.ensureVisible(find.byType(PrismButton)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(PrismButton)); + await tester.pumpAndSettle(); + expect(taps, 1); + }); + + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets('${scenario.name}: the action pill grows with its label on a ' + 'compact phone and still fires', (tester) async { + useWindow(tester, compactPhone); + var taps = 0; + await tester.pumpWidget( + _view( + onAction: () => taps += 1, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + _expectLabelFitsPill(tester); + + // Bring the action on screen before tapping it: the view is a scroll + // body and at large text the pill starts below the fold. + await tester.ensureVisible(find.byType(PrismButton)); + await tester.pumpAndSettle(); + + final buttonRect = tester.getRect(find.byType(PrismButton)); + expect(buttonRect.right, lessThanOrEqualTo(compactPhone.width)); + expect(buttonRect.left, greaterThanOrEqualTo(0)); + expect(buttonRect.bottom, lessThanOrEqualTo(compactPhone.height)); + + await tester.tap(find.byType(PrismButton)); + await tester.pumpAndSettle(); + expect(taps, 1); + }); + } + + testWidgets('composed 3.375x on a wide window: the pill grows with one full ' + 'line of its label', (tester) async { + useWindow(tester, wideDesktop); + await tester.pumpWidget( + _view(systemScaler: maxSystemScaler, appFontScale: maxAppFontScale), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + _expectLabelFitsPill(tester); + + // On a wide window the label has room to lay out within the pill it is given. + // The pill hugs its content, so the available label width comes from the + // paragraph's own box rather than from the window width: the claim is that the + // text fits that box, not that it must be one line. + final label = find + .descendant(of: find.byType(PrismButton), matching: find.byType(Text)) + .first; + final paragraph = paragraphOf(tester, label); + expect( + paragraph.size.height, + lessThanOrEqualTo(paragraphHeight(paragraph) + 0.5), + reason: 'the label is laid out no taller than its own span needs', + ); + expect( + paragraphLineCount(paragraph), + lessThanOrEqualTo(2), + reason: 'the pill caps its label at two lines', + ); + }); + + testWidgets('a long action label at 3.375x stays inside the pill instead of ' + 'overflowing it', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _view( + actionLabel: + 'Start using your system and open the fronting screen for today', + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + _expectLabelFitsPill(tester); + }); +} diff --git a/test/text_scale_fixes/access/onboarding_cta_progress_text_scale_test.dart b/test/text_scale_fixes/access/onboarding_cta_progress_text_scale_test.dart new file mode 100644 index 000000000..b69c4c808 --- /dev/null +++ b/test/text_scale_fixes/access/onboarding_cta_progress_text_scale_test.dart @@ -0,0 +1,318 @@ +// Onboarding progress and CTA: the progress strip fits the slot it is given at +// any width, and the Continue / Get started action stays inside the viewport and +// stays tappable at every text scale. +// +// The strip is fixed geometry - fifteen capsules with the current one double +// width - so it can exceed a narrow slot; the CTA is the only forward action, so +// it must never paint past the edge. Both are measured here from the painted +// boxes, and the CTA's tap is checked against the flow it advances. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; +import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; +import 'package:prism_plurality/features/onboarding/views/onboarding_screen.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; + +import 'access_text_scale_harness.dart'; + +/// Seeds onboarding on the features step (its body scrolls, so a case measures +/// the shared header, the step body and the shared bottom bar) and records +/// forwards instead of moving the flow, so a tap has an observable result +/// without dragging database providers into the case. +class _RecordingFeaturesNotifier extends OnboardingNotifier { + int nextCalls = 0; + + @override + OnboardingState build() => + const OnboardingState(currentStep: OnboardingStep.features); + + @override + void next() { + nextCalls += 1; + } +} + +class _Harness { + _Harness() { + container = ProviderContainer( + overrides: [ + onboardingProvider.overrideWith(_RecordingFeaturesNotifier.new), + hasCompletedOnboardingProvider.overrideWithValue(false), + syncDisconnectMarkerProvider.overrideWith((ref) async => null), + ], + ); + } + + late final ProviderContainer container; + + _RecordingFeaturesNotifier get notifier => + container.read(onboardingProvider.notifier) as _RecordingFeaturesNotifier; + + Future pump( + WidgetTester tester, { + TextScaler? systemScaler, + double appFontScale = 1.0, + ThemeData? theme, + }) async { + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + theme: theme, + ), + ); + await tester.pumpAndSettle(); + } + + void dispose() => container.dispose(); +} + +/// Every capsule in the progress strip, measured as the box it actually paints. +/// +/// An `AnimatedContainer` with a margin reports the *outer* box (painted width +/// plus both margins), so the margin the widget itself carries is subtracted here +/// rather than assumed: comparing outer boxes would read 28/16 for a 24/12 strip. +List _capsuleRects(WidgetTester tester) { + final rects = []; + for (final element in find.byType(AnimatedContainer).evaluate()) { + final widget = element.widget as AnimatedContainer; + final box = element.renderObject! as RenderBox; + // `margin` is an EdgeInsetsGeometry: resolve it with the direction this + // element is actually laid out in, so `left`/`right` follow the widget's + // directionality rather than being assumed. + final margin = (widget.margin ?? EdgeInsets.zero).resolve( + Directionality.of(element), + ); + if ((box.size.height - 4).abs() > 0.01) continue; // the strip's capsules + final painted = box.size.width - margin.horizontal; + final topLeft = box.localToGlobal(Offset.zero); + rects.add( + Rect.fromLTWH( + topLeft.dx + margin.left, + topLeft.dy + (box.size.height - 4) / 2, + painted, + 4, + ), + ); + } + return rects; +} + +/// The margin the strip's capsules carry, read from the widget itself. +double _capsuleMargin(WidgetTester tester) { + for (final element in find.byType(AnimatedContainer).evaluate()) { + final widget = element.widget as AnimatedContainer; + final geometry = widget.margin; + if (geometry == null) continue; + final margin = geometry.resolve(Directionality.of(element)); + if (margin.vertical == 0 && margin.horizontal > 0) { + return margin.horizontal; + } + } + return 0; +} + +void main() { + setUpAll(loadAccessFonts); + + // The header reserves 20dp padding plus a 48dp action slot on each side. + const headerPadding = 20.0; + const actionSlot = 48.0; + + testWidgets('default text: the 15 progress capsules fit the header slot on a ' + 'compact phone', (tester) async { + useWindow(tester, compactPhone); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump(tester); + + // Fifteen capsules cannot overflow the slot they are laid out in. + expect(tester.takeException(), isNull); + + final capsules = _capsuleRects(tester); + expect(capsules, hasLength(15)); + + const slotLeft = headerPadding + actionSlot; + final slotRight = compactPhone.width - headerPadding - actionSlot; + for (final rect in capsules) { + expect( + rect.left, + greaterThanOrEqualTo(slotLeft - 0.5), + reason: 'capsule at $rect starts left of the progress slot', + ); + expect( + rect.right, + lessThanOrEqualTo(slotRight + 0.5), + reason: + 'capsule at $rect paints past the progress slot on a 320dp ' + 'phone; the strip must fit the width it is given', + ); + } + + // Structure, from the render tree rather than assumed numbers: one current + // capsule wider than the fourteen others, all of them inside the slot. + final widths = capsules.map((r) => r.width).toList(); + final uniqueWidths = widths.toSet(); + expect( + uniqueWidths.length, + 2, + reason: 'exactly one capsule is the current one (widths: $uniqueWidths)', + ); + final sorted = uniqueWidths.toList()..sort(); + expect( + widths.where((w) => (w - sorted.last).abs() < 0.01), + hasLength(1), + reason: 'a single capsule carries the current-step emphasis', + ); + expect( + widths.where((w) => (w - sorted.first).abs() < 0.01), + hasLength(14), + reason: 'the other fourteen capsules share one width', + ); + }); + + testWidgets('wide layout: default capsule geometry and CTA placement are ' + 'unchanged', (tester) async { + useWindow(tester, wideDesktop); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ); + + expect(tester.takeException(), isNull); + + final capsules = _capsuleRects(tester); + expect(capsules, hasLength(15)); + + // Structure, not assumed numbers: on a wide window the strip keeps its + // ideal geometry, so the current capsule is exactly twice a peer, the other + // fourteen share one width, and the whole strip stays narrower than the slot + // (which is wide here, so the cap is what holds it). + final widths = capsules.map((r) => r.width).toList(); + final uniqueWidths = widths.toSet().toList()..sort(); + expect(uniqueWidths, hasLength(2), reason: 'widths: $uniqueWidths'); + expect( + uniqueWidths.last, + closeTo(uniqueWidths.first * 2, 0.01), + reason: 'the current capsule is double width', + ); + expect( + widths.where((w) => (w - uniqueWidths.last).abs() < 0.01), + hasLength(1), + ); + expect( + widths.where((w) => (w - uniqueWidths.first).abs() < 0.01), + hasLength(14), + ); + final stripWidth = + capsules.fold(0, (sum, r) => sum + r.width) + + capsules.length * _capsuleMargin(tester); + expect( + stripWidth, + lessThanOrEqualTo(252 + 0.5), + reason: 'the strip keeps its 252dp ideal width when it has room', + ); + + // On a wide screen no label needs to wrap: the CTA keeps one line and + // stays against the right edge of the shared 24dp padding. + final label = find.text('Continue'); + final paragraph = paragraphOf(tester, label); + expect( + paragraphLineCount(paragraph), + 1, + reason: 'the CTA label must not wrap when it has the width to fit', + ); + expect( + paragraph.size.height, + lessThanOrEqualTo(paragraphHeight(paragraph) + 0.5), + ); + final labelRect = paragraph.localToGlobal(Offset.zero) & paragraph.size; + expect(labelRect.right, lessThanOrEqualTo(wideDesktop.width - 24 + 0.5)); + expect(labelRect.right, greaterThan(wideDesktop.width - 24 - 240)); + }); + + for (final scenario + in <({String name, Size size, TextScaler? scaler, double app})>[ + (name: 'default text', size: compactPhone, scaler: null, app: 1.0), + ( + name: 'composed 1.5x', + size: compactPhone, + scaler: const TextScaler.linear(1.0), + app: 1.5, + ), + ( + name: 'composed 3.375x', + size: compactPhone, + scaler: maxSystemScaler, + app: maxAppFontScale, + ), + ( + name: 'Prism 50% small text', + size: compactPhone, + scaler: const TextScaler.linear(1.0), + app: 0.5, + ), + ]) { + testWidgets('${scenario.name}: the Continue CTA stays inside the viewport ' + 'and still forwards the flow', (tester) async { + useWindow(tester, scenario.size); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ); + + expect(tester.takeException(), isNull); + + final label = find.text('Continue'); + expect(label, findsOneWidget); + final labelRect = tester.getRect(label); + expect( + labelRect.left, + greaterThanOrEqualTo(0), + reason: + 'the CTA label must stay inside the ${320}dp viewport: it is at ' + '$labelRect', + ); + expect(labelRect.right, lessThanOrEqualTo(scenario.size.width)); + + // The label is not clipped: the paragraph that is really on screen is + // laid out as tall as its own resolved span needs at its own width. + final paragraph = paragraphOf(tester, label); + final needed = paragraphHeight(paragraph); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + 'the CTA label must be laid out at its full requested size ' + '(needs ${needed.toStringAsFixed(1)}dp, has ' + '${paragraph.size.height.toStringAsFixed(1)}dp)', + ); + + // The hit target itself is inside the viewport, and a tap reaches the + // flow: this is the only forward action on the step. + final surfaceRect = tester.getRect( + find.ancestor(of: label, matching: find.byType(AnimatedScale)).first, + ); + expect(surfaceRect.right, lessThanOrEqualTo(scenario.size.width + 0.5)); + expect(surfaceRect.left, greaterThanOrEqualTo(0)); + + expect(harness.notifier.nextCalls, 0); + await tester.tap(label); + await tester.pumpAndSettle(); + expect(harness.notifier.nextCalls, 1); + }); + } +} diff --git a/test/text_scale_fixes/access/onboarding_flow_action_pill_text_scale_test.dart b/test/text_scale_fixes/access/onboarding_flow_action_pill_text_scale_test.dart new file mode 100644 index 000000000..5a74073ee --- /dev/null +++ b/test/text_scale_fixes/access/onboarding_flow_action_pill_text_scale_test.dart @@ -0,0 +1,603 @@ +// Onboarding action pills inside their real flows. +// +// `sync_device_step.dart` and `import_data_step.dart` wrap PrismButton in +// `SizedBox(height: 52)`. PrismButton is 12dp of padding plus up to a two-line +// 15pt label, so a tight 52dp box clips the label from ~1.5x on. These cases +// drive the real step widgets - not a copy of the wrapper - and assert the +// label is laid out at the size the user asked for and stays inside its pill, +// plus the flow's own busy / disabled / back behaviour at the same text size. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; +import 'package:prism_plurality/features/onboarding/providers/device_pairing_provider.dart'; +import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; +import 'package:prism_plurality/features/onboarding/views/onboarding_screen.dart'; +import 'package:prism_plurality/features/onboarding/widgets/import_data_step.dart'; +import 'package:prism_plurality/features/onboarding/widgets/phase_segments.dart'; +import 'package:prism_plurality/features/onboarding/widgets/sync_device_step.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/widgets/prism_button.dart'; + +import 'access_text_scale_harness.dart'; + +// --------------------------------------------------------------------------- +// Harness: onboarding on the import step +// --------------------------------------------------------------------------- + +class _ImportStepNotifier extends OnboardingNotifier { + int nextCalls = 0; + + @override + OnboardingState build() => + const OnboardingState(currentStep: OnboardingStep.importData); + + /// Runs the real forward action and records that it happened, so a case can + /// assert the flow actually advanced rather than a counter that could fire + /// without the step moving. + @override + void next() { + nextCalls += 1; + super.next(); + } +} + +class _ImportHarness { + _ImportHarness() { + container = ProviderContainer( + overrides: [ + onboardingProvider.overrideWith(_ImportStepNotifier.new), + hasCompletedOnboardingProvider.overrideWithValue(false), + syncDisconnectMarkerProvider.overrideWith((ref) async => null), + ], + ); + } + + late final ProviderContainer container; + + OnboardingState get state => container.read(onboardingProvider); + + _ImportStepNotifier get notifier => + container.read(onboardingProvider.notifier) as _ImportStepNotifier; + + Future pump( + WidgetTester tester, { + TextScaler? systemScaler, + double appFontScale = 1.0, + }) async { + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); + await tester.pumpAndSettle(); + } + + void dispose() => container.dispose(); +} + +// --------------------------------------------------------------------------- +// Harness: the sync-device step on its own +// --------------------------------------------------------------------------- + +/// Pins the pairing step so the join prompt (or the connecting view) renders +/// without any network attempt. +class _FixedPairingNotifier extends DevicePairingNotifier { + _FixedPairingNotifier(this._state); + + final PairingState _state; + + @override + PairingState build() => _state; +} + +/// The real initial join prompt with its real action, but no network: the +/// rendezvous request is recorded instead of being sent. +class _RecordingPairingNotifier extends DevicePairingNotifier { + int requests = 0; + + @override + PairingState build() => const PairingState(step: PairingStep.enterUrl); + + @override + Future generateRequest({ + String? relayUrl, + String? registrationToken, + }) async { + requests += 1; + } +} + +Widget _syncStepHost({ + PairingState? pairing, + bool recordingPairing = false, + VoidCallback? onBack, + TextScaler? systemScaler, + double appFontScale = 1.0, +}) { + final pinned = pairing; + return ProviderScope( + overrides: [ + if (pinned != null) + devicePairingProvider.overrideWith(() => _FixedPairingNotifier(pinned)), + if (recordingPairing) + devicePairingProvider.overrideWith(_RecordingPairingNotifier.new), + ], + child: accessApp( + Scaffold( + body: SafeArea( + child: SyncDeviceStep(onBack: onBack ?? () {}, onComplete: () {}), + ), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); +} + +/// Scroll the import step's own body until [finder] is visible, then tap it. +/// +/// At large text the flow's cards and action button start below the fold, and a +/// lazy list only builds what is in view, so a plain find/tap can resolve to +/// nothing; `scrollUntilVisible` walks the body until the target exists. +Future _scrollAndTap(WidgetTester tester, Finder finder) async { + final bodyScrollable = find + .descendant( + of: find.byType(ImportDataStep), + matching: find.byType(Scrollable), + ) + .first; + await tester.scrollUntilVisible(finder, 120, scrollable: bodyScrollable); + await tester.pumpAndSettle(); + final trace = [_importHitTrace(tester, finder, 'after body reveal')]; + // A nested body can expose the label to its own viewport while the flow's + // pinned footer still covers it. Reveal through every real ancestor; never + // tap the footer or call the intended callback directly to bypass this case. + for (final alignment in [0.5, 0.0, 1.0]) { + if (finder.hitTestable().evaluate().isNotEmpty) break; + await Scrollable.ensureVisible( + tester.element(finder), + alignment: alignment, + ); + await tester.pumpAndSettle(); + trace.add(_importHitTrace(tester, finder, 'alignment $alignment')); + } + expect( + finder.hitTestable(), + findsOneWidget, + reason: + 'The intended import control must receive its own tap. ' + 'Bounded nested-scroll trace:\n${trace.join('\n')}', + ); + await tester.tap(finder); + await tester.pumpAndSettle(); +} + +String _importHitTrace(WidgetTester tester, Finder finder, String stage) { + final target = tester.renderObject(finder); + final center = target.localToGlobal(target.size.center(Offset.zero)); + final media = MediaQuery.of(tester.element(finder)); + final clipsAndOffsets = []; + final seen = {}; + tester.element(finder).visitAncestorElements((ancestor) { + if (ancestor is StatefulElement && ancestor.state is ScrollableState) { + final position = (ancestor.state as ScrollableState).position; + clipsAndOffsets.add( + 'scroll ${position.axisDirection}: ' + '${position.pixels} in ' + '[${position.minScrollExtent}, ${position.maxScrollExtent}]', + ); + } + final render = ancestor.renderObject; + if (render is RenderBox && + render.attached && + render.hasSize && + seen.add(render) && + (render is RenderAbstractViewport || + (render is RenderClipRect && render.clipBehavior != Clip.none) || + (render is RenderClipRRect && render.clipBehavior != Clip.none))) { + clipsAndOffsets.add( + 'clip ${render.runtimeType}: ' + '${MatrixUtils.transformRect(render.getTransformTo(null), render.paintBounds)}', + ); + } + return true; + }); + final message = + '$stage: $finder rect=${tester.getRect(finder)} ' + 'center=$center screen=${media.size} insets=${media.viewInsets} ' + 'padding=${media.padding} viewPadding=${media.viewPadding}; ' + '${clipsAndOffsets.join('; ')}; ' + 'hit=${tester.hitTestOnBinding(center)}'; + debugPrint(message); + return message; +} + +// --------------------------------------------------------------------------- +// Assertions +// --------------------------------------------------------------------------- + +/// The pill's label is at its requested size and inside the pill surface. +/// +/// Measured from the paragraph actually on screen - its resolved span, scaler, +/// width, line cap and text-height behaviour - so the expected height belongs to +/// the font the user is reading rather than to a style rebuilt in the test. +void _expectPillLabelFits(WidgetTester tester, String label) { + final text = find.text(label); + expect(text, findsOneWidget, reason: '"$label" must be on screen'); + final pill = find + .ancestor(of: text, matching: find.byType(PrismButton)) + .first; + final pillRect = tester.getRect(pill); + final paragraph = paragraphOf(tester, text); + final labelRect = paragraph.localToGlobal(Offset.zero) & paragraph.size; + + expect( + rectInside(labelRect, pillRect), + isTrue, + reason: + '"$label" ($labelRect) must sit inside its pill ($pillRect); the pill is a ' + 'minimum height, so it grows with the label instead of clipping it.', + ); + + final needed = paragraphHeight(paragraph); + final natural = paragraphMaxIntrinsicHeight(paragraph); + final lines = paragraphLineCount(paragraph); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + '"$label" needs ${needed.toStringAsFixed(1)}dp for its $lines natural ' + 'line(s) but is laid out at ' + '${paragraph.size.height.toStringAsFixed(1)}dp', + ); + expect( + paragraph.size.height, + lessThanOrEqualTo(natural + 0.5), + reason: '"$label" is laid out no taller than its own span needs', + ); +} + +void main() { + setUpAll(loadAccessFonts); + + // ------------------------------------------------------------------------- + // sync_device_step: the "Request to Join" pill + // ------------------------------------------------------------------------- + testWidgets('sync step at default text: the join pill keeps its 52dp height ' + 'and its label, and Back still leaves the step', (tester) async { + useWindow(tester, compactPhone); + var backs = 0; + await tester.pumpWidget(_syncStepHost(onBack: () => backs += 1)); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Request to Join'), findsOneWidget); + expect( + tester.getSize(find.byType(PrismButton).first).height, + closeTo(52, 0.5), + ); + _expectPillLabelFits(tester, 'Request to Join'); + + // The step's own Back control is on screen and leaves the step. + final back = find.text('Back'); + expect(back, findsOneWidget); + expect(tester.getRect(back).top, greaterThanOrEqualTo(0)); + await tester.tap(back); + await tester.pumpAndSettle(); + expect(backs, 1); + }); + + // The real initial join prompt, at large text, with its real action. The + // request itself is stubbed (recorded, never sent) so the case proves the + // wiring without a network attempt. + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets( + '${scenario.name} on a compact phone: the real join prompt keeps its ' + 'controls on screen and its Request to Join action still fires', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _syncStepHost( + recordingPairing: true, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: + 'the self-hosted toggle label must wrap inside its row rather than ' + 'overflowing to the right.', + ); + + final viewport = Offset.zero & compactPhone; + + // The self-hosted toggle: its label wraps at the requested size and the + // whole control stays inside the viewport. + final toggle = find.text('Self-hosted relay?'); + expect(toggle, findsOneWidget); + await tester.ensureVisible(toggle); + await tester.pumpAndSettle(); + final toggleParagraph = paragraphOf(tester, toggle); + expect( + toggleParagraph.size.height + 0.5, + greaterThanOrEqualTo(paragraphHeight(toggleParagraph)), + reason: 'the toggle label is laid out at its own wrapped height', + ); + expect(rectInside(tester.getRect(toggle), viewport), isTrue); + + // Back is on screen, and the only action is reachable and acts. + expect(find.text('Back'), findsOneWidget); + final action = find.text('Request to Join'); + expect(action, findsOneWidget); + await tester.ensureVisible(action); + await tester.pumpAndSettle(); + _expectPillLabelFits(tester, 'Request to Join'); + expect(rectInside(tester.getRect(action), viewport), isTrue); + + final notifier = + ProviderScope.containerOf( + tester.element(find.byType(SyncDeviceStep)), + ).read(devicePairingProvider.notifier) + as _RecordingPairingNotifier; + expect(notifier.requests, 0); + + await tester.tap(action); + await tester.pumpAndSettle(); + expect( + notifier.requests, + 1, + reason: 'the join action must still request a rendezvous', + ); + expect(tester.takeException(), isNull); + }, + ); + } + + // The error view is the flow's other real action surface (a scroll view with + // the same `_ActionButton` wrapper); kept as an independent case. + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets( + '${scenario.name} on a compact phone: the pairing error view is ' + 'scrollable, and its Try Again pill grows with its label instead of ' + 'clipping it', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _syncStepHost( + pairing: const PairingState( + step: PairingStep.error, + errorMessage: 'Could not reach the other device.', + ), + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: + 'the error view scrolls, so it must not overflow at ' + '${scenario.name}', + ); + + final pill = find.text('Try Again'); + expect(pill, findsOneWidget); + await tester.ensureVisible(pill); + await tester.pumpAndSettle(); + _expectPillLabelFits(tester, 'Try Again'); + + final pillRect = tester.getRect( + find.ancestor(of: pill, matching: find.byType(PrismButton)).first, + ); + expect(pillRect.right, lessThanOrEqualTo(compactPhone.width + 0.5)); + expect(pillRect.bottom, lessThanOrEqualTo(compactPhone.height + 0.5)); + }, + ); + } + + testWidgets( + 'sync step while a pairing attempt runs: the progress surface is on screen ' + 'and reachable, and no action is offered while it runs', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _syncStepHost( + pairing: const PairingState(step: PairingStep.connecting), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + // Bounded frames only: the spinner animates by design and the progress + // view rebuilds on a one-second timer, so pumpAndSettle would never stop. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(tester.takeException(), isNull); + + final title = find.text('Connecting…'); + expect(title, findsOneWidget); + await tester.ensureVisible(title); + await tester.pump(); + + final viewport = Offset.zero & compactPhone; + expect( + rectInside(tester.getRect(title), viewport), + isTrue, + reason: + 'the phase title must be reachable on a compact phone at max ' + 'text', + ); + + final segments = find.byType(PhaseSegments); + expect(segments, findsOneWidget); + await tester.ensureVisible(segments); + await tester.pump(); + expect(rectInside(tester.getRect(segments), viewport), isTrue); + + expect( + find.text('Request to Join'), + findsNothing, + reason: 'no action is offered while the pairing attempt runs', + ); + }, + ); + + // ------------------------------------------------------------------------- + // import_data_step inside the real screen: PK token flow + busy/Back + // ------------------------------------------------------------------------- + testWidgets( + 'import step at default text: the PluralKit import pill keeps its ' + '52dp height inside the real flow', + (tester) async { + useWindow(tester, compactPhone); + final harness = _ImportHarness(); + addTearDown(harness.dispose); + await harness.pump(tester); + + expect(tester.takeException(), isNull); + await _scrollAndTap(tester, find.text('PluralKit')); + await _scrollAndTap(tester, find.text('Import with a token')); + + final bodyScrollable = find + .descendant( + of: find.byType(ImportDataStep), + matching: find.byType(Scrollable), + ) + .first; + await tester.scrollUntilVisible( + find.text('Import PluralKit Data'), + 120, + scrollable: bodyScrollable, + ); + await tester.pumpAndSettle(); + _expectPillLabelFits(tester, 'Import PluralKit Data'); + }, + ); + + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets('${scenario.name} on a compact phone: the PluralKit import pill ' + 'in the real flow is laid out at full size, on screen, and a busy import ' + 'hides footer Back and disables Continue', (tester) async { + useWindow(tester, compactPhone); + final harness = _ImportHarness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ); + + expect(tester.takeException(), isNull); + + // Picker -> PluralKit -> token path. Every step is the real flow widget, + // and at this size each target starts below the fold, so it is scrolled to. + await _scrollAndTap(tester, find.text('PluralKit')); + await _scrollAndTap(tester, find.text('Import with a token')); + + final pill = find.text('Import PluralKit Data'); + final bodyScrollable = find + .descendant( + of: find.byType(ImportDataStep), + matching: find.byType(Scrollable), + ) + .first; + await tester.scrollUntilVisible(pill, 120, scrollable: bodyScrollable); + await tester.pumpAndSettle(); + _expectPillLabelFits(tester, 'Import PluralKit Data'); + + final pillRect = tester.getRect( + find.ancestor(of: pill, matching: find.byType(PrismButton)).first, + ); + expect(pillRect.right, lessThanOrEqualTo(compactPhone.width + 0.5)); + expect(pillRect.bottom, lessThanOrEqualTo(compactPhone.height + 0.5)); + + // During a running operation, visible Back is hidden and Continue is inert. + // System/hardware Back policy is outside these UI-scale cases. + harness.container.read(onboardingImportBusyProvider.notifier).set(true); + await tester.pumpAndSettle(); + + expect( + find.byIcon(AppIcons.arrowBack), + findsNothing, + reason: 'the footer back control is removed while an import runs', + ); + + await tester.ensureVisible(find.text('Continue')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + expect( + harness.notifier.nextCalls, + 0, + reason: 'a busy import step cannot be left by Continue', + ); + + // Idle again: the footer restores. While a sub-flow is open the footer's + // Continue runs that flow's pending action, so the step is left first and + // the real advance is asserted on the picker, where nothing shadows it. + harness.container.read(onboardingImportBusyProvider.notifier).set(false); + await tester.pumpAndSettle(); + expect(find.byIcon(AppIcons.arrowBack), findsOneWidget); + + await _scrollAndTap(tester, find.text('Other import options')); + expect( + find.text('Import with a token'), + findsOneWidget, + reason: 'the first Back returns from token entry to the method picker', + ); + expect(find.text('Import from pk;export file'), findsOneWidget); + expect(find.text('Import PluralKit Data'), findsNothing); + expect( + find.text('PluralKit'), + findsNothing, + reason: 'the method picker is still inside the PluralKit source', + ); + + await _scrollAndTap(tester, find.text('Other import options')); + expect(find.text('Import with a token'), findsNothing); + expect( + find.text('PluralKit'), + findsOneWidget, + reason: 'the flow returns to the source picker', + ); + + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + expect( + harness.notifier.nextCalls, + 1, + reason: 'an idle import step still advances', + ); + expect( + harness.state.currentStep, + isNot(OnboardingStep.importData), + reason: 'the real forward action moves the flow on', + ); + }); + } +} diff --git a/test/text_scale_fixes/access/onboarding_header_squeeze_text_scale_test.dart b/test/text_scale_fixes/access/onboarding_header_squeeze_text_scale_test.dart new file mode 100644 index 000000000..0b8c89e8b --- /dev/null +++ b/test/text_scale_fixes/access/onboarding_header_squeeze_text_scale_test.dart @@ -0,0 +1,323 @@ +// Onboarding header/body composition: on a 320x568 phone at the maximum +// composed text size the step body must still exist, and the step's controls +// and the only forward action must still be reachable. +// +// Source proof of the original defect (onboarding_screen.dart, pre-fix): the +// progress strip (28dp when the close action is hidden), the step header +// (8 + 56 logo + 12 + a 28pt title + 4 + a 15pt subtitle + 20) and the bottom +// bar (32 + a two-line 16pt pill) are all fixed blocks in one Column, while the +// step body is the only flexible child. At 3.375x the 28pt title alone is ~94.5px, +// so "Pick your tools" wraps to ~4 lines of ~118dp (472dp) and the subtitle to +// ~3 lines of ~64dp (192dp): the header is ~764dp, the pinned pieces are ~234dp, +// the body is laid out at 0dp and the Column overflows the 568dp viewport by +// several hundred dp. Nothing in the body can be hit-tested, so the step is +// unusable even though the CTA itself is on screen. +// +// Desired behaviour, asserted below: the body keeps a usable height, the header +// scrolls instead of eating it, the step body's own controls can be scrolled to +// and operated, and the flow still forwards. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; +import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; +import 'package:prism_plurality/features/onboarding/views/onboarding_screen.dart'; +import 'package:prism_plurality/features/onboarding/widgets/features_step.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; + +import 'access_text_scale_harness.dart'; + +class _RecordingFeaturesNotifier extends OnboardingNotifier { + int nextCalls = 0; + + @override + OnboardingState build() => + const OnboardingState(currentStep: OnboardingStep.features); + + @override + void next() { + nextCalls += 1; + } +} + +class _Harness { + _Harness() { + container = ProviderContainer( + overrides: [ + onboardingProvider.overrideWith(_RecordingFeaturesNotifier.new), + hasCompletedOnboardingProvider.overrideWithValue(false), + syncDisconnectMarkerProvider.overrideWith((ref) async => null), + ], + ); + } + + late final ProviderContainer container; + + OnboardingState get state => container.read(onboardingProvider); + + _RecordingFeaturesNotifier get notifier => + container.read(onboardingProvider.notifier) as _RecordingFeaturesNotifier; + + Future pump( + WidgetTester tester, { + TextScaler? systemScaler, + double appFontScale = 1.0, + }) async { + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); + await tester.pumpAndSettle(); + } + + void dispose() => container.dispose(); +} + +/// The step body's own viewport. +Rect _bodyRect(WidgetTester tester) => + tester.getRect(find.byType(FeaturesStep)); + +void main() { + setUpAll(loadAccessFonts); + + testWidgets('composed 3.375x on a 320x568 phone: the step body keeps a usable ' + 'height and its controls can be reached and operated', (tester) async { + useWindow(tester, compactPhone); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ); + + expect( + tester.takeException(), + isNull, + reason: + 'the onboarding column must fit its viewport: the header negotiates its ' + 'height with the parent that lays it out.', + ); + + // The body is not squeezed out of existence. + final body = _bodyRect(tester); + expect( + body.height, + greaterThanOrEqualTo(96), + reason: + 'the step body must keep a usable height on a compact phone at max ' + 'text, not be squeezed out of existence.', + ); + expect(body.top, greaterThanOrEqualTo(0)); + expect(body.bottom, lessThanOrEqualTo(compactPhone.height)); + + // The body's own scrolling still works, and it has content to reach. + final bodyScrollable = find.descendant( + of: find.byType(FeaturesStep), + matching: find.byType(Scrollable), + ); + expect(bodyScrollable, findsOneWidget); + final position = tester.state(bodyScrollable).position; + expect( + position.maxScrollExtent, + greaterThan(0), + reason: 'the step options are taller than the space they are given', + ); + + // A real control: bring the first feature switch on screen and flip it. + final firstSwitch = find.descendant( + of: find.byType(FeaturesStep), + matching: find.byType(Switch), + ); + expect(firstSwitch, findsWidgets); + final before = harness.state.chatEnabled; + + await tester.ensureVisible(firstSwitch.first); + await tester.pumpAndSettle(); + + final switchRect = tester.getRect(firstSwitch.first); + final visible = _bodyRect(tester); + expect( + switchRect.center.dy, + inInclusiveRange(visible.top, visible.bottom), + reason: 'the switch must be inside the body viewport before it is tapped', + ); + + await tester.tap(firstSwitch.first); + await tester.pumpAndSettle(); + expect( + harness.state.chatEnabled, + isNot(before), + reason: 'the step control must still act on the onboarding state', + ); + + // The only forward action is on screen and still forwards the flow. + final cta = find.text('Continue'); + expect(cta, findsOneWidget); + final ctaRect = tester.getRect(cta); + expect(ctaRect.bottom, lessThanOrEqualTo(compactPhone.height)); + expect(ctaRect.right, lessThanOrEqualTo(compactPhone.width)); + + await tester.tap(cta); + await tester.pumpAndSettle(); + expect(harness.notifier.nextCalls, 1); + }); + + testWidgets( + 'composed 3.375x: the header text stays at the requested size and ' + 'is reachable by scrolling the header, not by shrinking it', + (tester) async { + useWindow(tester, compactPhone); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ); + + final title = find.text('Pick your tools'); + expect(title, findsOneWidget); + + // Full requested size: 28pt title at 3.375x. + final scaler = effectiveScaler(tester, title); + expect(scaler.scale(28), closeTo(94.5, 0.01)); + expect(tester.widget(title).style!.fontSize, 28); + + // Measured composition: the title really wraps at the requested size + // instead of being compressed or ellipsised to one line, and the + // paragraph is laid out as tall as its own span needs. + final paragraph = paragraphOf(tester, title); + final lines = paragraphLineCount(paragraph); + expect( + lines, + greaterThan(1), + reason: + 'a 28pt title in a 272dp line box wraps (measured $lines line(s))', + ); + final needed = paragraphMaxIntrinsicHeight(paragraph); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + 'the title must be laid out at its full wrapped height (needs ' + '${needed.toStringAsFixed(1)}dp, has ' + '${paragraph.size.height.toStringAsFixed(1)}dp)', + ); + + // The header scrolls within its budget: its viewport is smaller than its + // content, so the title is reachable by scrolling. + final headerScrollable = find.ancestor( + of: title, + matching: find.byType(SingleChildScrollView), + ); + expect(headerScrollable, findsWidgets); + final headerPosition = tester + .state( + find.descendant( + of: headerScrollable.first, + matching: find.byType(Scrollable), + ), + ) + .position; + expect( + headerPosition.maxScrollExtent, + greaterThan(0), + reason: 'the header content is taller than the height it is given', + ); + }, + ); + + testWidgets('composed 1.5x and default text on a 320x568 phone: the header ' + 'keeps its natural height and nothing clips', (tester) async { + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'default text', scaler: null, app: 1.0), + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + ]) { + useWindow(tester, compactPhone); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ); + + expect(tester.takeException(), isNull, reason: scenario.name); + + // Header text is fully on screen (not clipped by a header budget that + // bites when it should not). + for (final text in [ + 'Pick your tools', + 'Turn on what you need. Change anytime.', + ]) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: '${scenario.name}: $text'); + final rect = tester.getRect(finder); + expect( + rect.top, + greaterThanOrEqualTo(0), + reason: '${scenario.name}: $text', + ); + expect( + rect.bottom, + lessThanOrEqualTo(compactPhone.height), + reason: '${scenario.name}: $text must not be pushed off screen', + ); + } + + // Nothing to scroll in the header at these sizes. + final headerScrollable = find.ancestor( + of: find.text('Pick your tools'), + matching: find.byType(SingleChildScrollView), + ); + final headerPosition = tester + .state( + find.descendant( + of: headerScrollable.first, + matching: find.byType(Scrollable), + ), + ) + .position; + expect( + headerPosition.maxScrollExtent, + lessThanOrEqualTo(0.5), + reason: + '${scenario.name}: the header keeps its natural height when it fits', + ); + + expect( + _bodyRect(tester).height, + greaterThan(96), + reason: '${scenario.name}: the body keeps its share', + ); + } + }); + + testWidgets('diagnostic: a tall narrow window shows the same header at max ' + 'text without needing the header budget', (tester) async { + useWindow(tester, narrowTallPhone); + final harness = _Harness(); + addTearDown(harness.dispose); + await harness.pump( + tester, + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ); + + expect(tester.takeException(), isNull); + expect( + _bodyRect(tester).height, + greaterThan(0), + reason: 'a tall window renders the body without needing the budget', + ); + }); +} diff --git a/test/text_scale_fixes/access/pk_fronting_access_text_scale_test.dart b/test/text_scale_fixes/access/pk_fronting_access_text_scale_test.dart new file mode 100644 index 000000000..815872dd9 --- /dev/null +++ b/test/text_scale_fixes/access/pk_fronting_access_text_scale_test.dart @@ -0,0 +1,257 @@ +// Who's fronting? sheet: the defer action is reachable in a sheet that cannot be +// dismissed by drag or barrier, and the recommendation badge wraps inside its +// card at large text. +// +// The title and the option cards scroll inside the sheet body while "Decide +// later" is pinned below them, so the only non-mutating way out is one gesture +// away. The badge is capped to a share of the row so its word wraps instead of +// pushing the title to zero width. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/pluralkit/models/pk_sync_config.dart'; +import 'package:prism_plurality/features/pluralkit/widgets/pk_fronter_choice_card.dart'; +import 'package:prism_plurality/features/pluralkit/widgets/pk_who_is_fronting_sheet.dart'; +import 'package:prism_plurality/shared/widgets/prism_surface.dart'; + +import 'access_text_scale_harness.dart'; + +const _localWren = (id: 'local-wren', name: 'Wren'); +const _localNico = (id: 'local-nico', name: 'Nico'); +const _pkAsh = (id: 'local-ash', name: 'Ash'); + +/// Opens the real non-dismissible sheet the way PluralKit sync does and keeps +/// the result the sheet returns. +class _SheetHost extends StatelessWidget { + const _SheetHost({required this.onResult}); + + final void Function(Set?) onResult; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Builder( + builder: (buttonContext) => TextButton( + onPressed: () async { + final result = await PkWhoIsFrontingSheet.show( + context: buttonContext, + localFronters: const [_localWren, _localNico], + pkFronters: const [_pkAsh], + direction: PkSyncDirection.bidirectional, + ); + onResult(result); + }, + child: const Text('open sheet'), + ), + ), + ), + ); + } +} + +void main() { + setUpAll(loadAccessFonts); + + testWidgets( + 'default text on a compact phone: the defer action is inside the sheet, ' + 'tapping it closes the sheet without choosing a fronter', + (tester) async { + useWindow(tester, compactPhone); + Set? result; + var closed = false; + await tester.pumpWidget( + accessApp( + _SheetHost( + onResult: (value) { + result = value; + closed = true; + }, + ), + ), + ); + await tester.tap(find.text('open sheet')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + + final defer = find.text('Decide later'); + final deferRect = tester.getRect(defer); + expect(deferRect.top, greaterThanOrEqualTo(0)); + expect( + deferRect.bottom, + lessThanOrEqualTo(compactPhone.height), + reason: 'the safe, non-mutating exit must be on the sheet', + ); + + // Non-dismissible by drag and barrier: pulling down on the body must not + // close the sheet (unchanged dismissal semantics). + await tester.drag(find.text("Who's fronting?"), const Offset(0, 300)); + await tester.pumpAndSettle(); + expect(find.text('Decide later'), findsOneWidget); + + await tester.tap(defer); + await tester.pumpAndSettle(); + + expect(closed, isTrue); + expect(result, isNull, reason: '"Decide later" defers, it does not pick'); + expect(find.byType(PkFronterChoiceCard), findsNothing); + }, + ); + + testWidgets( + 'composed 3.375x on a compact phone: the defer action stays reachable and ' + 'a choice further down the card list can still be scrolled to and taken', + (tester) async { + useWindow(tester, compactPhone); + Set? result; + var closed = false; + await tester.pumpWidget( + accessApp( + _SheetHost( + onResult: (value) { + result = value; + closed = true; + }, + ), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.tap(find.text('open sheet')); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: + 'a choice card row must not overflow: the recommendation badge is ' + 'capped to a share of the row so its word wraps beside the title.', + ); + + final deferRect = tester.getRect(find.text('Decide later')); + expect(deferRect.top, greaterThanOrEqualTo(0)); + expect( + deferRect.bottom, + lessThanOrEqualTo(compactPhone.height), + reason: + '"Decide later" must be inside the sheet: the cards scroll above it ' + 'and the defer action is pinned.', + ); + + // The body scrolls, so a card below the fold is still usable. + final scrollable = find.byType(Scrollable); + expect(scrollable, findsOneWidget); + final lastCard = find.byType(PkFronterChoiceCard).last; + await tester.scrollUntilVisible(lastCard, 160, scrollable: scrollable); + await tester.tap(lastCard); + await tester.pumpAndSettle(); + + expect(closed, isTrue); + expect(result, equals({'local-ash'})); + }, + ); + + testWidgets( + 'composed 3.375x: the recommendation badge stays inside its card at full ' + 'size instead of overflowing the row', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + accessApp( + _SheetHost(onResult: (_) {}), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.tap(find.text('open sheet')); + await tester.pumpAndSettle(); + + final badge = find.text('Recommended'); + expect(badge, findsOneWidget); + + // Not ellipsised and not clipped: the word keeps its requested size. + final badgeText = tester.widget(badge); + expect(badgeText.maxLines, isNull); + expect(badgeText.overflow, isNull); + + final cardRect = tester.getRect( + find.ancestor(of: badge, matching: find.byType(PrismSurface)).first, + ); + final badgeRect = tester.getRect(badge); + expect(badgeRect.left, greaterThanOrEqualTo(cardRect.left - 0.5)); + expect( + badgeRect.right, + lessThanOrEqualTo(cardRect.right + 0.5), + reason: 'the badge must stay inside its card.', + ); + + // The badge wraps rather than shrinking: measured from the paragraph it + // actually renders, the whole word is laid out at the requested size. + final paragraph = paragraphOf(tester, badge); + final needed = paragraphMaxIntrinsicHeight(paragraph); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + 'the badge must keep the whole word at the requested size (needs ' + '${needed.toStringAsFixed(1)}dp, has ' + '${paragraph.size.height.toStringAsFixed(1)}dp)', + ); + }, + ); + + testWidgets( + 'composed 1.5x on a compact phone: cards and defer action all fit', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + accessApp( + _SheetHost(onResult: (_) {}), + systemScaler: const TextScaler.linear(1.0), + appFontScale: 1.5, + ), + ); + await tester.tap(find.text('open sheet')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + final deferRect = tester.getRect(find.text('Decide later')); + expect(deferRect.bottom, lessThanOrEqualTo(compactPhone.height)); + for (final element in find.byType(PkFronterChoiceCard).evaluate()) { + final box = element.renderObject! as RenderBox; + expect(box.size.height, greaterThan(0)); + } + }, + ); + + testWidgets('wide layout at 3.375x: the badge stays inside its card and the ' + 'defer action stays on the sheet', (tester) async { + useWindow(tester, wideDesktop); + await tester.pumpWidget( + accessApp( + _SheetHost(onResult: (_) {}), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.tap(find.text('open sheet')); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + + final badge = find.text('Recommended'); + final badgeText = tester.widget(badge); + expect(badgeText.overflow, isNull); + final badgeRect = tester.getRect(badge); + final cardRect = tester.getRect( + find.ancestor(of: badge, matching: find.byType(PrismSurface)).first, + ); + expect(badgeRect.right, lessThanOrEqualTo(cardRect.right + 0.5)); + + final deferRect = tester.getRect(find.text('Decide later')); + expect(deferRect.top, greaterThanOrEqualTo(0)); + expect(deferRect.bottom, lessThanOrEqualTo(wideDesktop.height)); + }); +} diff --git a/test/text_scale_fixes/access/recovery_phrase_access_text_scale_test.dart b/test/text_scale_fixes/access/recovery_phrase_access_text_scale_test.dart new file mode 100644 index 000000000..db431ada3 --- /dev/null +++ b/test/text_scale_fixes/access/recovery_phrase_access_text_scale_test.dart @@ -0,0 +1,366 @@ +// Recovery-word entry: every slot a user must transcribe is laid out at the full +// requested size, the 1-12 ordinals are never clipped, the first and last slots +// are reachable, and the word-suggestion strip above the keyboard fits its chips. +// +// Rows and ordinals are sized from the text they hold - the original 40dp row and +// 18dp ordinal stay as floors, and one measured ordinal column covers 1..12 - and +// the suggestion band is one measured chip line plus its padding with the +// original 48dp floor. Paste, autocomplete, focus order and submit behave exactly +// as before and are asserted here. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/shared/widgets/glass_surface.dart'; +import 'package:prism_plurality/shared/widgets/prism_mnemonic_field.dart'; + +import 'access_text_scale_harness.dart'; + +/// A canonical BIP39 12-word mnemonic with a valid checksum (synthetic, not key +/// material: it is the published all-"abandon" test vector). +const _phrase = + 'abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon abandon abandon about'; + +Widget _host( + Widget child, { + TextScaler? systemScaler, + double appFontScale = 1.0, +}) { + return ProviderScope( + child: accessApp( + Scaffold( + body: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: child, + ), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ); +} + +Finder get _fields => find.byType(TextField); + +/// The word slot renders its word at the size the editable really uses. +/// +/// The editable's own span, scaler and width are the authority here: a painter +/// built from `TextField.style` loses the ambient DefaultTextStyle and font, so +/// its "needed" height would belong to a different font than the word on screen. +void _expectWordSlotFits( + WidgetTester tester, + int index, { + required String reason, +}) { + final editable = editableOf(tester, _fields.at(index)); + // `preferredLineHeight` comes from the style's font metrics rather than from + // this one word's glyphs, so allow a dp for ascent/descent variation. + final needed = editableLineHeight(editable); + expect( + editable.size.height + 1.0, + greaterThanOrEqualTo(needed), + reason: + '$reason: the word needs ${needed.toStringAsFixed(1)}dp but the slot ' + 'laid it out at ${editable.size.height.toStringAsFixed(1)}dp', + ); +} + +/// Distance between the tops of two fields in the same column, one row apart. +double _rowPitch(WidgetTester tester) { + return tester.getRect(_fields.at(2)).top - tester.getRect(_fields.at(0)).top; +} + +void main() { + setUpAll(loadAccessFonts); + + testWidgets('default text: the 2x6 grid keeps its 40dp row and 46dp pitch, ' + 'and every slot holds a full line', (tester) async { + useWindow(tester, compactPhone); + final controller = TextEditingController(); + addTearDown(controller.dispose); + + await tester.pumpWidget(_host(PrismMnemonicField(controller: controller))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(_fields, findsNWidgets(12)); + + // Baseline geometry preserved: one row is 40dp plus 6dp of spacing. + expect(_rowPitch(tester), closeTo(46, 0.5)); + + for (var i = 0; i < 12; i++) { + _expectWordSlotFits(tester, i, reason: 'slot ${i + 1} at 1x'); + } + }); + + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ]) { + testWidgets('${scenario.name}: all twelve slots and their numbers are laid ' + 'out at full size and the first and last slots are reachable', ( + tester, + ) async { + useWindow(tester, compactPhone); + final controller = TextEditingController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _host( + PrismMnemonicField(controller: controller), + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: + 'a word slot must hold its scaled word line box instead of reporting ' + 'an overflow.', + ); + + // Every word slot is tall enough for its own line box, measured from the + // editable that renders the word. + for (var i = 0; i < 12; i++) { + _expectWordSlotFits( + tester, + i, + reason: + 'slot ${i + 1} must show the whole word it asks the user to ' + 'type.', + ); + } + + // Rows do not overlap: the pitch grows with the slot height. + final pitch = _rowPitch(tester); + final fieldHeight = tester.getSize(_fields.first).height; + expect( + pitch, + greaterThan(fieldHeight), + reason: + 'row ${2} must start below row 1 (pitch $pitch, field $fieldHeight)', + ); + + // Slot numbers are not clipped and are not wrapped in a narrow column. + for (var slot = 1; slot <= 12; slot++) { + final label = find.text('$slot'); + expect(label, findsOneWidget); + final paragraph = paragraphOf(tester, label); + final neededWidth = paragraphIntrinsicWidth(paragraph); + expect( + paragraph.size.width + 0.5, + greaterThanOrEqualTo(neededWidth), + reason: + 'slot number "$slot" must not be clipped by its column (it needs ' + '${neededWidth.toStringAsFixed(1)}dp).', + ); + expect( + paragraphLineCount(paragraph), + 1, + reason: 'slot number "$slot" must stay on one line', + ); + } + + // First and last slot are inside the field's own box. + final fieldRect = tester.getRect(find.byType(PrismMnemonicField)); + expect( + tester.getRect(_fields.first).top, + greaterThanOrEqualTo(fieldRect.top - 0.5), + ); + expect( + tester.getRect(_fields.at(11)).bottom, + lessThanOrEqualTo(fieldRect.bottom + 0.5), + reason: 'the twelfth slot must not be pushed out of the field', + ); + }); + } + + testWidgets('nonlinear scaler: the fitting follows each font size instead of a ' + 'single ratio', (tester) async { + useWindow(tester, compactPhone); + final controller = TextEditingController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _host( + PrismMnemonicField(controller: controller), + systemScaler: const NonlinearTextScaler(), + appFontScale: 1.0, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + final scaler = effectiveScaler(tester, _fields.first); + // The nonlinear scaler triples sizes below 20 and multiplies larger ones by + // 1.6, so a width derived from one font size cannot serve the other. + expect(scaler.scale(11), closeTo(33, 0.01)); + expect(scaler.scale(28), closeTo(44.8, 0.01)); + + for (var i = 0; i < 12; i++) { + _expectWordSlotFits(tester, i, reason: 'nonlinear scaler, slot ${i + 1}'); + } + final paragraph = paragraphOf(tester, find.text('12')); + expect( + paragraph.size.width + 0.5, + greaterThanOrEqualTo(paragraphIntrinsicWidth(paragraph)), + reason: + 'the slot number keeps one full glyph width under a nonlinear ' + 'scaler', + ); + }); + + testWidgets('short window with the keyboard up: the suggestion strip and its ' + 'chips stay on screen at full size', (tester) async { + useWindow(tester, compactPhone, keyboardInset: 280); + final controller = TextEditingController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _host( + PrismMnemonicField(controller: controller, autofocus: true), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.pumpAndSettle(); + + await tester.enterText(_fields.first, 'abou'); + await tester.pumpAndSettle(); + + final suggestion = find.text('about'); + expect(suggestion, findsOneWidget); + + final suggestionRect = tester.getRect(suggestion); + expect( + suggestionRect.bottom, + lessThanOrEqualTo( + (tester.view.physicalSize.height - tester.view.viewInsets.bottom) / + tester.view.devicePixelRatio, + ), + reason: 'the suggestion strip must sit above the keyboard inset', + ); + expect(suggestionRect.top, greaterThanOrEqualTo(0)); + + // The chip paints its word at the requested size instead of clipping it in + // a fixed 48dp band: measured from the chip's own paragraph. + final paragraph = paragraphOf(tester, suggestion); + // Measured at the width the chip actually laid the word out with, using the + // paragraph's own resolved span: no padding or slack is invented for the band. + final needed = paragraphHeight(paragraph, atWidth: paragraph.size.width); + final chip = find.ancestor( + of: suggestion, + matching: find.byType(GlassSurface), + ); + expect(chip, findsOneWidget); + final surface = tester.widget(chip); + debugPrint( + 'RECOVERY_METRICS size=${paragraph.size} naturalHeight=$needed ' + 'paintBounds=${paragraph.paintBounds} span=${paragraph.text} ' + 'heightBehavior=${paragraph.textHeightBehavior} ' + 'scaler=${paragraph.textScaler} chip=${tester.getRect(chip)} ' + 'padding=${surface.padding} borderWidth=${surface.borderWidth}', + ); + tester.element(suggestion).visitAncestorElements((element) { + final object = element.renderObject; + if (object is RenderBox && + object.hasSize && + (object is RenderAbstractViewport || + (object is RenderClipRect && object.clipBehavior != Clip.none) || + (object is RenderClipRRect && + object.clipBehavior != Clip.none))) { + final clip = MatrixUtils.transformRect( + object.getTransformTo(null), + object.paintBounds, + ); + expect( + rectInside(suggestionRect, clip), + isTrue, + reason: 'the suggestion must survive ancestor clip $clip', + ); + } + return true; + }); + expect( + paragraph.size.height + 0.5, + greaterThanOrEqualTo(needed), + reason: + 'the suggestion chip must paint its word at the requested size: it ' + 'needs ${needed.toStringAsFixed(1)}dp and has ' + '${paragraph.size.height.toStringAsFixed(1)}dp.', + ); + + // Tapping the suggestion still inserts the full word and keeps the strip + // out of the way (unchanged autocomplete behaviour). + expect(suggestion.hitTestable(), findsOneWidget); + await tester.tap(suggestion); + await tester.pumpAndSettle(); + expect(controller.text, 'about'); + }); + + testWidgets('pasting a whole phrase and a long word keeps the slot semantics ' + 'intact', (tester) async { + useWindow(tester, compactPhone); + final controller = TextEditingController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _host( + PrismMnemonicField(controller: controller), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.pumpAndSettle(); + + // A whole phrase pasted into slot 1 distributes across all twelve slots. + await tester.enterText(_fields.first, _phrase); + await tester.pumpAndSettle(); + expect(controller.text, _phrase); + expect(find.text('12 of 12 words'), findsOneWidget); + + // The word formatter still caps one word at eight characters and leaves the + // other slots alone. + await tester.enterText(_fields.at(5), 'abcdefghij'); + await tester.pumpAndSettle(); + final words = controller.text.split(' '); + expect(words, hasLength(12)); + expect(words[5], 'abcdefgh'); + expect(words[11], 'about'); + expect(tester.takeException(), isNull); + }); + + testWidgets('submitting from the last slot still reports the phrase', ( + tester, + ) async { + useWindow(tester, compactPhone); + final controller = TextEditingController(); + addTearDown(controller.dispose); + String? submitted; + + await tester.pumpWidget( + _host( + PrismMnemonicField( + controller: controller, + onSubmitted: (value) => submitted = value, + ), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.pumpAndSettle(); + + await tester.enterText(_fields.at(11), 'about'); + await tester.pumpAndSettle(); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + + expect(submitted, 'about'); + }); +} diff --git a/test/text_scale_fixes/access/sync_progress_access_text_scale_test.dart b/test/text_scale_fixes/access/sync_progress_access_text_scale_test.dart new file mode 100644 index 000000000..f215ada92 --- /dev/null +++ b/test/text_scale_fixes/access/sync_progress_access_text_scale_test.dart @@ -0,0 +1,193 @@ +// Sync pairing progress: every part of the progress surface stays reachable on a +// real 320x568 phone, at default text, at the composed maximum and under a +// nonlinear platform scaler. +// +// Source proof of the original defect: `SyncProgressView` returned +// `Padding(24) > Center > Column(min, stretch)` with phases, a 48dp spinner, +// title, subtitle, the live count card and reassurance copy. Nothing there +// scrolls, and `PairingStep.connecting` renders it directly (no cancel, no +// scroll ancestor), so at 3.375x the column reported 196dp of bottom overflow +// and the counting card plus the reassurance copy were painted below the bottom +// edge with no way to reach them. The view now scrolls inside a centring +// constraint, so it looks identical when it fits and everything stays reachable +// when it does not. +// +// Bounded pumps only: the spinner animates by design and the view rebuilds on a +// one-second timer, so `pumpAndSettle` would never return here. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/onboarding/providers/sync_setup_progress_provider.dart'; +import 'package:prism_plurality/features/onboarding/widgets/live_count_card.dart'; +import 'package:prism_plurality/features/onboarding/widgets/phase_segments.dart'; +import 'package:prism_plurality/features/onboarding/widgets/sync_progress_view.dart'; + +import 'access_text_scale_harness.dart'; + +/// Pins the progress state so the view renders a known phase without a pairing +/// attempt: no network, no phase churn. +class _FixedProgressNotifier extends SyncSetupProgressNotifier { + _FixedProgressNotifier(this._state); + + final SyncSetupProgressState _state; + + @override + SyncSetupProgressState build() => _state; +} + +SyncSetupProgressState _restoringState({required bool reassurance}) { + return SyncSetupProgressState( + phase: PairingProgressPhase.restoring, + liveCounts: const { + 'members': 12, + 'chat_messages': 1400, + 'front_sessions': 320, + }, + phaseStartedAt: DateTime.now().subtract( + reassurance ? const Duration(seconds: 45) : const Duration(seconds: 1), + ), + timedOut: false, + wsConnected: true, + restoreApplied: 3, + restoreTotal: 8, + ); +} + +Future _pumpProgress( + WidgetTester tester, { + TextScaler? systemScaler, + double appFontScale = 1.0, + bool reassurance = true, +}) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + syncSetupProgressProvider.overrideWith( + () => + _FixedProgressNotifier(_restoringState(reassurance: reassurance)), + ), + ], + child: accessApp( + const Scaffold(body: SyncProgressView()), + systemScaler: systemScaler, + appFontScale: appFontScale, + ), + ), + ); + // Bounded frames: the progress indicator and the one-second rebuild timer + // never settle. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); +} + +/// Brings [finder] into view and asserts it is inside the 320x568 viewport. +Future _expectReachable(WidgetTester tester, Finder finder) async { + await tester.ensureVisible(finder); + await tester.pump(); + final rect = tester.getRect(finder); + expect( + rectInside(rect, Offset.zero & compactPhone), + isTrue, + reason: '$finder must be reachable on a compact phone, but it is at $rect', + ); +} + +void main() { + setUpAll(loadAccessFonts); + + testWidgets('default text on a 320x568 phone: the progress surface fits and ' + 'nothing scrolls', (tester) async { + useWindow(tester, compactPhone); + await _pumpProgress(tester); + + expect(tester.takeException(), isNull); + + for (final finder in [ + find.byType(PhaseSegments), + find.text('Restoring your data'), + find.byType(LiveCountCard), + ]) { + expect(finder, findsOneWidget); + await _expectReachable(tester, finder); + } + + final scrollable = find.descendant( + of: find.byType(SyncProgressView), + matching: find.byType(Scrollable), + ); + expect(scrollable, findsOneWidget); + expect( + tester.state(scrollable).position.maxScrollExtent, + lessThanOrEqualTo(0.5), + reason: + 'at default text the view keeps its centred, non-scrolling layout', + ); + }); + + for (final scenario in <({String name, TextScaler? scaler, double app})>[ + (name: 'composed 1.5x', scaler: const TextScaler.linear(1.0), app: 1.5), + (name: 'composed 3.375x', scaler: maxSystemScaler, app: maxAppFontScale), + ( + name: 'nonlinear platform scaler', + scaler: const NonlinearTextScaler(), + app: 1.0, + ), + ]) { + testWidgets('${scenario.name}: the whole progress surface stays reachable ' + 'instead of overflowing the bottom edge', (tester) async { + useWindow(tester, compactPhone); + await _pumpProgress( + tester, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + ); + + expect( + tester.takeException(), + isNull, + reason: + 'the progress column must fit or scroll: on a 320x568 phone at this ' + 'text size every piece stays reachable.', + ); + + // The phase strip, the progress indicator, the title, the live counts and + // the reassurance copy are all reachable. + final scrollable = find.descendant( + of: find.byType(SyncProgressView), + matching: find.byType(Scrollable), + ); + expect(scrollable, findsOneWidget); + expect( + tester.state(scrollable).position.maxScrollExtent, + greaterThan(0), + reason: 'the column is taller than the viewport at this text size', + ); + + for (final finder in [ + find.byType(PhaseSegments), + find.text('Restoring your data'), + find.text( + 'Still going — larger restores can take a minute on slow networks.', + ), + ]) { + expect(finder, findsOneWidget, reason: scenario.name); + await _expectReachable(tester, finder); + } + + // The count card is taller than a 568dp phone at these sizes, so + // reachability means each of its pieces can be scrolled to - its first and + // last rows here - not that the whole card fits at once. + final cardTexts = find.descendant( + of: find.byType(LiveCountCard), + matching: find.byType(Text), + ); + expect(cardTexts, findsWidgets, reason: scenario.name); + await _expectReachable(tester, cardTexts.first); + await _expectReachable(tester, cardTexts.last); + + expect(tester.takeException(), isNull); + }); + } +} diff --git a/test/text_scale_fixes/access/system_name_ime_access_text_scale_test.dart b/test/text_scale_fixes/access/system_name_ime_access_text_scale_test.dart new file mode 100644 index 000000000..257ad8bc3 --- /dev/null +++ b/test/text_scale_fixes/access/system_name_ime_access_text_scale_test.dart @@ -0,0 +1,474 @@ +// System-name step with the keyboard up: the field, its helper copy, the step +// title and the footer actions all stay reachable on a 320x568 phone at every +// text scale. +// +// With the IME up the body is whatever the keyboard leaves between the header and +// the bottom bar, which can be less than the field plus its gap and helper text. +// The name body scrolls inside that space, and when the pinned chrome would leave +// it unusably short the whole flow scrolls instead, so each piece can be reached +// in turn. Nothing is shrunk, and the field keeps its text, selection and focus +// across those layout modes. + +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/sync/sync_disconnect_marker.dart'; +import 'package:prism_plurality/features/onboarding/providers/onboarding_providers.dart'; +import 'package:prism_plurality/features/onboarding/views/onboarding_screen.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; + +import 'access_text_scale_harness.dart'; + +class _SystemNameNotifier extends OnboardingNotifier { + @override + OnboardingState build() => + const OnboardingState(currentStep: OnboardingStep.systemName); +} + +/// Height the software keyboard takes on the compact phone in this scenario. +const double _keyboardInset = 280; + +Future _pumpSystemName( + WidgetTester tester, { + TextScaler? systemScaler, + double appFontScale = 1.0, + String family = 'OpenDyslexic', +}) async { + final container = ProviderContainer( + overrides: [ + onboardingProvider.overrideWith(_SystemNameNotifier.new), + hasCompletedOnboardingProvider.overrideWithValue(false), + syncDisconnectMarkerProvider.overrideWith((ref) async => null), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + systemScaler: systemScaler, + appFontScale: appFontScale, + theme: accessTheme(family: family), + ), + ); + await tester.pumpAndSettle(); + return container; +} + +bool _clipsDescendants(RenderObject object) => + object is RenderAbstractViewport || + (object is RenderClipRect && object.clipBehavior != Clip.none) || + (object is RenderClipRRect && object.clipBehavior != Clip.none) || + (object is RenderClipPath && object.clipBehavior != Clip.none) || + (object is RenderPhysicalModel && object.clipBehavior != Clip.none) || + (object is RenderPhysicalShape && object.clipBehavior != Clip.none); + +/// Global paint bounds of clipping viewports and clip renderers above [finder]. +List _ancestorViewports(WidgetTester tester, Finder finder) { + final rects = []; + final seen = {}; + tester.element(finder).visitAncestorElements((ancestor) { + final renderObject = ancestor.renderObject; + if (renderObject is RenderBox && + _clipsDescendants(renderObject) && + renderObject.attached && + renderObject.hasSize && + seen.add(renderObject)) { + final rect = MatrixUtils.transformRect( + renderObject.getTransformTo(null), + renderObject.paintBounds, + ); + if (rect.width > 0 && rect.height > 0) rects.add(rect); + } + return true; + }); + return rects; +} + +// Diagnostic only: selection and line boxes are layout evidence, not raster ink. +void _traceParagraph( + WidgetTester tester, + Finder finder, + RenderParagraph paragraph, { + required Rect visible, + required String phase, + Rect? revealed, +}) { + final text = paragraph.text.toPlainText(); + final painter = + TextPainter( + text: paragraph.text, + textAlign: paragraph.textAlign, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + locale: paragraph.locale, + maxLines: paragraph.maxLines, + ellipsis: paragraph.overflow == TextOverflow.ellipsis ? '…' : null, + strutStyle: paragraph.strutStyle, + textWidthBasis: paragraph.textWidthBasis, + textHeightBehavior: paragraph.textHeightBehavior, + )..layout( + minWidth: paragraph.constraints.hasBoundedWidth + ? paragraph.constraints.minWidth + : 0, + maxWidth: + paragraph.softWrap || paragraph.overflow == TextOverflow.ellipsis + ? paragraph.constraints.maxWidth + : double.infinity, + ); + try { + final scrolls = >[]; + tester.element(finder).visitAncestorElements((element) { + if (element is StatefulElement && + element.state is ScrollableState && + scrolls.length < 8) { + final position = (element.state as ScrollableState).position; + scrolls.add({ + 'pixels': position.pixels, + 'minScrollExtent': position.minScrollExtent, + 'maxScrollExtent': position.maxScrollExtent, + 'viewportDimension': position.viewportDimension, + }); + } + return true; + }); + debugPrint( + 'IME_METRICS ${jsonEncode({ + 'phase': phase, + 'size': paragraph.size.toString(), + 'paintBounds': paragraph.paintBounds.toString(), + 'globalOrigin': paragraph.localToGlobal(Offset.zero).toString(), + 'resolvedSpan': paragraph.text.toStringDeep().substring(0, paragraph.text.toStringDeep().length > 1800 ? 1800 : paragraph.text.toStringDeep().length), + 'textHeightBehavior': paragraph.textHeightBehavior.toString(), + 'scaler': paragraph.textScaler.toString(), + 'selectionBoxes': paragraph.getBoxesForSelection(TextSelection(baseOffset: 0, extentOffset: text.length)).take(24).map((box) => box.toRect().toString()).toList(), + 'lineMetrics': painter.computeLineMetrics().take(24).map((line) => {'ascent': line.ascent, 'descent': line.descent, 'unscaledAscent': line.unscaledAscent, 'height': line.height, 'width': line.width, 'left': line.left, 'baseline': line.baseline}).toList(), + 'scrollAncestors': scrolls, + 'keyboardSafeClip': visible.toString(), + 'ancestorClips': _ancestorViewports(tester, finder).take(12).map((clip) => clip.toString()).toList(), + 'revealedLastLine': revealed?.toString(), + 'inkQualification': 'unknown; layout metrics only', + })}', + ); + } finally { + painter.dispose(); + } +} + +/// Every line of [finder]'s paragraph can be revealed by scrolling. +/// +/// A paragraph taller than the viewport can never be fully visible at once, so +/// reachability means each of its laid-out lines can be scrolled to and read: the +/// line boxes come from the render object itself (`getBoxesForSelection`), each is +/// shown with `showOnScreen`, and the revealed rect is then checked against the +/// area that is actually visible above the keyboard. +Future _expectParagraphLinesReachable( + WidgetTester tester, + Finder finder, { + required Rect visible, + required String reason, +}) async { + final paragraph = paragraphOf(tester, finder); + final plainText = paragraph.text.toPlainText(); + expect(plainText, isNotEmpty, reason: reason); + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: plainText.length), + ); + expect(boxes, isNotEmpty, reason: '$reason (no line boxes)'); + _traceParagraph( + tester, + finder, + paragraph, + visible: visible, + phase: '$reason: before reveal', + ); + // Trace the actual final-line reveal even if an earlier assertion later fails. + // The rectangle remains paragraph-local, just like the assertion loop below. + final lastLine = boxes.last.toRect(); + paragraph.showOnScreen(rect: lastLine); + await tester.pump(); + _traceParagraph( + tester, + finder, + paragraph, + visible: visible, + phase: '$reason: last-line reveal', + revealed: lastLine.shift(paragraph.localToGlobal(Offset.zero)), + ); + + for (final box in boxes) { + // `RenderObject.showOnScreen` takes the rect in its own coordinate space, so + // the local line box from `getBoxesForSelection` is passed as-is; it walks up + // and reveals the line through every scrollable ancestor. + paragraph.showOnScreen( + rect: Rect.fromLTRB(box.left, box.top, box.right, box.bottom), + ); + await tester.pump(); + final originAfter = paragraph.localToGlobal(Offset.zero); + final revealed = Rect.fromLTWH( + originAfter.dx + box.left, + originAfter.dy + box.top, + box.right - box.left, + box.bottom - box.top, + ); + expect( + rectInside(revealed, visible), + isTrue, + reason: '$reason: line at $revealed is outside $visible', + ); + // On screen is not enough: the line must also survive every ancestor clip - + // the header's own box and the body's viewport can slice a line that happens + // to lie inside the screen rect. + for (final clip in _ancestorViewports(tester, finder)) { + expect( + rectInside(revealed, clip), + isTrue, + reason: + '$reason: line at $revealed is clipped by an ancestor viewport ' + '($clip)', + ); + } + } +} + +void main() { + setUpAll(loadAccessFonts); + + for (final scenario + in <({String name, TextScaler? scaler, double app, String family})>[ + ( + name: 'default text, OpenDyslexic', + scaler: null, + app: 1.0, + family: 'OpenDyslexic', + ), + ( + name: 'default text, Lexend', + scaler: null, + app: 1.0, + family: 'Lexend', + ), + ( + name: 'composed 1.5x, OpenDyslexic', + scaler: const TextScaler.linear(1.0), + app: 1.5, + family: 'OpenDyslexic', + ), + ( + name: 'composed 3.375x, OpenDyslexic', + scaler: maxSystemScaler, + app: maxAppFontScale, + family: 'OpenDyslexic', + ), + ( + name: 'composed 3.375x, Lexend', + scaler: maxSystemScaler, + app: maxAppFontScale, + family: 'Lexend', + ), + ( + name: 'nonlinear platform scaler', + scaler: const NonlinearTextScaler(), + app: 1.0, + family: 'OpenDyslexic', + ), + ]) { + testWidgets('${scenario.name} with the keyboard up on a 320x568 phone: the ' + 'name field stays on screen and typing still reaches the flow', ( + tester, + ) async { + useWindow(tester, compactPhone, keyboardInset: _keyboardInset); + final container = await _pumpSystemName( + tester, + systemScaler: scenario.scaler, + appFontScale: scenario.app, + family: scenario.family, + ); + + expect( + tester.takeException(), + isNull, + reason: + 'The name body overflowed the space left above the keyboard. A red ' + 'here at the largest sizes points at the pinned bottom bar first: at ' + '3.375x it takes ~206dp of the 288dp a 280dp keyboard leaves, which ' + 'is a whole-flow constraint, not the name body (which now scrolls).', + ); + + // The field must be reachable in the area that is actually visible above + // the keyboard, not merely laid out somewhere below it. + final visible = Offset.zero & const Size(320, 568 - _keyboardInset); + final field = find.byType(TextField); + expect(field, findsOneWidget); + await tester.ensureVisible(field); + await tester.pump(); + expect( + rectInside(tester.getRect(field), visible), + isTrue, + reason: + 'the name field must be reachable while the IME is up (visible area ' + '$visible, field ${tester.getRect(field)}).', + ); + + // And so must the helper copy, which is the piece that used to be pushed + // out of the body entirely. + final helper = find.text( + 'This is how this profile will be identified in the app.', + ); + expect(helper, findsOneWidget); + // The helper can be taller than the body on a compact phone at max text, so + // reachability means every one of its lines can be scrolled to and read. + await _expectParagraphLinesReachable( + tester, + helper, + visible: visible, + reason: 'the helper copy must be readable above the keyboard', + ); + + // The footer must stay reachable as well: the whole flow scrolls when the + // keyboard leaves too little for the pinned layout, so Continue and Back + // are reachable by scrolling rather than pinned off-screen. + final cta = find.text('Continue'); + expect(cta, findsOneWidget); + await tester.ensureVisible(cta); + await tester.pump(); + expect( + rectInside(tester.getRect(cta), visible), + isTrue, + reason: 'Continue must be reachable while the IME is up', + ); + + final back = find.byIcon(AppIcons.arrowBack); + expect(back, findsOneWidget); + await tester.ensureVisible(back); + await tester.pump(); + expect( + rectInside(tester.getRect(back), visible), + isTrue, + reason: 'Back must be reachable while the IME is up', + ); + + // The step header is part of the flow too: it must never be collapsed to + // nothing to make room, and it must be reachable by scrolling. + final title = find.text('Name your profile'); + expect(title, findsOneWidget); + expect( + tester.getSize(title).height, + greaterThan(0), + reason: 'the header must keep a readable height', + ); + // The title wraps to several lines at the largest sizes, so each line must + // be readable rather than the whole paragraph fitting in one frame. + await _expectParagraphLinesReachable( + tester, + title, + visible: visible, + reason: 'the step title must be readable while the IME is up', + ); + + // And the field still edits the onboarding state. + await tester.enterText(field, 'The Wrens'); + await tester.pumpAndSettle(); + expect(container.read(onboardingProvider).systemName, 'The Wrens'); + }); + } + + testWidgets( + 'a focused input keeps its text, selection and focus across pinned, ' + 'fallback and pinned again on the same screen', + (tester) async { + // Pinned: 1x with no keyboard. + useWindow(tester, compactPhone); + final container = await _pumpSystemName(tester); + + final field = find.byType(TextField); + await tester.enterText(field, 'The Wrens'); + await tester.pumpAndSettle(); + expect(container.read(onboardingProvider).systemName, 'The Wrens'); + + final controller = tester.widget(field).controller!; + controller.selection = const TextSelection( + baseOffset: 4, + extentOffset: 9, + ); + await tester.pump(); + + bool fieldHasFocus() => tester + .widget(find.byType(EditableText)) + .focusNode + .hasFocus; + + expect(fieldHasFocus(), isTrue, reason: 'the field starts focused'); + + // Fallback: same screen, max text and the keyboard up. The layout mode + // changes, the element tree must not. + tester.view.viewInsets = const FakeViewPadding(bottom: _keyboardInset); + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + systemScaler: maxSystemScaler, + appFontScale: maxAppFontScale, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect( + controller.text, + 'The Wrens', + reason: 'the input keeps its text across the fallback', + ); + expect( + controller.selection, + const TextSelection(baseOffset: 4, extentOffset: 9), + ); + expect( + fieldHasFocus(), + isTrue, + reason: + 'the focused input keeps focus when the footer starts scrolling', + ); + + await tester.ensureVisible(field); + await tester.pump(); + expect( + rectInside( + tester.getRect(field), + Offset.zero & const Size(320, 568 - _keyboardInset), + ), + isTrue, + ); + + // Back to pinned: 1x, keyboard gone. + tester.view.resetViewInsets(); + await tester.pumpWidget( + accessApp( + UncontrolledProviderScope( + container: container, + child: const OnboardingScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(controller.text, 'The Wrens'); + expect( + controller.selection, + const TextSelection(baseOffset: 4, extentOffset: 9), + ); + expect(fieldHasFocus(), isTrue); + expect(container.read(onboardingProvider).systemName, 'The Wrens'); + }, + ); +} diff --git a/test/text_scale_fixes/chrome/chat_header_text_scale_test.dart b/test/text_scale_fixes/chrome/chat_header_text_scale_test.dart new file mode 100644 index 000000000..ad944a512 --- /dev/null +++ b/test/text_scale_fixes/chrome/chat_header_text_scale_test.dart @@ -0,0 +1,369 @@ +// The chat list's pinned header: `_ChatTopBar` is a `PrismTopBar` plus the +// segmented tab switcher, and `SliverPinnedTopBar` sizes the band from that +// measurement, so both children keep the text size the user asked for and the band +// is exactly their height instead of a constant. +// +// Desired behaviour, asserted on the real `ChatScreen` with the repo's fake +// repositories: the pinned band is sized from the same measurements its +// children use, both children are painted at their requested text size inside +// the band, and the band re-measures when the text scale changes. +// +// The switcher's own label geometry inside its track is covered by the +// segmented-control tests; this file covers the band's extent and the title. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:prism_plurality/domain/models/chat_message.dart' as domain; +import 'package:prism_plurality/domain/models/conversation.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/member_group.dart'; +import 'package:prism_plurality/domain/models/member_group_entry.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/domain/repositories/chat_message_repository.dart'; +import 'package:prism_plurality/features/chat/providers/category_providers.dart'; +import 'package:prism_plurality/features/chat/providers/chat_providers.dart'; +import 'package:prism_plurality/features/chat/views/chat_screen.dart'; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/features/members/providers/member_groups_providers.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/shared/widgets/prism_segmented_control.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'chrome_text_scale_harness.dart'; + +class _TestSpeakingAsNotifier extends SpeakingAsNotifier { + _TestSpeakingAsNotifier(this._memberId); + + final String? _memberId; + + @override + String? build() => _memberId; + + @override + void setMember(String? memberId, {bool recordLastUsed = true}) { + state = memberId; + } +} + +class _EmptyChatMessageRepository implements ChatMessageRepository { + @override + Future createMessage(domain.ChatMessage message) async {} + + @override + Future deleteMessage(String id) async {} + + @override + Future> getAllMessages() async => []; + + @override + Future getLatestMessage(String conversationId) async => + null; + + @override + Future getMessageById(String id) async => null; + + @override + Future isMessageDeleted(String messageId) async => false; + + @override + Future> getMessagesForConversation( + String conversationId, { + int? limit, + int? offset, + }) async => []; + + @override + Future< + List< + ({ + String messageId, + String conversationId, + String snippet, + DateTime timestamp, + String? authorId, + }) + > + > + searchMessages(String query, {int limit = 50}) async => []; + + @override + Future updateMessage(domain.ChatMessage message) async {} + + @override + Stream> watchAllUnreadCounts( + Map conversationSince, + ) => Stream.value({}); + + @override + Stream> watchConversationsWithMentions( + Map conversationSince, + String memberId, + ) => Stream.value({}); + + @override + Stream watchLatestMessage(String conversationId) => + Stream.value(null); + + @override + Stream> watchMessagesForConversation( + String conversationId, + ) => Stream.value([]); + + @override + Stream> watchRecentMessages( + String conversationId, { + required int limit, + }) => Stream.value([]); + + @override + Stream watchUnreadCount(String conversationId, DateTime since) => + Stream.value(0); + + @override + Stream watchUnreadMentionCount( + String conversationId, + DateTime since, + String memberId, + ) => Stream.value(0); +} + +Member _member(String id, String name) => + Member(id: id, name: name, createdAt: DateTime(2026, 5, 8)); + +Widget _subject({ + required double system, + required double app, + int groupUnread = 0, + int dmUnread = 0, + String fontFamily = 'Lexend', +}) { + SharedPreferences.setMockInitialValues({}); + final now = DateTime(2026, 5, 8, 12); + final alice = _member('alice', 'Alice'); + final bob = _member('bob', 'Bob'); + final members = FakeMemberRepository()..seed([alice, bob]); + final conversations = FakeConversationRepository() + ..conversations.addAll([ + Conversation( + id: 'dm-1', + createdAt: now, + lastActivityAt: now, + participantIds: const ['alice', 'bob'], + isDirectMessage: true, + ), + Conversation( + id: 'group-1', + createdAt: now.subtract(const Duration(minutes: 1)), + lastActivityAt: now.subtract(const Duration(minutes: 1)), + participantIds: const ['alice', 'bob'], + title: 'Planning', + ), + ]); + + return ProviderScope( + overrides: [ + memberRepositoryProvider.overrideWithValue(members), + conversationRepositoryProvider.overrideWithValue(conversations), + chatMessageRepositoryProvider.overrideWithValue( + _EmptyChatMessageRepository(), + ), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + currentChatViewerProvider.overrideWithValue(alice), + speakingAsProvider.overrideWith(() => _TestSpeakingAsNotifier('alice')), + conversationCategoriesProvider.overrideWith((ref) => Stream.value([])), + allGroupsProvider.overrideWith( + (ref) => Stream.value(const []), + ), + allGroupEntriesProvider.overrideWith( + (ref) => Stream.value(const []), + ), + unreadDmCountProvider.overrideWithValue(dmUnread), + unreadGroupCountProvider.overrideWithValue(groupUnread), + ], + child: chromeApp( + const ChatScreen(), + system: system, + app: app, + fontFamily: fontFamily, + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + for (final (system, app, label) in chromeScales) { + testWidgets('chat pinned header contains its bar and switcher ($label)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_subject(system: system, app: app)); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + // `_ChatSubTab` is private, so the generic control is matched by type test. + final switcher = find.byWidgetPredicate( + (w) => w is PrismSegmentedControl, + ); + expect(switcher, findsOneWidget); + final switcherRect = tester.getRect(switcher); + final titleRect = expectFullSizeText( + tester, + 'Chat', + label: label, + container: barRect, + ); + + expect( + switcherRect.top, + greaterThanOrEqualTo(barRect.bottom - 0.5), + reason: '$label: the switcher must sit below the top bar, not over it', + ); + expect( + titleRect.bottom, + lessThanOrEqualTo(switcherRect.top + 0.5), + reason: '$label: the title must not be pushed into the switcher', + ); + + // The band's own extent, from the pinned sliver: the chat list may put a + // visibility banner or a section header above the first conversation, so + // the first tile is not a band marker. + final bandBottom = barRect.top + pinnedBandHeight(tester); + expect( + switcherRect.bottom, + lessThanOrEqualTo(bandBottom + 0.5), + reason: + '$label: the switcher (bottom ${switcherRect.bottom.toStringAsFixed(1)}) ' + 'is clipped by the pinned band (bottom ${bandBottom.toStringAsFixed(1)})', + ); + // The band must be exactly the height its children paint: bar + 8 + track + // + 8. If the switcher reports less than it renders, the band is short and + // the track is clipped; if the header over-reserves, this catches the gap. + expect( + bandBottom, + closeTo(barRect.height + 16 + switcherRect.height, 0.5), + reason: + '$label: the pinned band (${bandBottom.toStringAsFixed(1)}) must equal ' + 'bar (${barRect.height.toStringAsFixed(1)}) + padding (16) + switcher ' + '(${switcherRect.height.toStringAsFixed(1)})', + ); + expectNoLayoutException(tester, label); + }); + } + + testWidgets('chat pinned header re-measures when the text scale changes', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_subject(system: 1.0, app: 1.0)); + await tester.pumpAndSettle(); + final before = tester.getRect(find.byType(PrismTopBar)).height; + + await tester.pumpWidget(_subject(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + expect( + barRect.height, + greaterThan(before), + reason: 'the pinned band must follow the new text scale', + ); + expectFullSizeText( + tester, + 'Chat', + label: 'chat after scale change', + container: barRect, + ); + expectNoLayoutException(tester, 'chat after scale change'); + }); + + // The pinned band must reserve exactly what the switcher renders, for the + // badges that are actually shown: a synthetic "widest badge" could force a + // needless label wrap and an extra line of reserve. + for (final fontFamily in ['Lexend', 'OpenDyslexic']) { + for (final width in [320.0, 390.0, 600.0, 1440.0]) { + for (final badges in [ + (label: 'no badges', group: 0, dm: 0), + (label: 'some badges', group: 3, dm: 1), + (label: 'max badges', group: 120, dm: 120), + ]) { + testWidgets( + 'chat pinned band matches the rendered switcher with ${badges.label} ' + 'at ${width.toInt()}dp, $fontFamily', + (tester) async { + useWindow(tester, Size(width, 900)); + await tester.pumpWidget( + _subject( + system: 1.0, + app: 1.0, + groupUnread: badges.group, + dmUnread: badges.dm, + fontFamily: fontFamily, + ), + ); + await tester.pumpAndSettle(); + + expect( + find.byType(PrismTopBar), + findsOneWidget, + reason: 'the chat list pane has exactly one top bar', + ); + final barRect = tester.getRect(find.byType(PrismTopBar)); + final switcher = find.byWidgetPredicate( + (widget) => widget is PrismSegmentedControl, + ); + final switcherRect = tester.getRect(switcher); + final bandBottom = barRect.top + pinnedBandHeight(tester); + + expect( + bandBottom, + closeTo(barRect.height + 16 + switcherRect.height, 0.5), + reason: + 'the band must be bar + padding + the switcher it renders, ' + 'with ${badges.label}', + ); + expectFullSizeText( + tester, + 'Chat', + label: badges.label, + container: barRect, + ); + expectNoLayoutException(tester, '${badges.label} at $width'); + + // At normal text the labels fit on one line with or without a badge, + // so a badge must not add height. + if (badges.group == 120) { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + await tester.pumpWidget( + _subject(system: 1.0, app: 1.0, fontFamily: fontFamily), + ); + await tester.pumpAndSettle(); + final withoutBadges = tester.getRect( + find.byWidgetPredicate( + (widget) => widget is PrismSegmentedControl, + ), + ); + expect( + withoutBadges.height, + closeTo(switcherRect.height, 0.5), + reason: + 'a badge must not add a line at normal text ' + '(${withoutBadges.height} vs ${switcherRect.height})', + ); + } + }, + ); + } + } + } +} diff --git a/test/text_scale_fixes/chrome/chrome_cache_invalidation_test.dart b/test/text_scale_fixes/chrome/chrome_cache_invalidation_test.dart new file mode 100644 index 000000000..955663c17 --- /dev/null +++ b/test/text_scale_fixes/chrome/chrome_cache_invalidation_test.dart @@ -0,0 +1,182 @@ +// Cache regressions for the pinned-header extent (`SliverPinnedTopBar` caches the +// measured height and must invalidate it on every input that can change it). +// +// Case 1: a fixed-width pane. The sliver's cross-axis extent does not change +// while the *window* crosses PrismTokens.desktopBreakpoint (768), which is what +// PrismTopBar uses to choose its title size (22 -> 18). The bar therefore needs a +// different height although the child instance, theme, scaler and sliver width +// are all identical: the band must follow the bar, and the title must still be +// painted at its requested size. +// +// Case 2: the sliver width itself changes at a constant window. That is a cache +// key, so the bar must be measured again at the new width. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; +import 'package:prism_plurality/shared/widgets/sliver_pinned_top_bar.dart'; + +import 'chrome_text_scale_harness.dart'; + +/// Pane width used for the fixed-pane case. It is also +/// [PrismTokens.contentMaxWidth], the width every content-primary screen clamps +/// its body to, so this is the real shape of a clamped page. +const double _paneWidth = PrismTokens.contentMaxWidth; + +class _Calls { + int count = 0; +} + +class _CountingBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { + const _CountingBar({required this.calls}); + + final _Calls calls; + + @override + Size get preferredSize => const Size.fromHeight(PrismTokens.topBarHeight); + + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + calls.count += 1; + return PrismTokens.topBarHeight + + MediaQuery.textScalerOf(context).scale(10) + + (availableWidth ?? 0) / 100000; + } + + @override + Widget build(BuildContext context) => + const SizedBox.expand(child: Center(child: Text('Counting bar'))); +} + +Widget _list({int count = 40}) => ListView.builder( + itemCount: count, + itemBuilder: (context, index) => + SizedBox(height: 48, child: Text('Row $index')), +); + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + testWidgets( + 'a fixed pane re-measures when the window crosses the desktop breakpoint', + (tester) async { + useWindow(tester, const Size(900, 700)); + const title = 'Fronting schedule today'; + const subtitle = '12 headmates'; + // One instance for both frames: neither theme, scaler nor child changes. + const bar = PrismTopBar(title: title, subtitle: subtitle); + + Widget page() => Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: _paneWidth, + child: PrismPageScaffold(topBar: bar, body: _list()), + ), + ); + + await tester.pumpWidget( + ProviderScope(child: chromeApp(page(), system: 2.25, app: 1.5)), + ); + await tester.pumpAndSettle(); + final wideBar = tester.getRect(find.byType(PrismTopBar)); + final wideBand = pinnedBandHeight(tester); + expectNoLayoutException(tester, 'fixed pane, 900dp window'); + expect( + wideBand, + closeTo(wideBar.height, 0.5), + reason: 'the band is the bar before the crossing', + ); + + // Same pane (720dp inside a 760dp window), same child instance, same theme + // and scaler: only the window width crosses 768, so the title goes from the + // 18pt desktop style to the 22pt one and the bar needs more room. + useWindow(tester, const Size(760, 700)); + await tester.pumpAndSettle(); + + final narrowBar = tester.getRect(find.byType(PrismTopBar)); + final narrowBand = pinnedBandHeight(tester); + expect( + narrowBar.height, + greaterThan(wideBar.height + 0.5), + reason: + 'the 22pt title needs more room than the 18pt one ' + '(${narrowBar.height} vs ${wideBar.height})', + ); + expect( + narrowBand, + closeTo(narrowBar.height, 0.5), + reason: + 'after the window crosses the breakpoint the band must follow the ' + 'bar ($narrowBand vs ${narrowBar.height}); a cached extent from the ' + 'other style is stale', + ); + expectFullSizeText( + tester, + title, + label: 'fixed pane after the crossing', + container: narrowBar, + ); + expectFullSizeText( + tester, + subtitle, + label: 'fixed pane after the crossing (subtitle)', + container: narrowBar, + ); + expectNoLayoutException(tester, 'fixed pane, 760dp window'); + }, + ); + + testWidgets( + 'a changed sliver width re-measures the bar at a constant window', + (tester) async { + useWindow(tester, const Size(900, 700)); + final calls = _Calls(); + final bar = _CountingBar(calls: calls); + + Widget page(double paneWidth) => Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: paneWidth, + child: Scaffold( + body: CustomScrollView( + slivers: [ + SliverPinnedTopBar(child: bar), + SliverList.builder( + itemCount: 40, + itemBuilder: (context, index) => + SizedBox(height: 48, child: Text('Row $index')), + ), + ], + ), + ), + ), + ); + + await tester.pumpWidget( + ProviderScope(child: chromeApp(page(700), system: 1.0, app: 1.0)), + ); + await tester.pumpAndSettle(); + final atSevenHundred = calls.count; + expect(atSevenHundred, greaterThan(0)); + + await tester.pumpWidget( + ProviderScope(child: chromeApp(page(800), system: 1.0, app: 1.0)), + ); + await tester.pumpAndSettle(); + expect( + calls.count, + greaterThan(atSevenHundred), + reason: 'a new cross-axis width is a cache key and must re-measure', + ); + }, + ); +} diff --git a/test/text_scale_fixes/chrome/chrome_contract_text_scale_test.dart b/test/text_scale_fixes/chrome/chrome_contract_text_scale_test.dart new file mode 100644 index 000000000..c4a9d109e --- /dev/null +++ b/test/text_scale_fixes/chrome/chrome_contract_text_scale_test.dart @@ -0,0 +1,482 @@ +// The shared chrome height negotiation, exercised directly: +// +// * `prismScaledPreferredSize(context, bar)` — the supported way to place a +// growing bar in a fixed-extent slot. `Scaffold.appBar` caps its child at +// `preferredSize.height + MediaQuery.padding.top`, and `preferredSize` is a +// getter without a `BuildContext`, so a bar cannot grow there on its own. The +// adapter resolves the content height with the caller's context; Scaffold adds +// the status padding once, and the declared size must NOT include it again. +// * `PrismSheetTopBar(titleWidget: …)` with a widget that reports its own height +// must be contained (no fixed 180dp ceiling, measured at the real middle width). +// * `SliverPinnedTopBar` leaves the bar unpinned when the viewport cannot hold +// both it and a usable body, so a short window with the keyboard up scrolls +// instead of squeezing the body to nothing. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; +import 'package:prism_plurality/shared/widgets/prism_segmented_control.dart'; +import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; +import 'package:prism_plurality/shared/widgets/sliver_pinned_top_bar.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; + +import 'chrome_text_scale_harness.dart'; + +/// A middle-slot widget that reports its own height, like a control does once it +/// adopts [PrismScaledHeight]. +class _MeasuredBox extends StatelessWidget implements PrismScaledHeight { + const _MeasuredBox({required this.height}); + + final double height; + + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) => + height; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: height, + child: const ColoredBox( + color: Color(0x11000000), + child: Center(child: Text('measured middle')), + ), + ); + } +} + +Widget _list({int count = 40}) => ListView.builder( + itemCount: count, + itemBuilder: (context, index) => + SizedBox(height: 48, child: Text('Row $index')), +); + +class _CallCounter { + int calls = 0; +} + +/// A bar that reports a scalable height and counts how often it is measured, so +/// the sliver's cache can be checked without touching the real bars. +class _CountingBar extends StatelessWidget + implements PreferredSizeWidget, PrismScaledHeight { + const _CountingBar({required this.counter}); + + final _CallCounter counter; + + @override + Size get preferredSize => const Size.fromHeight(PrismTokens.topBarHeight); + + @override + double preferredHeightFor(BuildContext context, {double? availableWidth}) { + counter.calls += 1; + return PrismTokens.topBarHeight + + MediaQuery.textScalerOf(context).scale(10) + + (availableWidth ?? 0) / 100000; + } + + @override + Widget build(BuildContext context) { + return const SizedBox.expand(child: Center(child: Text('Counting bar'))); + } +} + +Widget _countingPage(_CountingBar bar) { + return Scaffold( + body: CustomScrollView( + slivers: [ + SliverPinnedTopBar(child: bar), + SliverList.builder( + itemCount: 60, + itemBuilder: (context, index) => + SizedBox(height: 48, child: Text('Row $index')), + ), + ], + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + testWidgets('prismScaledPreferredSize keeps a growing bar whole in ' + 'Scaffold.appBar with a real status inset', (tester) async { + useWindow(tester, compactPhone); + const statusInset = 47.0; + const title = 'Fronting schedule today'; + const subtitle = '12 headmates'; + + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData( + padding: EdgeInsets.only(top: statusInset), + viewPadding: EdgeInsets.only(top: statusInset), + ), + child: ProviderScope( + child: chromeApp( + Builder( + builder: (context) { + // Exactly the production migration shape: the bar is built where + // the context exists, and its measured content height is declared + // to the fixed-extent slot. + const bar = PrismTopBar(title: title, subtitle: subtitle); + return Scaffold( + appBar: prismScaledPreferredSize(context, bar), + body: _list(), + ); + }, + ), + system: 2.25, + app: 1.5, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + expectNoLayoutException(tester, 'appBar adapter'); + + // The bar occupies the status inset plus its measured content height, and the + // inset appears exactly once: the title sits below the status area, and the + // declared slot is not padded twice. + expect( + barRect.top, + closeTo(0, 0.5), + reason: + 'the app bar starts at the top of the window, under the status bar', + ); + + final titleRect = expectFullSizeText( + tester, + title, + label: 'appBar adapter', + container: barRect, + ); + expectFullSizeText( + tester, + subtitle, + label: 'appBar adapter (subtitle)', + container: barRect, + ); + expect( + titleRect.top, + greaterThanOrEqualTo(statusInset - 0.5), + reason: 'the title must not paint under the status bar', + ); + + // The reserved extent is the bar's content height, plus the inset Scaffold + // adds itself - i.e. exactly the painted bar, with no empty status band. + final scaffold = tester.widget(find.byType(Scaffold)); + final appBar = scaffold.appBar!; + expect( + appBar.preferredSize.height + statusInset, + closeTo(barRect.height, 0.5), + reason: + 'declared ${appBar.preferredSize.height} + inset $statusInset must ' + 'equal the painted ${barRect.height}, so the inset is not added twice', + ); + }); + + testWidgets('a bar mounted directly in Scaffold.appBar only reserves its ' + 'minimum (documented limitation)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Fronting schedule today'; + + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + const Scaffold( + appBar: PrismTopBar(title: title), + body: SizedBox.shrink(), + ), + system: 2.25, + app: 1.5, + ), + ), + ); + await tester.pumpAndSettle(); + + // The legacy constructor cannot grow from a context-free getter, so a direct + // mount reserves only the 66dp minimum and the bar paints outside it at large + // text. This is the limitation the adapter exists for; it is asserted here so + // nobody mistakes the getter for a fix. + final barRect = tester.getRect(find.byType(PrismTopBar)); + expect( + barRect.height, + closeTo(PrismTokens.topBarHeight, 0.5), + reason: 'the legacy mount reserves only preferredSize (the minimum)', + ); + final paragraph = tester.renderObject(find.text(title)); + expect( + paragraph.size.height, + greaterThan(PrismTokens.topBarHeight), + reason: + 'the title needs more than the slot the legacy mount reserved ' + '(${neededHeight(paragraph).toStringAsFixed(1)}px at 3.375x)', + ); + expect( + tester.getRect(find.text(title)).bottom, + greaterThan(barRect.bottom + 0.5), + reason: + 'the title paints outside the reserved slot: use ' + 'prismScaledPreferredSize(context, bar), not a direct appBar mount', + ); + // The overflow is the documented consequence; clear it so this test reports + // the assertions above rather than the framework error. + tester.takeException(); + }); + + testWidgets('PrismSheetTopBar measures a titleWidget that reports its own ' + 'height and contains it', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + Scaffold( + body: SafeArea( + child: Column( + children: [ + const PrismSheetTopBar( + title: 'Segmented title', + titleWidget: _MeasuredBox(height: 120), + ), + Expanded(child: _list(count: 5)), + ], + ), + ), + ), + system: 2.25, + app: 1.5, + ), + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismSheetTopBar)); + final middleRect = tester.getRect(find.text('measured middle')); + expect( + barRect.height, + greaterThanOrEqualTo(120 + 12 - 0.5), + reason: + 'the bar must reserve the middle widget height plus its breathing', + ); + expect(middleRect.top, greaterThanOrEqualTo(barRect.top - 0.5)); + expect( + middleRect.bottom, + lessThanOrEqualTo(barRect.bottom + 0.5), + reason: 'the measured middle widget is contained, not clipped', + ); + expectNoLayoutException(tester, 'measured titleWidget'); + }); + + testWidgets('a real segmented titleWidget stays inside the sheet bar', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + Scaffold( + body: SafeArea( + child: Column( + children: [ + PrismSheetTopBar( + title: 'Tabs', + titleWidget: PrismSegmentedControl( + segments: const [ + PrismSegment(value: 0, label: 'Edit'), + PrismSegment(value: 1, label: 'Style'), + ], + selected: 0, + onChanged: (_) {}, + ), + ), + Expanded(child: _list(count: 5)), + ], + ), + ), + ), + system: 2.25, + app: 1.5, + ), + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismSheetTopBar)); + final track = tester.getRect( + find.byWidgetPredicate((widget) => widget is PrismSegmentedControl), + ); + expect(track.top, greaterThanOrEqualTo(barRect.top - 0.5)); + expect( + track.bottom, + lessThanOrEqualTo(barRect.bottom + 0.5), + reason: 'the switcher is contained by the sheet bar at 3.375x', + ); + expectNoLayoutException(tester, 'segmented titleWidget'); + }); + + testWidgets('a pinned bar scrolls away instead of squeezing the body on a ' + 'short viewport', (tester) async { + // Landscape-ish height with a software keyboard up: the bar needs more room + // than the viewport leaves for a usable body. + useWindow(tester, const Size(320, 200), keyboardInset: 90); + const title = 'Timeline'; + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + PrismPageScaffold( + topBar: const PrismTopBar(title: title, subtitle: '12 headmates'), + // Opt-in: a composite/growing header asks for room below itself. The + // default (0) keeps ordinary bars pinned whenever they fit at all. + topBarMinBodyExtent: 96, + body: _list(count: 20), + ), + system: 2.25, + app: 1.5, + ), + ), + ); + await tester.pumpAndSettle(); + + final barBefore = tester.getRect(find.byType(PrismTopBar)); + expectNoLayoutException(tester, 'short viewport'); + expectFullSizeText( + tester, + title, + label: 'short viewport', + container: barBefore, + ); + + // Not pinned: the header is part of the scroll extent, so the outer position + // advances and the body stays usable. The bar is not read again afterwards — + // once it scrolls out of view the sliver may legitimately not build it. + final outer = tester.state(find.byType(Scrollable).first); + expect( + outer.position.maxScrollExtent, + greaterThan(0), + reason: 'a short viewport must be scrollable, not clipped', + ); + outer.position.jumpTo(outer.position.maxScrollExtent); + await tester.pumpAndSettle(); + expect( + outer.position.pixels, + greaterThan(0), + reason: + 'the bar must scroll with the content when the viewport is too short', + ); + expect( + tester.getRect(find.byType(ListView)).height, + greaterThan(0), + reason: 'the body keeps a scrollable area', + ); + }); + + testWidgets( + 'a plain 66dp bar still pins in a very short viewport (default is ' + 'unchanged)', + (tester) async { + // A bare 66dp bar (default text size) in a very short viewport: no body + // minimum is requested, so pinning is exactly as before. + useWindow(tester, const Size(320, 150)); + const title = 'Members'; + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + PrismPageScaffold( + topBar: const PrismTopBar(title: title), + body: _list(count: 20), + ), + system: 1.0, + app: 1.0, + ), + ), + ); + await tester.pumpAndSettle(); + expectNoLayoutException(tester, 'short viewport, plain bar'); + + final barBefore = tester.getRect(find.byType(PrismTopBar)); + // Still pinned: scrolling does not move it. Only headers that opt in to a + // body minimum give up pinning. + await tester.drag(find.byType(ListView), const Offset(0, -80)); + await tester.pumpAndSettle(); + final barAfter = tester.getRect(find.byType(PrismTopBar)); + expect( + barAfter.top, + closeTo(barBefore.top, 0.5), + reason: + 'a plain bar keeps today\'s pinning behaviour on a short viewport', + ); + }, + ); + + testWidgets('the sliver measures a bar once per input, not once per scroll ' + 'frame', (tester) async { + useWindow(tester, const Size(320, 640)); + final counter = _CallCounter(); + final bar = _CountingBar(counter: counter); + + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + _countingPage(bar), + system: 1.0, + app: 1.0, + scalerOverride: const TextScaler.linear(1.0), + ), + ), + ); + await tester.pumpAndSettle(); + + final afterFirstLayout = counter.calls; + expect(afterFirstLayout, greaterThan(0)); + + for (var i = 0; i < 6; i++) { + await tester.drag(find.byType(CustomScrollView), const Offset(0, -40)); + await tester.pump(); + } + expect( + counter.calls, + afterFirstLayout, + reason: + 'scrolling at a stable width and scale must not re-measure the bar ' + '(${counter.calls} vs $afterFirstLayout)', + ); + + // A text-scale change with the same widget instance must re-measure. + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + _countingPage(bar), + system: 1.0, + app: 1.0, + scalerOverride: const TextScaler.linear(2.0), + ), + ), + ); + await tester.pumpAndSettle(); + final afterScaleChange = counter.calls; + expect( + afterScaleChange, + greaterThan(afterFirstLayout), + reason: 'a new text scale must invalidate the cached height', + ); + + // A width change with the same widget instance must re-measure too. + useWindow(tester, const Size(400, 640)); + await tester.pumpAndSettle(); + expect( + counter.calls, + greaterThan(afterScaleChange), + reason: 'a new cross-axis width must invalidate the cached height', + ); + }); +} diff --git a/test/text_scale_fixes/chrome/chrome_text_scale_harness.dart b/test/text_scale_fixes/chrome/chrome_text_scale_harness.dart new file mode 100644 index 000000000..9feb470fa --- /dev/null +++ b/test/text_scale_fixes/chrome/chrome_text_scale_harness.dart @@ -0,0 +1,319 @@ +// Shared harness for the chrome (top bar / sheet bar / pinned header) +// text-scale regressions. +// +// Mirrors how `lib/app.dart` composes text size: the user's system +// accessibility scaler, then Prism's own font-size preference, delegated per +// font size through [PrismTextScaler]. Nothing is clamped anywhere. The real +// bundled faces are loaded so measurements come from the glyphs the app paints. +// +// Every assertion here is global painted geometry: the paragraph's laid-out +// height is compared with the rect it is actually painted into, because a +// `FittedBox(scaleDown)` ancestor leaves the laid-out height intact and only +// shrinks the painted rect. + +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/sliver_pinned_top_bar.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// Compact phone used for the narrow cases. +const Size compactPhone = Size(320, 568); + +/// Wide window: above PrismTokens.desktopBreakpoint, so the desktop title size +/// (18pt) is in play. +const Size wideWindow = Size(1440, 900); + +/// (system accessibility scaler, Prism font-size preference, label). +const List<(double, double, String)> chromeScales = [ + (1.0, 0.5, 'system 100% x Prism 50% = 0.5x'), + (1.0, 1.0, 'default text'), + (1.5, 1.0, 'large text'), + (2.25, 1.5, 'system 225% x Prism 150% = 3.375x'), +]; + +/// The two bundled faces the app ships for body text. +const List chromeFontFamilies = ['Lexend', 'OpenDyslexic']; + +Future loadChromeFonts() => loadPrismGoldenFonts(); + +/// Deterministic window size, with an optional software-keyboard inset. +void useWindow(WidgetTester tester, Size size, {double keyboardInset = 0}) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + if (keyboardInset > 0) { + tester.view.viewInsets = FakeViewPadding(bottom: keyboardInset); + } + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + tester.view.resetViewInsets(); + }); +} + +ThemeData chromeTheme(String fontFamily) => ThemeData( + fontFamily: fontFamily, + fontFamilyFallback: const ['NotoColorEmoji'], +); + +/// MaterialApp that composes the system scaler with Prism's preference exactly +/// like `app.dart`. +Widget chromeApp( + Widget home, { + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + TextDirection? textDirection, + bool boldText = false, + Locale locale = const Locale('en'), +}) { + return MaterialApp( + theme: chromeTheme(fontFamily), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en'), Locale('es')], + locale: locale, + builder: (context, child) { + final content = child ?? const SizedBox.shrink(); + final scaler = + scalerOverride ?? PrismTextScaler(TextScaler.linear(system), app); + return MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: scaler, boldText: boldText), + child: textDirection == null + ? content + : Directionality(textDirection: textDirection, child: content), + ); + }, + home: home, + ); +} + +/// A deliberately nonlinear scaler: no chrome case may assume that one length +/// follows from multiplying another by a single ratio. +class NonlinearTextScaler extends TextScaler { + const NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize <= 14 ? fontSize * 3.0 : fontSize * 1.6; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.0; + + @override + bool operator ==(Object other) => other is NonlinearTextScaler; + + @override + int get hashCode => 0x6368726f; // 'chro' +} + +/// Height one line of [text] needs under [scaler], measured from real glyphs. +double lineHeightFor( + String text, + TextStyle style, + TextScaler scaler, { + double maxWidth = double.infinity, + int maxLines = 1, +}) { + final painter = TextPainter( + text: TextSpan(text: text, style: style), + textDirection: TextDirection.ltr, + textScaler: scaler, + maxLines: maxLines, + )..layout(maxWidth: maxWidth); + final height = painter.height; + painter.dispose(); + return height; +} + +/// The paragraph that paints [text]; exactly one must exist. +RenderParagraph paragraphOf(WidgetTester tester, String text) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: 'exactly one "$text" paragraph'); + return tester.renderObject(finder); +} + +/// Height the paragraph would occupy if nothing constrained it: same text, +/// same style, same inherited scaler, no vertical clamp. +double neededHeight(RenderParagraph paragraph) { + final painter = TextPainter( + text: TextSpan( + text: paragraph.text.toPlainText(), + style: paragraph.text.style, + ), + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + textAlign: paragraph.textAlign, + maxLines: 1, + )..layout(); + final height = painter.height; + painter.dispose(); + return height; +} + +/// Asserts [text] is painted at the size the user asked for, inside [container] +/// and inside the window, without a shrink or a clamp. Returns the painted rect. +Rect expectFullSizeText( + WidgetTester tester, + String text, { + required String label, + Rect? container, + Finder? finder, +}) { + final target = finder ?? find.text(text); + expect(target, findsOneWidget, reason: 'exactly one paragraph for "$text"'); + final paragraph = tester.renderObject(target); + final needed = neededHeight(paragraph); + final laidOut = paragraph.size.height; + final painted = tester.getRect(target); + + expect( + laidOut, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: CLIPPED - "$text" needs ${needed.toStringAsFixed(1)}px but its ' + 'paragraph is laid out at ${laidOut.toStringAsFixed(1)}px', + ); + expect( + painted.height, + greaterThanOrEqualTo(laidOut * 0.98), + reason: + '$label: SHRUNK - "$text" is painted at ${painted.height.toStringAsFixed(1)}px ' + 'for a ${laidOut.toStringAsFixed(1)}px layout ' + '(x${(painted.height / (laidOut == 0 ? 1 : laidOut)).toStringAsFixed(3)})', + ); + if (container != null) { + expect( + painted.top, + greaterThanOrEqualTo(container.top - 0.5), + reason: '$label: "$text" is cut off at the top of its container', + ); + expect( + painted.bottom, + lessThanOrEqualTo(container.bottom + 0.5), + reason: '$label: "$text" is cut off at the bottom of its container', + ); + } + final windowSize = Size( + tester.view.physicalSize.width / tester.view.devicePixelRatio, + tester.view.physicalSize.height / tester.view.devicePixelRatio, + ); + final window = Offset.zero & windowSize; + expect( + painted.left, + greaterThanOrEqualTo(window.left - 0.5), + reason: '$label: "$text" starts outside the window', + ); + expect( + painted.right, + lessThanOrEqualTo(window.right + 0.5), + reason: '$label: "$text" runs past the right edge of the window', + ); + return painted; +} + +/// No layout exception was reported by any ancestor this frame. +void expectNoLayoutException(WidgetTester tester, String label) { + final exception = tester.takeException(); + expect(exception, isNull, reason: '$label: layout exception: $exception'); +} + +/// Height the pinned header currently occupies, read from its own sliver +/// geometry instead of from whatever content happens to sit below it (a list's +/// first tile can be preceded by banners, padding or section headers). +double pinnedBandHeight(WidgetTester tester, {Finder? finder}) { + final target = finder ?? find.byType(SliverPinnedTopBar); + expect(target, findsOneWidget, reason: 'exactly one pinned header sliver'); + final sliver = tester.renderObject(target); + final geometry = sliver.geometry; + expect(geometry, isNotNull, reason: 'the pinned header has been laid out'); + return geometry!.scrollExtent; +} + +/// Laid-out glyph-run boxes for [text]: the ink extents the paragraph will paint, +/// including runs resolved to a fallback face (emoji, CJK, Arabic). +/// +/// A paragraph's line box does not prove a fallback face's ink stays inside it, so +/// the chrome regressions check these boxes against the bar's rect — the same +/// allowance the timeline header tests use. +List glyphBoxes(WidgetTester tester, String text) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: 'exactly one "$text" paragraph'); + final paragraph = tester.renderObject(finder); + final boxes = paragraph.getBoxesForSelection( + TextSelection(baseOffset: 0, extentOffset: text.length), + ); + return boxes; +} + +/// Asserts the painted glyph runs of [text] (not just the paragraph box) stay +/// inside [container]. +void expectInkInside( + WidgetTester tester, + String text, { + required Rect container, + required String label, +}) { + final rect = tester.getRect(find.text(text)); + final boxes = glyphBoxes(tester, text); + expect( + boxes, + isNotEmpty, + reason: '$label: "$text" rendered no glyph runs, including fallback ink', + ); + for (final box in boxes) { + expect( + rect.top + box.top, + greaterThanOrEqualTo(container.top - 0.5), + reason: '$label: "$text" ink is clipped at the top of its container', + ); + expect( + rect.top + box.bottom, + lessThanOrEqualTo(container.bottom + 0.5), + reason: '$label: "$text" ink is clipped at the bottom of its container', + ); + } +} + +/// Height the bars' own rule needs for this text, computed from what is painted: +/// the laid-out line box of each paragraph plus breathing that covers the measured +/// ink escape (`max(12, 2 * escape + 2)`), with the 3dp title/subtitle gap. +/// +/// This is the *actual fit* criterion for "does it still fit 66dp" - a scale +/// threshold is not, because a face whose ink escapes its line box needs more room +/// even below 1.5x, and a face that fits needs none. +double naturalBarBlockHeight( + WidgetTester tester, { + required String title, + String? subtitle, +}) { + double escape(String text) { + final boxes = glyphBoxes(tester, text); + final lineHeight = paragraphOf(tester, text).size.height; + var value = 0.0; + for (final box in boxes) { + value = math.max(value, -box.top); + value = math.max(value, box.bottom - lineHeight); + } + return math.max(0.0, value); + } + + final titleLine = paragraphOf(tester, title).size.height; + final block = subtitle == null + ? titleLine + : titleLine + 3 + paragraphOf(tester, subtitle).size.height; + final maxEscape = subtitle == null + ? escape(title) + : math.max(escape(title), escape(subtitle)); + return block + math.max(12.0, maxEscape * 2 + 2); +} diff --git a/test/text_scale_fixes/chrome/member_list_view_settings_short_viewport_test.dart b/test/text_scale_fixes/chrome/member_list_view_settings_short_viewport_test.dart new file mode 100644 index 000000000..b2257ee9d --- /dev/null +++ b/test/text_scale_fixes/chrome/member_list_view_settings_short_viewport_test.dart @@ -0,0 +1,325 @@ +// The member list "View Settings" sheet on a viewport shorter than its own header. +// +// The sheet's body decides between a column (bar + expanded list) and a scroll +// fallback by comparing the available height against the height the bar needs, and +// the bar grows with the ambient text scale. On a 320x100 viewport at composed +// 3.375x the body is shorter than the bar alone, so the sheet must still present its +// title, its close action and its settings - with the rest reachable through the +// scroll controller the sheet hands it - instead of collapsing to an empty box. +// +// The case is deliberately not vacuous: it captures the constraints the sheet body +// really receives and the bar height the shared contract reports, and asserts +// `bodyHeight < barHeight` *before* anything else. It also does not prescribe the +// implementation's scroll widget: the sheet may host a ListView or a +// CustomScrollView, so the checks go through the scroll controller the sheet +// provides and the rendered settings content. +// +// Hermetic: the sheet is opened through its real entry point (`PrismSheet. +// showFullScreen`, as `members_screen` does) with the providers this screen reads +// overridden to values; no database, no device, no timers. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/domain/preferences/fronting_terms.dart'; +import 'package:prism_plurality/features/members/providers/member_groups_providers.dart'; +import 'package:prism_plurality/features/members/widgets/member_list_view_settings_sheet.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; +import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; +import 'package:prism_plurality/shared/widgets/prism_switch_row.dart'; + +import '../../helpers/fronting_term_fixtures.dart'; +import 'chrome_text_scale_harness.dart'; + +const _openSheetKey = Key('openViewSettingsSheet'); + +/// Values observed from the opened sheet. +class _SheetProbe { + ScrollController? controller; + double? bodyHeight; + double? barHeight; +} + +class _RecordingSettings extends SettingsNotifier { + final pronouns = []; + final frontButtons = []; + + @override + Future updateMembersShowPronouns(bool value) async { + pronouns.add(value); + } + + @override + Future updateMembersShowFrontButtons(bool value) async { + frontButtons.add(value); + } +} + +Widget _host(_SheetProbe probe) { + return Scaffold( + body: Builder( + builder: (context) => Center( + child: TextButton( + key: _openSheetKey, + onPressed: () { + PrismSheet.showFullScreen( + context: context, + builder: (context, scrollController) { + probe.controller = scrollController; + // Transparent pass-through: the sheet body's real constraints, and + // the height the shared contract says its bar needs. + return LayoutBuilder( + builder: (context, constraints) { + probe.bodyHeight = constraints.maxHeight; + probe.barHeight = prismScaledHeightOf( + context, + PrismSheetTopBar( + title: AppLocalizations.of( + context, + )!.memberListViewSettingsTitle, + ), + availableWidth: constraints.maxWidth, + ); + return MemberListViewSettingsSheet( + scrollController: scrollController, + ); + }, + ); + }, + ); + }, + child: const Text('Open'), + ), + ), + ), + ); +} + +Widget _subject({ + required _SheetProbe probe, + required double system, + required double app, + required String family, + _RecordingSettings? settings, +}) { + return ProviderScope( + overrides: [ + if (settings != null) + settingsNotifierProvider.overrideWith(() => settings), + allGroupsProvider.overrideWithValue(const AsyncValue.data([])), + membersShowGroupsProvider.overrideWithValue(false), + membersListViewModeProvider.overrideWithValue( + MembersListViewMode.groupedSections, + ), + membersGroupedDefaultStateProvider.overrideWithValue( + MembersGroupedDefaultState.open, + ), + membersFolderMemberVisibilityProvider.overrideWithValue( + MembersFolderMemberVisibility.allMembers, + ), + membersShowPronounsProvider.overrideWithValue(true), + membersShowFrontButtonsProvider.overrideWithValue(true), + membersFrontButtonBehaviorProvider.overrideWithValue( + FrontStartBehavior.additive, + ), + frontingTermsSettingProvider.overrideWithValue( + FrontingTerms.custom(testFrontingTermBundle), + ), + ], + child: chromeApp( + _host(probe), + system: system, + app: app, + fontFamily: family, + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + for (final family in chromeFontFamilies) { + testWidgets('view settings on a 320x100 viewport keeps its title, close action and ' + 'settings reachable ($family)', (tester) async { + useWindow(tester, const Size(320, 100)); + final probe = _SheetProbe(); + await tester.pumpWidget( + _subject(probe: probe, system: 2.25, app: 1.5, family: family), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(_openSheetKey)); + await tester.pumpAndSettle(); + expectNoLayoutException(tester, 'view settings 320x100 (open)'); + + // Precondition, asserted first so the case cannot pass vacuously: the sheet + // body really is shorter than the bar it has to hold. + expect( + probe.bodyHeight, + isNotNull, + reason: 'the sheet body must have been laid out', + ); + expect( + probe.barHeight, + isNotNull, + reason: 'the bar height must have been resolvable for the same context', + ); + expect( + probe.bodyHeight, + lessThan(probe.barHeight!), + reason: + 'precondition: body ${probe.bodyHeight} must be shorter than the bar ' + '${probe.barHeight} for this case to mean anything', + ); + + // Not blank: the sheet still presents its header and its close action. + expect( + find.text('View Settings'), + findsOneWidget, + reason: + 'the sheet must not collapse to an empty box on a short viewport', + ); + expect( + find.byTooltip('Close'), + findsWidgets, + reason: 'the close action must stay reachable', + ); + + // The controller the sheet provided must be the one carrying the settings, + // whatever scroll widget the fallback uses. + final controller = probe.controller; + expect(controller, isNotNull, reason: 'the sheet provides a controller'); + expect( + controller!.hasClients, + isTrue, + reason: + 'the provided controller must be attached to the scrollable that ' + 'hosts the settings; otherwise nothing below the bar is reachable', + ); + expect( + controller.position.maxScrollExtent, + greaterThan(0), + reason: + 'on a viewport shorter than the content the settings must scroll, so ' + 'everything stays reachable', + ); + + // Settings content exists and is reachable through that controller. + expect( + find.text('Groups'), + findsWidgets, + reason: 'the first settings group is present', + ); + final pixelsBefore = controller.position.pixels; + controller.jumpTo(controller.position.maxScrollExtent); + await tester.pumpAndSettle(); + expect( + controller.position.pixels, + greaterThan(pixelsBefore), + reason: 'the provided controller really scrolls the settings', + ); + + // Close still works from the short viewport. + await tester.ensureVisible(find.byTooltip('Close').first); + await tester.pumpAndSettle(); + expect(find.byTooltip('Close').first.hitTestable(), findsOneWidget); + await tester.tap(find.byTooltip('Close').first); + await tester.pumpAndSettle(); + expect( + find.text('View Settings'), + findsNothing, + reason: 'the close action dismisses the sheet', + ); + expectNoLayoutException(tester, 'view settings 320x100 (close)'); + }); + } + + for (final family in chromeFontFamilies) { + for (final keyboard in [false, true]) { + testWidgets('short landscape settings controls remain hittable ' + 'with safe area and keyboard=$keyboard ($family)', (tester) async { + useWindow( + tester, + const Size(568, 240), + keyboardInset: keyboard ? 108 : 0, + ); + tester.view.viewPadding = const FakeViewPadding(top: 12, bottom: 16); + tester.view.padding = FakeViewPadding( + top: 12, + bottom: keyboard ? 0 : 16, + ); + addTearDown(tester.view.resetViewPadding); + addTearDown(tester.view.resetPadding); + final probe = _SheetProbe(); + final settings = _RecordingSettings(); + await tester.pumpWidget( + _subject( + probe: probe, + system: 2.25, + app: 1.5, + family: family, + settings: settings, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(_openSheetKey)); + await tester.pumpAndSettle(); + final body = tester.getRect(find.byType(MemberListViewSettingsSheet)); + // The route consumes the top safe area and max(keyboard, bottom safe + // area) exactly once, before the body makes its layout decision. + expect(body.top, greaterThanOrEqualTo(12)); + expect(body.bottom, keyboard ? 132 : 224); + expect(body.height, probe.bodyHeight); + final controller = probe.controller!; + expect(controller.hasClients, isTrue); + expect(controller.position.maxScrollExtent, greaterThan(0)); + + final switches = find.byType(PrismSwitchRow); + expect(switches, findsNWidgets(3)); + // All controls are present, including the disabled no-groups switch. + expect(tester.widget(switches.at(0)).enabled, isFalse); + for (final index in [1, 2]) { + final row = switches.at(index); + final target = find.descendant( + of: row, + matching: find.byType(Switch), + ); + expect(target, findsOneWidget); + await tester.ensureVisible(target); + await tester.pumpAndSettle(); + final rect = tester.getRect(target); + expect(rect.width, greaterThanOrEqualTo(44)); + expect(rect.height, greaterThanOrEqualTo(44)); + expect(rect.top, greaterThanOrEqualTo(body.top)); + expect(rect.bottom, lessThanOrEqualTo(body.bottom)); + expect(target.hitTestable(), findsOneWidget); + await tester.tap(target); + await tester.pumpAndSettle(); + } + expect(settings.frontButtons, [false]); + expect(settings.pronouns, [false]); + expectNoLayoutException(tester, 'landscape settings callbacks'); + + final close = find.byTooltip('Close').first; + await tester.ensureVisible(close); + await tester.pumpAndSettle(); + expect(close.hitTestable(), findsOneWidget); + final closeRect = tester.getRect(close); + expect(closeRect.width, greaterThanOrEqualTo(44)); + expect(closeRect.height, greaterThanOrEqualTo(44)); + await tester.tap(close); + await tester.pumpAndSettle(); + expect(find.byType(MemberListViewSettingsSheet), findsNothing); + expectNoLayoutException(tester, 'landscape settings close'); + }); + } + } +} diff --git a/test/text_scale_fixes/chrome/notes_filter_header_text_scale_test.dart b/test/text_scale_fixes/chrome/notes_filter_header_text_scale_test.dart new file mode 100644 index 000000000..55f453275 --- /dev/null +++ b/test/text_scale_fixes/chrome/notes_filter_header_text_scale_test.dart @@ -0,0 +1,460 @@ +// The notes list pins one header: the top bar plus, when a search or member filter +// is active, the filter bar whose height is the search field's line box plus its +// content padding, the chip strip's tallest chip (label line or the text-scaled +// avatar, plus the chip's own border), the gap between them and the bottom +// padding. +// +// Desired behaviour, asserted on the real `NotesListScreen`: the pinned band is +// sized from the same measurements its children use, so the filter bar (field +// and chips) is painted inside the band at full size, before and after the list +// scrolls, and the band re-measures when the text scale changes. +// +// `NotesFilterBar` is exercised through the screen rather than by calling its own +// size API, so the assertion covers what is actually painted. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/domain/models/note.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/domain/repositories/notes_repository.dart'; +import 'package:prism_plurality/features/fronting/providers/fronting_providers.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/members/providers/notes_providers.dart'; +import 'package:prism_plurality/features/notes/views/notes_list_screen.dart'; +import 'package:prism_plurality/features/notes/widgets/notes_filter_bar.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/member_search_sheet.dart'; +import 'package:prism_plurality/shared/widgets/prism_text_field.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'chrome_text_scale_harness.dart'; + +class _FakeNotesRepository implements NotesRepository { + _FakeNotesRepository(List initialNotes) { + for (final note in initialNotes) { + _notes[note.id] = note; + } + } + + final Map _notes = {}; + + @override + Future createNote(Note note) async => _notes[note.id] = note; + + @override + Future deleteNote(String id) async => _notes.remove(id); + + @override + Future> getAllNotes() async => _notes.values.toList(); + + @override + Future getNoteById(String id) async => _notes[id]; + + @override + Future updateNote(Note note) async => _notes[note.id] = note; + + @override + Stream> watchAllNotes() => Stream.value(_notes.values.toList()); + + @override + Stream watchNoteById(String id) => Stream.value(_notes[id]); + + @override + Stream> watchNotesForMember(String memberId) => Stream.value( + _notes.values.where((note) => note.memberId == memberId).toList(), + ); + + @override + Stream> watchRecentNotesForMember( + String memberId, { + int limit = 5, + }) => Stream.value( + _notes.values + .where((note) => note.memberId == memberId) + .take(limit) + .toList(), + ); +} + +final _note = Note( + id: 'note-1', + title: 'Test Note', + body: 'Some body text', + colorHex: '#FF0000', + memberId: 'mem-a', + date: DateTime(2026, 3, 21), + createdAt: DateTime(2026, 3, 21), + modifiedAt: DateTime(2026, 3, 21), +); + +final _alice = Member(id: 'mem-a', name: 'Alice', createdAt: DateTime(2024)); +final _bob = Member(id: 'mem-b', name: 'Bob', createdAt: DateTime(2024)); + +Widget _subject({ + required double system, + required double app, + String fontFamily = 'Lexend', + Locale locale = const Locale('en'), + bool boldText = false, +}) { + final notes = [_note]; + final members = [_alice, _bob]; + return ProviderScope( + overrides: [ + memberRepositoryProvider.overrideWithValue( + FakeMemberRepository()..seed(members), + ), + notesRepositoryProvider.overrideWithValue(_FakeNotesRepository(notes)), + allNotesProvider.overrideWith((ref) => Stream.value(notes)), + activeMemberListProvider.overrideWith((ref) => Stream.value(members)), + currentFronterProvider.overrideWithValue(const AsyncValue.data(null)), + systemSettingsProvider.overrideWithValue( + const AsyncValue.data(SystemSettings()), + ), + ], + child: chromeApp( + const NotesListScreen(), + system: system, + app: app, + fontFamily: fontFamily, + locale: locale, + boldText: boldText, + ), + ); +} + +/// The bottom of the pinned band, read from the header sliver's own geometry so +/// it does not depend on what the list renders first. +double _bandBottom(WidgetTester tester, String label) { + final bar = find.byType(PrismTopBar); + expect(bar, findsOneWidget, reason: '$label: one top bar'); + return tester.getRect(bar).top + pinnedBandHeight(tester); +} + +/// The screen's own localizations, so a non-English locale finds the real control +/// instead of a hardcoded English tooltip. +AppLocalizations _l10n(WidgetTester tester) => + AppLocalizations.of(tester.element(find.byType(NotesListScreen))); + +Future _enableSearch(WidgetTester tester) async { + await tester.tap(find.byTooltip(_l10n(tester).memberNoteSearchNotes)); + await tester.pumpAndSettle(); + expect(find.byType(NotesFilterBar), findsOneWidget); +} + +Future _selectMemberFilter(WidgetTester tester) async { + await tester.tap(find.byTooltip(_l10n(tester).memberNoteFilterByMember)); + await tester.pumpAndSettle(); + await tester.tap( + find.descendant( + of: find.byType(MemberSearchSheet), + matching: find.text('Alice'), + ), + ); + await tester.pumpAndSettle(); + await tester.tap( + find.byWidgetPredicate( + (widget) => + widget is Tooltip && + (widget.message?.startsWith('Confirm selected ') ?? false), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + for (final (system, app, label) in chromeScales) { + // The 60dp search slot holds the field's content padding plus its line box and + // the 8dp bottom padding. Whether it still does is read from the rendered field + // below, not from the scale. + final composedScale = system * app; + + testWidgets('notes search field stays inside the pinned band ($label)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_subject(system: system, app: app)); + await tester.pumpAndSettle(); + + // With no filter bar the pinned header is the bare top bar; its height is the + // bar's own, whatever the scale. + expect( + _bandBottom(tester, label), + greaterThanOrEqualTo(PrismTokens.topBarHeight - 0.5), + reason: '$label: the bar alone keeps at least its own height', + ); + + await _enableSearch(tester); + + final bandBottom = _bandBottom(tester, label); + final filterRect = tester.getRect(find.byType(NotesFilterBar)); + expect( + filterRect.bottom, + lessThanOrEqualTo(bandBottom + 0.5), + reason: + '$label: the filter bar (bottom ${filterRect.bottom.toStringAsFixed(1)}) ' + 'is clipped by the pinned band (bottom ${bandBottom.toStringAsFixed(1)})', + ); + // The slot is preserved only while the field really fits inside it; the + // field's own measured height decides, not the scale. + final fieldSlotFits = + tester.getRect(find.byType(PrismTextField)).height + + NotesFilterBar.searchSlotBottomPadding <= + NotesFilterBar.searchSlotHeight + 0.01; + final barHeight = tester.getRect(find.byType(PrismTopBar)).height; + if (fieldSlotFits) { + expect( + bandBottom, + closeTo(barHeight + NotesFilterBar.searchSlotHeight, 0.5), + reason: + '$label: the search slot keeps its 60dp when the field fits, so the ' + 'band is the bar plus that slot', + ); + } else { + expect( + bandBottom, + greaterThan(barHeight + NotesFilterBar.searchSlotHeight + 0.5), + reason: + '$label: the field needs more than the 60dp slot, so the band must ' + 'grow past it', + ); + } + + // The hint paragraph must keep the line box the field's own text needs. + final fieldText = expectFullSizeText( + tester, + 'Search notes…', + label: '$label (search field)', + ); + expect( + fieldText.bottom, + lessThanOrEqualTo(bandBottom + 0.5), + reason: '$label: the search text is painted below the pinned band', + ); + expectNoLayoutException(tester, '$label (search)'); + }); + } + + // The chip strip's own slot is 44dp today and needs 50dp from 1.5x on. Run at + // 1.5x on a taller window: the defect under test is the header slot, and the + // member-picker flow used to select the filter must not also be squeezed by + // the compact phone's height. + testWidgets('notes member-filter chips stay inside the pinned band', ( + tester, + ) async { + useWindow(tester, const Size(320, 900)); + await tester.pumpWidget(_subject(system: 1.5, app: 1.0)); + await tester.pumpAndSettle(); + + await _selectMemberFilter(tester); + + final bandBottom = _bandBottom(tester, 'chips'); + final chipText = expectFullSizeText( + tester, + 'Alice', + label: 'chip label', + finder: find.descendant( + of: find.byType(NotesFilterBar), + matching: find.text('Alice'), + ), + ); + expect( + chipText.bottom, + lessThanOrEqualTo(bandBottom + 0.5), + reason: + 'the member chip (bottom ${chipText.bottom.toStringAsFixed(1)}) is ' + 'painted below the pinned band (bottom ${bandBottom.toStringAsFixed(1)})', + ); + final filterRect = tester.getRect(find.byType(NotesFilterBar)); + expect( + filterRect.bottom, + lessThanOrEqualTo(bandBottom + 0.5), + reason: 'the chip strip is clipped by the pinned band', + ); + expectNoLayoutException(tester, 'chips'); + }); + + testWidgets('notes pinned filter header keeps the field visible after the ' + 'list scrolls', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_subject(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + await _enableSearch(tester); + + final before = tester.getRect(find.byType(NotesFilterBar)); + await tester.drag(find.byType(ListView), const Offset(0, -240)); + await tester.pumpAndSettle(); + final after = tester.getRect(find.byType(NotesFilterBar)); + + expect( + after.top, + closeTo(before.top, 0.5), + reason: 'the filter bar is pinned: it must not scroll away', + ); + expect( + after.bottom, + lessThanOrEqualTo(_bandBottom(tester, 'scrolled') + 0.5), + reason: 'the pinned filter bar stays inside the band while scrolled', + ); + expectFullSizeText(tester, 'Search notes…', label: 'scrolled search field'); + expectNoLayoutException(tester, 'scrolled'); + }); + + // D3 demonstration: a pinned composite that grows must not outgrow the + // viewport. Landscape-ish window with the keyboard up, search active: today the + // pinned band is a fixed 126dp against a 220dp viewport and its own content + // needs 179dp, so it overflows and squeezes the list to nothing. Desired: no + // clipping, and the note content stays reachable (header scrolls). + testWidgets('notes header and content stay reachable on a short viewport with ' + 'the keyboard up', (tester) async { + useWindow(tester, const Size(320, 360), keyboardInset: 140); + await tester.pumpWidget(_subject(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + await _enableSearch(tester); + + expectNoLayoutException(tester, 'short viewport'); + expectFullSizeText(tester, 'Search notes…', label: 'short viewport'); + + // Drive the outer scroll position directly: on a viewport this short the + // header can be taller than the viewport, so a drag cannot be relied on to + // hit the inner list. + final outer = tester.state(find.byType(Scrollable).first); + expect( + outer.position.maxScrollExtent, + greaterThan(0), + reason: 'the header and the list must be scrollable, i.e. reachable', + ); + outer.position.jumpTo(outer.position.maxScrollExtent); + await tester.pumpAndSettle(); + + // The header itself is not read here: once it scrolls away the sliver may not + // build it at all, so a `getRect` on the bar would fail for a legitimate cull. + // The scroll offset is the honest witness that it moved instead of pinning. + expect( + outer.position.pixels, + greaterThan(0), + reason: + 'the composite header scrolls with the content instead of staying ' + 'pinned and squeezing the list to nothing', + ); + final noteCard = find.text('Test Note'); + expect( + noteCard, + findsOneWidget, + reason: 'the note list is reachable after scrolling on a short viewport', + ); + final noteRect = tester.getRect(noteCard); + final listRect = tester.getRect(find.byType(ListView)); + expect( + noteRect.top, + greaterThanOrEqualTo(listRect.top - 0.5), + reason: + 'the note content is inside the list viewport, not clipped above it', + ); + expect( + noteRect.bottom, + lessThanOrEqualTo(listRect.bottom + 0.5), + reason: 'the note content is reachable, not clipped out of the viewport', + ); + expectNoLayoutException(tester, 'short viewport after scroll'); + }); + + testWidgets('notes pinned header re-measures when the text scale changes', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_subject(system: 1.0, app: 1.0)); + await tester.pumpAndSettle(); + await _enableSearch(tester); + final before = _bandBottom(tester, 'before'); + + await tester.pumpWidget(_subject(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + final after = _bandBottom(tester, 'after'); + expect( + after, + greaterThan(before), + reason: 'the pinned band must follow the new text scale', + ); + expectFullSizeText(tester, 'Search notes…', label: 'after scale change'); + expectNoLayoutException(tester, 'after scale change'); + }); + + // The pinned band must be exactly what the filter bar paints, not merely an + // envelope around it: a bar that over-reserves is as wrong as one that clips. + for (final fontFamily in ['Lexend', 'OpenDyslexic']) { + for (final (system, app, label) in [ + (1.0, 1.5, '1.5x'), + (1.5, 1.5, '2.25x'), + ]) { + testWidgets('notes band equals the rendered bar plus filter bar ' + '($label, $fontFamily)', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _subject(system: system, app: app, fontFamily: fontFamily), + ); + await tester.pumpAndSettle(); + await _enableSearch(tester); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final filterRect = tester.getRect(find.byType(NotesFilterBar)); + final band = pinnedBandHeight(tester); + expect( + band, + closeTo(barRect.height + filterRect.height, 0.5), + reason: + '$label/$fontFamily: the pinned band ($band) must equal the bar ' + '(${barRect.height}) plus the filter bar (${filterRect.height})', + ); + expectNoLayoutException(tester, '$label/$fontFamily notes band'); + }); + } + } + + // Cache parity: the same child at the same width with bold text or a + // different locale must still produce a band equal to what is painted. + for (final variant in [ + (label: 'bold text', boldText: true, locale: const Locale('en')), + (label: 'Spanish locale', boldText: false, locale: const Locale('es')), + ]) { + testWidgets('notes band stays equal under ${variant.label}', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _subject( + system: 1.0, + app: 1.5, + boldText: variant.boldText, + locale: variant.locale, + ), + ); + await tester.pumpAndSettle(); + await _enableSearch(tester); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final filterRect = tester.getRect(find.byType(NotesFilterBar)); + final band = pinnedBandHeight(tester); + expect( + band, + closeTo(barRect.height + filterRect.height, 0.5), + reason: + '${variant.label}: the band must be the rendered bar plus filter bar', + ); + expectNoLayoutException(tester, variant.label); + }); + } +} diff --git a/test/text_scale_fixes/chrome/prism_text_style_measurement_test.dart b/test/text_scale_fixes/chrome/prism_text_style_measurement_test.dart new file mode 100644 index 000000000..832728f72 --- /dev/null +++ b/test/text_scale_fixes/chrome/prism_text_style_measurement_test.dart @@ -0,0 +1,254 @@ +// Measurement parity for the shared text-style helper. +// +// The bars size themselves from a `TextPainter`, so the painter's style must be the +// one the `Text` really paints with: `Text.build` merges the ambient +// `DefaultTextStyle` only when the given style is null or `inherit`, then applies +// `MediaQuery.boldText` as w700, and `RichText` resolves the locale and the inherited +// `TextHeightBehavior`. `prismTextStyleForMeasurement` mirrors those steps; these +// cases compare its output, and the heights measured from it, with a rendered `Text`. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; + +import 'chrome_text_scale_harness.dart'; + +const _family = 'OpenDyslexic'; + +Widget _app( + Widget child, { + required TextStyle inherited, + bool boldText = false, + Locale locale = const Locale('en'), + TextHeightBehavior? textHeightBehavior, +}) { + return MaterialApp( + theme: chromeTheme(_family), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en'), Locale('es')], + locale: locale, + builder: (context, home) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(1.0), boldText: boldText), + child: DefaultTextStyle( + style: inherited, + textHeightBehavior: textHeightBehavior, + child: home ?? const SizedBox.shrink(), + ), + ), + home: child, + ); +} + +/// The style the rendered paragraph ended up with. +TextStyle _paintedStyle(WidgetTester tester, String text) { + final paragraph = tester.renderObject(find.text(text)); + return paragraph.text.style!; +} + +/// The style the helper reports for the same context. +TextStyle _measuredStyle(WidgetTester tester, String text) { + final context = tester.element(find.text(text)); + final painted = _paintedStyle(tester, text); + return prismTextStyleForMeasurement(context, painted); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + testWidgets('an inheriting style measures the text it paints', ( + tester, + ) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontSize: 20, color: Colors.black); + const style = TextStyle(fontSize: 15, height: 1.2); + await tester.pumpWidget( + _app( + const Center(child: Text('Members', style: style)), + inherited: inherited, + ), + ); + await tester.pumpAndSettle(); + + final measured = _measuredStyle(tester, 'Members'); + expect(measured.fontSize, 15); + expect(measured.height, 1.2); + // The default family wins where the given style leaves it null, exactly as the + // painted paragraph resolved it. + expect(measured.fontFamily, _paintedStyle(tester, 'Members').fontFamily); + expect( + prismLineHeight( + tester.element(find.text('Members')), + style, + text: 'Members', + ), + closeTo( + tester.renderObject(find.text('Members')).size.height, + 0.01, + ), + reason: 'the measured line box is the painted line box', + ); + }); + + testWidgets( + 'an explicit inherit:false style does not take the default style', + (tester) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontFamily: 'Lexend', fontSize: 20); + const style = TextStyle( + inherit: false, + fontFamily: _family, + fontSize: 15, + color: Colors.black, + ); + await tester.pumpWidget( + _app( + const Center(child: Text('Members', style: style)), + inherited: inherited, + ), + ); + await tester.pumpAndSettle(); + + final measured = _measuredStyle(tester, 'Members'); + expect( + measured.fontSize, + 15, + reason: 'inherit:false keeps its own size, not the default 20', + ); + expect(measured.fontFamily, _family); + expect(measured.fontFamily, _paintedStyle(tester, 'Members').fontFamily); + }, + ); + + testWidgets('bold text is applied as w700 for measurement too', ( + tester, + ) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontSize: 16); + const style = TextStyle(fontSize: 16, fontWeight: FontWeight.w400); + await tester.pumpWidget( + _app( + const Center(child: Text('Members', style: style)), + inherited: inherited, + boldText: true, + ), + ); + await tester.pumpAndSettle(); + + final measured = _measuredStyle(tester, 'Members'); + expect(measured.fontWeight, FontWeight.bold); + expect(measured.fontWeight, _paintedStyle(tester, 'Members').fontWeight); + expect( + prismLineHeight( + tester.element(find.text('Members')), + style, + text: 'Members', + ), + closeTo( + tester.renderObject(find.text('Members')).size.height, + 0.01, + ), + reason: 'a bold paragraph is measured at the bold line box', + ); + }); + + testWidgets('an inherited TextHeightBehavior changes the measured line box', ( + tester, + ) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontSize: 18, height: 2.0); + const style = TextStyle(fontSize: 18, height: 2.0); + const behaviour = TextHeightBehavior( + applyHeightToFirstAscent: false, + applyHeightToLastDescent: false, + ); + await tester.pumpWidget( + _app( + const Center(child: Text('Members', style: style)), + inherited: inherited, + textHeightBehavior: behaviour, + ), + ); + await tester.pumpAndSettle(); + + final paragraph = tester.renderObject( + find.text('Members'), + ); + expect( + prismLineHeight( + tester.element(find.text('Members')), + style, + text: 'Members', + ), + closeTo(paragraph.size.height, 0.01), + reason: + 'the helper passes the inherited textHeightBehavior, so the measurement ' + 'matches the paragraph it will paint', + ); + }); + + testWidgets('a locale-dependent string measures as it paints', ( + tester, + ) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontSize: 18); + const style = TextStyle(fontSize: 18); + const text = 'نور 中文'; + for (final locale in const [Locale('en'), Locale('es')]) { + await tester.pumpWidget( + _app( + const Center(child: Text(text, style: style)), + inherited: inherited, + locale: locale, + ), + ); + await tester.pumpAndSettle(); + + final paragraph = tester.renderObject(find.text(text)); + expect( + prismLineHeight(tester.element(find.text(text)), style, text: text), + closeTo(paragraph.size.height, 0.01), + reason: 'locale $locale: the measured line box is the painted one', + ); + expect( + prismTextInkEscape(tester.element(find.text(text)), style, text: text), + greaterThanOrEqualTo(0.0), + ); + } + }); + + testWidgets('ordinary theme styles are unchanged by the helper', ( + tester, + ) async { + useWindow(tester, compactPhone); + const inherited = TextStyle(fontFamily: _family, fontSize: 14); + await tester.pumpWidget( + _app( + Builder( + builder: (context) { + // A settings-provided style (concrete family and size, inherit true). + final style = TextStyle( + fontFamily: _family, + fontSize: 17, + fontWeight: FontWeight.w500, + ); + final measured = prismTextStyleForMeasurement(context, style); + expect(measured.fontFamily, _family); + expect(measured.fontSize, 17); + expect(measured.fontWeight, FontWeight.w500); + return const SizedBox.shrink(); + }, + ), + inherited: inherited, + ), + ); + await tester.pumpAndSettle(); + }); +} diff --git a/test/text_scale_fixes/chrome/shared_sheet_bar_text_scale_test.dart b/test/text_scale_fixes/chrome/shared_sheet_bar_text_scale_test.dart new file mode 100644 index 000000000..f14ef38a4 --- /dev/null +++ b/test/text_scale_fixes/chrome/shared_sheet_bar_text_scale_test.dart @@ -0,0 +1,276 @@ +// `PrismSheetTopBar` in the compositions its call sites use +// (`SafeArea > Column > [bar, Expanded(body)]`, plus the `SliverToBoxAdapter` form +// `member_search_sheet` uses). +// +// The bar is at least 66dp and grows to contain its title: one ellipsised line at +// the requested size, inset between the action slots so it cannot paint under +// them, measured from the same text it paints. +// - the bar is at least 66dp and grows to contain its own title, +// - the title is laid out and painted at the requested size, inside the bar, +// - the title never paints under the leading/trailing action, +// - a short window with the keyboard up still lays out the body, +// - the bar re-measures when the text scale changes on a live tree. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_glass_icon_button.dart'; +import 'package:prism_plurality/shared/widgets/prism_sheet.dart'; + +import 'chrome_text_scale_harness.dart'; + +const _trailingKey = Key('sheetBarTrailing'); + +Widget _bar({required String title, bool trailing = true}) { + return PrismSheetTopBar( + title: title, + trailing: trailing + ? PrismGlassIconButton( + key: _trailingKey, + icon: AppIcons.check, + tooltip: 'Done', + size: PrismTokens.topBarActionSize, + onPressed: () {}, + ) + : null, + ); +} + +Widget _columnSheet({ + required String title, + bool trailing = true, + double bodyHeight = 400, +}) { + return Scaffold( + body: SafeArea( + child: Column( + children: [ + _bar(title: title, trailing: trailing), + Expanded( + child: SingleChildScrollView( + child: SizedBox( + key: const Key('sheetBody'), + height: bodyHeight, + child: const Text('body'), + ), + ), + ), + ], + ), + ), + ); +} + +Widget _sliverSheet({required String title}) { + return Scaffold( + body: CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: _bar(title: title)), + const SliverToBoxAdapter( + child: SizedBox( + key: Key('sheetBody'), + height: 400, + child: Text('body'), + ), + ), + ], + ), + ); +} + +Widget _app( + Widget sheet, { + required double system, + required double app, + required String family, +}) { + return ProviderScope( + child: chromeApp(sheet, system: system, app: app, fontFamily: family), + ); +} + +void _expectTitleClearOfTrailing( + WidgetTester tester, { + required Rect titleRect, + required String label, +}) { + final trailing = find.byKey(_trailingKey); + if (trailing.evaluate().isEmpty) return; + final trailingRect = tester.getRect(trailing); + expect( + titleRect.right, + lessThanOrEqualTo(trailingRect.left + 0.5), + reason: + '$label: the title runs under the trailing action ' + '(${titleRect.right.toStringAsFixed(1)} > ${trailingRect.left.toStringAsFixed(1)})', + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + for (final family in chromeFontFamilies) { + for (final (system, app, label) in chromeScales) { + final scaleLabel = '$label, $family'; + + testWidgets('PrismSheetTopBar contains its title in a sheet column ' + '($scaleLabel)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Edit fronting session'; + await tester.pumpWidget( + _app( + _columnSheet(title: title), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismSheetTopBar)); + expect( + barRect.height, + greaterThanOrEqualTo(PrismTokens.topBarHeight - 0.5), + reason: '$scaleLabel: the sheet bar may never reserve less than 66dp', + ); + // Fit, not a scale threshold: a face whose ink escapes its line box needs + // more than 66dp even at 1.5x. + final natural = naturalBarBlockHeight(tester, title: title); + if (natural <= PrismTokens.topBarHeight + 0.01) { + expect( + barRect.height, + closeTo(PrismTokens.topBarHeight, 0.5), + reason: + '$scaleLabel: the title needs ${natural.toStringAsFixed(1)}px, so ' + '66dp must be preserved exactly', + ); + } else { + expect( + barRect.height, + greaterThanOrEqualTo(natural - 0.5), + reason: + '$scaleLabel: the title needs ${natural.toStringAsFixed(1)}px, so ' + 'the bar must grow to it', + ); + } + final titleRect = expectFullSizeText( + tester, + title, + label: scaleLabel, + container: barRect, + ); + _expectTitleClearOfTrailing( + tester, + titleRect: titleRect, + label: scaleLabel, + ); + + final bodyRect = tester.getRect(find.byKey(const Key('sheetBody'))); + expect( + bodyRect.top, + greaterThanOrEqualTo(barRect.bottom - 0.5), + reason: '$scaleLabel: the body starts under the bar', + ); + expectNoLayoutException(tester, scaleLabel); + }); + + testWidgets('PrismSheetTopBar keeps its title in a scrolling sliver ' + '($scaleLabel)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Add members to this group conversation'; + await tester.pumpWidget( + _app( + _sliverSheet(title: title), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismSheetTopBar)); + final titleRect = expectFullSizeText( + tester, + title, + label: '$scaleLabel (sliver)', + container: barRect, + ); + _expectTitleClearOfTrailing( + tester, + titleRect: titleRect, + label: '$scaleLabel (sliver)', + ); + expectNoLayoutException(tester, '$scaleLabel (sliver)'); + }); + } + } + + testWidgets('PrismSheetTopBar leaves the body a laid-out area on a short ' + 'window with the keyboard up', (tester) async { + useWindow(tester, compactPhone, keyboardInset: 260); + const title = 'Edit fronting session'; + await tester.pumpWidget( + _app( + _columnSheet(title: title), + system: 2.25, + app: 1.5, + family: 'Lexend', + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismSheetTopBar)); + expectFullSizeText( + tester, + title, + label: 'short window', + container: barRect, + ); + final bodyRect = tester.getRect(find.byKey(const Key('sheetBody'))); + expect( + bodyRect.top, + greaterThanOrEqualTo(barRect.bottom - 0.5), + reason: 'the body must start under the bar, not overlap it', + ); + expectNoLayoutException(tester, 'short window'); + }); + + testWidgets('PrismSheetTopBar re-measures when the text scale changes on a ' + 'live tree', (tester) async { + useWindow(tester, compactPhone); + const title = 'Edit fronting session'; + final sheet = _columnSheet(title: title); + + await tester.pumpWidget( + _app(sheet, system: 1.0, app: 1.0, family: 'Lexend'), + ); + await tester.pumpAndSettle(); + final before = tester.getRect(find.byType(PrismSheetTopBar)).height; + expect(before, closeTo(PrismTokens.topBarHeight, 0.5)); + + await tester.pumpWidget( + _app(sheet, system: 2.25, app: 1.5, family: 'Lexend'), + ); + await tester.pumpAndSettle(); + + final after = tester.getRect(find.byType(PrismSheetTopBar)).height; + expect( + after, + greaterThan(before), + reason: 'the sheet bar must follow the new text scale', + ); + expectFullSizeText( + tester, + title, + label: 'sheet bar after scale change', + container: tester.getRect(find.byType(PrismSheetTopBar)), + ); + expectNoLayoutException(tester, 'sheet bar after scale change'); + }); +} diff --git a/test/text_scale_fixes/chrome/shared_top_bar_text_scale_test.dart b/test/text_scale_fixes/chrome/shared_top_bar_text_scale_test.dart new file mode 100644 index 000000000..02cf48f2c --- /dev/null +++ b/test/text_scale_fixes/chrome/shared_top_bar_text_scale_test.dart @@ -0,0 +1,439 @@ +// `PrismTopBar` in a pinned header. +// +// The bar is 66dp whenever its content fits there, and grows with the ambient text +// scale when it does not: the title is laid out and painted at the size the user +// asked for (one ellipsised line, full string in its semantics) instead of being +// shrunk to fit, and the pinned band is sized from the same measurement so the bar +// never paints outside it. +// +// Asserted through the app's real mount (`PrismPageScaffold(topBar:)` -> +// `SliverPinnedTopBar` -> `SliverPersistentHeader`): +// - the title is laid out, painted at the requested size and clear of the actions, +// - the bar/header height contains it, +// - 66dp stays exactly 66 whenever the text really fits it, and the bar grows +// when it does not (decided by the measured block, not by a scale threshold), +// - the bar re-measures when the text scale changes on a live tree, +// - RTL, a nonlinear scaler and a wide window behave the same, +// - a fallback face's ink stays inside the bar. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/theme/prism_tokens.dart'; +import 'package:prism_plurality/shared/widgets/prism_page_scaffold.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar.dart'; +import 'package:prism_plurality/shared/widgets/prism_top_bar_action.dart'; + +import 'chrome_text_scale_harness.dart'; + +Widget _page({ + required String title, + String? subtitle, + bool showBackButton = true, +}) { + return PrismPageScaffold( + topBar: PrismTopBar( + title: title, + subtitle: subtitle, + showBackButton: showBackButton, + actions: [ + PrismTopBarAction(icon: AppIcons.add, tooltip: 'Add', onPressed: () {}), + ], + ), + body: ListView.builder( + itemCount: 40, + itemBuilder: (context, index) => + SizedBox(height: 48, child: Text('Row $index')), + ), + ); +} + +Widget _app( + Widget page, { + required double system, + required double app, + required String family, + TextDirection? textDirection, +}) { + return ProviderScope( + child: chromeApp( + page, + system: system, + app: app, + fontFamily: family, + textDirection: textDirection, + ), + ); +} + +/// The bar must never paint its title over a leading or trailing action. +void _expectTitleClearOfActions( + WidgetTester tester, { + required Rect titleRect, + required String label, +}) { + final actions = find.byType(PrismTopBarAction); + for (var i = 0; i < actions.evaluate().length; i++) { + final rect = tester.getRect(find.byType(PrismTopBarAction).at(i)); + final overlapsHorizontally = + titleRect.left < rect.right - 0.5 && titleRect.right > rect.left + 0.5; + expect( + overlapsHorizontally, + isFalse, + reason: + '$label: the title (${titleRect.left.toStringAsFixed(1)}..' + '${titleRect.right.toStringAsFixed(1)}) paints under action $i ' + '(${rect.left.toStringAsFixed(1)}..${rect.right.toStringAsFixed(1)})', + ); + } +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadChromeFonts(); + }); + + for (final family in chromeFontFamilies) { + for (final (system, app, label) in chromeScales) { + final scaleLabel = '$label, $family'; + + testWidgets('PrismTopBar keeps its title inside the pinned header ' + '($scaleLabel)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Members'; + await tester.pumpWidget( + _app( + _page(title: title), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + expect( + barRect.height, + greaterThanOrEqualTo(PrismTokens.topBarHeight - 0.5), + reason: '$scaleLabel: the bar may never reserve less than 66dp', + ); + // Whether 66dp survives is decided by what the text actually needs, not by + // a scale threshold: a face whose ink escapes its line box needs more room + // even at 1.5x, and one that fits needs none. + final natural = naturalBarBlockHeight(tester, title: title); + if (natural <= PrismTokens.topBarHeight + 0.01) { + expect( + barRect.height, + closeTo(PrismTokens.topBarHeight, 0.5), + reason: + '$scaleLabel: the block needs ${natural.toStringAsFixed(1)}px, so ' + 'the default 66dp must be preserved exactly', + ); + } else { + expect( + barRect.height, + greaterThanOrEqualTo(natural - 0.5), + reason: + '$scaleLabel: the block needs ${natural.toStringAsFixed(1)}px, so ' + 'the bar must grow to it', + ); + } + + final titleRect = expectFullSizeText( + tester, + title, + label: scaleLabel, + container: barRect, + ); + _expectTitleClearOfActions( + tester, + titleRect: titleRect, + label: scaleLabel, + ); + expectNoLayoutException(tester, scaleLabel); + }); + + testWidgets('PrismTopBar keeps a title with a subtitle ' + '($scaleLabel)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Timeline'; + const subtitle = '12 headmates'; + await tester.pumpWidget( + _app( + _page(title: title, subtitle: subtitle), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final natural = naturalBarBlockHeight( + tester, + title: title, + subtitle: subtitle, + ); + if (natural <= PrismTokens.topBarHeight + 0.01) { + expect( + barRect.height, + closeTo(PrismTokens.topBarHeight, 0.5), + reason: + '$scaleLabel: title plus subtitle need ' + '${natural.toStringAsFixed(1)}px, so 66dp must be preserved ' + 'exactly', + ); + } else { + expect( + barRect.height, + greaterThanOrEqualTo(natural - 0.5), + reason: + '$scaleLabel: title plus subtitle need ' + '${natural.toStringAsFixed(1)}px, so the bar must grow to it', + ); + } + final titleRect = expectFullSizeText( + tester, + title, + label: '$scaleLabel (title)', + container: barRect, + ); + expectFullSizeText( + tester, + subtitle, + label: '$scaleLabel (subtitle)', + container: barRect, + ); + _expectTitleClearOfActions( + tester, + titleRect: titleRect, + label: scaleLabel, + ); + expectNoLayoutException(tester, scaleLabel); + }); + + testWidgets('PrismTopBar paints a long title at the requested size ' + '($scaleLabel)', (tester) async { + useWindow(tester, compactPhone); + const title = 'Fronting schedule today'; + await tester.pumpWidget( + _app( + _page(title: title), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final titleRect = expectFullSizeText( + tester, + title, + label: scaleLabel, + container: barRect, + ); + _expectTitleClearOfActions( + tester, + titleRect: titleRect, + label: scaleLabel, + ); + expectNoLayoutException(tester, scaleLabel); + }); + } + } + + testWidgets('PrismTopBar re-measures when the text scale changes on a live ' + 'tree', (tester) async { + useWindow(tester, compactPhone); + const title = 'Members'; + final page = _page(title: title, subtitle: '12 headmates'); + + await tester.pumpWidget( + _app(page, system: 1.0, app: 1.0, family: 'Lexend'), + ); + await tester.pumpAndSettle(); + final before = tester.getRect(find.byType(PrismTopBar)).height; + expect(before, closeTo(PrismTokens.topBarHeight, 0.5)); + + await tester.pumpWidget( + _app(page, system: 2.25, app: 1.5, family: 'Lexend'), + ); + await tester.pumpAndSettle(); + + final after = tester.getRect(find.byType(PrismTopBar)).height; + expect( + after, + greaterThan(before), + reason: 'the bar must follow the new text scale, not a cached height', + ); + final barRect = tester.getRect(find.byType(PrismTopBar)); + expectFullSizeText( + tester, + title, + label: 'after scale change', + container: barRect, + ); + expectFullSizeText( + tester, + '12 headmates', + label: 'after scale change (subtitle)', + container: barRect, + ); + expectNoLayoutException(tester, 'after scale change'); + }); + + testWidgets('PrismTopBar contains its title on a nonlinear scaler', ( + tester, + ) async { + useWindow(tester, compactPhone); + const title = 'Members'; + await tester.pumpWidget( + ProviderScope( + child: chromeApp( + _page(title: title, subtitle: '12 headmates'), + system: 1.0, + app: 1.0, + scalerOverride: const NonlinearTextScaler(), + ), + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + expectFullSizeText(tester, title, label: 'nonlinear', container: barRect); + expectFullSizeText( + tester, + '12 headmates', + label: 'nonlinear (subtitle)', + container: barRect, + ); + expectNoLayoutException(tester, 'nonlinear'); + }); + + testWidgets('PrismTopBar keeps the title between the actions in RTL', ( + tester, + ) async { + useWindow(tester, compactPhone); + const title = 'Members'; + await tester.pumpWidget( + _app( + _page(title: title), + system: 2.25, + app: 1.5, + family: 'Lexend', + textDirection: TextDirection.rtl, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final titleRect = expectFullSizeText( + tester, + title, + label: 'RTL', + container: barRect, + ); + _expectTitleClearOfActions(tester, titleRect: titleRect, label: 'RTL'); + expectNoLayoutException(tester, 'RTL'); + }); + + testWidgets('PrismTopBar keeps the default height and a full-size title on ' + 'a wide window', (tester) async { + useWindow(tester, wideWindow); + const title = 'Fronting schedule today'; + await tester.pumpWidget( + _app(_page(title: title), system: 1.5, app: 1.0, family: 'Lexend'), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + final natural = naturalBarBlockHeight(tester, title: title); + if (natural <= PrismTokens.topBarHeight + 0.01) { + expect( + barRect.height, + closeTo(PrismTokens.topBarHeight, 0.5), + reason: + 'the 18pt desktop title needs ${natural.toStringAsFixed(1)}px at 1.5x, ' + 'so 66dp must hold', + ); + } else { + expect( + barRect.height, + greaterThanOrEqualTo(natural - 0.5), + reason: 'the wide bar must grow to the ink it paints', + ); + } + final titleRect = expectFullSizeText( + tester, + title, + label: 'wide 1.5x', + container: barRect, + ); + _expectTitleClearOfActions( + tester, + titleRect: titleRect, + label: 'wide 1.5x', + ); + expectNoLayoutException(tester, 'wide 1.5x'); + }); + + // The bar's height comes from the line box of the text it will paint, and a run + // resolved to a fallback face (emoji, CJK, Arabic) can report a taller line box + // and draw ink beyond the primary face's. These cases check the ink the + // paragraph actually paints, not just its box, at both ends of the scale. + for (final family in chromeFontFamilies) { + for (final (system, app, label) in chromeScales) { + testWidgets('mixed-script title and subtitle ink stays inside the bar ' + '($label, $family)', (tester) async { + useWindow(tester, compactPhone); + const title = 'ÉÅgjpq 🜁'; + const subtitle = 'نور 中文 ١٢'; + await tester.pumpWidget( + _app( + _page(title: title, subtitle: subtitle), + system: system, + app: app, + family: family, + ), + ); + await tester.pumpAndSettle(); + + final barRect = tester.getRect(find.byType(PrismTopBar)); + expectFullSizeText( + tester, + title, + label: '$label (mixed title)', + container: barRect, + ); + expectFullSizeText( + tester, + subtitle, + label: '$label (mixed subtitle)', + container: barRect, + ); + expectInkInside( + tester, + title, + container: barRect, + label: '$label (mixed title)', + ); + expectInkInside( + tester, + subtitle, + container: barRect, + label: '$label (mixed subtitle)', + ); + expect( + tester.getRect(find.text(title)).width, + greaterThan(0), + reason: 'the mixed-script title must render glyphs', + ); + expectNoLayoutException(tester, '$label (mixed script)'); + }); + } + } +} diff --git a/test/text_scale_fixes/controls/mention_row_text_scale_test.dart b/test/text_scale_fixes/controls/mention_row_text_scale_test.dart new file mode 100644 index 000000000..4b56b5f82 --- /dev/null +++ b/test/text_scale_fixes/controls/mention_row_text_scale_test.dart @@ -0,0 +1,304 @@ +// Member-mention suggestion rows under text scaling. +// +// Suggestion rows must grow with their text. Pinning the name inside a fixed 48dp +// row (and the broadcast row inside 52dp) cut the glyphs off once the composed +// scale grew, and cut the broadcast row's second line even earlier. The row +// heights below are floors, not limits. + +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/features/chat/widgets/mention_overlay.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/member_mention_text_field.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +class _NonLinearTextScaler extends TextScaler { + const _NonLinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 1.4 : 28.0 + (fontSize - 20) * 3.0; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.0; +} + +const _scales = <(String, TextScaler)>[ + ( + 'system 100% x Prism 50% = 0.5x', + PrismTextScaler(TextScaler.noScaling, 0.5), + ), + ('default text', PrismTextScaler(TextScaler.noScaling, 1.0)), + ('large text 1.5x', PrismTextScaler(TextScaler.linear(1.5), 1.0)), + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ( + 'nonlinear system scaler x Prism 150%', + PrismTextScaler(_NonLinearTextScaler(), 1.5), + ), +]; + +Widget _app( + Widget home, { + required TextScaler textScaler, + List overrides = const [], +}) { + return ProviderScope( + overrides: overrides, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'OpenDyslexic', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child ?? const SizedBox.shrink(), + ), + home: home, + ), + ); +} + +void _useCompactPhone(WidgetTester tester) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(320, 568); + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +Member _member(String id, String name) => + Member(id: id, name: name, createdAt: DateTime(2026, 1, 1)); + +void _expectNotVerticallyClamped( + WidgetTester tester, + String text, + String scaleLabel, { + int maxLines = 1, +}) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: '$scaleLabel: one "$text" label'); + final paragraph = tester.renderObject(finder); + final painter = TextPainter( + text: TextSpan( + text: paragraph.text.toPlainText(), + style: paragraph.text.style, + ), + textDirection: TextDirection.ltr, + textScaler: paragraph.textScaler, + maxLines: maxLines, + )..layout(maxWidth: paragraph.size.width); + final needed = painter.height; + painter.dispose(); + expect( + paragraph.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$scaleLabel: "$text" needs ${needed.toStringAsFixed(1)}px but its row ' + 'gives it ${paragraph.size.height.toStringAsFixed(1)}px, so glyphs are ' + 'cut off', + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + for (final (label, scaler) in _scales) { + testWidgets('composer suggestion row keeps its name glyphs ($label)', ( + tester, + ) async { + _useCompactPhone(tester); + final controller = TextEditingController(); + final focusNode = FocusNode(); + addTearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + await tester.pumpWidget( + _app( + Scaffold( + body: Padding( + padding: const EdgeInsets.all(16), + child: Align( + alignment: Alignment.topCenter, + child: MemberMentionTextField( + controller: controller, + focusNode: focusNode, + mentionCandidates: [_member('m1', 'Alexandria')], + maxLines: 3, + ), + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + await tester.enterText(find.byType(TextField), '@'); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + expect(find.text('Alexandria'), findsOneWidget); + _expectNotVerticallyClamped(tester, 'Alexandria', label); + + // Selecting the suggestion still inserts the atomic mention token. + await tester.tap(find.text('Alexandria')); + await tester.pumpAndSettle(); + expect(controller.text, contains('@[m1]')); + }); + + testWidgets('chat overlay member row keeps its name glyphs ($label)', ( + tester, + ) async { + _useCompactPhone(tester); + final selected = []; + + await tester.pumpWidget( + _app( + Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: MentionOverlay( + members: [_member('m1', 'Alexandria')], + filter: 'alex', + onSelect: (member) => selected.add(member.id), + onBroadcastSelect: (_) {}, + availableWidth: 320, + ), + ), + ), + textScaler: scaler, + overrides: [memberNamePreferDisplayProvider.overrideWithValue(false)], + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + _expectNotVerticallyClamped(tester, 'Alexandria', label); + + await tester.tap(find.text('Alexandria')); + await tester.pumpAndSettle(); + expect(selected, ['m1']); + }); + + testWidgets('broadcast row keeps both lines ($label)', (tester) async { + _useCompactPhone(tester); + final broadcast = []; + + await tester.pumpWidget( + _app( + Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: MentionOverlay( + members: const [], + filter: 'everyone', + onSelect: (_) {}, + onBroadcastSelect: broadcast.add, + availableWidth: 320, + ), + ), + ), + textScaler: scaler, + overrides: [memberNamePreferDisplayProvider.overrideWithValue(false)], + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + _expectNotVerticallyClamped(tester, '@everyone', label); + _expectNotVerticallyClamped( + tester, + 'Mention everyone in this chat', + label, + ); + + await tester.tap(find.text('@everyone')); + await tester.pumpAndSettle(); + expect(broadcast, isNotEmpty); + }); + } + + testWidgets('default geometry: suggestion rows stay 48dp tall at 1x', ( + tester, + ) async { + _useCompactPhone(tester); + await tester.pumpWidget( + _app( + Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: MentionOverlay( + members: [_member('m1', 'Alexandria')], + filter: 'alex', + onSelect: (_) {}, + onBroadcastSelect: (_) {}, + availableWidth: 320, + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + overrides: [memberNamePreferDisplayProvider.overrideWithValue(false)], + ), + ); + await tester.pumpAndSettle(); + + // Resolve the height from the paragraph the row really laid out - not from a + // repainted assumption about its style. The row is max(48dp, one line + 8dp + // above and below) and the list adds 4dp over and under it; the font stays at + // full size, so a taller face legitimately asks for a taller row. + final nameParagraph = tester.renderObject( + find.text('Alexandria'), + ); + final lineHeight = nameParagraph.size.height; + final surfaceContainer = tester.widget( + find + .ancestor( + of: find.byType(ListView), + matching: find.byWidgetPredicate( + (widget) => + widget is Container && widget.decoration is BoxDecoration, + ), + ) + .first, + ); + final decoration = surfaceContainer.decoration! as BoxDecoration; + final borderInsets = decoration.padding.resolve(TextDirection.ltr); + // The surface includes its decoration border outside the row/list padding. + final expectedSurface = + math.max(48.0, math.max(32.0, lineHeight) + 16) + + 8 + + borderInsets.vertical; + final surface = tester.getSize( + find.byKey(const Key('mentionOverlaySurface')), + ); + expect( + surface.height, + closeTo(expectedSurface, 0.5), + reason: + 'a one-line name laid out at ${lineHeight.toStringAsFixed(1)}dp needs a ' + '${expectedSurface.toStringAsFixed(1)}dp surface at 1x', + ); + }); +} diff --git a/test/text_scale_fixes/controls/nav_bar_label_offset_text_scale_test.dart b/test/text_scale_fixes/controls/nav_bar_label_offset_text_scale_test.dart new file mode 100644 index 000000000..c87a6eef1 --- /dev/null +++ b/test/text_scale_fixes/controls/nav_bar_label_offset_text_scale_test.dart @@ -0,0 +1,365 @@ +// Mobile nav bar label placement under text scaling. +// +// The row height comes from the scaled label, so the label's offset below the row +// centre and the icon's lift have to follow that same measured line box. A constant +// tuned for 1x text puts the label over the icon as soon as the text scales - about +// 20dp of overlap at 3.375x. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:prism_plurality/core/database/database_providers.dart' + show appPreferenceRepositoryProvider; +import 'package:prism_plurality/core/router/app_routes.dart'; +import 'package:prism_plurality/core/sync/prism_sync_providers.dart'; +import 'package:prism_plurality/domain/models/member.dart' as domain; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/chat/providers/chat_providers.dart'; +import 'package:prism_plurality/features/fronting/providers/fronting_providers.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/pluralkit/providers/pk_auto_poll_provider.dart'; +import 'package:prism_plurality/features/pluralkit/providers/pluralkit_providers.dart'; +import 'package:prism_plurality/features/pluralkit/services/pluralkit_sync_service.dart'; +import 'package:prism_plurality/features/settings/providers/pin_lock_providers.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/app_shell.dart'; + +import '../../helpers/fake_repositories.dart' show FakeAppPreferenceRepository; +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +class _NonLinearTextScaler extends TextScaler { + const _NonLinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 1.4 : 28.0 + (fontSize - 20) * 3.0; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.0; +} + +const _scales = <(String, TextScaler)>[ + ( + 'system 100% x Prism 50% = 0.5x', + PrismTextScaler(TextScaler.noScaling, 0.5), + ), + ('default text', PrismTextScaler(TextScaler.noScaling, 1.0)), + ('large text 1.5x', PrismTextScaler(TextScaler.linear(1.5), 1.0)), + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ( + 'nonlinear system scaler x Prism 150%', + PrismTextScaler(_NonLinearTextScaler(), 1.5), + ), +]; + +const _tabIds = ['home', 'chat', 'habits', 'polls', 'settings']; + +class _FakeSyncStatusNotifier extends SyncStatusNotifier { + @override + SyncStatus build() => const SyncStatus(); +} + +class _UnreadCountNotifier extends Notifier { + @override + int build() => 0; + + set value(int newValue) => state = newValue; +} + +final _unreadCountStateProvider = NotifierProvider<_UnreadCountNotifier, int>( + _UnreadCountNotifier.new, +); + +class _FakePkAutoPollNotifier extends PkAutoPollNotifier { + @override + void build() {} + + @override + void markForegrounded(bool value) {} + + @override + void noteLocalPush() {} +} + +class _FakePluralKitSyncNotifier extends PluralKitSyncNotifier { + @override + PluralKitSyncState build() => const PluralKitSyncState(); + + @override + Future pushPendingSwitches() async => 0; + + @override + Future pushMemberUpdate(domain.Member member) async {} +} + +GoRouter _router() => GoRouter( + initialLocation: AppRoutePaths.home, + routes: [ + StatefulShellRoute.indexedStack( + builder: (context, state, navigationShell) => + AppShell(navigationShell: navigationShell, routePath: state.uri.path), + branches: [ + StatefulShellBranch( + routes: [ + GoRoute( + path: AppRoutePaths.home, + builder: (context, state) => + const Scaffold(body: SizedBox.expand()), + ), + ], + ), + ], + ), + ], +); + +Widget _subject({ + required GoRouter router, + required TextScaler textScaler, + NavBarLabelVisibility labelVisibility = NavBarLabelVisibility.always, +}) { + return ProviderScope( + overrides: [ + activeNavBarTabsProvider.overrideWithValue(appShellTabs.take(5).toList()), + navBarOverflowTabsProvider.overrideWithValue(const []), + navBarLabelVisibilityProvider.overrideWithValue(labelVisibility), + appPreferenceRepositoryProvider.overrideWithValue( + FakeAppPreferenceRepository(), + ), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + isPinSetProvider.overrideWith((ref) async => false), + syncStatusProvider.overrideWith(_FakeSyncStatusNotifier.new), + pkAutoPollProvider.overrideWith(_FakePkAutoPollNotifier.new), + pluralKitSyncProvider.overrideWith(_FakePluralKitSyncNotifier.new), + habitsBadgeEnabledProvider.overrideWith((ref) => false), + activeSessionsProvider.overrideWith((ref) => Stream.value(const [])), + allMembersProvider.overrideWith((ref) => Stream.value(const [])), + unreadConversationCountProvider.overrideWith( + (ref) => ref.watch(_unreadCountStateProvider), + ), + ], + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'OpenDyslexic', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child!, + ), + routerConfig: router, + ), + ); +} + +void _useViewport(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +Rect _rowRect(WidgetTester tester, Finder label) { + return tester.getRect( + find.ancestor(of: label, matching: find.byType(Stack)).first, + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + for (final (label, scaler) in _scales) { + testWidgets('label sits below its icon and inside its row ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + final router = _router(); + addTearDown(router.dispose); + final semantics = tester.ensureSemantics(); + + try { + await tester.pumpWidget(_subject(router: router, textScaler: scaler)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: '$label: layout error'); + + var checked = 0; + for (final id in _tabIds) { + final labelFinder = find.byKey(ValueKey('nav_label_$id')); + final iconFinder = find.byKey(ValueKey('nav_icon_slot_$id')); + if (labelFinder.evaluate().isEmpty || iconFinder.evaluate().isEmpty) { + continue; // collapsed into the overflow menu at this width/scale + } + checked++; + + final labelRect = tester.getRect(labelFinder); + final iconRect = tester.getRect(iconFinder); + final rowRect = _rowRect(tester, labelFinder); + + expect( + labelRect.top, + greaterThanOrEqualTo(iconRect.bottom - 1.0), + reason: + '$label: the "$id" label starts at ' + '${labelRect.top.toStringAsFixed(1)} but its icon ends at ' + '${iconRect.bottom.toStringAsFixed(1)}', + ); + expect( + labelRect.top - iconRect.bottom, + lessThanOrEqualTo(4.0), + reason: '$label: the "$id" label floats away from its icon', + ); + expect( + labelRect.bottom, + lessThanOrEqualTo(rowRect.bottom + 0.5), + reason: + '$label: the "$id" label is clipped by its row ' + '(${labelRect.bottom.toStringAsFixed(1)} > ' + '${rowRect.bottom.toStringAsFixed(1)})', + ); + expect( + iconRect.top, + greaterThanOrEqualTo(rowRect.top - 0.5), + reason: '$label: the "$id" icon is lifted out of its row', + ); + + // The label keeps its requested size (no clamping to the old slot). + final paragraph = tester.renderObject(labelFinder); + final painter = TextPainter( + text: TextSpan( + text: paragraph.text.toPlainText(), + style: paragraph.text.style, + ), + textDirection: TextDirection.ltr, + textScaler: paragraph.textScaler, + maxLines: 1, + )..layout(); + final needed = painter.height; + painter.dispose(); + expect( + paragraph.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: the "$id" label needs ${needed.toStringAsFixed(1)}px ' + 'but got ${paragraph.size.height.toStringAsFixed(1)}px', + ); + } + expect(checked, greaterThan(0), reason: '$label: no labelled tab'); + } finally { + semantics.dispose(); + } + }); + } + + testWidgets('default geometry: 1x row keeps its padding and pill centre', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + final router = _router(); + addTearDown(router.dispose); + final semantics = tester.ensureSemantics(); + + try { + await tester.pumpWidget( + _subject( + router: router, + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + ), + ); + await tester.pumpAndSettle(); + + final labelFinder = find.byKey(const ValueKey('nav_label_home')); + final iconFinder = find.byKey(const ValueKey('nav_icon_slot_home')); + expect(labelFinder, findsOneWidget); + expect(iconFinder, findsOneWidget); + + final rowRect = _rowRect(tester, labelFinder); + final labelRect = tester.getRect(labelFinder); + final iconRect = tester.getRect(iconFinder); + + expect(rowRect.height, lessThanOrEqualTo(70)); + expect(rowRect.bottom - labelRect.bottom, greaterThanOrEqualTo(2.0)); + expect(labelRect.top, greaterThanOrEqualTo(iconRect.bottom - 1.0)); + + final pill = tester.getRect( + find.byKey(const ValueKey('nav_selected_pill')), + ); + expect( + (pill.center.dy - iconRect.center.dy).abs(), + lessThanOrEqualTo(1.5), + reason: 'the selected pill stays centred on the icon', + ); + } finally { + semantics.dispose(); + } + }); + + for (final (label, scaler) in const [ + ('large text 1.5x', PrismTextScaler(TextScaler.linear(1.5), 1.0)), + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ]) { + testWidgets('revealed labels keep the icon inside its row ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + final router = _router(); + addTearDown(router.dispose); + final semantics = tester.ensureSemantics(); + + try { + await tester.pumpWidget( + _subject( + router: router, + textScaler: scaler, + labelVisibility: NavBarLabelVisibility.whenExpanded, + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: '$label: layout error'); + + final iconFinder = find.byKey(const ValueKey('nav_icon_slot_home')); + if (iconFinder.evaluate().isEmpty) return; // overflowed at this size + final iconRect = tester.getRect(iconFinder); + final rowRect = tester.getRect( + find.ancestor(of: iconFinder, matching: find.byType(Stack)).first, + ); + expect( + iconRect.top, + greaterThanOrEqualTo(rowRect.top - 0.5), + reason: '$label: the icon is lifted out of its row', + ); + + final pill = tester.getRect( + find.byKey(const ValueKey('nav_selected_pill')), + ); + expect( + (pill.center.dy - iconRect.center.dy).abs(), + lessThanOrEqualTo(1.5), + reason: '$label: the selected pill stays centred on the icon', + ); + } finally { + semantics.dispose(); + } + }); + } +} diff --git a/test/text_scale_fixes/controls/pin_caller_reachability_test.dart b/test/text_scale_fixes/controls/pin_caller_reachability_test.dart new file mode 100644 index 000000000..a9278ad55 --- /dev/null +++ b/test/text_scale_fixes/controls/pin_caller_reachability_test.dart @@ -0,0 +1,456 @@ +// Caller reachability for the PIN pad after the keys grew with the digit. +// +// The set-PIN screen used a centred Spacer column. Once keys hold a 3.375x digit +// the pad is taller than a short phone viewport - and a short window can overflow +// even at 1x - so the screen now measures the height it really has (keyboard +// included) and scrolls only when the content does not fit. These tests walk the +// real flow (settings -> set PIN -> confirm) and tap through the pad: first key, +// last row, backspace, back/cancel, at 1x and large text, short windows, with an +// open keyboard, and across a live resize/scale change. + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:prism_plurality/core/database/database_providers.dart' + show systemSettingsRepositoryProvider; +import 'package:prism_plurality/core/services/pin_lock_service.dart'; +import 'package:prism_plurality/core/services/screen_security_service.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/settings/providers/pin_lock_providers.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/features/settings/views/pin_lock_settings_screen.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_button.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; + +import '../../helpers/fake_repositories.dart'; +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +class _NonLinearTextScaler extends TextScaler { + const _NonLinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 1.4 : 28.0 + (fontSize - 20) * 3.0; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.0; +} + +/// Stands in for the off-isolate PIN hash; nothing here touches the keychain. +class _FakePinLockService extends PinLockService { + final storeCalls = []; + var stored = false; + + @override + Future isPinSet() async => stored; + + @override + Future storePin(String pin) async { + storeCalls.add(pin); + stored = true; + } + + @override + Future verifyStoredPin(String pin) async => false; + + @override + Future authenticateBiometric() async => false; +} + +/// Live text scale + keyboard inset so a test can change them mid-flow and prove +/// the entered digits survive. +class _Harness extends ChangeNotifier { + _Harness(this.textScaler); + + TextScaler textScaler; + double keyboardInset = 0.0; + + void update({TextScaler? textScaler, double? keyboardInset}) { + if (textScaler != null) this.textScaler = textScaler; + if (keyboardInset != null) this.keyboardInset = keyboardInset; + notifyListeners(); + } +} + +Widget _launcher({ + required _FakePinLockService service, + required FakeSystemSettingsRepository settingsRepository, + _Harness? harness, + TextScaler textScaler = const PrismTextScaler(TextScaler.noScaling, 1.0), +}) { + return ProviderScope( + overrides: [ + targetPlatformProvider.overrideWithValue(TargetPlatform.android), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + systemSettingsRepositoryProvider.overrideWithValue(settingsRepository), + isPinSetProvider.overrideWith((ref) => service.isPinSet()), + pinLockServiceProvider.overrideWithValue(service), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'OpenDyslexic', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) { + Widget wrap(BuildContext context, TextScaler scaler, double inset) { + return MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: scaler, + viewInsets: EdgeInsets.only(bottom: inset), + ), + child: child ?? const SizedBox.shrink(), + ); + } + + if (harness == null) { + return wrap(context, textScaler, 0); + } + return ListenableBuilder( + listenable: harness, + builder: (context, _) => + wrap(context, harness.textScaler, harness.keyboardInset), + ); + }, + home: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const PinLockSettingsScreen(), + ), + ), + child: const Text('open'), + ), + ), + ), + ); +} + +Future _openCaptureStep(WidgetTester tester) async { + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + // The settings page is a lazy list: at large text the PIN section is below the + // fold, so drive the real control (scroll it into view) rather than assuming it + // is already built. + final enable = find.text('Enable PIN Lock'); + if (enable.evaluate().isEmpty) { + await tester.scrollUntilVisible( + enable, + 200, + scrollable: find.byType(Scrollable).first, + ); + } + // A cached label can exist below the viewport even at normal text. + await tester.ensureVisible(enable); + await tester.pumpAndSettle(); + expect( + enable.hitTestable(), + findsOneWidget, + reason: 'Enable PIN Lock must receive the real toggle tap', + ); + await tester.tap(enable); + await tester.pumpAndSettle(); + + // The flow enables PIN lock asynchronously before it shows the capture step, so + // wait for the step itself and its keypad - not merely for a label - or the test + // would assert geometry against an intermediate screen. + await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); + expect( + find.text('Set PIN'), + findsOneWidget, + reason: 'the set-PIN capture step is on screen', + ); + expect( + find.byType(PinNumpadButton), + findsWidgets, + reason: 'the capture step renders its keypad', + ); +} + +/// Taps a keypad digit, scrolling it into view first (the pad may be taller than +/// the viewport once the keys grow with the digit). +Future _tapDigit(WidgetTester tester, String digit) async { + final finder = find.text(digit).first; + await tester.ensureVisible(finder); + await tester.pumpAndSettle(); + await tester.tap(finder); + await tester.pump(); +} + +Future _revealAndTap(WidgetTester tester, Finder finder) async { + await tester.ensureVisible(finder); + await tester.pumpAndSettle(); + await tester.tap(finder); + await tester.pumpAndSettle(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const secureStorageChannel = MethodChannel( + 'plugins.it_nomads.com/flutter_secure_storage', + ); + const secureDisplayChannel = MethodChannel( + 'com.prism.prism_plurality/secure_display', + ); + const localAuthChannel = MethodChannel('plugins.flutter.io/local_auth'); + + setUpAll(() async { + await loadPrismGoldenFonts(); + }); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureStorageChannel, (_) async => null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureDisplayChannel, (_) async => null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(localAuthChannel, (call) async { + switch (call.method) { + case 'canCheckBiometrics': + return false; + case 'isDeviceSupported': + return false; + case 'getAvailableBiometrics': + return []; + } + return null; + }); + ScreenSecurityService.debugResetForTests(); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureStorageChannel, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(secureDisplayChannel, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(localAuthChannel, null); + ScreenSecurityService.debugResetForTests(); + }); + + void useViewport(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); + } + + for (final (label, scaler) in const [ + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ( + 'nonlinear system scaler x Prism 150%', + PrismTextScaler(_NonLinearTextScaler(), 1.5), + ), + ]) { + testWidgets('every key of the set-PIN pad is reachable ($label)', ( + tester, + ) async { + useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _launcher( + service: _FakePinLockService(), + settingsRepository: FakeSystemSettingsRepository(), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + await _openCaptureStep(tester); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + + // First key, then the last row ('0'), then a backspace, then all six. + await _tapDigit(tester, '1'); + await _tapDigit(tester, '0'); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: '$label: pad taps fine'); + + await _revealAndTap( + tester, + find.byIcon(AppIcons.backspaceOutlined).first, + ); + + // '1' is still entered; five more digits complete the set step. + for (final digit in const ['2', '3', '4', '5', '6']) { + await _tapDigit(tester, digit); + } + await tester.pumpAndSettle(); + // Reaching the confirm step proves the whole pad (including the bottom + // row) is reachable and the flow is intact. + expect(find.text('Confirm PIN'), findsOneWidget); + }); + } + + testWidgets('a short window scrolls even at normal text', (tester) async { + // 320x360 is shorter than the pad plus its header at 1x, so the fit has to be + // driven by the measured height - a text-scale threshold would miss this. + useViewport(tester, const Size(320, 360)); + await tester.pumpWidget( + _launcher( + service: _FakePinLockService(), + settingsRepository: FakeSystemSettingsRepository(), + ), + ); + await tester.pumpAndSettle(); + await _openCaptureStep(tester); + + expect(tester.takeException(), isNull); + expect(find.byType(SingleChildScrollView), findsWidgets); + expect(find.text('Set PIN'), findsOneWidget); + + for (final digit in const ['1', '2', '3', '4', '5', '6']) { + await _tapDigit(tester, digit); + } + await tester.pumpAndSettle(); + expect(find.text('Confirm PIN'), findsOneWidget); + }); + + testWidgets('an open keyboard keeps the pad reachable', (tester) async { + // Real viewInsets, as the platform reports them: 300dp of keyboard over a + // 320x568 window leaves 268dp, far less than the pad needs at 3.375x. + useViewport(tester, const Size(320, 568)); + final harness = _Harness( + const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ); + addTearDown(harness.dispose); + harness.keyboardInset = 300; + + await tester.pumpWidget( + _launcher( + service: _FakePinLockService(), + settingsRepository: FakeSystemSettingsRepository(), + harness: harness, + ), + ); + await tester.pumpAndSettle(); + await _openCaptureStep(tester); + + expect(tester.takeException(), isNull); + await _tapDigit(tester, '9'); + await _tapDigit(tester, '0'); + + // Back/Cancel stays reachable and still returns to PIN lock settings. + await _revealAndTap(tester, find.byTooltip('Back').first); + expect(find.text('Enable PIN Lock'), findsOneWidget); + }); + + testWidgets('normal text on a tall window keeps the centred geometry', ( + tester, + ) async { + useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _launcher( + service: _FakePinLockService(), + settingsRepository: FakeSystemSettingsRepository(), + ), + ); + await tester.pumpAndSettle(); + await _openCaptureStep(tester); + + expect(tester.takeException(), isNull); + for (final digit in const ['1', '5', '9', '0']) { + final rect = tester.getRect(find.text(digit).first); + expect( + rect.bottom, + lessThanOrEqualTo(568), + reason: '"$digit" must be on screen without scrolling at normal text', + ); + } + + // Geometry, not the absence of a scroll view: the Spacers keep their 2:2:1 + // weights, i.e. the gap above the title is twice the gap under the pad. + final back = tester.getRect(find.byTooltip('Back').first); + final title = tester.getRect(find.text('Set PIN')); + // The pad's own column, so its row padding is included in the gap below. + final padRect = tester.getRect( + find + .ancestor( + of: find + .ancestor( + of: find.text('0').first, + matching: find.byType(PinNumpadButton), + ) + .first, + matching: find.byType(Column), + ) + .first, + ); + final padTop = padRect.top; + final padBottom = padRect.bottom; + final aboveTitle = title.top - back.bottom; + final belowPad = 568 - padBottom; + expect( + aboveTitle, + greaterThan(10), + reason: 'the top Spacer must still distribute free space', + ); + expect( + aboveTitle, + closeTo(belowPad * 2, 2.0), + reason: + 'the centred layout is flex 2 / flex 1 above and below the content ' + '(above $aboveTitle, below $belowPad)', + ); + expect(padTop, greaterThan(title.bottom)); + }); + + testWidgets('resizing and changing scale keeps the entered digits', ( + tester, + ) async { + useViewport(tester, const Size(320, 568)); + final harness = _Harness( + const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ); + addTearDown(harness.dispose); + + await tester.pumpWidget( + _launcher( + service: _FakePinLockService(), + settingsRepository: FakeSystemSettingsRepository(), + harness: harness, + ), + ); + await tester.pumpAndSettle(); + await _openCaptureStep(tester); + + for (final digit in const ['1', '2', '3']) { + await _tapDigit(tester, digit); + } + await tester.pumpAndSettle(); + expect(find.text('Set PIN'), findsOneWidget); + + // Shrink the window and drop to normal text while the sheet is mid-entry. + tester.view.physicalSize = const Size(320, 360); + await tester.pumpAndSettle(); + harness.update( + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text('Set PIN'), findsOneWidget); + + // Three more digits complete six: the buffer survived the relayout. + for (final digit in const ['4', '5', '6']) { + await _tapDigit(tester, digit); + } + await tester.pumpAndSettle(); + expect(find.text('Confirm PIN'), findsOneWidget); + }); +} diff --git a/test/text_scale_fixes/controls/pin_input_short_viewport_test.dart b/test/text_scale_fixes/controls/pin_input_short_viewport_test.dart new file mode 100644 index 000000000..b01b29994 --- /dev/null +++ b/test/text_scale_fixes/controls/pin_input_short_viewport_test.dart @@ -0,0 +1,194 @@ +// PinInputScreen must reflow on the height it actually has. It scrolls when the +// content does not fit and keeps its centred Spacer layout when it does, so: +// +// * a 320x360 window at NORMAL text stays usable even though the pad is taller +// than the window; +// * with an open keyboard (viewInsets.bottom) the pad ends above the inset +// instead of being hidden behind it; +// * a 320x568 phone at 1x keeps the existing layout untouched. +// +// The keyboard inset is reserved once: a parent that has already shrunk the body +// for it (Scaffold's resizeToAvoidBottomInset) must not be subtracted from twice. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/features/settings/views/pin_input_screen.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_button.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_metrics.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +Widget _app( + Widget home, { + TextScaler textScaler = const PrismTextScaler(TextScaler.noScaling, 1.0), + double keyboardInset = 0, +}) { + return ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: textScaler, + viewInsets: EdgeInsets.only(bottom: keyboardInset), + ), + child: child ?? const SizedBox.shrink(), + ), + home: home, + ), + ); +} + +void _useViewport(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +Future _tapKey(WidgetTester tester, Finder finder) async { + await tester.ensureVisible(finder); + await tester.pumpAndSettle(); + await tester.tap(finder); + await tester.pumpAndSettle(); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + testWidgets('1x on a 320x360 window: the pad scrolls and stays usable', ( + tester, + ) async { + _useViewport(tester, const Size(320, 360)); + String? entered; + + await tester.pumpWidget( + _app( + Scaffold( + body: PinInputScreen( + mode: PinInputMode.set, + allowBiometric: false, + onPinEntered: (pin) => entered = pin, + onSuccess: () {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'no layout error'); + expect( + find.byType(SingleChildScrollView), + findsWidgets, + reason: + 'a 320x360 window at 1x is shorter than the pad plus its header, so ' + 'the screen must scroll instead of laying the last row out below the ' + 'bottom edge', + ); + + for (final digit in kPinNumpadDigits.take(6)) { + await _tapKey(tester, find.text(digit).first); + } + expect(entered, '012345'); + }); + + testWidgets('1x with an open keyboard: keys stay above the inset', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + const inset = 260.0; + + await tester.pumpWidget( + _app( + Scaffold( + body: PinInputScreen( + mode: PinInputMode.set, + allowBiometric: false, + onPinEntered: (_) {}, + onSuccess: () {}, + ), + ), + keyboardInset: inset, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'no layout error'); + + // Reachability is proven by driving the keys, not by an unrendered rect: scroll + // the last row into view above the inset and tap it. + final zeroFinder = find.text('0').first; + await tester.ensureVisible(zeroFinder); + await tester.pumpAndSettle(); + final zero = tester.getRect( + find + .ancestor(of: zeroFinder, matching: find.byType(PinNumpadButton)) + .first, + ); + expect( + zero.bottom, + lessThanOrEqualTo(568 - inset + 0.5), + reason: + 'the pad must sit above the keyboard inset (zero key bottom ' + '${zero.bottom.toStringAsFixed(1)})', + ); + await tester.tap(zeroFinder); + await tester.pumpAndSettle(); + + final backspaceFinder = find.byIcon(AppIcons.backspaceOutlined).first; + await tester.ensureVisible(backspaceFinder); + await tester.pumpAndSettle(); + final backspace = tester.getRect(backspaceFinder); + expect( + backspace.bottom, + lessThanOrEqualTo(568 - inset + 0.5), + reason: 'the backspace key must sit above the keyboard inset', + ); + await tester.tap(backspaceFinder); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + + testWidgets('1x on a normal phone: the existing layout still fits', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + Scaffold( + body: PinInputScreen( + mode: PinInputMode.set, + allowBiometric: false, + onPinEntered: (_) {}, + onSuccess: () {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + for (final digit in kPinNumpadDigits) { + final rect = tester.getRect(find.text(digit).first); + expect( + rect.bottom, + lessThanOrEqualTo(568), + reason: '"$digit" must be on screen at 1x on a 320x568 phone', + ); + } + }); +} diff --git a/test/text_scale_fixes/controls/pin_numpad_text_scale_test.dart b/test/text_scale_fixes/controls/pin_numpad_text_scale_test.dart new file mode 100644 index 000000000..0938dfbef --- /dev/null +++ b/test/text_scale_fixes/controls/pin_numpad_text_scale_test.dart @@ -0,0 +1,579 @@ +// PIN numpad keys under text scaling. +// +// A PIN key has to hold its digit at the size the user asked for. The digit keeps +// its font role (28pt headlineMedium on PinNumpadButton, 24pt on PinNumpadCell) at +// whatever scale the system and app sliders compose to, so the key grows with that +// glyph box in both axes: a fixed 72dp key (lockscreen) or 64dp key (change-PIN / +// sync) clipped it from about 1.8x, and growing only vertically would still clip a +// wide substituted digit. +// +// Every digit 0-9 is checked, in both bundled faces and under a nonlinear system +// scaler, because the key is sized from the widest/tallest digit rather than from +// one sample, and because a pad whose keys disagreed would show ragged rows. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_button.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_cell.dart'; +import 'package:prism_plurality/shared/widgets/pin_numpad_metrics.dart'; +import 'package:prism_plurality/shared/widgets/tinted_glass_surface.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// System accessibility scaling that is not linear, like iOS/Android allow. +class _NonLinearTextScaler extends TextScaler { + const _NonLinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 1.4 : 28.0 + (fontSize - 20) * 3.0; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.0; +} + +const _scales = <(String, TextScaler)>[ + ( + 'system 100% x Prism 50% = 0.5x', + PrismTextScaler(TextScaler.noScaling, 0.5), + ), + ('default text', PrismTextScaler(TextScaler.noScaling, 1.0)), + ('large text 1.5x', PrismTextScaler(TextScaler.linear(1.5), 1.0)), + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ( + 'nonlinear system scaler x Prism 150%', + PrismTextScaler(_NonLinearTextScaler(), 1.5), + ), +]; + +const _fonts = ['Lexend', 'OpenDyslexic']; + +Widget _app( + Widget home, { + required TextScaler textScaler, + String font = 'Lexend', + bool boldText = false, +}) { + return ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: font, + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: textScaler, boldText: boldText), + child: child ?? const SizedBox.shrink(), + ), + home: home, + ), + ); +} + +void _useViewport(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +/// A whole keypad's worth of digit keys, as the pad renders them. +Widget _digitPad({required double size, required bool flatCell}) { + return Padding( + padding: const EdgeInsets.all(8), + child: Wrap( + spacing: 4, + runSpacing: 4, + children: [ + for (final digit in kPinNumpadDigits) + Builder( + builder: (context) => flatCell + ? PinNumpadCell( + label: digit, + onTap: () {}, + theme: Theme.of(context), + ) + : PinNumpadButton(label: digit, onTap: () {}, size: size), + ), + ], + ), + ); +} + +RenderParagraph _digitParagraph(WidgetTester tester, String digit) { + final finder = find.text(digit); + expect(finder, findsOneWidget, reason: 'exactly one "$digit" key'); + return tester.renderObject(finder); +} + +/// Natural, unconstrained size of the digit as painted. +Size _naturalSize(RenderParagraph paragraph) { + final painter = TextPainter( + text: TextSpan( + text: paragraph.text.toPlainText(), + style: paragraph.text.style, + ), + textDirection: TextDirection.ltr, + textScaler: paragraph.textScaler, + maxLines: 1, + )..layout(); + final size = Size(painter.width, painter.height); + painter.dispose(); + return size; +} + +void _expectEveryDigitPaintedWhole( + WidgetTester tester, { + required Type keyType, + required String scaleLabel, + required String font, + required double minKeySize, +}) { + final keySizes = {}; + for (final digit in kPinNumpadDigits) { + final paragraph = _digitParagraph(tester, digit); + final natural = _naturalSize(paragraph); + + expect( + paragraph.size.height, + greaterThanOrEqualTo(natural.height - 0.5), + reason: + '$scaleLabel/$font: "$digit" needs ${natural.height.toStringAsFixed(1)}' + 'px of height but its key gives it ' + '${paragraph.size.height.toStringAsFixed(1)}px', + ); + expect( + paragraph.size.width, + greaterThanOrEqualTo(natural.width - 0.5), + reason: + '$scaleLabel/$font: "$digit" needs ${natural.width.toStringAsFixed(1)}' + 'px of width but its key gives it ' + '${paragraph.size.width.toStringAsFixed(1)}px', + ); + + final digitRect = tester.getRect(find.text(digit)); + final keyRect = tester.getRect( + find.ancestor(of: find.text(digit), matching: find.byType(keyType)).first, + ); + keySizes.add(keyRect.size); + if (keyType == PinNumpadButton) { + final surface = find + .ancestor( + of: find.text(digit), + matching: find.byType(TintedGlassSurface), + ) + .first; + final container = tester.widget( + find.descendant(of: surface, matching: find.byType(Container)).first, + ); + final border = (container.decoration! as BoxDecoration).border!; + final insets = border.dimensions.resolve(TextDirection.ltr); + // Exact real decoration budget on both axes; no half-pixel allowance. + expect( + keyRect.width - insets.horizontal, + greaterThanOrEqualTo(natural.width), + ); + expect( + keyRect.height - insets.vertical, + greaterThanOrEqualTo(natural.height), + ); + expect(paragraph.size.width, greaterThanOrEqualTo(natural.width)); + expect(paragraph.size.height, greaterThanOrEqualTo(natural.height)); + } + expect(keyRect.width, greaterThanOrEqualTo(minKeySize)); + expect(keyRect.height, greaterThanOrEqualTo(minKeySize)); + expect( + digitRect.left, + greaterThanOrEqualTo(keyRect.left - 0.5), + reason: '$scaleLabel/$font: "$digit" painted outside its key (left)', + ); + expect( + digitRect.right, + lessThanOrEqualTo(keyRect.right + 0.5), + reason: '$scaleLabel/$font: "$digit" painted outside its key (right)', + ); + expect( + digitRect.top, + greaterThanOrEqualTo(keyRect.top - 0.5), + reason: '$scaleLabel/$font: "$digit" painted outside its key (top)', + ); + expect( + digitRect.bottom, + lessThanOrEqualTo(keyRect.bottom + 0.5), + reason: '$scaleLabel/$font: "$digit" painted outside its key (bottom)', + ); + } + expect( + keySizes, + hasLength(1), + reason: + '$scaleLabel/$font: every key in a pad must resolve to one extent, ' + 'otherwise the rows are ragged', + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + for (final (label, scaler) in _scales) { + for (final font in _fonts) { + testWidgets('64dp keys hold all ten digits ($label, $font)', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + Scaffold(body: _digitPad(size: 64, flatCell: false)), + textScaler: scaler, + font: font, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$label/$font: no layout error', + ); + _expectEveryDigitPaintedWhole( + tester, + keyType: PinNumpadButton, + scaleLabel: label, + font: font, + minKeySize: 64, + ); + }); + + testWidgets('72dp keys hold all ten digits ($label, $font)', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + Scaffold(body: _digitPad(size: 72, flatCell: false)), + textScaler: scaler, + font: font, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$label/$font: no layout error', + ); + _expectEveryDigitPaintedWhole( + tester, + keyType: PinNumpadButton, + scaleLabel: label, + font: font, + minKeySize: 72, + ); + }); + + testWidgets('flat cells hold all ten digits ($label, $font)', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + Scaffold(body: _digitPad(size: 72, flatCell: true)), + textScaler: scaler, + font: font, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$label/$font: no layout error', + ); + _expectEveryDigitPaintedWhole( + tester, + keyType: PinNumpadCell, + scaleLabel: label, + font: font, + minKeySize: 72, + ); + }); + } + } + + for (final font in _fonts) { + for (final (label, scaler) in [_scales[3], _scales[4]]) { + testWidgets('glass interior resolves inherited style and bold ' + '($font, $label)', (tester) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + Scaffold( + body: DefaultTextStyle( + style: TextStyle( + fontFamily: font, + height: 1.3, + letterSpacing: 0.7, + ), + child: _digitPad(size: 72, flatCell: false), + ), + ), + textScaler: scaler, + font: font, + boldText: true, + ), + ); + await tester.pumpAndSettle(); + for (final digit in kPinNumpadDigits) { + expect( + _digitParagraph(tester, digit).text.style!.fontWeight, + FontWeight.bold, + ); + } + _expectEveryDigitPaintedWhole( + tester, + keyType: PinNumpadButton, + scaleLabel: 'inherited/bold/$scaler', + font: font, + minKeySize: 72, + ); + expect(tester.takeException(), isNull); + }); + } + } + + for (final font in _fonts) { + testWidgets('metrics match ambient default style and bold paint ($font)', ( + tester, + ) async { + _useViewport(tester, const Size(500, 1000)); + await tester.pumpWidget( + _app( + Scaffold( + body: DefaultTextStyle( + style: TextStyle( + fontFamily: font, + height: 1.3, + letterSpacing: 0.7, + ), + child: Wrap( + children: [ + for (final digit in kPinNumpadDigits) + Builder( + builder: (context) { + const style = TextStyle( + fontSize: 28, + fontWeight: FontWeight.w500, + ); + final extent = pinNumpadKeyExtent( + context, + size: 72, + style: style, + ); + return TintedGlassSurface( + key: ValueKey('ambient-$digit'), + width: extent.width, + height: extent.height, + child: Text(digit, style: style), + ); + }, + ), + ], + ), + ), + ), + textScaler: const PrismTextScaler(_NonLinearTextScaler(), 1.5), + font: font, + boldText: true, + ), + ); + await tester.pumpAndSettle(); + for (final digit in kPinNumpadDigits) { + final paragraph = _digitParagraph(tester, digit); + expect(paragraph.text.style!.fontFamily, font); + expect(paragraph.text.style!.height, 1.3); + expect(paragraph.text.style!.letterSpacing, 0.7); + expect(paragraph.text.style!.fontWeight, FontWeight.bold); + final natural = _naturalSize(paragraph); + final surface = find.byKey(ValueKey('ambient-$digit')); + final container = tester.widget( + find.descendant(of: surface, matching: find.byType(Container)).first, + ); + final inset = (container.decoration! as BoxDecoration) + .border! + .dimensions + .resolve(TextDirection.ltr); + final rect = tester.getRect(surface); + expect( + rect.width - inset.horizontal, + greaterThanOrEqualTo(natural.width), + ); + expect( + rect.height - inset.vertical, + greaterThanOrEqualTo(natural.height), + ); + expect(paragraph.size.width, greaterThanOrEqualTo(natural.width)); + expect(paragraph.size.height, greaterThanOrEqualTo(natural.height)); + } + expect(tester.takeException(), isNull); + }); + } + + testWidgets('a small requested digit key still has a 44dp tap target', ( + tester, + ) async { + var taps = 0; + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: PinNumpadButton(label: '8', size: 24, onTap: () => taps++), + ), + ), + textScaler: TextScaler.noScaling, + ), + ); + await tester.pumpAndSettle(); + final key = find.byType(PinNumpadButton); + expect(tester.getSize(key).width, greaterThanOrEqualTo(44)); + expect(tester.getSize(key).height, greaterThanOrEqualTo(44)); + expect(key.hitTestable(), findsOneWidget); + await tester.tap(key); + await tester.pumpAndSettle(); + expect(taps, 1); + expect(tester.takeException(), isNull); + }); + + testWidgets('default geometry is unchanged at normal text sizes', ( + tester, + ) async { + for (final (scaler, size) in const [ + (PrismTextScaler(TextScaler.noScaling, 1.0), 72.0), + (PrismTextScaler(TextScaler.noScaling, 1.0), 64.0), + (PrismTextScaler(TextScaler.linear(1.5), 1.0), 72.0), + (PrismTextScaler(TextScaler.linear(1.5), 1.0), 64.0), + ]) { + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: Builder( + builder: (context) => + PinNumpadButton(label: '0', onTap: () {}, size: size), + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + expect( + tester.getSize(find.byType(PinNumpadButton)), + Size(size, size), + reason: 'a $size dp key stays square while every digit fits', + ); + } + }); + + testWidgets('icon-only key keeps its square geometry and its semantics', ( + tester, + ) async { + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: Builder( + builder: (context) => PinNumpadButton( + icon: Icons.backspace_outlined, + onTap: () {}, + size: 64, + semanticLabel: 'Delete', + ), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.getSize(find.byType(PinNumpadButton)), const Size(64, 64)); + final semantics = tester.getSemantics(find.byType(PinNumpadButton)); + expect(semantics.label, contains('Delete')); + expect(find.byIcon(Icons.backspace_outlined), findsOneWidget); + }); + + testWidgets('flat backspace cell keeps its tooltip and semantics', ( + tester, + ) async { + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: Builder( + builder: (context) => PinNumpadCell( + icon: Icons.backspace_outlined, + onTap: () {}, + theme: Theme.of(context), + ), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.getSize(find.byType(PinNumpadCell)), const Size(72, 72)); + expect(find.byType(Tooltip), findsOneWidget); + final semantics = tester.getSemantics(find.byType(PinNumpadCell)); + expect(semantics.label, isNotEmpty); + }); + + testWidgets('a grown 64dp key is still tappable and keeps its digit label', ( + tester, + ) async { + var taps = 0; + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: Builder( + builder: (context) => + PinNumpadButton(label: '3', onTap: () => taps++, size: 64), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ); + await tester.pumpAndSettle(); + + final keyRect = tester.getRect(find.byType(PinNumpadButton)); + expect(keyRect.height, greaterThan(64)); + expect(keyRect.width, greaterThanOrEqualTo(64)); + + await tester.tap(find.byType(PinNumpadButton)); + await tester.pump(); + expect(taps, 1); + + final semantics = tester.getSemantics(find.byType(PinNumpadButton)); + expect(semantics.label, contains('3')); + }); +} diff --git a/test/text_scale_fixes/controls/segmented_control_text_scale_test.dart b/test/text_scale_fixes/controls/segmented_control_text_scale_test.dart new file mode 100644 index 000000000..0e9fceeb6 --- /dev/null +++ b/test/text_scale_fixes/controls/segmented_control_text_scale_test.dart @@ -0,0 +1,884 @@ +// Segmented control under text scaling. +// +// The track must hold its labels. A fixed 44dp box with single-line labels sliced +// the glyph band vertically (and ellipsised it horizontally) once the composed text +// grew. The track follows the label's real line box, keeps 44dp as its floor so +// normal-text geometry is unchanged, and lets a label take a second line before it +// ellipsises. + +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import 'package:prism_plurality/shared/widgets/prism_scaled_height.dart'; +import 'package:prism_plurality/shared/widgets/prism_segmented_control.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// Non-linear system scaler (as iOS/Android accessibility allow) composed with +/// the app's own factor; the fitting math has to follow the real line box. +class _NonLinearTextScaler extends TextScaler { + const _NonLinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize < 20 ? fontSize * 1.4 : 28.0 + (fontSize - 20) * 3.0; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.0; +} + +const _scales = <(String, TextScaler)>[ + ( + 'system 100% x Prism 50% = 0.5x', + PrismTextScaler(TextScaler.noScaling, 0.5), + ), + ('default text', PrismTextScaler(TextScaler.noScaling, 1.0)), + ('large text 1.5x', PrismTextScaler(TextScaler.linear(1.5), 1.0)), + ( + 'system 225% x Prism 150% = 3.375x', + PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ( + 'nonlinear system scaler x Prism 150%', + PrismTextScaler(_NonLinearTextScaler(), 1.5), + ), +]; + +void _useViewport(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +Widget _app(Widget home, {required TextScaler textScaler}) { + return MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: textScaler), + child: child ?? const SizedBox.shrink(), + ), + home: home, + ); +} + +/// Puts a control where it really lives: a column inside a scrolling page, i.e. under +/// a parent whose vertical axis is unbounded. A bounded parent (a Scaffold body, or a +/// sliver band) must not stretch the track - the bounded-parent cases below check +/// exactly that - so this host is used where only the control's own extent matters. +Widget _naturalHost(Widget child) { + return Scaffold( + body: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [child], + ), + ), + ); +} + +Widget _control({ + required ValueChanged onChanged, + String selected = 'list', + int? badgeCount, +}) { + return PrismSegmentedControl( + segments: [ + const PrismSegment(value: 'list', label: 'List'), + PrismSegment(value: 'chart', label: 'Chart', badgeCount: badgeCount), + ], + selected: selected, + onChanged: onChanged, + ); +} + +/// Height the paragraph would take at its own width if its box never clipped +/// it (2 lines are allowed, matching the control's own policy). +double _naturalHeight(RenderParagraph paragraph, {int maxLines = 2}) { + final painter = TextPainter( + text: TextSpan( + text: paragraph.text.toPlainText(), + style: paragraph.text.style, + ), + textDirection: TextDirection.ltr, + textScaler: paragraph.textScaler, + textAlign: paragraph.textAlign, + maxLines: maxLines, + )..layout(maxWidth: paragraph.size.width); + final height = painter.height; + painter.dispose(); + return height; +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadPrismGoldenFonts(); + }); + + for (final (label, scaler) in _scales) { + testWidgets('track holds its label glyphs on a compact phone ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + var selected = 'list'; + + await tester.pumpWidget( + _app( + _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: StatefulBuilder( + builder: (context, setState) => _control( + selected: selected, + onChanged: (value) => setState(() => selected = value), + ), + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + + final track = tester.getRect(find.byType(PrismSegmentedControl)); + expect(track.height, greaterThanOrEqualTo(44)); + + for (final text in const ['List', 'Chart']) { + final paragraph = tester.renderObject(find.text(text)); + final needed = _naturalHeight(paragraph); + expect( + paragraph.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: "$text" needs ${needed.toStringAsFixed(1)}px but the ' + 'track gives it ${paragraph.size.height.toStringAsFixed(1)}px', + ); + final rect = tester.getRect(find.text(text)); + expect( + rect.top, + greaterThanOrEqualTo(track.top - 0.5), + reason: '$label: "$text" painted above the track', + ); + expect( + rect.bottom, + lessThanOrEqualTo(track.bottom + 0.5), + reason: '$label: "$text" painted below the track', + ); + } + + // The control still works: tapping the second segment reports its value. + await tester.tap(find.text('Chart')); + await tester.pumpAndSettle(); + expect(selected, 'chart'); + }); + + testWidgets('badge grows with its count instead of being sliced ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + await tester.pumpWidget( + _app( + _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _control(onChanged: (_) {}, badgeCount: 9999), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + final badge = tester.renderObject(find.text('9+')); + final needed = _naturalHeight(badge, maxLines: 1); + expect( + badge.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: badge needs ${needed.toStringAsFixed(1)}px but has ' + '${badge.size.height.toStringAsFixed(1)}px', + ); + final track = tester.getRect(find.byType(PrismSegmentedControl)); + final badgeRect = tester.getRect(find.text('9+')); + expect(badgeRect.top, greaterThanOrEqualTo(track.top - 0.5)); + expect(badgeRect.bottom, lessThanOrEqualTo(track.bottom + 0.5)); + }); + } + + // A finite parent height is what every non-scrolling page gives the track, so the + // track must keep its own 44dp there instead of filling the parent (it once read + // 780). The unbounded hosts used elsewhere cannot observe this. + testWidgets('default geometry is 44dp inside a full-height bounded body', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + await tester.pumpWidget( + _app( + Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: _control(onChanged: (_) {}), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + ), + ); + await tester.pumpAndSettle(); + final track = tester.getRect(find.byType(PrismSegmentedControl)); + expect( + track.height, + 44, + reason: + 'a finite parent height must not stretch the track to the parent ' + '(the regression read 780 here)', + ); + }); + + testWidgets('default geometry is 44dp inside a short bounded box', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + await tester.pumpWidget( + _app( + // The 300dp box is a viewport, not a constraint on the control: an Align + // hands the track loose constraints, the way a page column does, so the + // track keeps its own 44dp instead of being stretched (or forced) by it. + Center( + child: SizedBox( + height: 300, + width: 358, + child: Align( + alignment: Alignment.topCenter, + child: _control(onChanged: (_) {}), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + ), + ); + await tester.pumpAndSettle(); + final track = tester.getRect(find.byType(PrismSegmentedControl)); + expect( + track.height, + 44, + reason: 'a 300dp parent must not stretch the track', + ); + expect(track.top, greaterThan(0)); + }); + + testWidgets('four segments at 3.375x stay inside their track', ( + tester, + ) async { + _useViewport(tester, const Size(320, 568)); + await tester.pumpWidget( + _app( + _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: PrismSegmentedControl( + segments: const [ + PrismSegment(value: 'a', label: 'Default'), + PrismSegment(value: 'b', label: 'Pixels'), + PrismSegment(value: 'c', label: 'Percent'), + PrismSegment(value: 'd', label: 'Em'), + ], + selected: 'a', + onChanged: (_) {}, + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.linear(2.25), 1.5), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + final track = tester.getRect(find.byType(PrismSegmentedControl)); + for (final text in const ['Default', 'Pixels', 'Percent', 'Em']) { + final rect = tester.getRect(find.text(text)); + expect(rect.top, greaterThanOrEqualTo(track.top - 0.5), reason: text); + expect(rect.bottom, lessThanOrEqualTo(track.bottom + 0.5), reason: text); + } + }); + + // The pinned-header contract: a caller that reserves space for this control + // must get exactly the height it renders - labels' real wrapping (two lines), + // badges and the hairline border included. + for (final (name, segments) in <(String, List>)>[ + ( + 'two segments', + const [ + PrismSegment(value: 'a', label: 'List'), + PrismSegment(value: 'b', label: 'Chart'), + ], + ), + ( + 'three segments with a badge', + const [ + PrismSegment(value: 'a', label: 'Group Chats', badgeCount: 12), + PrismSegment(value: 'b', label: 'Direct Messages'), + PrismSegment(value: 'c', label: 'Archived'), + ], + ), + ( + 'four segments', + const [ + PrismSegment(value: 'a', label: 'Default'), + PrismSegment(value: 'b', label: 'Pixels'), + PrismSegment(value: 'c', label: 'Percent'), + PrismSegment(value: 'd', label: 'Em'), + ], + ), + ]) { + for (final (label, scaler) in _scales) { + testWidgets('preferredHeightFor matches the rendering ($name, $label)', ( + tester, + ) async { + for (final width in const [320.0, 390.0, 800.0]) { + _useViewport(tester, Size(width, 780)); + await tester.pumpWidget( + _app( + _naturalHost( + SizedBox( + width: width - 32, + child: PrismSegmentedControl( + segments: segments, + selected: 'a', + onChanged: (_) {}, + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$name/$label/$width: no layout error', + ); + final finder = find.byType(PrismSegmentedControl); + final rendered = tester.getRect(finder).height; + final control = tester.widget>(finder); + final context = tester.element(finder); + expect( + control, + isA(), + reason: 'the control opts into the pinned-header height contract', + ); + expect( + control.preferredHeightFor(context, availableWidth: width - 32), + closeTo(rendered, 0.01), + reason: + '$name/$label/$width: the reported height must be the height ' + 'that is really painted', + ); + expect( + rendered, + greaterThanOrEqualTo(44.0 - 0.01), + reason: '$name/$label/$width: the 44dp floor is preserved', + ); + } + }); + } + } + + // A label whose line count differs between the unselected weight (w500) and the + // selected one (w600) at this segment width. The measurement has to use the + // weight the segment really renders, otherwise a selected label that wraps only + // when bold is reserved one line short and the pinned band clips it. + // A label whose line count differs between two weights at this segment width. + // Used to prove the measurement picks the weight the segment really renders: + // w600 for the selected segment (vs w500), and w700 for every segment once + // MediaQuery.boldText is on (Text.build merges FontWeight.bold). + ({String label, double segmentWidth})? wrapBoundaryLabel({ + required double controlWidth, + required int segmentCount, + required TextScaler scaler, + required TextStyle base, + required TextDirection direction, + required FontWeight weightA, + required FontWeight weightB, + }) { + final segmentWidth = (controlWidth - 1) / segmentCount; + + double heightFor(String label, FontWeight weight) { + final painter = TextPainter( + text: TextSpan( + text: label, + style: base.copyWith(fontWeight: weight), + ), + textDirection: direction, + textScaler: scaler, + maxLines: 2, + )..layout(maxWidth: segmentWidth); + final height = painter.height; + painter.dispose(); + return height; + } + + for (var words = 1; words <= 10; words++) { + final label = List.filled(words, 'Word').join(' '); + if (heightFor(label, weightA) != heightFor(label, weightB)) { + return (label: label, segmentWidth: segmentWidth); + } + } + return null; + } + + for (final (label, scaler) in _scales) { + testWidgets('selected weight decides the wrap it reserves ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + const controlWidth = 358.0; + final base = ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ).textTheme.labelLarge!; + + final boundary = wrapBoundaryLabel( + controlWidth: controlWidth, + segmentCount: 2, + scaler: scaler, + base: base, + direction: TextDirection.ltr, + weightA: FontWeight.w500, + weightB: FontWeight.w600, + ); + // When this face's metrics do not separate the two weights at this width, + // every candidate label wraps the same way under both. The case then falls back + // to a fixed label: it checks only that the reported height matches the height + // that is painted, and says nothing about the weight difference. + final caseLabel = boundary?.label ?? 'Word Word Word'; + + for (final selectedFirst in const [true, false]) { + await tester.pumpWidget( + _app( + _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: PrismSegmentedControl( + segments: [ + PrismSegment( + value: 'a', + label: selectedFirst ? caseLabel : 'Ab', + ), + PrismSegment( + value: 'b', + label: selectedFirst ? 'Ab' : caseLabel, + ), + ], + selected: selectedFirst ? 'a' : 'b', + onChanged: (_) {}, + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + expect( + tester.takeException(), + isNull, + reason: '$label: no layout error', + ); + final finder = find.byType(PrismSegmentedControl); + final control = tester.widget>(finder); + final context = tester.element(finder); + final rendered = tester.getRect(finder).height; + expect( + control.preferredHeightFor(context, availableWidth: controlWidth), + closeTo(rendered, 0.01), + reason: + '$label: selected=${selectedFirst ? 'first' : 'second'}; the ' + 'reserved height must match the track that really renders the ' + 'label at its own weight', + ); + final boundaryFinder = find.text(caseLabel); + final trackRect = tester.getRect(finder); + final labelRect = tester.getRect(boundaryFinder); + expect( + labelRect.bottom, + lessThanOrEqualTo(trackRect.bottom + 0.5), + reason: '$label: the boundary label must not be clipped', + ); + } + }); + + testWidgets('the segment target itself is >= 44dp and takes edge taps', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + final calls = []; + + await tester.pumpWidget( + _app( + _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: PrismSegmentedControl( + segments: const [ + PrismSegment(value: 'a', label: 'Alpha'), + PrismSegment(value: 'b', label: 'Beta'), + ], + selected: 'a', + onChanged: calls.add, + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + // The real hit area, not the track: the hairline border insets the segments + // by 0.5dp on each side, so this rect - not `track.height` - is what the + // 44dp target rule applies to. + final beta = find.ancestor( + of: find.text('Beta'), + matching: find.byType(GestureDetector), + ); + expect(beta, findsWidgets, reason: '$label: the segment is tappable'); + final target = tester.getRect(beta.first); + expect( + target.height, + greaterThanOrEqualTo(44.0 - 0.01), + reason: + '$label: the segment gesture target is ' + '${target.height.toStringAsFixed(2)}dp tall; the contract needs ' + '44dp, and the 0.5dp border inset plus the 43dp inner floor can ' + 'leave it short', + ); + expect(target.width, greaterThanOrEqualTo(44.0 - 0.01)); + + await tester.tapAt(Offset(target.center.dx, target.top + 0.25)); + await tester.pumpAndSettle(); + expect(calls, [ + 'b', + ], reason: '$label: a tap on the target top edge selects'); + + final alpha = tester.getRect( + find + .ancestor( + of: find.text('Alpha'), + matching: find.byType(GestureDetector), + ) + .first, + ); + await tester.tapAt(Offset(alpha.center.dx, alpha.bottom - 0.25)); + await tester.pumpAndSettle(); + expect(calls, [ + 'b', + ], reason: '$label: tapping the already-selected segment does nothing'); + }); + } + + testWidgets('bold text: the reserved height still matches the rendering', ( + tester, + ) async { + // Text merges `FontWeight.bold` (w700) when MediaQuery.boldText is true, so the + // painted label is w700 while the control measures w500/w600; the measurement has + // to apply that same merge to predict the same height. + _useViewport(tester, const Size(390, 780)); + const controlWidth = 358.0; + const scaler = PrismTextScaler(TextScaler.linear(2.25), 1.5); + final base = ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ).textTheme.labelLarge!; + + final boundary = wrapBoundaryLabel( + controlWidth: controlWidth, + segmentCount: 2, + scaler: scaler, + base: base, + direction: TextDirection.ltr, + weightA: FontWeight.w600, + weightB: FontWeight.w700, + ); + // As above: if this face's metrics do not separate w600 from w700 at this width, + // the case falls back to a fixed label and checks only that the reported height + // matches the painted one. + final caseLabel = boundary?.label ?? 'Word Word Word Word'; + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + theme: ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: scaler, boldText: true), + child: child ?? const SizedBox.shrink(), + ), + home: _naturalHost( + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: PrismSegmentedControl( + segments: [ + PrismSegment(value: 'a', label: caseLabel), + const PrismSegment(value: 'b', label: 'Ab'), + ], + selected: 'a', + onChanged: (_) {}, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: 'no layout error'); + final finder = find.byType(PrismSegmentedControl); + final control = tester.widget>(finder); + final context = tester.element(finder); + expect( + control.preferredHeightFor(context, availableWidth: controlWidth), + closeTo(tester.getRect(finder).height, 0.01), + reason: + 'with bold text the painted label is w700, so the measurement has to ' + 'be bold too', + ); + }); + + // The badge is painted at w600 (`_SegmentBadge` merges fontWeight w600) but the + // height prediction measures it from the bare labelSmall style. Its width feeds + // the label's available width ("slot - badge - 6"), so a badge measured at the + // wrong weight can move a label across the wrap boundary and reserve one line + // less than the label renders. `9999` gives the two-character "9+" badge, where + // the weight difference is largest. + for (final (label, scaler) in _scales) { + testWidgets('a w600 badge keeps the label wrap it reserves ($label)', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + const controlHeightFloor = 44.0; + final theme = ThemeData( + fontFamily: 'Lexend', + fontFamilyFallback: const ['NotoColorEmoji'], + ); + final labelStyle = theme.textTheme.labelLarge!; + final badgeBase = theme.textTheme.labelSmall!.copyWith(height: 1.0); + + double lineHeight(String text, TextStyle style, double maxWidth) { + final painter = TextPainter( + text: TextSpan(text: text, style: style), + textDirection: TextDirection.ltr, + textScaler: scaler, + maxLines: 2, + )..layout(maxWidth: maxWidth); + final height = painter.height; + painter.dispose(); + return height; + } + + double badgeWidth(FontWeight weight) { + final painter = TextPainter( + text: TextSpan( + text: '9+', + style: badgeBase.copyWith(fontWeight: weight), + ), + textDirection: TextDirection.ltr, + textScaler: scaler, + maxLines: 1, + )..layout(); + final width = math.max(18.0, painter.width + 12); + painter.dispose(); + return width; + } + + final realBadge = badgeWidth(FontWeight.w600); + final measuredBadge = badgeWidth(FontWeight.w400); + + // Prefer a (width, label) pair whose wrap differs between the badge width as + // painted (w600) and a narrower one (w400): only such a pair can show the + // difference. Where the badge metrics do not move the wrap at any tried width, + // the case falls back to a fixed label and checks only that the reported height + // matches the painted one. + ({double width, String label})? boundary; + for (final width in const [200.0, 240.0, 280.0, 320.0, 358.0]) { + final slot = (width - 1) / 2; + final realLabelWidth = math.max(1.0, slot - realBadge - 6); + final measuredLabelWidth = math.max(1.0, slot - measuredBadge - 6); + for (var n = 1; n <= 12 && boundary == null; n++) { + for (final candidate in [ + List.filled(n, 'Word').join(' '), + List.filled(n + 1, 'W').join(), + ]) { + if (lineHeight(candidate, labelStyle, realLabelWidth) != + lineHeight(candidate, labelStyle, measuredLabelWidth)) { + boundary = (width: width, label: candidate); + break; + } + } + } + if (boundary != null) break; + } + final badgeCase = boundary ?? (width: 358.0, label: 'Word Word Word'); + + await tester.pumpWidget( + _app( + _naturalHost( + SizedBox( + width: badgeCase.width, + child: PrismSegmentedControl( + segments: [ + PrismSegment( + value: 'a', + label: badgeCase.label, + badgeCount: 9999, + badgeSemanticLabel: '9999 unread', + ), + const PrismSegment(value: 'b', label: 'Ab'), + ], + selected: 'a', + onChanged: (_) {}, + ), + ), + ), + textScaler: scaler, + ), + ); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull, reason: '$label: no layout error'); + final finder = find.byType(PrismSegmentedControl); + final control = tester.widget>(finder); + final context = tester.element(finder); + final trackRect = tester.getRect(finder); + expect(trackRect.height, greaterThanOrEqualTo(controlHeightFloor - 0.01)); + expect( + control.preferredHeightFor(context, availableWidth: badgeCase.width), + closeTo(trackRect.height, 0.01), + reason: + '$label: the badge is painted at w600, so its width - and therefore ' + 'the label width it leaves - must be measured at w600 too', + ); + + final badgeParagraph = tester.renderObject( + find.text('9+'), + ); + final badgeNatural = _naturalHeight(badgeParagraph, maxLines: 1); + expect( + badgeParagraph.size.height, + greaterThanOrEqualTo(badgeNatural - 0.5), + reason: '$label: the badge glyphs must not be clipped', + ); + }); + } + + // A 44dp viewport pins the geometry exactly, so the segment target can be measured + // without depending on the face's line height. The track paints 44dp tall and its + // segments are the tap targets, so each one has to be 44dp too; the assertion + // reports the value it measured, so the failure text is the measurement itself. + testWidgets('forced 44dp track: the real segment target is at least 44dp', ( + tester, + ) async { + _useViewport(tester, const Size(390, 780)); + final calls = []; + var selected = 'a'; + + await tester.pumpWidget( + _app( + Center( + child: SizedBox( + height: 44, + width: 358, + child: Align( + alignment: Alignment.topCenter, + child: StatefulBuilder( + builder: (context, setSelected) => + PrismSegmentedControl( + segments: const [ + PrismSegment(value: 'a', label: 'Alpha'), + PrismSegment(value: 'b', label: 'Beta'), + ], + selected: selected, + onChanged: (value) { + calls.add(value); + setSelected(() => selected = value); + }, + ), + ), + ), + ), + ), + textScaler: const PrismTextScaler(TextScaler.noScaling, 1.0), + ), + ); + await tester.pumpAndSettle(); + + final track = tester.getRect(find.byType(PrismSegmentedControl)); + expect( + track.height, + 44, + reason: 'the track keeps its own 44dp height inside the 44dp viewport', + ); + + final target = tester.getRect( + find + .ancestor( + of: find.text('Beta'), + matching: find.byType(GestureDetector), + ) + .first, + ); + expect( + target.height, + greaterThanOrEqualTo(44.0 - 0.01), + reason: + 'the segment gesture target measures ' + '${target.height.toStringAsFixed(2)}dp inside the 44dp track: the 0.5dp ' + 'hairline is an inset in decoration:, so the tappable content is 43dp', + ); + + // The target still behaves across its real extent: the top edge of the second + // segment selects it, and the bottom edge of the first selects that one. + await tester.tapAt(Offset(target.center.dx, target.top + 0.25)); + await tester.pumpAndSettle(); + expect(calls, ['b']); + expect(selected, 'b', reason: 'the controlled host must accept the change'); + + final firstTarget = tester.getRect( + find + .ancestor( + of: find.text('Alpha'), + matching: find.byType(GestureDetector), + ) + .first, + ); + await tester.tapAt( + Offset(firstTarget.center.dx, firstTarget.bottom - 0.25), + ); + await tester.pumpAndSettle(); + expect(calls, ['b', 'a']); + expect(selected, 'a'); + }); +} diff --git a/test/text_scale_fixes/habits/habit_glyph_text_scale_test.dart b/test/text_scale_fixes/habits/habit_glyph_text_scale_test.dart new file mode 100644 index 000000000..8f073990c --- /dev/null +++ b/test/text_scale_fixes/habits/habit_glyph_text_scale_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:prism_plurality/domain/models/habit.dart'; +import 'package:prism_plurality/features/habits/widgets/habit_chip.dart'; +import 'package:prism_plurality/features/habits/widgets/habit_row.dart'; +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_shapes.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +class _NonlinearScaler extends TextScaler { + const _NonlinearScaler(); + @override + double scale(double size) => size < 20 ? size * 2.7 : size * 3.2; + @override + // ignore: deprecated_member_use + double get textScaleFactor => 3.2; +} + +void main() { + setUpAll(loadPrismGoldenFonts); + for (final family in ['Lexend', 'OpenDyslexic']) { + for (final scale in [0.5, 1.0, 1.5, 3.375, -1.0]) { + for (final compact in [false, true]) { + testWidgets( + '$family ${compact ? 'chip' : 'row'} glyph fits at $scale', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(320, 568); + addTearDown(tester.view.reset); + final scaler = scale == -1.0 + ? const _NonlinearScaler() + : PrismTextScaler( + TextScaler.linear(scale == 3.375 ? 2.25 : 1), + scale == 3.375 ? 1.5 : scale, + ); + var quick = 0; + var opened = 0; + final habit = Habit( + id: 'synthetic-habit', + name: 'Water', + icon: '🎯', + frequency: HabitFrequency.daily, + createdAt: DateTime(2026, 1, 1), + modifiedAt: DateTime(2026, 1, 1), + ); + final child = compact + ? HabitChip( + habit: habit, + todayCompletions: const [], + onTap: () => opened++, + onQuickComplete: () async { + quick++; + }, + ) + : HabitRow( + habit: habit, + todayCompletions: const [], + onTap: () => opened++, + onQuickComplete: () async { + quick++; + }, + ); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + fontFamily: family, + fontFamilyFallback: const ['NotoColorEmoji'], + extensions: const [PrismShapes.rounded], + ), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en')], + builder: (context, child) => MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: scaler), + child: child!, + ), + home: Scaffold(body: SingleChildScrollView(child: child)), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + final glyph = find.text('🎯'); + final paragraph = tester.renderObject(glyph); + final natural = TextPainter( + text: paragraph.text, + textScaler: paragraph.textScaler, + textDirection: paragraph.textDirection, + locale: paragraph.locale, + maxLines: 1, + )..layout(); + try { + expect( + paragraph.size.height, + greaterThanOrEqualTo(natural.height - .5), + reason: + 'The actual emoji line must not be clamped by its circle.', + ); + expect( + paragraph.size.width, + greaterThanOrEqualTo(natural.width - .5), + ); + } finally { + natural.dispose(); + } + final role = compact ? 18.0 : 20.0; + expect( + paragraph.textScaler.scale(role), + closeTo(scaler.scale(role), .001), + ); + expect( + tester.getRect(glyph).height, + closeTo(paragraph.size.height, .01), + reason: 'A transform must not shrink the requested glyph.', + ); + final circle = find + .ancestor(of: glyph, matching: find.byType(AnimatedContainer)) + .first; + final target = find + .ancestor( + of: glyph, + matching: find.byWidgetPredicate( + (widget) => + widget is GestureDetector && widget.onTap != null, + ), + ) + .first; + final circleRect = tester.getRect(circle); + final glyphRect = tester.getRect(glyph); + expect(glyphRect.left, greaterThanOrEqualTo(circleRect.left - .5)); + expect(glyphRect.right, lessThanOrEqualTo(circleRect.right + .5)); + expect(glyphRect.top, greaterThanOrEqualTo(circleRect.top - .5)); + expect(glyphRect.bottom, lessThanOrEqualTo(circleRect.bottom + .5)); + expect( + tester.getSize(target).shortestSide, + greaterThanOrEqualTo(44), + ); + await tester.tap(glyph); + await tester.pumpAndSettle(); + expect(quick, 1); + expect(opened, 0); + await tester.tap(find.text('Water')); + expect(opened, 1); + expect(quick, 1); + }, + ); + } + } + } +} diff --git a/test/text_scale_fixes/rows/boards_and_reminder_rows_text_scale_test.dart b/test/text_scale_fixes/rows/boards_and_reminder_rows_text_scale_test.dart new file mode 100644 index 000000000..28a82c08c --- /dev/null +++ b/test/text_scale_fixes/rows/boards_and_reminder_rows_text_scale_test.dart @@ -0,0 +1,526 @@ +// The post tile's header, the board section header and the reminder composer's +// label/control rows at large text sizes. +// +// Post header: the timestamp and the audience pill were non-flex children, so they kept +// their intrinsic width and collapsed the participant strip, whose own non-shrinkable +// pieces (two avatars and the "to" connector) then no longer fit. The header keeps the +// metadata inline whenever it fits beside those pieces and gives it its own line when it +// does not. +// +// Board section header: the title was a non-flex `Text` behind a `Spacer`, so the actor +// selector and the compose "+" were pushed past the card edge - the entry point for +// writing a post went off-screen. +// +// Reminder composer: `_LabeledRow` was `Row(spaceBetween, [Text(label), control])` with +// neither side flexible, so the label's intrinsic width pushed the control past the card. +// +// Each case asserts painted geometry and, where relevant, that the control, the selector +// and the compose action stay inside the window. The reminder sheet also renders the +// trigger/frequency segmented control; an overflow inside that control fails this test +// too, so read the failure location before attributing it to a row. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/member_board_post.dart'; +import 'package:prism_plurality/domain/models/member_group.dart'; +import 'package:prism_plurality/domain/models/member_group_entry.dart'; +import 'package:prism_plurality/domain/models/reminder.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/boards/providers/board_posts_providers.dart'; +import 'package:prism_plurality/features/boards/widgets/board_message_section.dart'; +import 'package:prism_plurality/features/boards/widgets/post_tile.dart'; +import 'package:prism_plurality/features/chat/providers/chat_providers.dart' + show SpeakingAsNotifier, speakingAsProvider; +import 'package:prism_plurality/features/members/providers/member_groups_providers.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/reminders/widgets/create_reminder_sheet.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'rows_text_scale_harness.dart'; + +final _now = DateTime.now(); +final _alice = Member( + id: 'alice', + name: 'Alice', + createdAt: _now.subtract(const Duration(days: 20)), + isActive: true, +); +final _bob = Member( + id: 'bob', + name: 'Bob', + createdAt: _now.subtract(const Duration(days: 20)), + isActive: true, +); + +MemberBoardPost _post() => MemberBoardPost( + id: 'post-1', + authorId: 'alice', + targetMemberId: 'bob', + audience: 'public', + body: 'Hello system', + createdAt: _now.subtract(const Duration(hours: 2)), + writtenAt: _now.subtract(const Duration(hours: 2)), +); + +/// A deliberately long user name: it must ellipsise on the inline header line instead +/// of forcing the metadata onto a second line. +const _longAuthorName = 'Alexandra-Rose Montgomery the Third'; + +class _FakeBoardPostNotifier extends MemberBoardPostNotifier { + @override + Future build() async {} +} + +class _FakeSpeakingAsNotifier extends SpeakingAsNotifier { + @override + String? build() => null; +} + +Widget _postTile({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + String? authorName, +}) { + final post = _post(); + final author = authorName == null + ? _alice + : Member( + id: _alice.id, + name: authorName, + createdAt: _alice.createdAt, + isActive: true, + ); + return ProviderScope( + overrides: [ + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + memberByIdProvider.overrideWith( + (ref, id) => Stream.value( + [author, _bob].firstWhere((m) => m.id == id, orElse: () => author), + ), + ), + memberBoardPostNotifierProvider.overrideWith(_FakeBoardPostNotifier.new), + ], + child: rowsApp( + Scaffold( + body: SingleChildScrollView( + child: PostTile( + post: post, + viewerMember: author, + showAudiencePill: true, + onTap: () {}, + ), + ), + ), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +Widget _boardSection({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, +}) { + return ProviderScope( + overrides: [ + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + boardsEnabledProvider.overrideWithValue(true), + speakingAsProvider.overrideWith(_FakeSpeakingAsNotifier.new), + activeMembersProvider.overrideWith((ref) => Stream.value([_alice, _bob])), + activeMemberListProvider.overrideWith( + (ref) => Stream.value([_alice, _bob]), + ), + memberByIdProvider.overrideWith( + (ref, id) => Stream.value( + [_alice, _bob].firstWhere((m) => m.id == id, orElse: () => _alice), + ), + ), + memberBoardSectionProvider.overrideWith( + (ref, memberId) => Stream.value( + MemberBoardSection(publicPosts: [_post()], totalPublic: 1), + ), + ), + memberBoardPostNotifierProvider.overrideWith(_FakeBoardPostNotifier.new), + ], + child: rowsApp( + const SizedBox.shrink(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + routerConfig: GoRouter( + initialLocation: '/', + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: SingleChildScrollView( + child: BoardMessageSection(memberId: _alice.id), + ), + ), + ), + GoRoute( + path: '/boards/member/:memberId', + builder: (context, state) => Scaffold( + body: Text('member board ${state.pathParameters['memberId']}'), + ), + ), + ], + ), + ), + ); +} + +Reminder _intervalReminder() => Reminder( + id: 'r1', + name: 'Test', + message: '', + trigger: ReminderTrigger.scheduled, + frequency: ReminderFrequency.interval, + intervalDays: 7, + createdAt: DateTime(2024), + modifiedAt: DateTime(2024), +); + +Widget _reminderSheet({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + TextDirection? textDirection, +}) { + final appPrefs = FakeAppPreferenceRepository(); + addTearDown(appPrefs.close); + return ProviderScope( + overrides: [ + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + activeMembersProvider.overrideWith((ref) => Stream.value([_alice, _bob])), + allGroupsProvider.overrideWith( + (ref) => Stream.value(const []), + ), + allGroupEntriesProvider.overrideWith( + (ref) => Stream.value(const []), + ), + systemSettingsProvider.overrideWithValue( + const AsyncValue.data(SystemSettings()), + ), + ], + child: rowsApp( + Scaffold(body: CreateReminderSheet(editing: _intervalReminder())), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + textDirection: textDirection, + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + group('B1 post tile header', () { + testWidgets('default text keeps the whole header on one line (control)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_postTile(system: 1, app: 1)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'post tile at 1x'); + for (final name in ['Alice', 'Bob']) { + final finder = find.text(name); + expect(finder, findsOneWidget, reason: name); + expectNotVerticallyClipped(tester, finder, label: '$name at 1x'); + } + expectOnTheSameLine( + tester, + find.text('Alice'), + find.text('2h ago'), + label: 'participants/timestamp at 1x', + ); + }); + + for (final (system, app, scaleLabel) in [ + (1.0, 1.0, 'default text'), + (1.5, 1.0, 'large text'), + ]) { + testWidgets('a long author name keeps the inline header - $scaleLabel', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _postTile(system: system, app: app, authorName: _longAuthorName), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'post tile long name $scaleLabel'); + + // The metadata stays on the name's line: the old, sound geometry, where the + // user's name ellipsises instead of pushing the header apart. + final author = find.text(_longAuthorName); + final timestamp = find.text('2h ago'); + expect(author, findsOneWidget); + expect(timestamp, findsOneWidget); + expectOnTheSameLine( + tester, + author, + timestamp, + label: 'long name / timestamp ($scaleLabel)', + ); + expect( + paragraphOf(tester, author).didExceedMaxLines, + isTrue, + reason: + '$scaleLabel: the long name is expected to ellipsise on the inline line', + ); + expectDescendantTextInside( + tester, + find.byType(PostTile), + label: 'post tile (long name, $scaleLabel)', + ); + }); + } + + for (final (system, app, scaleLabel) in rowsScales) { + testWidgets('the header never paints outside the tile - $scaleLabel', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_postTile(system: system, app: app)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'post tile $scaleLabel'); + expectDescendantTextInside( + tester, + find.byType(PostTile), + label: 'post tile ($scaleLabel)', + ); + expectPaintedInside(tester, find.text('2h ago'), label: 'timestamp'); + expectPaintedInside( + tester, + find.text('public'), + label: 'audience pill', + ); + }); + } + + testWidgets('B1 wide window where it fits: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_postTile(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'post tile wide 3.375x'); + expectNotVerticallyClipped( + tester, + find.text('Alice'), + label: 'author (wide)', + ); + expectOnTheSameLine( + tester, + find.text('Alice'), + find.text('2h ago'), + label: 'participants/timestamp (wide 3.375x)', + ); + }); + }); + + group('B6 board section header', () { + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets( + 'compose + and actor selector stay reachable - $scaleLabel / $fontFamily', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _boardSection(system: system, app: app, fontFamily: fontFamily), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'board section $scaleLabel'); + + final title = find.text('Public Posts'); + expect(title, findsOneWidget); + expectStaticLabelFullyPainted( + tester, + title, + label: 'section title', + ); + + // A control whose rect leaves the window cannot be tapped on the + // device, so the compose entry point would be unreachable. + final compose = find.byIcon(AppIcons.add); + expect(compose, findsOneWidget); + expectPaintedInside( + tester, + compose, + label: 'compose + ($scaleLabel)', + ); + final selector = find.byKey(const ValueKey('boards.actorSelector')); + expect(selector, findsOneWidget); + expectPaintedInside( + tester, + selector, + label: 'actor selector ($scaleLabel)', + ); + }, + ); + } + } + + testWidgets('B6 wide window where it fits: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_boardSection(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'board section wide 3.375x'); + expectOnTheSameLine( + tester, + find.text('Public Posts'), + find.byIcon(AppIcons.add), + label: 'title/compose (wide 3.375x)', + ); + }); + }); + + group('R1 reminder composer rows', () { + testWidgets('default text keeps the control beside its label (control)', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget(_reminderSheet(system: 1, app: 1)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'reminder sheet at 1x'); + final label = find.text('Repeat every'); + final control = find.text('7 days'); + expect(label, findsOneWidget); + expect(control, findsOneWidget); + expectOnTheSameLine( + tester, + label, + control, + label: 'repeat label/control at 1x', + ); + }); + + for (final (system, app, scaleLabel) in rowsScales) { + testWidgets('label and control stay on the card - $scaleLabel', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget(_reminderSheet(system: system, app: app)); + await tester.pumpAndSettle(); + + expectNoLayoutError( + tester, + label: 'reminder sheet $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ignoreAlso: segmentedControlLayoutErrors, + ); + + final label = find.text('Repeat every'); + expect(label, findsOneWidget); + expectStaticLabelFullyPainted( + tester, + label, + label: 'repeat label ($scaleLabel)', + ); + expectPaintedInside(tester, label, label: 'repeat label ($scaleLabel)'); + + // The control keeps its own size and must remain on the sheet. + final control = find.text('7 days'); + expect(control, findsOneWidget); + expectStaticLabelFullyPainted( + tester, + control, + label: 'control ($scaleLabel)', + ); + expectPaintedInside(tester, control, label: 'control ($scaleLabel)'); + + // The "Time" row is a second label/control pair of the same shape. + expectPaintedInside( + tester, + find.text('Time'), + label: 'time label ($scaleLabel)', + ); + expectPaintedInside( + tester, + find.text('9:00 AM'), + label: 'time control ($scaleLabel)', + ); + }); + } + + testWidgets('RTL keeps the label and control on the card at 3.375x', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _reminderSheet( + system: 2.25, + app: 1.5, + textDirection: TextDirection.rtl, + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError( + tester, + label: 'reminder sheet rtl 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ignoreAlso: segmentedControlLayoutErrors, + ); + for (final text in ['Repeat every', '7 days']) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: text); + expectPaintedInside(tester, finder, label: '$text (rtl 3.375x)'); + } + }); + + testWidgets('R1 wide window where it fits: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_reminderSheet(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + expectNoLayoutError( + tester, + label: 'reminder sheet wide 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ignoreAlso: segmentedControlLayoutErrors, + ); + expectOnTheSameLine( + tester, + find.text('Repeat every'), + find.text('7 days'), + label: 'repeat label/control (wide 3.375x)', + ); + }); + }); +} diff --git a/test/text_scale_fixes/rows/crypto_storage_debug_rows_text_scale_test.dart b/test/text_scale_fixes/rows/crypto_storage_debug_rows_text_scale_test.dart new file mode 100644 index 000000000..623f09eb4 --- /dev/null +++ b/test/text_scale_fixes/rows/crypto_storage_debug_rows_text_scale_test.dart @@ -0,0 +1,307 @@ +// The crypto-storage debug screen's engine-state label/value rows at large text sizes. +// +// `_EngineStateCard` builds each row as +// `Row(spaceBetween, [Text(label), Text(value, monospace)])` with neither side +// flexible, inside `PrismSurface`'s `ClipRRect`, so at 3.375x the pair exceeds the +// card and the value is cut off at the card edge. +// +// HERMETIC GUARDS - every external read on this screen is explicitly taken over, +// none of them is left to "it throws in tests": +// 1. secure storage: `FlutterSecureStorage.setMockInitialValues` swaps in the +// plugin's own in-memory `TestFlutterSecureStoragePlatform`. No keychain, no +// real key material; the entries are placeholders. +// 2. filesystem: the `plugins.flutter.io/path_provider` channel is answered with +// `null`, so `getApplicationDocumentsDirectory()` fails before any `File` is +// constructed (that is the exact path `CryptoBootLog._file()` takes: +// documents dir -> `File.readAsString`). Nothing under the real home is read +// or written; `CryptoBootLog.readAll()` turns the failure into an empty log. +// The call is counted so the test can assert the denial was really used. +// 3. runtime DEK wrapper: the `com.prism.prism_plurality/runtime_dek_wrap` channel +// answers `getRuntimeDekDiagnostics` with a synthetic map, so +// `DeviceBoundRuntimeDekStore().getDiagnostics()` never reaches native code. +// 4. FFI: `prismSyncHandleProvider` is overridden with a notifier that has no +// handle, so `ffi.isUnlocked` is not called at all. +// 5. the database: `databaseProvider` throws, so an accidental DB read fails. +// All mocks are torn down in `tearDown`, and the tests do not use `runAsync`. +// +// The rows must stay inside their card at 3.375x, where the pair used to overflow and the +// value was clipped at the card edge, and must keep their inline geometry wherever they +// fit. +// +// This screen's top bar has a title and a subtitle, so its constant-height bar can +// overflow at large text (`prism_top_bar.dart`). Those errors can be ignored by cause only +// through the opt-in switch in the harness, and this test then proves nothing about the +// bar. + +import 'dart:io' show Platform; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:prism_sync/generated/api.dart' as ffi; + +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/sync/prism_sync_providers.dart'; +import 'package:prism_plurality/features/settings/views/crypto_storage_debug_screen.dart'; +import 'package:prism_plurality/shared/widgets/prism_loading_state.dart'; +import 'package:prism_plurality/shared/widgets/prism_section_card.dart'; +import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; + +import 'rows_text_scale_harness.dart'; + +/// `path_provider`'s channel: denying it keeps every file read inside the test. +const _pathProviderChannel = MethodChannel('plugins.flutter.io/path_provider'); + +/// The app's runtime-DEK wrapper channel (native key wrapping + diagnostics). +const _runtimeDekChannel = MethodChannel( + 'com.prism.prism_plurality/runtime_dek_wrap', +); + +/// No engine handle at all: the screen then skips every FFI call. +class _NoHandleNotifier extends PrismSyncHandleNotifier { + @override + Future build() async => null; +} + +Widget _cryptoScreen({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, +}) { + return ProviderScope( + overrides: [ + databaseProvider.overrideWith((ref) { + throw StateError('crypto debug row tests must not open a database'); + }), + prismSyncHandleProvider.overrideWith(_NoHandleNotifier.new), + ], + child: rowsApp( + const CryptoStorageDebugScreen(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +void main() { + final channelCalls = []; + // Any channel method that is not one the screen is expected to use. Returning a + // value for an unknown method would make a brand-new read look legitimate, so it is + // recorded here and asserted empty instead. + final unexpectedChannelCalls = []; + + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + setUp(() { + channelCalls.clear(); + unexpectedChannelCalls.clear(); + + // 1) Secure storage: the plugin's in-memory test platform. Placeholder values + // only - no real key, and the platform keychain is never touched. + FlutterSecureStorage.setMockInitialValues({ + 'prism_sync.db_key': 'QUJDRA==', + 'prism_sync.sync_db_key': 'RUZHSA==', + }); + + // 2) Filesystem: deny it. `path_provider` returns null, so + // `getApplicationDocumentsDirectory()` throws before `CryptoBootLog._file()` + // can build a `File`, and `readAll()` reports an empty history. + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_pathProviderChannel, (call) async { + channelCalls.add('path_provider/${call.method}'); + if (call.method != 'getApplicationDocumentsDirectory') { + unexpectedChannelCalls.add('path_provider/${call.method}'); + } + return null; + }); + + // 3) Runtime DEK wrapper: synthetic diagnostics, never native code. + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_runtimeDekChannel, (call) async { + channelCalls.add('runtime_dek/${call.method}'); + if (call.method != 'getRuntimeDekDiagnostics') { + unexpectedChannelCalls.add('runtime_dek/${call.method}'); + } + if (call.method == 'getRuntimeDekDiagnostics') { + return { + 'provider': 'synthetic', + 'key_security': {'level': 'synthetic'}, + }; + } + return null; + }); + }); + + tearDown(() { + FlutterSecureStorage.setMockInitialValues({}); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_pathProviderChannel, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_runtimeDekChannel, null); + }); + + /// Waits for the engine-state rows *and* for the loading indicators to clear, then + /// proves the fixture really served data. Deliberately does not look at + /// `hasRunningAnimations`: ambient animations on this screen (spinners, animated + /// containers) keep that true even when every read has resolved, so it is not a + /// read-pending signal. + Future waitForEngineRows( + WidgetTester tester, { + required String label, + }) async { + await pumpUntilFound(tester, find.text('Handle'), label: 'engine rows'); + await pumpUntilGone( + tester, + find.byType(PrismLoadingState), + label: '$label: loading state', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: '$label: spinner', + ); + // No diagnostic channel method beyond the ones this screen is known to use: an + // unknown call is recorded by the handlers above and fails here rather than being + // answered with a plausible null. + expect( + unexpectedChannelCalls, + isEmpty, + reason: + '$label: unexpected diagnostic channel call(s): ' + '${unexpectedChannelCalls.join(', ')}', + ); + // The filesystem denial really was consulted (CryptoBootLog.readAll at mount). + expect( + channelCalls, + contains('path_provider/getApplicationDocumentsDirectory'), + reason: '$label: the filesystem guard was never exercised', + ); + expect( + channelCalls.any((call) => call.startsWith('path_provider/get')), + isTrue, + ); + // No other path_provider method may have been reached. + expect( + channelCalls.where( + (call) => + call.startsWith('path_provider/') && + call != 'path_provider/getApplicationDocumentsDirectory', + ), + isEmpty, + reason: '$label: an unexpected path_provider method was requested', + ); + // (The synthetic entries are asserted separately, after scrolling to them - at a + // wide window the keychain card sits below the fold and is built lazily.) + // The runtime-DEK channel is only consulted off Linux; assert it was taken + // over where the screen would reach native code. + if (!Platform.isLinux) { + expect( + channelCalls, + contains('runtime_dek/getRuntimeDekDiagnostics'), + reason: '$label: the runtime-DEK guard was not exercised', + ); + } + } + + /// Scrolls to the keychain card and proves the in-memory secure-storage guard + /// actually served synthetic entries (the card is lazy and may start off-screen). + Future expectSyntheticKeyEntries(WidgetTester tester) async { + final entry = find.text('db_key'); + if (entry.evaluate().isEmpty) { + await tester.scrollUntilVisible( + entry, + 300, + scrollable: find.byType(Scrollable).first, + ); + } + await tester.pumpAndSettle(); + expect( + entry, + findsWidgets, + reason: 'the in-memory secure-storage guard was not exercised', + ); + } + + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets( + 'engine-state rows stay inside their card - $scaleLabel / $fontFamily', + (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _cryptoScreen(system: system, app: app, fontFamily: fontFamily), + ); + await waitForEngineRows(tester, label: 'crypto $scaleLabel'); + await expectSyntheticKeyEntries(tester); + + expectNoLayoutError( + tester, + label: 'crypto debug $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + + final handleLabel = find.text('Handle'); + expect(handleLabel, findsOneWidget); + expectStaticLabelFullyPainted( + tester, + handleLabel, + label: 'handle label ($scaleLabel)', + ); + + final cards = find.byType(PrismSectionCard); + expect(cards, findsWidgets); + for (var i = 0; i < cards.evaluate().length; i++) { + expectDescendantTextInside( + tester, + cards.at(i), + label: 'crypto card $i ($scaleLabel)', + ); + } + }, + ); + } + } + + testWidgets('wide window where the rows fit: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_cryptoScreen(system: 2.25, app: 1.5)); + await waitForEngineRows(tester, label: 'crypto wide 3.375x'); + await expectSyntheticKeyEntries(tester); + // Scrolling to the keychain entries culls the engine card at a wide window: bring + // that row back into view before the inline-geometry checks below. + await tester.scrollUntilVisible( + find.text('Unlocked'), + -300, + scrollable: find.byType(Scrollable).first, + ); + await tester.pumpAndSettle(); + + expectNoLayoutError( + tester, + label: 'crypto debug wide 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + expectStaticLabelFullyPainted( + tester, + find.text('Unlocked'), + label: 'unlocked label (wide 3.375x)', + ); + expectOnTheSameLine( + tester, + find.text('Unlocked'), + find.text('unknown'), + label: 'label/value (wide 3.375x)', + ); + }); +} diff --git a/test/text_scale_fixes/rows/data_browser_rows_text_scale_test.dart b/test/text_scale_fixes/rows/data_browser_rows_text_scale_test.dart new file mode 100644 index 000000000..4b1361c54 --- /dev/null +++ b/test/text_scale_fixes/rows/data_browser_rows_text_scale_test.dart @@ -0,0 +1,192 @@ +// The data-browser record rows' subtitle at large text sizes. +// +// `_ExpandableRecord` passes a subtitle of +// `Row([Text(truncatedId, monospace), if secondary: Text(secondary)])` to +// `PrismListRow`. The subtitle sits in a **bounded** column, but that bounds the +// Row, not its children: both `Text`s are non-flex, so each takes its intrinsic +// width and the second one paints past the row (and past the card edge at +// 320dp). The monospace id alone is ~11 characters at fontSize 11, which is +// already wider than the subtitle at 3.375x even when the secondary field is +// empty. +// +// Hermetic pump: `memberRepositoryProvider` is overridden with the repo's +// existing `FakeMemberRepository` seeded with synthetic members, the terminology +// provider is fixed, and `databaseProvider` throws if anything reaches for the +// real database. No network, no real storage. +// +// The subtitle must stay inside its row at 3.375x, where the non-flex id and secondary +// field used to overflow it, and keep its inline geometry wherever both fit. +// +// The screen also renders the five-tab table selector; an overflow inside that control +// fails this test too, so read the failure location before attributing it to the rows. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; +import 'package:prism_plurality/features/settings/views/data_browser_screen.dart'; +import 'package:prism_plurality/shared/widgets/prism_list_row.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'rows_text_scale_harness.dart'; + +const _terminology = ( + term: SystemTerminology.headmates, + customSingular: null, + customPlural: null, + useEnglish: false, +); + +/// `_ExpandableRecord` truncates the id to its first eight characters. +const _shortMemberId = 'member-alpha-001'; +const _shortMemberTruncatedId = 'member-a...'; + +/// A long secondary field (pronouns) is legal user data. +const _longPronouns = + 'they them their theirs themself she her hers herself he him his'; + +/// Counts `getAllMembers` calls so the test can prove the rows came from this fake +/// and not from the (throwing) real repository. +class _CountingMemberRepository extends FakeMemberRepository { + int getAllMembersCalls = 0; + + @override + Future> getAllMembers() { + getAllMembersCalls++; + return super.getAllMembers(); + } +} + +late _CountingMemberRepository _repo; + +Widget _dataBrowser({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, +}) { + final repo = _CountingMemberRepository() + ..seed([ + Member(id: _shortMemberId, name: 'Alice', createdAt: DateTime.utc(2024)), + Member( + id: 'member-beta-002', + name: 'Bob', + pronouns: _longPronouns, + createdAt: DateTime.utc(2024, 1, 2), + ), + ]); + _repo = repo; + return ProviderScope( + overrides: [ + // No database is opened: the rows come from the counted fake below, and an + // accidental read through the real repository fails loudly. + databaseProvider.overrideWith((ref) { + throw StateError('data browser row tests must not open a database'); + }), + memberRepositoryProvider.overrideWithValue(repo), + terminologySettingProvider.overrideWith((ref) => _terminology), + ], + child: rowsApp( + const DataBrowserScreen(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets('record rows keep their subtitle inside the row - ' + '$scaleLabel / $fontFamily', (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _dataBrowser(system: system, app: app, fontFamily: fontFamily), + ); + await pumpUntilFound( + tester, + find.text(_shortMemberTruncatedId), + label: 'record rows', + ); + + expectNoLayoutError( + tester, + label: 'data browser $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ignoreAlso: segmentedControlLayoutErrors, + ); + + // The truncated monospace id is the first subtitle child; it alone can + // outgrow the subtitle at a large text size. + // The guarded fake repository really produced these rows. + expect( + _repo.getAllMembersCalls, + greaterThan(0), + reason: 'the record rows must come from the fake repository', + ); + + final id = find.text(_shortMemberTruncatedId); + expect(id, findsOneWidget); + expectPaintedInside(tester, id, label: 'record id ($scaleLabel)'); + + final rows = find.byType(PrismListRow); + expect(rows, findsWidgets); + for (var i = 0; i < rows.evaluate().length; i++) { + expectDescendantTextInside( + tester, + rows.at(i), + label: 'record row $i ($scaleLabel)', + ); + } + + // The long secondary field must not escape the row either. + final pronouns = find.text(_longPronouns); + if (pronouns.evaluate().isNotEmpty) { + expectPaintedInside( + tester, + pronouns, + label: 'record secondary field ($scaleLabel)', + ); + } + }); + } + } + + testWidgets('wide window where the row fits: one line, nothing reflowed (' + 'control)', (tester) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_dataBrowser(system: 2.25, app: 1.5)); + await pumpUntilFound( + tester, + find.text(_shortMemberTruncatedId), + label: 'record rows', + ); + + expectNoLayoutError( + tester, + label: 'data browser wide 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ignoreAlso: segmentedControlLayoutErrors, + ); + final id = find.text(_shortMemberTruncatedId); + expectPaintedInside(tester, id, label: 'record id (wide 3.375x)'); + expectDescendantTextInside( + tester, + find.byType(PrismListRow).first, + label: 'record row (wide 3.375x)', + ); + }); +} diff --git a/test/text_scale_fixes/rows/member_detail_stats_text_scale_test.dart b/test/text_scale_fixes/rows/member_detail_stats_text_scale_test.dart new file mode 100644 index 000000000..a0c6c1347 --- /dev/null +++ b/test/text_scale_fixes/rows/member_detail_stats_text_scale_test.dart @@ -0,0 +1,272 @@ +// The member profile's "Stats" card at large text sizes. +// +// `_StatRow` is `Row(spaceBetween, [Text(label), Text(value)])` with both sides +// unbounded, so at 2.25-3.375x the pair ran past the card that holds it. What is checked +// is that every paragraph inside each section card paints inside that card and that no +// layout error is reported; the test does not prescribe how the row should be laid out. +// +// The whole MemberDetailScreen is pumped, so an overflow on another part of that screen +// fails this test too - read the failure location before attributing it to the card. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/domain/models/fronting_session.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/member_board_post.dart'; +import 'package:prism_plurality/domain/models/member_group.dart'; +import 'package:prism_plurality/domain/models/member_group_entry.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/boards/providers/board_posts_providers.dart'; +import 'package:prism_plurality/features/fronting/providers/fronting_providers.dart'; +import 'package:prism_plurality/features/fronting/providers/member_fronting_history_providers.dart'; +import 'package:prism_plurality/features/fronting/services/derive_periods.dart'; +import 'package:prism_plurality/features/members/navigation/member_navigation_branch.dart'; +import 'package:prism_plurality/features/members/providers/custom_fields_providers.dart'; +import 'package:prism_plurality/features/members/providers/member_groups_providers.dart'; +import 'package:prism_plurality/features/members/providers/member_stats_providers.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; +import 'package:prism_plurality/features/members/providers/notes_providers.dart'; +import 'package:prism_plurality/features/members/views/member_detail_screen.dart'; +import 'package:prism_plurality/features/pluralkit/models/pk_sync_config.dart'; +import 'package:prism_plurality/features/pluralkit/providers/pluralkit_providers.dart'; +import 'package:prism_plurality/features/pluralkit/services/pluralkit_sync_service.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/shared/widgets/prism_section_card.dart'; +import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'rows_text_scale_harness.dart'; + +final _now = DateTime(2026, 5, 1, 12); + +final _alice = Member( + id: 'alice', + name: 'Alice', + createdAt: _now.subtract(const Duration(days: 40)), + isActive: true, +); + +Widget _memberDetail({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + Duration totalDuration = const Duration(hours: 40, minutes: 20), + bool longValues = false, +}) { + final appPrefs = FakeAppPreferenceRepository(); + addTearDown(appPrefs.close); + + return ProviderScope( + overrides: [ + // No test may open the real database. + databaseProvider.overrideWith((ref) { + throw StateError('member detail row tests must not open a database'); + }), + systemSettingsProvider.overrideWith( + (ref) => Stream.value( + const SystemSettings(notesEnabled: false, boardsEnabled: false), + ), + ), + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + memberByIdProvider(_alice.id).overrideWith((ref) => Stream.value(_alice)), + allMembersProvider.overrideWith((ref) => Stream.value([_alice])), + activeMembersProvider.overrideWith((ref) => Stream.value([_alice])), + activeMemberListProvider.overrideWith((ref) => Stream.value([_alice])), + activeSessionsProvider.overrideWith( + (ref) => Stream.value(const []), + ), + // Three stat rows, so the label/value pairs under test all render. + memberFrontingStatsProvider(_alice.id).overrideWith( + (ref) async => MemberFrontingStats( + // A four-digit session count and a many-day duration are legal values; + // the row must hold them without letting either side escape the card. + totalSessions: longValues ? 12345 : 12, + totalDuration: totalDuration, + lastFronted: _now.subtract(const Duration(hours: 3)), + ), + ), + memberRecentSessionsProvider( + _alice.id, + ).overrideWith((ref) async => []), + memberFrontingHistoryProvider.overrideWith( + (ref, requestedMemberId) => const AsyncValue.data( + MemberFrontingHistoryData( + periods: [], + targetSessions: [], + hasMore: false, + ), + ), + ), + memberConversationActivityProvider( + _alice.id, + ).overrideWith((ref) async => const []), + memberConversationPreviewActivityProvider( + _alice.id, + ).overrideWith((ref) async => const []), + recentMemberNotesProvider( + _alice.id, + ).overrideWith((ref) => Stream.value(const [])), + memberBoardSectionProvider(_alice.id).overrideWith( + (ref) => Stream.value( + const MemberBoardSection( + publicPosts: [], + totalPublic: 0, + ), + ), + ), + memberGroupsProvider( + _alice.id, + ).overrideWith((ref) => Stream.value(const [])), + allGroupsProvider.overrideWith( + (ref) => Stream.value(const []), + ), + allGroupEntriesProvider.overrideWith( + (ref) => Stream.value(const []), + ), + customFieldsProvider.overrideWith((ref) => Stream.value(const [])), + pluralKitSyncProvider.overrideWith( + () => _FakePluralKitSyncNotifier( + const PluralKitSyncState(isConnected: false), + ), + ), + pkSyncDirectionProvider.overrideWith( + () => _FakePkSyncDirectionNotifier(PkSyncDirection.pullOnly), + ), + memberCustomFieldValuesProvider( + _alice.id, + ).overrideWith((ref) => Stream.value(const [])), + ], + child: rowsApp( + const SizedBox.shrink(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + routerConfig: GoRouter( + initialLocation: '/members/${_alice.id}', + routes: [ + GoRoute( + path: '/members/:id', + builder: (context, state) => MemberDetailScreen( + memberId: state.pathParameters['id']!, + branch: MemberNavigationBranch.members, + ), + ), + ], + ), + ), + ); +} + +class _FakePluralKitSyncNotifier extends PluralKitSyncNotifier { + _FakePluralKitSyncNotifier(this._state); + + final PluralKitSyncState _state; + + @override + PluralKitSyncState build() => _state; +} + +class _FakePkSyncDirectionNotifier extends PkSyncDirectionNotifier { + _FakePkSyncDirectionNotifier(this._direction); + + final PkSyncDirection _direction; + + @override + PkSyncDirection build() => _direction; +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets('every profile section keeps its own text inside its card - ' + '$scaleLabel / $fontFamily', (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _memberDetail(system: system, app: app, fontFamily: fontFamily), + ); + await pumpUntilFound( + tester, + find.byType(PrismSectionCard), + label: 'the profile sections', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'profile loading', + ); + + expectNoLayoutError( + tester, + label: 'member detail $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + + final cards = find.byType(PrismSectionCard); + expect(cards, findsWidgets, reason: 'the stats card should render'); + for (var i = 0; i < cards.evaluate().length; i++) { + expectDescendantTextInside( + tester, + cards.at(i), + label: 'member detail card $i ($scaleLabel)', + ); + } + }); + } + } + + // A long value must not be able to escape the card either: a "flexible label + + // unbounded intrinsic value" row survives the short counts above and fails + // here, which is why the fix has to let either side take its own line. + testWidgets( + 'long session count and duration stay inside the card at 3.375x', + (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _memberDetail( + system: 2.25, + app: 1.5, + longValues: true, + totalDuration: const Duration(hours: 98765, minutes: 40), + ), + ); + await pumpUntilFound( + tester, + find.byType(PrismSectionCard), + label: 'the profile sections', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'profile loading', + ); + + expectNoLayoutError( + tester, + label: 'member detail long values 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + final cards = find.byType(PrismSectionCard); + expect(cards, findsWidgets); + for (var i = 0; i < cards.evaluate().length; i++) { + expectDescendantTextInside( + tester, + cards.at(i), + label: 'long-value card $i (3.375x)', + ); + } + }, + ); +} diff --git a/test/text_scale_fixes/rows/ranking_and_navigation_rows_text_scale_test.dart b/test/text_scale_fixes/rows/ranking_and_navigation_rows_text_scale_test.dart new file mode 100644 index 000000000..952b58b29 --- /dev/null +++ b/test/text_scale_fixes/rows/ranking_and_navigation_rows_text_scale_test.dart @@ -0,0 +1,500 @@ +// The ranking chart's slot bounds and the navigation editor's rows at large text sizes. +// +// Chart: it measures every label with the ambient scaler and then clamped the result to +// a constant 88dp ceiling, so the measurement was discarded above ~1.5x and names were +// ellipsised although the chart's own doc promises "labels never wrap or clip". A +// control keeps the intentional ceiling: an extreme name may not inflate every column. +// +// Navigation editor: a reorderable row holds up to three 44dp actions plus a drag handle +// in a non-flex trailing column (~156dp), and the disabled rows capped their +// "Enable in Features" hint at 104dp with two lines and an ellipsis. The checks are that +// the hint is not ellipsised and that each row action keeps a 44dp target inside the +// window, with the completion/detail callbacks still firing through the real widget. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/router/app_routes.dart'; +import 'package:prism_plurality/domain/models/fronting_analytics.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/members/providers/members_batch_provider.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; +import 'package:prism_plurality/features/settings/widgets/member_ranking_chart.dart'; +import 'package:prism_plurality/features/settings/widgets/navigation_layout_editor.dart'; +import 'package:prism_plurality/shared/theme/app_icons.dart'; +import 'package:prism_plurality/shared/widgets/member_avatar.dart'; + +import 'rows_text_scale_harness.dart'; + +const _terminology = ( + term: SystemTerminology.headmates, + customSingular: null, + customPlural: null, + useEnglish: false, +); + +const _flags = ( + chat: true, + polls: true, + habits: false, + sleep: true, + notes: false, + reminders: true, + boards: false, +); + +MemberAnalytics _stat(String id, int totalMinutes, double pct) => + MemberAnalytics( + memberId: id, + totalTime: Duration(minutes: totalMinutes), + percentageOfTotal: pct, + sessionCount: 1, + averageDuration: Duration(minutes: totalMinutes), + medianDuration: Duration(minutes: totalMinutes), + shortestSession: Duration(minutes: totalMinutes), + longestSession: Duration(minutes: totalMinutes), + timeOfDayBreakdown: const {}, + ); + +Member _member(String id, String name) => + Member(id: id, name: name, createdAt: DateTime(2026)); + +Widget _chart({ + required double system, + required double app, + required List members, + required List stats, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, +}) { + return ProviderScope( + overrides: [ + membersByIdsProvider.overrideWith( + (ref, idsKey) => Stream.value({for (final m in members) m.id: m}), + ), + terminologySettingProvider.overrideWith((ref) => _terminology), + ], + child: rowsApp( + Scaffold( + body: SingleChildScrollView( + child: MemberRankingChart(memberStats: stats), + ), + ), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +List _enabledTabs() => [ + for (final tab in appShellTabs) + if (tab.isEnabled(_flags)) tab, +]; + +Widget _editor({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + void Function(List, List)? onLayoutChanged, +}) { + final enabled = _enabledTabs(); + return rowsApp( + Scaffold( + body: SingleChildScrollView( + child: NavigationLayoutEditor( + primaryTabs: enabled.take(4).toList(), + overflowTabs: enabled.skip(4).toList(), + flags: _flags, + terminologyPlural: 'headmates', + onLayoutChanged: onLayoutChanged ?? (primary, overflow) {}, + ), + ), + ), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ); +} + +/// Editor harness that keeps the lists it is given back, so a row action can be +/// proven to run its callback through the real widget. +class _EditorHarness extends StatefulWidget { + const _EditorHarness(); + + @override + State<_EditorHarness> createState() => _EditorHarnessState(); +} + +class _EditorHarnessState extends State<_EditorHarness> { + late List _primary; + late List _overflow; + + @override + void initState() { + super.initState(); + final enabled = _enabledTabs(); + _primary = enabled.take(4).toList(); + _overflow = enabled.skip(4).toList(); + } + + @override + Widget build(BuildContext context) { + return NavigationLayoutEditor( + primaryTabs: _primary, + overflowTabs: _overflow, + flags: _flags, + terminologyPlural: 'headmates', + onLayoutChanged: (primary, overflow) => setState(() { + _primary = primary; + _overflow = overflow; + }), + ); + } +} + +Finder _slot(String id) => find.byKey(ValueKey('member_ranking_slot_$id')); + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + group('ST3 ranking-chart slot bounds', () { + testWidgets('default text keeps the 40-88dp slot bounds', (tester) async { + useWindow(tester, phoneWindow); + await tester.pumpWidget( + _chart( + system: 1, + app: 1, + stats: [_stat('a', 600, 60.0), _stat('b', 300, 40.0)], + members: [_member('a', 'Alice'), _member('b', 'Bob')], + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'ranking chart at 1x'); + final slotWidth = tester.getSize(_slot('a')).width; + expect(slotWidth, greaterThanOrEqualTo(40)); + expect(slotWidth, lessThanOrEqualTo(88)); + expectHonoursSingleLineWidth( + tester, + find.text('Alice'), + label: 'Alice at 1x', + ); + }); + + testWidgets('at 0.5x the slot keeps its floor so the avatar still fits (' + 'control)', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _chart( + system: 1, + app: 0.5, + stats: [_stat('a', 600, 100.0)], + members: [_member('a', 'Al')], + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'ranking chart at 0.5x'); + + // The slot bounds do not shrink with the text preference: the avatar inside a + // slot is a fixed 24dp and needs its breathing room, so a short name still gets + // the original 40dp floor rather than a 20dp box. + final slotWidth = tester.getSize(_slot('a')).width; + expect(slotWidth, greaterThanOrEqualTo(40)); + expect(slotWidth, lessThanOrEqualTo(88)); + + // The text itself still honours the 0.5x preference: the chart's slot is at + // least as wide as the name needs on one line at that requested size. + expectHonoursSingleLineWidth( + tester, + find.text('Al'), + label: 'name at 0.5x', + ); + // ...and the avatar is painted inside the slot. + final avatar = find.descendant( + of: _slot('a'), + matching: find.byType(MemberAvatar), + ); + expect(avatar, findsOneWidget); + expect( + tester.getSize(avatar).width, + lessThanOrEqualTo(slotWidth), + reason: 'the avatar must fit the slot it is given', + ); + }); + + for (final (system, app, scaleLabel) in [ + (1.5, 1.0, 'large text'), + (2.25, 1.5, 'system 225% x Prism 150% = 3.375x'), + ]) { + // The chart's own contract: the slot is measured from the widest visible name + // "so labels never wrap or clip", while the intentional ceiling still stops one + // extreme name from inflating every column. What is checked here is that the + // measured width is honoured - not a general "no ellipsis" rule for user names. + testWidgets('the chart honours its measured name width - $scaleLabel', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _chart( + system: system, + app: app, + stats: [_stat('a', 600, 60.0), _stat('b', 300, 40.0)], + // ~117dp at 1.5x and ~234dp at 3.375x: the chart measures exactly + // this width for its slot, so a 13-character name is the ordinary + // case the slot width exists for. + members: [_member('a', 'Cassandra Joy'), _member('b', 'Bob')], + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'ranking chart $scaleLabel'); + final name = find.text('Cassandra Joy'); + expect(name, findsOneWidget); + expectHonoursSingleLineWidth( + tester, + name, + label: 'Cassandra Joy ($scaleLabel)', + ); + // The chart lives in the page's scrollable: bring the slot into view before + // asserting window containment (at max scale the second row is below the fold). + await tester.ensureVisible(name); + await tester.pumpAndSettle(); + expectPaintedInside(tester, name, label: 'Cassandra Joy ($scaleLabel)'); + }); + } + + testWidgets('the extreme-name ceiling is kept (control)', (tester) async { + useWindow(tester, compactPhone); + final longName = 'A' * 200; + await tester.pumpWidget( + _chart( + system: 2.25, + app: 1.5, + stats: [_stat('a', 600, 100.0)], + members: [_member('a', longName)], + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'ranking chart long name'); + // Whatever the bounds become, one 200-character name may not inflate the + // column without limit; it is still ellipsised rather than allowed to grow. + expect(tester.getSize(_slot('a')).width, lessThanOrEqualTo(88 * 3.375)); + expect( + paragraphOf(tester, find.text(longName)).didExceedMaxLines, + isTrue, + reason: 'the ceiling must still ellipsise an extreme name', + ); + }); + + testWidgets('tapping a bar still toggles every label (control)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _chart( + system: 2.25, + app: 1.5, + stats: [_stat('a', 600, 60.0), _stat('b', 300, 40.0)], + members: [_member('a', 'Alice'), _member('b', 'Bob')], + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('10h'), findsOneWidget); + await tester.tap(_slot('a')); + await tester.pumpAndSettle(); + expect(find.text('60%'), findsOneWidget); + expect(find.text('10h'), findsNothing); + expect( + tester.widget(find.byType(ListView)).scrollDirection, + Axis.horizontal, + ); + }); + + testWidgets('a non-linear scaler does not break the chart', (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _chart( + system: 1, + app: 1, + scalerOverride: const NonlinearTextScaler(), + stats: [_stat('a', 600, 100.0)], + members: [_member('a', 'Alexandra')], + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'ranking chart nonlinear'); + // labelSmall is 11pt: the nonlinear scaler triples it, so the slot is sized + // from the measured name and must hold a 9-character one. + expectHonoursSingleLineWidth( + tester, + find.text('Alexandra'), + label: 'Alexandra (nonlinear)', + ); + }); + }); + + group('ST4 navigation-editor rows', () { + testWidgets( + 'at the default size the actions stay beside the label (control)', + (tester) async { + useWindow(tester, phoneWindow); + await tester.pumpWidget(_editor(system: 1, app: 1)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'navigation editor at 1x'); + + final row = find.byKey(const ValueKey(AppShellTabId.chat)); + expect(row, findsOneWidget); + final label = find.descendant(of: row, matching: find.text('Chat')); + final action = find.descendant( + of: row, + matching: find.byIcon(AppIcons.arrowDownward), + ); + expect(label, findsOneWidget); + expect(action, findsOneWidget); + expectOnTheSameLine(tester, label, action, label: 'label/action at 1x'); + expectStaticLabelFullyPainted(tester, label, label: 'Chat at 1x'); + }, + ); + + testWidgets('a row action still runs its callback (control)', ( + tester, + ) async { + useWindow(tester, phoneWindow); + await tester.pumpWidget( + rowsApp( + const Scaffold(body: SingleChildScrollView(child: _EditorHarness())), + system: 1, + app: 1, + ), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'navigation editor behaviour'); + final row = find.byKey(const ValueKey(AppShellTabId.chat)); + expect(row, findsOneWidget); + final remove = find.descendant( + of: row, + matching: find.byIcon(AppIcons.removeCircleOutline), + ); + expect(remove, findsOneWidget); + await tester.tap(remove); + await tester.pumpAndSettle(); + + // The editor hands the new layout back and re-renders without the removed + // destination. + expect(find.byKey(const ValueKey(AppShellTabId.chat)), findsNothing); + }); + + for (final (system, app, scaleLabel) in [ + (1.5, 1.0, 'large text'), + (2.25, 1.5, 'system 225% x Prism 150% = 3.375x'), + ]) { + for (final fontFamily in rowsFontFamilies) { + testWidgets('destination label and actions stay readable and reachable - ' + '$scaleLabel / $fontFamily', (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _editor(system: system, app: app, fontFamily: fontFamily), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'navigation editor $scaleLabel'); + + // A guard, not a defect report: at the largest size the label box is still + // wide enough, so this only catches a future change that shatters a finite, + // app-authored destination label into one or two characters per line. + for (final id in [AppShellTabId.chat, AppShellTabId.settings]) { + final row = find.byKey(ValueKey(id)); + if (row.evaluate().isEmpty) continue; + final label = find.descendant( + of: row, + matching: find.byType(RichText), + ); + expect(label, findsWidgets, reason: '$id label'); + expectAtMostLines( + tester, + label.first, + maxLines: 2, + label: '$id destination label ($scaleLabel)', + ); + } + + // The disabled rows' hint is finite, app-authored text, and a 104dp / + // two-line box ellipsises it at the largest size in both bundled faces - + // real clipping of a static label, not a style preference. + final hint = find.text('Enable in Features'); + expect(hint, findsWidgets); + for (var i = 0; i < hint.evaluate().length; i++) { + // The editor sits in the page's scrollable; bring each hint into view before + // asserting window containment (it is below the fold at max scale). + await tester.ensureVisible(hint.at(i)); + await tester.pumpAndSettle(); + expectStaticLabelFullyPainted( + tester, + hint.at(i), + label: 'enable hint $i', + ); + expectPaintedInside(tester, hint.at(i), label: 'enable hint $i'); + } + + // Action semantics: every row action keeps a 44dp target, stays on + // screen and keeps its accessible label. + final row = find.byKey(const ValueKey(AppShellTabId.chat)); + final remove = find.descendant( + of: row, + matching: find.byIcon(AppIcons.removeCircleOutline), + ); + expect(remove, findsOneWidget); + final removeRect = tester.getRect(remove); + expect(removeRect.width, greaterThanOrEqualTo(44)); + expect(removeRect.height, greaterThanOrEqualTo(44)); + expectPaintedInside(tester, remove, label: 'remove action'); + expect( + find.byTooltip('Remove from navigation'), + findsWidgets, + reason: '$scaleLabel: the action lost its accessible label', + ); + }); + } + } + + testWidgets('wide window where it fits: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_editor(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'navigation editor wide 3.375x'); + + final row = find.byKey(const ValueKey(AppShellTabId.chat)); + final label = find.descendant(of: row, matching: find.text('Chat')); + final action = find.descendant( + of: row, + matching: find.byIcon(AppIcons.arrowDownward), + ); + expectStaticLabelFullyPainted(tester, label, label: 'Chat (wide 3.375x)'); + // There is room for both, so the label and its actions stay on one line. + expectOnTheSameLine( + tester, + label, + action, + label: 'label/action (wide 3.375x)', + ); + }); + }); +} diff --git a/test/text_scale_fixes/rows/rows_text_scale_harness.dart b/test/text_scale_fixes/rows/rows_text_scale_harness.dart new file mode 100644 index 000000000..f5b193c2c --- /dev/null +++ b/test/text_scale_fixes/rows/rows_text_scale_harness.dart @@ -0,0 +1,511 @@ +// Shared harness for the list-row text-scale regressions: label/value rows (member +// stats, statistics overview, database diagnostics, the crypto engine state), the +// ranking chart's slot bounds, navigation-editor rows, the sleep warning chip, the +// conversation tile, the post header, the board section header and the reminder +// composer's label/control rows. +// +// Text size is composed exactly like `lib/app.dart`: the user's system +// accessibility scaler, then Prism's own font-size preference, delegated per +// font size through [PrismTextScaler]. Nothing is clamped. The real bundled +// faces are loaded so measurements come from the glyphs the app paints. +// +// Every assertion is about painted geometry: a paragraph's own laid-out width +// is compared with the text it would need, and its rect is compared with the +// row/card/window it has to stay inside. An ancestor such as `FittedBox` or a +// squeezed `Row` can leave a paragraph's width intact while painting it +// outside, so both are checked. + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/l10n/app_localizations.dart'; +import 'package:prism_plurality/shared/theme/prism_text_scaler.dart'; + +import '../../helpers/prism_golden.dart' show loadPrismGoldenFonts; + +/// Narrow phone: the narrowest width these rows have to survive. +const Size compactPhone = Size(320, 568); + +/// Ordinary phone width. +const Size phoneWindow = Size(390, 780); + +/// Compact phone width with a tall viewport, for screens whose body is a lazy +/// `ListView`: the horizontal geometry under test is the compact 320dp width, +/// while the height only makes sure every section is actually built. +const Size tallCompactPage = Size(320, 4000); + +/// Wide window (tablet/desktop) used to prove the fix does not depend on a +/// narrow viewport. +const Size wideWindow = Size(1024, 900); + +/// (system accessibility scaler, Prism font-size preference, label). +const List<(double, double, String)> rowsScales = [ + (1.0, 0.5, 'system 100% x Prism 50% = 0.5x'), + (1.0, 1.0, 'default text'), + (1.5, 1.0, 'large text'), + (2.25, 1.5, 'system 225% x Prism 150% = 3.375x'), +]; + +/// The two bundled faces the app ships for body text. +const List rowsFontFamilies = ['Lexend', 'OpenDyslexic']; + +Future loadRowsFonts() => loadPrismGoldenFonts(); + +/// Deterministic window size for one test. +void useWindow(WidgetTester tester, Size size) { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = size; + addTearDown(() { + tester.view.resetPhysicalSize(); + tester.view.resetDevicePixelRatio(); + }); +} + +ThemeData rowsTheme(String fontFamily) => ThemeData( + fontFamily: fontFamily, + fontFamilyFallback: const ['NotoColorEmoji'], +); + +/// MaterialApp that composes the system scaler with Prism's preference exactly +/// like `app.dart`. +Widget rowsApp( + Widget home, { + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + Locale locale = const Locale('en'), + RouterConfig? routerConfig, + TextDirection? textDirection, +}) { + final scaler = + scalerOverride ?? PrismTextScaler(TextScaler.linear(system), app); + Widget builder(BuildContext context, Widget? child) { + final content = MediaQuery( + data: MediaQuery.of(context).copyWith(textScaler: scaler), + child: child ?? const SizedBox.shrink(), + ); + if (textDirection == null) return content; + return Directionality(textDirection: textDirection, child: content); + } + + if (routerConfig != null) { + return MaterialApp.router( + theme: rowsTheme(fontFamily), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en'), Locale('es')], + locale: locale, + routerConfig: routerConfig, + builder: builder, + ); + } + + return MaterialApp( + theme: rowsTheme(fontFamily), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: const [Locale('en'), Locale('es')], + locale: locale, + builder: builder, + home: home, + ); +} + +/// A deliberately nonlinear scaler: no row may assume that one length follows +/// from multiplying another by a single ratio. +class NonlinearTextScaler extends TextScaler { + const NonlinearTextScaler(); + + @override + double scale(double fontSize) => + fontSize <= 14 ? fontSize * 3.0 : fontSize * 1.6; + + @override + // ignore: deprecated_member_use + double get textScaleFactor => 1.0; + + @override + bool operator ==(Object other) => other is NonlinearTextScaler; + + @override + int get hashCode => 0x726f7773; // 'rows' +} + +/// The paragraph that paints [finder]; exactly one must match. +RenderParagraph paragraphOf(WidgetTester tester, Finder finder) { + expect(finder, findsOneWidget); + return tester.renderObject(finder); +} + +/// Height [paragraph] needs at the width it was actually given. +/// +/// Measured through the render object's own intrinsics: `RenderParagraph` keeps a +/// **separate** cached painter for this (`_textIntrinsics`) and re-copies the real +/// one into it on every access - same `InlineSpan` tree, same `maxLines`, same +/// `ellipsis`, locale, strut style and height behaviour - so the measurement can +/// neither disagree with what the paragraph paints nor disturb its layout. In +/// particular an intentionally ellipsised one-line string measures as one line and +/// is not mistaken for vertically clipped text. +double neededHeightAt(RenderParagraph paragraph) => + paragraph.getMaxIntrinsicHeight(paragraph.size.width); + +/// Width [paragraph] needs if none of its text may wrap (the "one line" width). +/// +/// Same intrinsic path as [neededHeightAt], so a mixed `InlineSpan` tree keeps its +/// per-span styles; nothing is flattened to a single `TextStyle`. +double neededSingleLineWidth(RenderParagraph paragraph) => + paragraph.getMaxIntrinsicWidth(double.infinity); + +/// A painter that mirrors [paragraph] exactly, for measurements the render object +/// does not expose (line count). +/// +/// Every property that changes shaping is copied from the paragraph itself, and +/// the text is the paragraph's own `InlineSpan`, so mixed span styles survive. +TextPainter clonedParagraphPainter(RenderParagraph paragraph) { + return TextPainter( + text: paragraph.text, + textAlign: paragraph.textAlign, + textDirection: paragraph.textDirection, + textScaler: paragraph.textScaler, + locale: paragraph.locale, + strutStyle: paragraph.strutStyle, + textWidthBasis: paragraph.textWidthBasis, + textHeightBehavior: paragraph.textHeightBehavior, + maxLines: paragraph.maxLines, + ellipsis: paragraph.overflow == TextOverflow.ellipsis ? '\u2026' : null, + ); +} + +/// Number of lines [paragraph] is actually laid out in. +/// +/// Counted from the layout's own line metrics, using a painter that mirrors the +/// paragraph (see [clonedParagraphPainter]); a one-line ellipsised string counts as +/// one line. +int lineCountOf(RenderParagraph paragraph) { + final painter = clonedParagraphPainter(paragraph) + ..layout(maxWidth: paragraph.size.width); + final lines = painter.computeLineMetrics().length; + painter.dispose(); + return lines; +} + +/// Opt-in switch for the cause filters below, read from the environment at compile +/// time. +/// +/// It exists so a single widget's layout defect can be measured while a *different* +/// surface on the same screen (a fixed-height top bar, a segmented control) is still +/// being fixed. It is unset by default, and when it is unset the filters are `null` and +/// no layout error is ever ignored - a passing run cannot hide a real overflow. +const bool kLayoutBaseline = bool.fromEnvironment('PRISM_LAYOUT_BASELINE'); + +/// Layout errors caused by a fixed-height top or sheet bar (`prism_top_bar.dart`, +/// `prism_sheet.dart`), i.e. a title/subtitle that outgrows a constant bar height. Only +/// ever non-`null` when [kLayoutBaseline] asks for it. +final RegExp? fixedHeightBarLayoutErrors = kLayoutBaseline + ? RegExp(r'prism_(top_bar|sheet)\.dart') + : null; + +/// Layout errors caused by the segmented control (`prism_segmented_control.dart`), i.e. +/// a fixed-height track whose labels outgrow it. Only ever non-`null` when +/// [kLayoutBaseline] asks for it. +final RegExp? segmentedControlLayoutErrors = kLayoutBaseline + ? RegExp(r'prism_segmented_control\.dart') + : null; + +/// Pumps in small steps until [finder] matches, then stops. +/// +/// `pumpAndSettle` cannot be used on a screen that shows a [PrismSpinner]: its +/// `AnimationController.repeat()` never settles, so `pumpAndSettle` reports a +/// timeout even though the widget under test rendered. This waits for the real +/// condition instead (the expected content) and fails with a readable message if +/// it never arrives, which distinguishes "the fixture never produced data" from a +/// geometry failure. +Future pumpUntilFound( + WidgetTester tester, + Finder finder, { + String label = 'content', + Duration timeout = const Duration(seconds: 10), +}) async { + final steps = (timeout.inMilliseconds / 20).ceil(); + for (var i = 0; i < steps; i++) { + if (finder.evaluate().isNotEmpty) return; + await tester.pump(const Duration(milliseconds: 20)); + } + // One last frame so the failure message shows the tree that actually built. + await tester.pump(); + expect( + finder, + findsWidgets, + reason: + '$label did not appear within ${timeout.inSeconds}s of pumped frames - ' + 'the fixture, not the layout, is the likely cause', + ); +} + +/// Pumps in small steps until [finder] matches nothing. +/// +/// The readiness signal for screens whose data arrives asynchronously and whose +/// loading state is animated: a repeating spinner never lets `pumpAndSettle` finish, +/// and "the widget exists" can be true on the very first frame, before the futures +/// resolve. Asserting that the loading indicator is *gone* is both bounded and +/// meaningful. +Future pumpUntilGone( + WidgetTester tester, + Finder finder, { + String label = 'loading indicator', + Duration timeout = const Duration(seconds: 10), +}) async { + final steps = (timeout.inMilliseconds / 20).ceil(); + for (var i = 0; i < steps; i++) { + if (finder.evaluate().isEmpty) return; + await tester.pump(const Duration(milliseconds: 20)); + } + expect( + finder, + findsNothing, + reason: '$label was still on screen after ${timeout.inSeconds}s of pumping', + ); +} + +/// Fails when layout reported a `RenderFlex overflowed` (or any other) error. +/// +/// Drains every pending exception, not just the first: several rows can overflow +/// in one frame, and a leftover would otherwise fail the test at teardown with no +/// useful message. +/// +/// [ignoreCauseMatching] drops errors whose text names a surface owned by another +/// surface. Use it only with a specific file reference (for example a fixed-height +/// top bar), and say so in the test comment: this test +/// then proves nothing about that surface. +void expectNoLayoutError( + WidgetTester tester, { + required String label, + RegExp? ignoreCauseMatching, + RegExp? ignoreAlso, +}) { + bool isIgnored(String text) => + (ignoreCauseMatching?.hasMatch(text) ?? false) || + (ignoreAlso?.hasMatch(text) ?? false); + final patterns = [ignoreCauseMatching, ignoreAlso].nonNulls.toList(); + final errors = []; + final ignored = []; + for ( + Object? error = tester.takeException(); + error != null; + error = tester.takeException() + ) { + final text = error.toString(); + if (isIgnored(text)) { + ignored.add(text.split('\n').first); + continue; + } + errors.add(text.split('\n').first); + } + expect( + errors, + isEmpty, + reason: + '$label: layout reported ${errors.length} error(s): ' + '${errors.join(' | ')}' + '${ignored.isEmpty ? '' : ' (ignored ${ignored.length} from ' + '${patterns.map((p) => p.pattern).join(', ')})'}', + ); +} + +/// Asserts [finder] paints inside [bounds] (defaults to the window). +void expectPaintedInside( + WidgetTester tester, + Finder finder, { + required String label, + Rect? bounds, +}) { + final window = + bounds ?? + Offset.zero & tester.view.physicalSize / tester.view.devicePixelRatio; + final rect = tester.getRect(finder); + expect( + rect.left, + greaterThanOrEqualTo(window.left - 0.5), + reason: '$label: left edge ${rect.left} is outside ${window.left}', + ); + expect( + rect.right, + lessThanOrEqualTo(window.right + 0.5), + reason: '$label: right edge ${rect.right} is outside ${window.right}', + ); + expect( + rect.top, + greaterThanOrEqualTo(window.top - 0.5), + reason: '$label: top edge ${rect.top} is outside ${window.top}', + ); + expect( + rect.bottom, + lessThanOrEqualTo(window.bottom + 0.5), + reason: '$label: bottom edge ${rect.bottom} is outside ${window.bottom}', + ); +} + +/// Asserts every paragraph inside [container] paints inside its rect. +/// +/// A `Row` that overflows still reports its own constrained size, so the +/// overflow shows up in its children instead: a non-flex child keeps its +/// intrinsic width and its rect leaves the container. This walks the painted +/// paragraphs rather than trusting the row's own box. +void expectDescendantTextInside( + WidgetTester tester, + Finder container, { + required String label, +}) { + final containerRect = tester.getRect(container); + final paragraphs = find.descendant( + of: container, + matching: find.byType(RichText), + ); + for (final element in paragraphs.evaluate()) { + final paragraph = element.renderObject! as RenderParagraph; + final rect = paragraph.localToGlobal(Offset.zero) & paragraph.size; + final text = paragraph.text.toPlainText(); + expect( + rect.left, + greaterThanOrEqualTo(containerRect.left - 0.5), + reason: + '$label: "$text" starts outside its container ' + '(${rect.left} < ${containerRect.left})', + ); + expect( + rect.right, + lessThanOrEqualTo(containerRect.right + 0.5), + reason: + '$label: "$text" paints past its container ' + '(${rect.right} > ${containerRect.right})', + ); + } +} + +/// Asserts [finder]'s paragraph is laid out in at most [maxLines] lines. +/// +/// Rule, deliberately narrow: **finite, static label text that the app authors** - +/// a navigation destination name ("Chat", "Settings") - must stay readable as a +/// label instead of being shattered into one or two characters per line behind a +/// row of 44dp controls. +/// +/// It is **not** a general policy. Unbounded user content (conversation titles, +/// member names, note titles) is out of scope: it may ellipsise or wrap freely, and +/// that trade-off is accepted - do not assert against it with this helper. +void expectAtMostLines( + WidgetTester tester, + Finder finder, { + required int maxLines, + required String label, +}) { + final paragraph = paragraphOf(tester, finder); + final lines = lineCountOf(paragraph); + expect( + lines, + lessThanOrEqualTo(maxLines), + reason: + '$label: "${paragraph.text.toPlainText()}" is laid out in $lines line(s); ' + 'at most $maxLines expected for finite label text', + ); +} + +/// Asserts a **static, app-authored label** is painted in full at the requested +/// size: no ellipsis and no vertical clamp. +/// +/// Use this only for text the app itself writes and the user cannot make longer - +/// section labels, row labels, hints, counts, formatted timestamps. For unbounded +/// user content use [expectNotVerticallyClipped] instead. +void expectStaticLabelFullyPainted( + WidgetTester tester, + Finder finder, { + required String label, +}) { + final paragraph = paragraphOf(tester, finder); + expect( + paragraph.didExceedMaxLines, + isFalse, + reason: '$label: "${paragraph.text.toPlainText()}" was ellipsised', + ); + final needed = neededHeightAt(paragraph); + expect( + paragraph.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: "${paragraph.text.toPlainText()}" needs ' + '${needed.toStringAsFixed(1)}px but is laid out at ' + '${paragraph.size.height.toStringAsFixed(1)}px', + ); +} + +/// Asserts a paragraph is not chopped vertically. +/// +/// This is the right check for **user content that is allowed to truncate +/// horizontally** (conversation titles, member names): a single-line ellipsis is +/// accepted, being clipped by a shorter box is not. The comparison uses the +/// paragraph's own `maxLines`/`ellipsis`, so an ellipsised one-liner measures as one +/// line. +void expectNotVerticallyClipped( + WidgetTester tester, + Finder finder, { + required String label, +}) { + final paragraph = paragraphOf(tester, finder); + final needed = neededHeightAt(paragraph); + expect( + paragraph.size.height, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: "${paragraph.text.toPlainText()}" needs ' + '${needed.toStringAsFixed(1)}px at this width but is laid out at ' + '${paragraph.size.height.toStringAsFixed(1)}px', + ); +} + +/// Asserts a single-line paragraph is given at least the width its text needs at +/// the requested size, i.e. its own measured width was honoured. +/// +/// Used for the ranking chart, whose contract is that the slot is sized from the +/// measured name ("labels never wrap or clip"). It says nothing about how the width +/// is won, and it does not treat a name as required to be ellipsis-free elsewhere. +void expectHonoursSingleLineWidth( + WidgetTester tester, + Finder finder, { + required String label, +}) { + final paragraph = paragraphOf(tester, finder); + final needed = neededSingleLineWidth(paragraph); + expect( + paragraph.size.width, + greaterThanOrEqualTo(needed - 0.5), + reason: + '$label: "${paragraph.text.toPlainText()}" is given ' + '${paragraph.size.width.toStringAsFixed(1)}px but needs ' + '${needed.toStringAsFixed(1)}px on one line', + ); +} + +/// Asserts two widgets are laid out beside each other (their rects overlap +/// vertically). Content that fits must not be pushed onto separate lines. +void expectOnTheSameLine( + WidgetTester tester, + Finder a, + Finder b, { + required String label, +}) { + final rectA = tester.getRect(a); + final rectB = tester.getRect(b); + expect( + rectA.top, + lessThan(rectB.bottom), + reason: + '$label: not on the same line - A is ${rectA.top}..${rectA.bottom}, ' + 'B is ${rectB.top}..${rectB.bottom}', + ); + expect( + rectB.top, + lessThan(rectA.bottom), + reason: + '$label: not on the same line - B is ${rectB.top}..${rectB.bottom}, ' + 'A is ${rectA.top}..${rectA.bottom}', + ); +} diff --git a/test/text_scale_fixes/rows/settings_label_value_rows_text_scale_test.dart b/test/text_scale_fixes/rows/settings_label_value_rows_text_scale_test.dart new file mode 100644 index 000000000..caff32d2b --- /dev/null +++ b/test/text_scale_fixes/rows/settings_label_value_rows_text_scale_test.dart @@ -0,0 +1,490 @@ +// Label/value rows on the statistics and database-diagnostics screens, and the +// statistics top-fronters row, at large text sizes. The shared rows are +// `Row(spaceBetween, [Text(label), Text(value)])` with neither side flexible, so both +// keep an intrinsic width and the pair runs past the card; the top-fronters row also put +// the rank numeral in a constant 24dp box and let an un-flexed session count squeeze the +// name away. Each case asserts painted geometry: nothing may leave its card, a rank +// numeral stays on one line, a count stays inside the window, and content that fits stays +// on one line. +// +// These are written as desired-behaviour expectations, not as a description of +// any particular fix. Each assertion names a defect that is visible through the +// real screens: +// +// * a `RenderFlex` overflow (layout error), or +// * a paragraph painting outside the card that must contain it (a non-flex +// `Row` child keeps its intrinsic width and leaves the box), or +// * a paragraph whose box is too narrow to hold its own widest word, or whose +// text had to be ellipsised although it is an ordinary short label. +// +// Expected on the restored prior delivery (source before any fix): +// * 3.375x compact - RED: the statistics, diagnostics and top-fronter rows +// overflow by tens of dp, the count paints past the card, "#1" is clipped by +// its fixed 24dp box and the name column collapses. +// * 1.5x - RED for the rank numeral only ("#1" needs ~34dp in a 24dp box). +// * 0.5x / 1x - GREEN: everything fits; these are controls. +// * 3.375x on a 1024dp window - GREEN: content fits, so nothing may be +// reflowed; also a control against a fix that stacks on font size alone. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/core/database/database_provider.dart' + show databaseProvider; +import 'package:prism_plurality/core/database/database_providers.dart'; +import 'package:prism_plurality/core/services/database_health_providers.dart'; +import 'package:prism_plurality/core/sync/prism_sync_providers.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/domain/models/system_settings.dart'; +import 'package:prism_plurality/features/settings/providers/database_diagnostics_providers.dart'; +import 'package:prism_plurality/features/settings/providers/settings_providers.dart'; +import 'package:prism_plurality/features/settings/providers/statistics_providers.dart'; +import 'package:prism_plurality/features/settings/providers/terminology_provider.dart'; +import 'package:prism_plurality/features/settings/views/database_diagnostics_screen.dart'; +import 'package:prism_plurality/features/settings/views/statistics_screen.dart'; +import 'package:prism_plurality/shared/widgets/prism_section_card.dart'; +import 'package:prism_plurality/shared/widgets/prism_spinner.dart'; + +import '../../helpers/fake_repositories.dart'; +import 'rows_text_scale_harness.dart'; + +final _alice = Member(id: 'm1', name: 'Alice', createdAt: DateTime.utc(2024)); +final _bob = Member(id: 'm2', name: 'Bob', createdAt: DateTime.utc(2024, 1, 2)); + +const _terminology = ( + term: SystemTerminology.headmates, + customSingular: null, + customPlural: null, + useEnglish: false, +); + +Widget _statisticsScreen({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + Locale locale = const Locale('en'), + TextDirection? textDirection, + List> topFronters = const [], +}) { + final appPrefs = FakeAppPreferenceRepository(); + addTearDown(appPrefs.close); + return ProviderScope( + overrides: [ + // No database is opened by this fixture: every statistic is overridden below, + // and an accidental read through the real provider fails loudly. + databaseProvider.overrideWith((ref) { + throw StateError('statistics row tests must not open a database'); + }), + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + terminologySettingProvider.overrideWith((ref) => _terminology), + memberCountStatProvider.overrideWith((ref) async => 2), + allMembersStatProvider.overrideWith((ref) async => [_alice, _bob]), + sessionCountStatProvider.overrideWith((ref) async => 3), + allSessionsStatProvider.overrideWith((ref) async => const []), + allConversationsCountProvider.overrideWith((ref) async => 1), + allPollsCountProvider.overrideWith((ref) async => 0), + topFrontersProvider.overrideWith((ref) async => topFronters), + ], + child: rowsApp( + const StatisticsScreen(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + locale: locale, + textDirection: textDirection, + ), + ); +} + +Widget _diagnosticsScreen({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, +}) { + final appPrefs = FakeAppPreferenceRepository(); + addTearDown(appPrefs.close); + return ProviderScope( + overrides: [ + // Every diagnostics provider is overridden below; the database stays closed. + databaseProvider.overrideWith((ref) { + throw StateError('diagnostics row tests must not open a database'); + }), + appPreferenceRepositoryProvider.overrideWithValue(appPrefs), + systemSettingsProvider.overrideWith( + (ref) => Stream.value(const SystemSettings()), + ), + terminologySettingProvider.overrideWith((ref) => _terminology), + nodeIdProvider.overrideWith((ref) async => 'node-1'), + crdtLatestHlcProvider.overrideWith((ref) async => null), + dbPathProvider.overrideWith((ref) async => '/tmp/prism.db'), + memberCountProvider.overrideWith((ref) async => 2), + sessionCountProvider.overrideWith((ref) async => 3), + conversationCountProvider.overrideWith((ref) async => 4), + pollCountProvider.overrideWith((ref) async => 5), + healthReportProvider.overrideWith( + (ref) => throw UnimplementedError('health check not opened'), + ), + ], + child: rowsApp( + const DatabaseDiagnosticsScreen(), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +/// The section card that holds [text]; sections are `PrismSectionCard`s. +Finder _cardContaining(String text) => find + .ancestor(of: find.text(text), matching: find.byType(PrismSectionCard)) + .first; + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + group('S7 statistics label/value rows', () { + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets( + 'label and count stay inside their card - $scaleLabel / $fontFamily', + (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _statisticsScreen( + system: system, + app: app, + fontFamily: fontFamily, + ), + ); + await pumpUntilFound( + tester, + find.text('Total sessions'), + label: 'the overview labels', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'statistics $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + + // Every label of the overview card, and the card itself, must keep + // the label/value pair inside the card. + for (final label in ['Total sessions', 'Conversations', 'Polls']) { + final finder = find.text(label); + expect(finder, findsOneWidget, reason: label); + expectStaticLabelFullyPainted( + tester, + finder, + label: '$label $scaleLabel', + ); + expectDescendantTextInside( + tester, + _cardContaining(label), + label: 'overview card ($scaleLabel)', + ); + } + + // Where the pair demonstrably fits, it must stay on one line rather + // than being reflowed for its own sake. + if (system * app <= 1.5) { + expectOnTheSameLine( + tester, + find.text('Total sessions'), + find.text('3'), + label: 'label/value pair ($scaleLabel)', + ); + } + }, + ); + } + } + + testWidgets('a non-linear scaler does not break the rows', (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _statisticsScreen( + system: 1, + app: 1, + scalerOverride: const NonlinearTextScaler(), + ), + ); + await pumpUntilFound( + tester, + find.text('Total sessions'), + label: 'the Total sessions', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'statistics nonlinear', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + expectDescendantTextInside( + tester, + _cardContaining('Total sessions'), + label: 'overview card (nonlinear)', + ); + }); + }); + + group('ST2 statistics top fronters', () { + final topFronters = [MapEntry(_alice, 12), MapEntry(_bob, 7)]; + + for (final (system, app, scaleLabel) in rowsScales) { + testWidgets('rank numeral, name and count keep their size - $scaleLabel', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _statisticsScreen(system: system, app: app, topFronters: topFronters), + ); + await pumpUntilFound(tester, find.text('#1'), label: 'the #1'); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'top fronters $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + + // The rank gutter is a single-line field: "#1" is finite, app-authored + // text and is not allowed to be broken across lines by its 24dp box. + final rank = find.text('#1'); + expect(rank, findsOneWidget); + expectAtMostLines( + tester, + rank, + maxLines: 1, + label: 'rank numeral ($scaleLabel)', + ); + expectPaintedInside(tester, rank, label: 'rank numeral ($scaleLabel)'); + + // The session count keeps its own size and stays on the card. + final count = find.text('12 sessions'); + expect(count, findsOneWidget); + expectStaticLabelFullyPainted( + tester, + count, + label: 'count ($scaleLabel)', + ); + expectPaintedInside(tester, count, label: 'count ($scaleLabel)'); + + // The member name is content: it may ellipsise or wrap (accepted), so it + // is only required to stay painted inside the window. + final name = find.text('Alice'); + expect(name, findsOneWidget); + expectPaintedInside(tester, name, label: 'name ($scaleLabel)'); + + if (system * app <= 1.5) { + expectOnTheSameLine( + tester, + name, + count, + label: 'name/count ($scaleLabel)', + ); + } + }); + } + }); + + group('S7 database diagnostics label/value rows', () { + for (final (system, app, scaleLabel) in rowsScales) { + testWidgets('label and count stay inside their card - $scaleLabel', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget(_diagnosticsScreen(system: system, app: app)); + await pumpUntilFound( + tester, + find.text('Fronting Sessions'), + label: 'the Fronting Sessions', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'diagnostics loading', + ); + + expectNoLayoutError( + tester, + label: 'diagnostics $scaleLabel', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + + // Literal row labels only: the first row's label is the terminology plural, + // which depends on the settings fixture, so it is not asserted by string. + for (final label in ['Fronting Sessions', 'Conversations', 'Polls']) { + final finder = find.text(label); + expect(finder, findsOneWidget, reason: label); + expectStaticLabelFullyPainted( + tester, + finder, + label: '$label $scaleLabel', + ); + expectDescendantTextInside( + tester, + _cardContaining(label), + label: 'record counts card ($scaleLabel)', + ); + } + }); + } + }); + + group('S7 longer localized labels and RTL', () { + testWidgets('Spanish labels keep the pair inside the card at 3.375x', ( + tester, + ) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _statisticsScreen(system: 2.25, app: 1.5, locale: const Locale('es')), + ); + // Locale-independent readiness: the Spanish labels are not the English ones, + // so wait for the cards to build and the loading indicator to clear. + await pumpUntilFound( + tester, + find.byType(PrismSectionCard), + label: 'the overview cards', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'statistics es 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + // Spanish labels are longer than the English ones these rows were sized + // for; whichever row is on the overview card, its text stays inside it. + final cards = find.byType(PrismSectionCard); + expect(cards, findsWidgets); + for (var i = 0; i < cards.evaluate().length; i++) { + expectDescendantTextInside( + tester, + cards.at(i), + label: 'es card $i (3.375x)', + ); + } + }); + + testWidgets('RTL keeps the pair inside the card at 3.375x', (tester) async { + useWindow(tester, tallCompactPage); + await tester.pumpWidget( + _statisticsScreen( + system: 2.25, + app: 1.5, + textDirection: TextDirection.rtl, + ), + ); + // Locale-independent readiness: the Spanish labels are not the English ones, + // so wait for the cards to build and the loading indicator to clear. + await pumpUntilFound( + tester, + find.byType(PrismSectionCard), + label: 'the overview cards', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'statistics rtl 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + expectDescendantTextInside( + tester, + _cardContaining('Total sessions'), + label: 'overview card (rtl 3.375x)', + ); + }); + }); + + group('S7 wide window where the content fits', () { + testWidgets('nothing is clipped and nothing is reflowed at 3.375x', ( + tester, + ) async { + useWindow(tester, const Size(1024, 2400)); + await tester.pumpWidget( + _statisticsScreen( + system: 2.25, + app: 1.5, + topFronters: [MapEntry(_alice, 12)], + ), + ); + await pumpUntilFound( + tester, + find.text('12 sessions'), + label: 'the top-fronter count', + ); + await pumpUntilGone( + tester, + find.byType(PrismSpinner), + label: 'statistics loading', + ); + + expectNoLayoutError( + tester, + label: 'statistics wide 3.375x', + ignoreCauseMatching: fixedHeightBarLayoutErrors, + ); + // Section label text is finite and app-authored; the count keeps its size. + for (final text in ['Total sessions', '12 sessions']) { + expectStaticLabelFullyPainted( + tester, + find.text(text), + label: '$text (wide)', + ); + } + // Names and numbers only have to stay painted inside the window. + for (final text in ['#1', 'Alice']) { + expectPaintedInside(tester, find.text(text), label: '$text (wide)'); + } + // There is room for the pair on one line here, so a fix must not push it + // apart just because the font is large. + expectOnTheSameLine( + tester, + find.text('Total sessions'), + find.text('3'), + label: 'label/value pair (wide 3.375x)', + ); + expectOnTheSameLine( + tester, + find.text('Alice'), + find.text('12 sessions'), + label: 'name/count (wide 3.375x)', + ); + }); + }); +} diff --git a/test/text_scale_fixes/rows/sleep_and_conversation_rows_text_scale_test.dart b/test/text_scale_fixes/rows/sleep_and_conversation_rows_text_scale_test.dart new file mode 100644 index 000000000..e45979d1d --- /dev/null +++ b/test/text_scale_fixes/rows/sleep_and_conversation_rows_text_scale_test.dart @@ -0,0 +1,292 @@ +// The sleep row's "date looks off" chip and the conversation tile at large text sizes. +// +// Chip: its label was a hardcoded English literal, so a Spanish UI showed English, and +// its `Row(mainAxisSize.min, [Icon, Text])` gave the label no width bound, so at 3.375x +// the warning could only paint past the row edge. The checks are that the warning is +// localised and that it stays inside its row. +// +// Conversation tile: a title is unbounded user content, so a single-line ellipsis is the +// intended behaviour and is not treated as a defect here. What is checked is genuine +// health: no layout error, nothing paints outside the tile, the timestamp and unread +// badge keep their requested size, and the row's tap callback still fires. + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:prism_plurality/domain/models/conversation.dart'; +import 'package:prism_plurality/domain/models/fronting_session.dart'; +import 'package:prism_plurality/domain/models/member.dart'; +import 'package:prism_plurality/features/chat/providers/chat_providers.dart'; +import 'package:prism_plurality/features/chat/widgets/conversation_tile.dart'; +import 'package:prism_plurality/features/fronting/widgets/sleep_session_row.dart'; +import 'package:prism_plurality/features/members/providers/members_providers.dart'; + +import 'rows_text_scale_harness.dart'; + +FrontingSession _futureSleep() { + final start = DateTime.now().add(const Duration(hours: 6)); + return FrontingSession( + id: 'sleep-future', + startTime: start, + endTime: start.add(const Duration(hours: 8)), + sessionType: SessionType.sleep, + quality: SleepQuality.good, + ); +} + +Widget _sleepRow({ + required double system, + required double app, + String fontFamily = 'Lexend', + Locale locale = const Locale('en'), + TextScaler? scalerOverride, +}) { + return rowsApp( + // A ListView item, like the fronting/sleep list: the row gets its natural height + // rather than the body's tight one, which is the geometry it really runs in. + Scaffold( + body: ListView( + children: [ + SleepSessionRow( + session: _futureSleep(), + onTap: () {}, + onLongPress: () {}, + ), + ], + ), + ), + system: system, + app: app, + fontFamily: fontFamily, + locale: locale, + scalerOverride: scalerOverride, + ); +} + +final _now = DateTime(2026, 5, 1, 12); + +final _alice = Member(id: 'alice', name: 'Alice', createdAt: _now); +final _bob = Member(id: 'bob', name: 'Bob', createdAt: _now); + +// `_relativeTimestamp` compares against the real clock, so the sample activity time has +// to be relative to `DateTime.now()`: a fixed calendar date renders as a date, not as +// the "5m" these assertions read. +Conversation _conversation() => Conversation( + id: 'c1', + title: 'Book Club', + participantIds: const ['alice', 'bob'], + createdAt: _now, + lastActivityAt: DateTime.now().subtract(const Duration(minutes: 5)), +); + +Widget _tile({ + required double system, + required double app, + String fontFamily = 'Lexend', + TextScaler? scalerOverride, + VoidCallback? onTap, +}) { + final conversation = _conversation(); + return ProviderScope( + overrides: [ + conversationTileDataProvider(conversation.id).overrideWith((ref) { + return ConversationTileData( + conversation: conversation, + participantMap: {'alice': _alice, 'bob': _bob}, + unreadCount: 3, + showUnreadBadge: true, + speakingAs: 'alice', + lastMessageAuthorName: 'Bob', + lastMessageDisplayContent: 'Hello there', + ); + }), + memberNamePreferDisplayProvider.overrideWithValue(true), + ], + child: rowsApp( + // A ListView item, like the chat conversation list: the tile gets its natural + // height instead of the full window, which is what the header geometry (and + // the trailing column's vertical centring) depends on. + Scaffold( + body: ListView( + children: [ + ConversationTile(conversation: conversation, onTap: onTap ?? () {}), + ], + ), + ), + system: system, + app: app, + fontFamily: fontFamily, + scalerOverride: scalerOverride, + ), + ); +} + +void main() { + setUpAll(() async { + TestWidgetsFlutterBinding.ensureInitialized(); + await loadRowsFonts(); + }); + + group('F1 sleep date warning chip', () { + testWidgets('the warning is shown in the user\'s language (es)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _sleepRow(system: 1, app: 1, locale: const Locale('es')), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'sleep row es'); + // sleepDateLooksOff already ships in app_es.arb; a Spanish UI must not + // show the English literal. + expect(find.text('La fecha parece incorrecta'), findsOneWidget); + expect(find.text('Date looks off'), findsNothing); + }); + + for (final (system, app, scaleLabel) in rowsScales) { + for (final fontFamily in rowsFontFamilies) { + testWidgets( + 'the warning stays inside the sleep row - $scaleLabel / $fontFamily', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget( + _sleepRow(system: system, app: app, fontFamily: fontFamily), + ); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'sleep row $scaleLabel'); + + final hint = find.text('Date looks off'); + expect(hint, findsOneWidget); + // The row is a list item: bring the warning into view first, and bound it by + // the row it belongs to rather than by the viewport (at 3.375x the chip can sit + // below the fold). + await tester.ensureVisible(hint); + await tester.pumpAndSettle(); + expectPaintedInside( + tester, + hint, + label: 'warning chip ($scaleLabel)', + bounds: tester.getRect(find.byType(SleepSessionRow)), + ); + expectDescendantTextInside( + tester, + find.byType(SleepSessionRow), + label: 'sleep row ($scaleLabel)', + ); + }, + ); + } + } + }); + + group('C4 conversation tile', () { + testWidgets('default text keeps the timestamp beside the title (control)', ( + tester, + ) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_tile(system: 1, app: 1)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'conversation tile at 1x'); + final title = find.text('Book Club'); + expectNotVerticallyClipped(tester, title, label: 'title at 1x'); + // The tile's metadata layout is deliberately unchanged, so this only checks that + // the timestamp is painted at its own size inside the tile. + expectStaticLabelFullyPainted( + tester, + find.text('5m'), + label: 'timestamp at 1x', + ); + expectPaintedInside(tester, find.text('5m'), label: 'timestamp at 1x'); + }); + + testWidgets('tapping the tile still runs its callback (control)', ( + tester, + ) async { + useWindow(tester, compactPhone); + var taps = 0; + await tester.pumpWidget( + _tile(system: 2.25, app: 1.5, onTap: () => taps++), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(ConversationTile)); + await tester.pumpAndSettle(); + expect(taps, 1); + }); + + // Accepted disposition (parent, matched): a conversation title is unbounded + // user content, so a single-line ellipsis is the intended behaviour and is + // NOT treated as a defect. What is still required is that the tile holds its + // own geometry and that the metadata keeps its requested size. + for (final (system, app, scaleLabel) in [ + (1.5, 1.0, 'large text'), + (2.25, 1.5, 'system 225% x Prism 150% = 3.375x'), + ]) { + testWidgets( + 'the tile keeps its geometry and full-size metadata - $scaleLabel', + (tester) async { + useWindow(tester, compactPhone); + await tester.pumpWidget(_tile(system: system, app: app)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'conversation tile $scaleLabel'); + + // Nothing escapes the tile (paint overflow). + expectDescendantTextInside( + tester, + find.byType(ConversationTile), + label: 'conversation tile ($scaleLabel)', + ); + // The title may ellipsise; it still has to be painted on the tile. + expectPaintedInside( + tester, + find.text('Book Club'), + label: 'title ($scaleLabel)', + ); + // The metadata is not allowed to shrink, clip or drop out. + for (final text in ['5m', '3']) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: text); + expectStaticLabelFullyPainted( + tester, + finder, + label: '$text ($scaleLabel)', + ); + expectPaintedInside(tester, finder, label: '$text ($scaleLabel)'); + } + }, + ); + } + + testWidgets('wide window where it fits: nothing is reflowed (control)', ( + tester, + ) async { + useWindow(tester, wideWindow); + await tester.pumpWidget(_tile(system: 2.25, app: 1.5)); + await tester.pumpAndSettle(); + + expectNoLayoutError(tester, label: 'conversation tile wide 3.375x'); + // Metadata layout unchanged: on a wide window this only checks that the tile holds + // its geometry and that both texts paint inside it. + for (final text in ['Book Club', '5m']) { + final finder = find.text(text); + expect(finder, findsOneWidget, reason: text); + expectNotVerticallyClipped( + tester, + finder, + label: '$text (wide 3.375x)', + ); + expectPaintedInside(tester, finder, label: '$text (wide 3.375x)'); + } + expectDescendantTextInside( + tester, + find.byType(ConversationTile), + label: 'conversation tile (wide 3.375x)', + ); + }); + }); +}