diff --git a/app/lib/screens/body_screen.dart b/app/lib/screens/body_screen.dart index 29b5a7e..f0d8c76 100644 --- a/app/lib/screens/body_screen.dart +++ b/app/lib/screens/body_screen.dart @@ -18,6 +18,8 @@ import 'package:diet_guard_app/services/body_prefs.dart'; import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/services/health_steps.dart'; import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/macro_kind.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/activity_card.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; @@ -109,22 +111,13 @@ class _BodyScreenState extends State { final (exercise, _, _) = bodyExercise(body, bio, today); final tiles = _tiles(body, bio, exercise); return Scaffold( - appBar: AppBar(title: const Text('Body')), + appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(AppSpacing.md), child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: AppWidth.prose), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - BodyTileGrid(tiles: tiles), - const SizedBox(height: AppSpacing.sm), - BodyNote( - 'Age ${bodyAgeText(body, today)} · synced with the PC.', - ), - ], - ), + child: BodyTileGrid(tiles: tiles), ), ), ), @@ -159,8 +152,12 @@ class _BodyScreenState extends State { ) { final weight = body.latestWeight?.$2; final bodyFat = body.latestBodyFat?.$2; + final age = bodyAgeText(body, DateTime.now()); final profile = BodyTileSpec( - title: 'Profile', + semanticLabel: 'Profile', + icon: Icons.person, + value: age, + valueIcon: age == null ? null : Icons.cake, builder: (_) => ProfileCard(onSaved: _onChanged), ); final goal = bio == null @@ -174,45 +171,65 @@ class _BodyScreenState extends State { return [ if (_profileAtTop) profile, BodyTileSpec( - title: 'Daily calorie target', - value: goal == null ? null : '$goal kcal', + semanticLabel: 'Daily calorie target', + icon: Icons.flag, + value: goal == null ? null : '$goal', + valueIcon: goal == null ? null : MacroKind.kcal.icon, builder: (_) => bio == null ? BodySection( - title: 'Daily calorie target', - children: [BodyNote(bodyMissingNote(body))], + semanticLabel: 'Daily calorie target', + children: [ + Row( + children: [ + for (final icon in bodyMissingIcons(body)) + StatusCue( + kind: CueKind.warn, + icon: icon, + semanticLabel: bodyMissingNote(body), + ), + ], + ), + ], ) : GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat), ), BodyTileSpec( - title: 'Weight', + semanticLabel: 'Weight', + icon: Icons.monitor_weight, value: weight == null ? null : formatKg(weight), builder: (_) => WeightCard(onChanged: _onChanged), ), if (bio != null) ...[ BodyTileSpec( - title: 'BMI', + semanticLabel: 'BMI', + icon: Icons.accessibility_new, value: oneDecimal(bmiReport(bio).bmi), builder: (_) => BmiCard(bio: bio), ), BodyTileSpec( - title: 'Ideal weight', + semanticLabel: 'Ideal weight', + icon: Icons.balance, builder: (_) => IdealWeightCard(bio: bio), ), BodyTileSpec( - title: 'Resting metabolism (BMR)', - value: '${whole(tableBmr(bio, bodyFat).value!)} kcal', + semanticLabel: 'Resting metabolism (BMR)', + icon: Icons.bedtime, + value: whole(tableBmr(bio, bodyFat).value!), + valueIcon: MacroKind.kcal.icon, builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat), ), ], BodyTileSpec( - title: 'Activity', + semanticLabel: 'Activity', + icon: Icons.directions_run, builder: (_) => ValueListenableBuilder( valueListenable: _canConnectSteps, builder: (_, canConnect, _) => _activityCard(canConnect: canConnect), ), ), BodyTileSpec( - title: 'Week planner (info only)', + semanticLabel: 'Week planner', + icon: Icons.calendar_view_week, builder: (_) => WeekPlanCard( defaultTarget: AppSettingsService.dailyKcalGoal, logged: _logged, @@ -220,7 +237,8 @@ class _BodyScreenState extends State { ), if (!_profileAtTop) profile, BodyTileSpec( - title: 'Body fat', + semanticLabel: 'Body fat', + icon: Icons.percent, value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %', builder: (_) => BodyFatCard(onChanged: _onChanged), ), diff --git a/app/lib/screens/body_screen_data.dart b/app/lib/screens/body_screen_data.dart index f32735d..00974ed 100644 --- a/app/lib/screens/body_screen_data.dart +++ b/app/lib/screens/body_screen_data.dart @@ -6,6 +6,7 @@ import 'package:diet_guard_app/services/body_calc.dart'; import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/services/body_steps.dart'; import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:flutter/material.dart' show IconData, Icons; /// Builds the person from the stored profile and newest weight, or null /// when anything the formulas need is missing. @@ -61,7 +62,16 @@ Map kcalByDay(DayLog log) => { .fold(0, (sum, food) => sum + food.kcal), }; -/// Why the numbers are missing. +/// Glyphs of the inputs still missing (profile, weight), in the order the +/// user should supply them; the visible counterpart of [bodyMissingNote]. +List bodyMissingIcons(BodyService body) => [ + if (body.birth == null || body.heightCm == null || body.sex == null) + Icons.person, + if (body.latestWeight == null) Icons.monitor_weight, +]; + +/// Spoken reason the numbers are missing (screen readers, tests; never +/// painted). String bodyMissingNote(BodyService body) { if (body.latestWeight == null && body.birth == null) { return 'Set your profile and enter your weight to see BMI, ideal ' @@ -71,8 +81,8 @@ String bodyMissingNote(BodyService body) { return 'Set your profile (birth date, height, sex) to see the numbers.'; } -/// The age line value. -String bodyAgeText(BodyService body, DateTime today) { +/// The age in whole years, or null while no birth date is stored. +String? bodyAgeText(BodyService body, DateTime today) { final birth = DateTime.tryParse(body.birth ?? ''); - return birth == null ? 'unknown' : '${ageOn(birth, today)}'; + return birth == null ? null : '${ageOn(birth, today)}'; } diff --git a/app/lib/services/activity_kcal.dart b/app/lib/services/activity_kcal.dart index 7db7ac0..6745db5 100644 --- a/app/lib/services/activity_kcal.dart +++ b/app/lib/services/activity_kcal.dart @@ -22,13 +22,6 @@ export 'package:diet_guard_app/models/workout_session.dart'; /// Formula names, in display order. const List activityFormulas = ['MET', 'ACSM', 'Per-km']; -/// The methods explained, shown under the Activity card. -const String methodsNote = - 'MET = standard activity values x your weight x time. ' - 'ACSM = American College of Sports Medicine running/walking equation ' - 'from your speed. Per-km = ~0.9 kcal per kg per km running, ~0.5 ' - 'walking. All are energy above resting.'; - /// Measured activity averages at most the last two full weeks. const int maxWindowDays = 14; diff --git a/app/lib/services/body_calc.dart b/app/lib/services/body_calc.dart index 4caf5bc..8241310 100644 --- a/app/lib/services/body_calc.dart +++ b/app/lib/services/body_calc.dart @@ -31,16 +31,6 @@ const List<(double, String)> _bmiBands = [ ]; const String _topBand = 'obese class III'; -/// BMI Prime explained, shown under the numbers on both surfaces. -const String bmiPrimeNote = - 'BMI Prime = BMI / 25: 1.00 is the top of the healthy range, ' - 'so 1.02 means 2% above it.'; - -/// Trefethen's BMI explained, shown under the numbers on both surfaces. -const String trefethenNote = - "Trefethen's new BMI = 1.3 x kg / m^2.5: corrects classic BMI, which " - 'over-reads tall people and under-reads short ones.'; - /// The lean-mass formula the calorie table switches to with a body fat %. const String katchMcArdle = 'Katch-McArdle'; diff --git a/app/lib/widgets/body/activity_card.dart b/app/lib/widgets/body/activity_card.dart index 10c32c7..ebaaab7 100644 --- a/app/lib/widgets/body/activity_card.dart +++ b/app/lib/widgets/body/activity_card.dart @@ -2,7 +2,9 @@ library; import 'package:diet_guard_app/services/activity_kcal.dart'; -import 'package:diet_guard_app/services/body_steps.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/macro_kind.dart'; +import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:flutter/material.dart'; @@ -55,48 +57,113 @@ class ActivityCard extends StatelessWidget { final lastDay = steps.isEmpty ? null : steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b); + final muted = Theme.of(context).colorScheme.onSurfaceVariant; return BodySection( - title: 'Activity', + semanticLabel: 'Activity', children: [ if (sessions == null && steps.isEmpty) - const BodyNote('No activity data yet -- published by the PC.'), + const StatusCue( + kind: CueKind.info, + icon: Icons.directions_run, + semanticLabel: 'No activity data yet -- published by the PC.', + ), if (means != null) ...[ - BodyNote('Mean daily exercise, last $window full days:'), + Row( + children: [ + Icon( + Icons.date_range, + size: 18, + color: muted, + semanticLabel: 'Mean daily exercise, last $window full days:', + ), + const SizedBox(width: AppSpacing.xs), + Text('$window'), + ], + ), for (final name in activityFormulas) - BodyStatRow(name, '${whole(means[name] ?? 0)} kcal/day'), + _FormulaRow(name, whole(means[name] ?? 0)), ], if (lastDay != null && stepKcal != null) - BodyNote( - 'Steps outside workouts: ${steps[lastDay]} on $lastDay; above ' - '$stepBaseline/day they add ${whole(stepKcal)} kcal/day ' - '(included above).', + Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), + child: Row( + children: [ + Icon( + Icons.directions_walk, + size: 18, + color: muted, + semanticLabel: 'Steps outside workouts', + ), + const SizedBox(width: AppSpacing.xs), + Text('${steps[lastDay]} $lastDay'), + const Spacer(), + Icon(Icons.add, size: 16, color: muted), + MacroFigure( + kind: MacroKind.kcal, + value: whole(stepKcal), + size: 16, + ), + ], + ), ), if (onConnectSteps != null) Align( alignment: Alignment.centerLeft, - child: OutlinedButton.icon( - icon: const Icon(Icons.directions_walk), - label: const Text('Connect Health Connect steps'), + child: OutlinedButton( onPressed: onConnectSteps, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.directions_walk, + semanticLabel: 'Connect Health Connect steps', + ), + Icon(Icons.link), + ], + ), ), ), if (sessions != null && kg == null) - const BodyNote('Enter your weight to estimate exercise kcal.'), + const StatusCue( + kind: CueKind.warn, + icon: Icons.monitor_weight, + semanticLabel: 'Enter your weight to estimate exercise kcal.', + ), if (sessions != null && kg != null) ...[ const Divider(), if (newest.isEmpty) - const BodyNote('No workouts in the last 28 days.'), + const StatusCue( + kind: CueKind.info, + icon: Icons.event_busy, + semanticLabel: 'No workouts in the last 28 days.', + ), for (final session in newest.take(activityListLimit)) _SessionTile(result: sessionKcal(session, kg)), - if (newest.isNotEmpty) - const BodyNote('~ = no distance, MET estimate used instead.'), - const BodyNote(methodsNote), ], ], ); } } +/// A formula's proper name on the left, its kcal figure on the right. +class _FormulaRow extends StatelessWidget { + const _FormulaRow(this.name, this.value); + + final String name; + final String value; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2), + child: Row( + children: [ + Expanded(child: Text(name)), + MacroFigure(kind: MacroKind.kcal, value: value, size: 16), + ], + ), + ); +} + class _SessionTile extends StatelessWidget { const _SessionTile({required this.result}); @@ -106,19 +173,43 @@ class _SessionTile extends StatelessWidget { Widget build(BuildContext context) { final session = result.session; final km = session.km; - final distance = km == null ? '' : ', ${oneDecimal(km)} km'; + final muted = Theme.of(context).colorScheme.onSurfaceVariant; final kcal = [ for (final name in activityFormulas) _formulaKcal(name, result.kcal[name]!, result.fallback.contains(name)), ].join(' · '); - return ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - title: Text('${session.day} ${session.label}'), - subtitle: Text( - '${whole(session.minutes)} min$distance\n$kcal kcal', + return Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${session.day} ${session.label}'), + Row( + children: [ + Icon( + Icons.timer_outlined, + size: 16, + color: muted, + semanticLabel: 'minutes', + ), + Text(' ${whole(session.minutes)}'), + if (km != null) ...[ + const SizedBox(width: AppSpacing.md), + Icon(Icons.route, size: 16, color: muted, semanticLabel: 'km'), + Text(' ${oneDecimal(km)}'), + ], + const SizedBox(width: AppSpacing.md), + Icon( + MacroKind.kcal.icon, + size: 16, + color: MacroKind.kcal.color, + semanticLabel: 'kcal', + ), + Expanded(child: Text(' $kcal')), + ], + ), + ], ), - isThreeLine: true, ); } } diff --git a/app/lib/widgets/body/body_section.dart b/app/lib/widgets/body/body_section.dart index 5ca15b1..1ca6e9a 100644 --- a/app/lib/widgets/body/body_section.dart +++ b/app/lib/widgets/body/body_section.dart @@ -1,52 +1,74 @@ -/// A titled card, the building block of every Body screen section. +/// A card, the building block of every Body screen section, plus the +/// icon-led stat rows the cards are made of. No headings: the overview tile +/// that opened the sheet already says what it is. library; import 'package:diet_guard_app/services/body_calc.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:flutter/material.dart'; -/// A card with a title row and [children] stacked below it. +/// A card with [children] stacked in it; [semanticLabel] names it for screen +/// readers and tests and is never painted. class BodySection extends StatelessWidget { /// Creates a section. const BodySection({ - required this.title, + required this.semanticLabel, required this.children, super.key, }); - /// Section heading. - final String title; + /// Spoken name of the section. + final String semanticLabel; /// Section content. final List children; @override Widget build(BuildContext context) { - final theme = Theme.of(context); - return Card( - margin: const EdgeInsets.only(bottom: AppSpacing.md), - child: Padding( - padding: const EdgeInsets.all(AppSpacing.md), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(title, style: theme.textTheme.titleMedium), - const SizedBox(height: AppSpacing.sm), - ...children, - ], + return Semantics( + container: true, + label: semanticLabel, + child: Card( + margin: const EdgeInsets.only(bottom: AppSpacing.md), + child: Padding( + padding: const EdgeInsets.all(AppSpacing.md), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), ), ), ); } } -/// A label on the left, a value on the right; one line of a stats card. +/// One line of a stats card: a leading mark on the left, a value on the right. +/// +/// The mark is either a formula name ([BodyStatRow.named]: a proper noun such +/// as Devine or ACSM, shown as is) or an icon ([BodyStatRow.icon]). class BodyStatRow extends StatelessWidget { - /// Creates a row. - const BodyStatRow(this.label, this.value, {this.color, super.key}); + /// A row led by a formula's proper name. + const BodyStatRow.named(this.name, this.value, {this.color, super.key}) + : icon = null, + semanticLabel = null; - /// What the value is. - final String label; + /// A row led by [icon], spoken as [semanticLabel]. + const BodyStatRow.icon( + IconData this.icon, + String this.semanticLabel, + this.value, { + this.color, + super.key, + }) : name = null; + + /// Proper-noun lead, or null when an icon leads. + final String? name; + + /// Icon lead, or null when a name leads. + final IconData? icon; + + /// Spoken description of [icon]. + final String? semanticLabel; /// The formatted value. final String value; @@ -56,11 +78,19 @@ class BodyStatRow extends StatelessWidget { @override Widget build(BuildContext context) { + final lead = icon; return Padding( padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2), child: Row( children: [ - Expanded(child: Text(label)), + Expanded( + child: lead == null + ? Text(name!) + : Align( + alignment: Alignment.centerLeft, + child: Icon(lead, size: 20, semanticLabel: semanticLabel), + ), + ), Text( value, style: TextStyle( @@ -74,28 +104,8 @@ class BodyStatRow extends StatelessWidget { } } -/// A muted one-line explanation (missing data, notes). -class BodyNote extends StatelessWidget { - /// Creates a note. - const BodyNote(this.text, {super.key}); - - /// The note. - final String text; - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - return Text( - text, - style: theme.textTheme.bodySmall?.copyWith( - color: theme.colorScheme.onSurfaceVariant, - ), - ); - } -} - -/// `74.99` -> `"75.0 kg"`, null -> `"n/a"`. Half-up, like the PC. -String formatKg(double? kg) => kg == null ? 'n/a' : '${oneDecimal(kg)} kg'; +/// `74.99` -> `"75.0 kg"`, null -> a dash. Half-up, like the PC. +String formatKg(double? kg) => kg == null ? '—' : '${oneDecimal(kg)} kg'; /// [value] to one decimal, rounded half-up like the PC prints it. String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1); diff --git a/app/lib/widgets/body/body_stats_cards.dart b/app/lib/widgets/body/body_stats_cards.dart index 0b2f347..8de20f6 100644 --- a/app/lib/widgets/body/body_stats_cards.dart +++ b/app/lib/widgets/body/body_stats_cards.dart @@ -2,9 +2,26 @@ library; import 'package:diet_guard_app/services/body_calc.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/macro_kind.dart'; +import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:flutter/material.dart'; +/// The BMI band as glyph + colour (never colour alone): a green check inside +/// the healthy range, an amber or red arrow towards the side it is off by. +(IconData, CueKind) bmiBandCue(String category) { + if (category == 'normal') return (Icons.check_circle, CueKind.ok); + if (category.contains('thinness')) { + return (Icons.trending_down, CueKind.warn); + } + if (category.startsWith('overweight')) { + return (Icons.trending_up, CueKind.warn); + } + if (category.startsWith('obese')) return (Icons.trending_up, CueKind.error); + return (Icons.help_outline, CueKind.info); +} + /// BMI, BMI Prime, Trefethen's BMI and the WHO category. class BmiCard extends StatelessWidget { /// Creates the card for [bio]. @@ -17,30 +34,40 @@ class BmiCard extends StatelessWidget { Widget build(BuildContext context) { final report = bmiReport(bio); final (low, high) = healthyRange(bio); - final normal = report.category == 'normal'; + final (icon, kind) = bmiBandCue(report.category); + final tint = kind.tint(context); return BodySection( - title: 'BMI', + semanticLabel: 'BMI', children: [ - BodyStatRow( - 'BMI', - oneDecimal(report.bmi), - color: normal ? null : Theme.of(context).colorScheme.error, + Row( + children: [ + Icon(icon, color: tint, semanticLabel: report.category), + const SizedBox(width: AppSpacing.sm), + Text( + oneDecimal(report.bmi), + style: Theme.of( + context, + ).textTheme.headlineMedium?.copyWith(color: tint), + ), + ], ), - BodyStatRow('Category', report.category), - BodyStatRow('BMI Prime', halfUp(report.prime, 2).toStringAsFixed(2)), - BodyStatRow('Trefethen (new BMI)', oneDecimal(report.trefethen)), - BodyStatRow( + const SizedBox(height: AppSpacing.sm), + BodyStatRow.named( + 'BMI Prime', + halfUp(report.prime, 2).toStringAsFixed(2), + ), + BodyStatRow.named('Trefethen', oneDecimal(report.trefethen)), + BodyStatRow.icon( + Icons.favorite, 'Healthy weight for your height (BMI 18.5-24.9)', '${oneDecimal(low)}-${oneDecimal(high)} kg', ), - const BodyNote(bmiPrimeNote), - const BodyNote(trefethenNote), ], ); } } -/// Every ideal-weight formula; `n/a` where one is undefined. +/// Every ideal-weight formula; a dash where one is undefined. class IdealWeightCard extends StatelessWidget { /// Creates the card for [bio]. const IdealWeightCard({required this.bio, super.key}); @@ -51,25 +78,25 @@ class IdealWeightCard extends StatelessWidget { @override Widget build(BuildContext context) { final formulas = idealWeights(bio); - final undefined = formulas.any((f) => f.value == null); final summary = idealSummary(formulas); return BodySection( - title: 'Ideal weight', + semanticLabel: 'Ideal weight', children: [ for (final formula in formulas) - BodyStatRow(formula.name, formatKg(formula.value)), + BodyStatRow.named(formula.name, formatKg(formula.value)), if (summary != null) ...[ const Divider(), - BodyStatRow('Average of all', formatKg(summary.$1)), - BodyStatRow( + BodyStatRow.icon( + Icons.functions, + 'Average of all', + formatKg(summary.$1), + ), + BodyStatRow.icon( + Icons.swap_horiz, 'Ideal range', '${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg', ), ], - if (undefined) - const BodyNote( - 'Devine, Robinson and Miller are undefined below 152.4 cm.', - ), ], ); } @@ -89,14 +116,29 @@ class BmrCard extends StatelessWidget { @override Widget build(BuildContext context) { return BodySection( - title: 'Resting metabolism (BMR)', + semanticLabel: 'Resting metabolism (BMR)', children: [ for (final formula in bmrFormulas(bio, bodyFatPct)) - BodyStatRow( - formula.name, - formula.value == null - ? 'n/a -- log a body-fat %' - : '${whole(formula.value!)} kcal', + Padding( + padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2), + child: Row( + children: [ + Expanded(child: Text(formula.name)), + if (formula.value == null) + Icon( + Icons.percent, + size: 18, + color: CueKind.warn.tint(context), + semanticLabel: 'n/a -- log a body-fat %', + ) + else + MacroFigure( + kind: MacroKind.kcal, + value: whole(formula.value!), + size: 16, + ), + ], + ), ), ], ); diff --git a/app/lib/widgets/body/body_tile_grid.dart b/app/lib/widgets/body/body_tile_grid.dart index 890e197..6452af0 100644 --- a/app/lib/widgets/body/body_tile_grid.dart +++ b/app/lib/widgets/body/body_tile_grid.dart @@ -1,22 +1,34 @@ -/// The Body screen's overview: two-column metric tiles that fit one phone +/// The Body screen's overview: two-column icon tiles that fit one phone /// screen. Tapping a tile opens the section's full card in a bottom sheet. library; import 'package:diet_guard_app/ui/theme.dart'; import 'package:flutter/material.dart'; -/// One tile: a section [title], an optional headline [value], and the -/// [builder] of the full card shown in the sheet. +/// One tile: a big [icon] (spoken as [semanticLabel]), an optional headline +/// [value] and the [builder] of the full card shown in the sheet. class BodyTileSpec { /// Creates a tile spec. - const BodyTileSpec({required this.title, required this.builder, this.value}); + const BodyTileSpec({ + required this.semanticLabel, + required this.icon, + required this.builder, + this.value, + this.valueIcon, + }); - /// Section name, the same text the full card carries. - final String title; + /// Spoken name of the section; never painted. + final String semanticLabel; + + /// The section's glyph. + final IconData icon; /// Headline number for the tile (null when the section has none). final String? value; + /// Small glyph in front of [value] (e.g. a bolt for kcal). + final IconData? valueIcon; + /// Builds the full card for the sheet. final WidgetBuilder builder; } @@ -76,33 +88,43 @@ class _Tile extends StatelessWidget { @override Widget build(BuildContext context) { final theme = Theme.of(context); + final value = spec.value; + final valueIcon = spec.valueIcon; return Card( margin: EdgeInsets.zero, - child: InkWell( - onTap: () => _open(context), - borderRadius: BorderRadius.circular(AppRadius.md), - child: Padding( - padding: const EdgeInsets.all(AppSpacing.sm), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - spec.title, - maxLines: 2, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium, - ), - if (spec.value != null) - Text( - spec.value!, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleMedium?.copyWith( - color: theme.colorScheme.primary, + child: Semantics( + button: true, + label: spec.semanticLabel, + child: InkWell( + onTap: () => _open(context), + borderRadius: BorderRadius.circular(AppRadius.md), + child: Padding( + padding: const EdgeInsets.all(AppSpacing.sm), + child: Row( + children: [ + ExcludeSemantics( + child: Icon( + spec.icon, + size: 36, + color: theme.colorScheme.onSurfaceVariant, ), ), - ], + const Spacer(), + if (valueIcon != null) + Icon(valueIcon, size: 18, color: theme.colorScheme.primary), + if (value != null) + Flexible( + child: Text( + value, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleMedium?.copyWith( + color: theme.colorScheme.primary, + ), + ), + ), + ], + ), ), ), ), diff --git a/app/lib/widgets/body/dated_value_card.dart b/app/lib/widgets/body/dated_value_card.dart new file mode 100644 index 0000000..27eaa2b --- /dev/null +++ b/app/lib/widgets/body/dated_value_card.dart @@ -0,0 +1,223 @@ +/// Dated-value entry card: save or delete any day, undo a delete, and chart +/// the history. Shared by weight and body fat (see `weight_card.dart`). +library; + +import 'package:diet_guard_app/models/local_time.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/body/body_section.dart'; +import 'package:diet_guard_app/widgets/body/weight_chart.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +/// Enters/deletes a day's value and charts the history. +class DatedValueCard extends StatefulWidget { + /// Creates the card. + const DatedValueCard({ + required this.semanticLabel, + required this.fieldSemanticLabel, + required this.icon, + required this.unit, + required this.min, + required this.max, + required this.latest, + required this.series, + required this.onSave, + required this.onDelete, + required this.onChanged, + super.key, + }); + + /// Spoken name of the card; never painted. + final String semanticLabel; + + /// Spoken name of the input; never painted. + final String fieldSemanticLabel; + + /// Glyph captioning the input. + final IconData icon; + + /// Unit suffix (`kg`, `%`). + final String unit; + + /// Smallest accepted value. + final double min; + + /// Largest accepted value. + final double max; + + /// Newest `(day, value)`, or null. + final (String, double)? latest; + + /// Every live `(day, value)`, oldest first. + final List<(String, double)> series; + + /// Writes a value for a day. + final Future Function(String day, double value) onSave; + + /// Deletes a day. + final Future Function(String day) onDelete; + + /// Called once a value has been written or deleted. + final VoidCallback onChanged; + + @override + State createState() => _DatedValueCardState(); +} + +class _DatedValueCardState extends State { + final _value = TextEditingController(); + String _day = localDateKey(DateTime.now()); + Widget? _status; + (String, double)? _undo; + + @override + void dispose() { + _value.dispose(); + super.dispose(); + } + + String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}'; + + Future _pickDay() async { + final picked = await showDatePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime.now(), + initialDate: DateTime.parse(_day), + ); + if (picked == null || !mounted) return; + setState(() => _day = localDateKey(picked)); + } + + Future _save() async { + final value = double.tryParse(_value.text.replaceAll(',', '.')); + if (value == null || value < widget.min || value > widget.max) { + setState( + () => _status = StatusCue( + key: UniqueKey(), + kind: CueKind.error, + icon: widget.icon, + semanticLabel: + '${widget.semanticLabel} must be ${whole(widget.min)}-' + '${whole(widget.max)} ${widget.unit}.', + ), + ); + return; + } + await widget.onSave(_day, value); + if (!mounted) return; + _value.clear(); + setState(() { + _undo = null; + _status = StatusCue( + key: UniqueKey(), + kind: CueKind.ok, + semanticLabel: 'Saved ${_fmt(value)} for $_day.', + ); + }); + widget.onChanged(); + } + + /// Deletes at once; the undo arrow restores the value that was there. + Future _delete() async { + final day = _day; + final removed = [ + for (final point in widget.series) + if (point.$1 == day) point, + ]; + await widget.onDelete(day); + if (!mounted) return; + setState(() { + _undo = removed.isEmpty ? null : removed.first; + _status = StatusCue( + key: UniqueKey(), + kind: CueKind.ok, + icon: Icons.delete_outline, + semanticLabel: 'Deleted $day.', + ); + }); + widget.onChanged(); + } + + Future _restore() async { + final undo = _undo; + if (undo == null) return; + await widget.onSave(undo.$1, undo.$2); + if (!mounted) return; + setState(() { + _undo = null; + _status = null; + }); + widget.onChanged(); + } + + @override + Widget build(BuildContext context) { + final latest = widget.latest; + final scheme = Theme.of(context).colorScheme; + final undo = _undo; + return BodySection( + semanticLabel: widget.semanticLabel, + children: [ + Row( + children: [ + const Icon(Icons.update, size: 18, semanticLabel: 'Latest'), + const SizedBox(width: AppSpacing.xs), + if (latest == null) + Icon(Icons.block, size: 18, color: scheme.outline) + else + Text('${_fmt(latest.$2)} ${latest.$1}'), + ], + ), + Row( + children: [ + Expanded( + child: IconField( + icon: widget.icon, + semanticLabel: widget.fieldSemanticLabel, + controller: _value, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), + ], + ), + ), + TextButton( + onPressed: _pickDay, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [const Icon(Icons.event, size: 18), Text(' $_day')], + ), + ), + ], + ), + Row( + children: [ + if (_status != null) _status! else const SizedBox.shrink(), + if (undo != null) + IconButton( + onPressed: _restore, + icon: const Icon(Icons.undo, semanticLabel: 'Undo'), + ), + const Spacer(), + IconButton( + icon: const Icon( + Icons.delete_outline, + semanticLabel: 'Delete this day', + ), + onPressed: _delete, + ), + IconButton.filled( + onPressed: _save, + icon: const Icon(Icons.check, semanticLabel: 'Save'), + ), + ], + ), + WeightChart(series: widget.series), + ], + ); + } +} diff --git a/app/lib/widgets/body/goal_card.dart b/app/lib/widgets/body/goal_card.dart index 5a24b05..c27f915 100644 --- a/app/lib/widgets/body/goal_card.dart +++ b/app/lib/widgets/body/goal_card.dart @@ -1,6 +1,7 @@ -/// The Body screen's top line: "To [lose] [0.5] [kg] / [week] on -/// [Moderate] eat 2019 kcal". Every bracket is tappable and opens a picker; -/// the choice is saved (and synced) immediately. Informational only. +/// The Body screen's top line as marks instead of a sentence: direction +/// arrow, amount, unit, per-period calendar, activity glyph, then a bolt and +/// the daily kcal answer. Every mark is tappable and opens a picker; the +/// choice is saved (and synced) immediately. Informational only. library; import 'dart:async'; @@ -9,12 +10,15 @@ import 'package:diet_guard_app/services/body_calc.dart'; import 'package:diet_guard_app/services/body_energy.dart'; import 'package:diet_guard_app/services/body_prefs.dart'; import 'package:diet_guard_app/services/body_service.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/macro_kind.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; +import 'package:diet_guard_app/widgets/body/goal_icons.dart'; import 'package:diet_guard_app/widgets/body/goal_pickers.dart'; import 'package:flutter/material.dart'; -/// The goal sentence and its answer. +/// The goal row and its answer. class GoalCard extends StatefulWidget { /// Creates the card. const GoalCard({ @@ -47,26 +51,59 @@ class _GoalCardState extends State { await setGoal(BodyService.instance, picked); } - Widget _choice(String text, Future Function(BuildContext, Goal) p) { + /// A bordered, tappable mark spoken as [spoken]; [child] is its look. + Widget _choice( + String spoken, + Widget child, + Future Function(BuildContext, Goal) picker, + ) { final scheme = Theme.of(context).colorScheme; - return InkWell( - onTap: () => unawaited(_pick(p)), - borderRadius: BorderRadius.circular(AppRadius.sm), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs), - child: Text( - text, - style: TextStyle( - color: scheme.primary, - fontWeight: FontWeight.w600, - decoration: TextDecoration.underline, - decorationColor: scheme.primary, + return Semantics( + button: true, + label: spoken, + child: InkWell( + onTap: () => unawaited(_pick(picker)), + borderRadius: BorderRadius.circular(AppRadius.sm), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.sm, + vertical: AppSpacing.xs, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(AppRadius.sm), + border: Border.all(color: scheme.outline), + ), + child: ExcludeSemantics( + child: DefaultTextStyle.merge( + style: TextStyle( + color: scheme.primary, + fontWeight: FontWeight.w600, + ), + child: IconTheme.merge( + data: IconThemeData(color: scheme.primary), + child: child, + ), + ), ), ), ), ); } + Widget _iconChoice( + String spoken, + IconData icon, + Future Function(BuildContext, Goal) picker, { + String? caption, + }) => _choice( + spoken, + Row( + mainAxisSize: MainAxisSize.min, + children: [Icon(icon), if (caption != null) Text(caption)], + ), + picker, + ); + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -76,51 +113,81 @@ class _GoalCardState extends State { final tdee = target.tdee; final maintain = _goal.direction == 'maintain'; return BodySection( - title: 'Daily calorie target', + semanticLabel: 'Daily calorie target', children: [ Wrap( crossAxisAlignment: WrapCrossAlignment.center, - runSpacing: AppSpacing.xs, + spacing: AppSpacing.sm, + runSpacing: AppSpacing.sm, children: [ - const Text('To'), - _choice(_goal.direction, pickDirection), + _iconChoice( + _goal.direction, + directionIcon(_goal.direction), + pickDirection, + ), if (!maintain) ...[ - _choice(formatG(_goal.amount), pickAmount), - _choice(_goal.weightUnit, pickWeightUnit), - const Text('/'), - _choice(_goal.timeUnit, pickTimeUnit), - ], - const Text('on'), - _choice(activityLabel(_goal.activity), pickActivity), - if (kcal != null) ...[ - const Text('eat '), - Text( - '$kcal', - style: theme.textTheme.headlineMedium?.copyWith( - color: theme.colorScheme.primary, - fontWeight: FontWeight.w700, - ), + _choice( + formatG(_goal.amount), + Text(formatG(_goal.amount)), + pickAmount, + ), + _choice(_goal.weightUnit, Text(_goal.weightUnit), pickWeightUnit), + _iconChoice( + _goal.timeUnit, + timeUnitIcon(_goal.timeUnit), + pickTimeUnit, ), - const Text(' kcal'), ], + _iconChoice( + activityLabel(_goal.activity), + activityIcon(_goal.activity), + pickActivity, + caption: activityCaption(_goal.activity), + ), + if (kcal != null) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(MacroKind.kcal.icon, color: theme.colorScheme.primary), + Text( + '$kcal', + style: theme.textTheme.headlineMedium?.copyWith( + color: theme.colorScheme.primary, + fontWeight: FontWeight.w700, + ), + ), + ], + ), ], ), const SizedBox(height: AppSpacing.sm), if (kcal == null) - const BodyNote('no workouts published yet (the PC publishes them).'), + const StatusCue( + kind: CueKind.warn, + icon: Icons.directions_run, + semanticLabel: 'no workouts published yet (the PC publishes them).', + ), if (target.belowFloor) - Text( - 'That is below the $minTargetKcal kcal floor.', - style: TextStyle(color: theme.colorScheme.error), + const StatusCue( + kind: CueKind.error, + icon: Icons.vertical_align_bottom, + semanticLabel: 'That is below the $minTargetKcal kcal floor.', ), if (tdee != null) - BodyNote( - 'Maintenance ${whole(tdee)} kcal (${target.bmrName} resting ' - 'burn x activity); 1 kg of fat = ${formatG(kcalPerKg)} kcal.', + Row( + children: [ + Icon( + Icons.balance, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + semanticLabel: 'Maintenance', + ), + const SizedBox(width: AppSpacing.xs), + MacroFigure(kind: MacroKind.kcal, value: whole(tdee), size: 16), + const SizedBox(width: AppSpacing.sm), + Text(target.bmrName), + ], ), - const BodyNote( - 'Informational only — the budget is never changed from here.', - ), ], ); } diff --git a/app/lib/widgets/body/goal_icons.dart b/app/lib/widgets/body/goal_icons.dart new file mode 100644 index 0000000..4ba2f94 --- /dev/null +++ b/app/lib/widgets/body/goal_icons.dart @@ -0,0 +1,43 @@ +/// Glyphs for the goal's enumerations (direction, time unit, activity), so +/// the goal reads as a row of icons and numbers instead of a sentence. +library; + +import 'package:diet_guard_app/services/body_energy.dart'; +import 'package:flutter/material.dart'; + +/// Lose = down arrow, maintain = level bar, gain = up arrow. +IconData directionIcon(String direction) => switch (direction) { + 'lose' => Icons.south, + 'gain' => Icons.north, + _ => Icons.drag_handle, +}; + +/// Day / week / month / year as calendar views of growing span. +IconData timeUnitIcon(String unit) => switch (unit) { + 'day' => Icons.calendar_view_day, + 'week' => Icons.calendar_view_week, + 'month' => Icons.calendar_view_month, + _ => Icons.event_repeat, +}; + +/// The five levels ramp from a chair to a barbell; measured is a gauge. +IconData activityIcon(String key) => switch (key) { + 'sedentary' => Icons.chair, + 'light' => Icons.directions_walk, + 'moderate' => Icons.directions_bike, + 'very' => Icons.directions_run, + 'extra' => Icons.fitness_center, + _ => Icons.speed, +}; + +/// Short non-word caption under an activity icon: the TDEE multiplier of a +/// level, or the proper name of the measured formula. +String activityCaption(String key) { + if (key.startsWith(measuredPrefix)) { + return key.substring(measuredPrefix.length); + } + for (final level in activityLevels) { + if (level.key == key) return formatG(level.factor); + } + return key; +} diff --git a/app/lib/widgets/body/goal_pickers.dart b/app/lib/widgets/body/goal_pickers.dart index f77e7fc..5ad8583 100644 --- a/app/lib/widgets/body/goal_pickers.dart +++ b/app/lib/widgets/body/goal_pickers.dart @@ -1,71 +1,141 @@ -/// The pickers behind each tappable word of the goal sentence. +/// The pickers behind each tappable mark of the goal row. /// -/// Each returns the edited [Goal], or null when dismissed. +/// Each returns the edited [Goal], or null when dismissed. Options are icons +/// (plus a number or proper name where one exists); the spoken name of every +/// option is its semantic label. library; import 'package:diet_guard_app/services/body_energy.dart'; +import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/ui/theme.dart'; +import 'package:diet_guard_app/widgets/body/goal_icons.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +/// One choice in a picker sheet. +typedef PickerOption = ({ + String value, + String spoken, + IconData icon, + String? caption, +}); + Future _sheet( BuildContext context, - String title, - List<(String, String, String?)> options, + List options, String selected, ) => showModalBottomSheet( context: context, builder: (context) => SafeArea( - child: ListView( - shrinkWrap: true, - children: [ - ListTile(title: Text(title)), - for (final (value, label, subtitle) in options) - ListTile( - title: Text(label), - subtitle: subtitle == null ? null : Text(subtitle), - selected: value == selected, - trailing: value == selected ? const Icon(Icons.check) : null, - onTap: () => Navigator.of(context).pop(value), - ), - ], + child: Padding( + padding: const EdgeInsets.all(AppSpacing.md), + child: Wrap( + spacing: AppSpacing.sm, + runSpacing: AppSpacing.sm, + children: [ + for (final option in options) + _OptionButton( + option: option, + selected: option.value == selected, + onTap: () => Navigator.of(context).pop(option.value), + ), + ], + ), ), ), ); +class _OptionButton extends StatelessWidget { + const _OptionButton({ + required this.option, + required this.selected, + required this.onTap, + }); + + final PickerOption option; + final bool selected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final tint = selected ? scheme.primary : scheme.onSurfaceVariant; + return Semantics( + button: true, + selected: selected, + label: option.spoken, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(AppRadius.md), + child: Container( + width: 72, + padding: const EdgeInsets.all(AppSpacing.sm), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(AppRadius.md), + border: Border.all( + color: selected ? scheme.primary : scheme.outline, + ), + color: selected ? scheme.primary.withValues(alpha: 0.16) : null, + ), + child: ExcludeSemantics( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(option.icon, color: tint, size: 28), + if (option.caption != null) + Text( + option.caption!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: tint), + ), + if (selected) + Icon(Icons.check, size: 14, color: scheme.primary), + ], + ), + ), + ), + ), + ); + } +} + /// Lose / maintain / gain. Future pickDirection(BuildContext context, Goal goal) async { - final value = await _sheet(context, 'Direction', [ - for (final d in directions) (d, d, null), + final value = await _sheet(context, [ + for (final d in directions) + (value: d, spoken: d, icon: directionIcon(d), caption: null), ], goal.direction); return value == null ? null : goal.copyWith(direction: value); } -/// Kilograms, pounds, grams or stones. +/// Kilograms, pounds, grams or stones (the unit symbols are the captions). Future pickWeightUnit(BuildContext context, Goal goal) async { - final value = await _sheet(context, 'Weight unit', [ - for (final u in weightUnits.keys) (u, u, null), + final value = await _sheet(context, [ + for (final u in weightUnits.keys) + (value: u, spoken: u, icon: Icons.scale, caption: u), ], goal.weightUnit); return value == null ? null : goal.copyWith(weightUnit: value); } /// Per day, week, month or year. Future pickTimeUnit(BuildContext context, Goal goal) async { - final value = await _sheet(context, 'Per', [ - for (final u in timeUnits.keys) (u, u, null), + final value = await _sheet(context, [ + for (final u in timeUnits.keys) + (value: u, spoken: u, icon: timeUnitIcon(u), caption: null), ], goal.timeUnit); return value == null ? null : goal.copyWith(timeUnit: value); } /// The five levels, then the three measured formulas. Future pickActivity(BuildContext context, Goal goal) async { - final meaning = {for (final l in activityLevels) l.key: l.meaning}; - final value = await _sheet(context, 'Activity', [ + final value = await _sheet(context, [ for (final key in activityChoices) ( - key, - activityLabel(key), - meaning[key] ?? 'BMR x 1.2 + your real workouts and steps', + value: key, + spoken: activityLabel(key), + icon: activityIcon(key), + caption: activityCaption(key), ), ], goal.activity); return value == null ? null : goal.copyWith(activity: value); @@ -95,6 +165,7 @@ class _AmountDialogState extends State<_AmountDialog> { late final _controller = TextEditingController( text: formatG(widget.goal.amount), ); + bool _rejected = false; @override void dispose() { @@ -104,14 +175,17 @@ class _AmountDialogState extends State<_AmountDialog> { void _submit() { final typed = double.tryParse(_controller.text.replaceAll(',', '.')); - if (typed != null && typed >= 0) Navigator.of(context).pop(typed); + if (typed != null && typed >= 0) { + Navigator.of(context).pop(typed); + return; + } + setState(() => _rejected = true); } @override Widget build(BuildContext context) { final goal = widget.goal; return AlertDialog( - title: Text('How much (${goal.weightUnit} / ${goal.timeUnit})'), content: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -126,23 +200,29 @@ class _AmountDialogState extends State<_AmountDialog> { ), ], ), - TextField( + IconField( + icon: Icons.edit, + semanticLabel: 'Other amount', controller: _controller, - decoration: const InputDecoration(labelText: 'Other amount'), keyboardType: const TextInputType.numberWithOptions(decimal: true), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), ], onSubmitted: (_) => _submit(), ), + if (_rejected) + const StatusCue(kind: CueKind.error, semanticLabel: 'not a number'), ], ), actions: [ - TextButton( + IconButton( onPressed: () => Navigator.of(context).pop(), - child: const Text('Cancel'), + icon: const Icon(Icons.close, semanticLabel: 'Cancel'), + ), + IconButton.filled( + onPressed: _submit, + icon: const Icon(Icons.check, semanticLabel: 'OK'), ), - FilledButton(onPressed: _submit, child: const Text('OK')), ], ); } diff --git a/app/lib/widgets/body/profile_card.dart b/app/lib/widgets/body/profile_card.dart index 92a7b66..d97b140 100644 --- a/app/lib/widgets/body/profile_card.dart +++ b/app/lib/widgets/body/profile_card.dart @@ -3,6 +3,7 @@ library; import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/services/body_service.dart'; +import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:flutter/material.dart'; @@ -24,7 +25,7 @@ class _ProfileCardState extends State { final _height = TextEditingController(); String? _birth; String? _sex; - String? _status; + Widget? _status; @override void initState() { @@ -59,7 +60,14 @@ class _ProfileCardState extends State { Future _save() async { final height = double.tryParse(_height.text.replaceAll(',', '.')); if (height == null || height < 50 || height > 260) { - setState(() => _status = 'Height must be 50-260 cm.'); + setState( + () => _status = StatusCue( + key: UniqueKey(), + kind: CueKind.error, + icon: Icons.height, + semanticLabel: 'Height must be 50-260 cm.', + ), + ); return; } await BodyService.instance.setProfile( @@ -68,28 +76,45 @@ class _ProfileCardState extends State { sex: _sex, ); if (!mounted) return; - setState(() => _status = 'Saved.'); + setState( + () => _status = StatusCue( + key: UniqueKey(), + kind: CueKind.ok, + semanticLabel: 'Saved.', + ), + ); widget.onSaved(); } @override Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final birth = _birth; + final status = _status; return BodySection( - title: 'Profile', + semanticLabel: 'Profile', children: [ - Row( - children: [ - Expanded(child: Text('Born: ${_birth ?? 'not set'}')), - TextButton.icon( - icon: const Icon(Icons.cake), - label: const Text('Birth date'), - onPressed: _pickBirth, + Align( + alignment: Alignment.centerLeft, + child: TextButton( + onPressed: _pickBirth, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.cake, + color: birth == null ? scheme.error : null, + semanticLabel: 'Birth date', + ), + if (birth != null) Text(' $birth'), + ], ), - ], + ), ), - TextField( + IconField( + icon: Icons.height, + semanticLabel: 'Height (cm)', controller: _height, - decoration: const InputDecoration(labelText: 'Height (cm)'), keyboardType: const TextInputType.numberWithOptions(decimal: true), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), @@ -97,9 +122,16 @@ class _ProfileCardState extends State { ), const SizedBox(height: AppSpacing.sm), SegmentedButton( + showSelectedIcon: false, segments: const [ - ButtonSegment(value: 'm', label: Text('Male')), - ButtonSegment(value: 'f', label: Text('Female')), + ButtonSegment( + value: 'm', + icon: Icon(Icons.male, semanticLabel: 'Male'), + ), + ButtonSegment( + value: 'f', + icon: Icon(Icons.female, semanticLabel: 'Female'), + ), ], selected: {?_sex}, emptySelectionAllowed: true, @@ -109,8 +141,11 @@ class _ProfileCardState extends State { const SizedBox(height: AppSpacing.sm), Row( children: [ - Expanded(child: BodyNote(_status ?? 'Syncs to the PC.')), - FilledButton(onPressed: _save, child: const Text('Save profile')), + if (status != null) Expanded(child: status) else const Spacer(), + IconButton.filled( + onPressed: _save, + icon: const Icon(Icons.check, semanticLabel: 'Save profile'), + ), ], ), ], diff --git a/app/lib/widgets/body/week_plan_card.dart b/app/lib/widgets/body/week_plan_card.dart index 1b5689a..267c9a7 100644 --- a/app/lib/widgets/body/week_plan_card.dart +++ b/app/lib/widgets/body/week_plan_card.dart @@ -4,7 +4,10 @@ /// day overrides it (a planned feast on Saturday too). library; +import 'package:diet_guard_app/services/body_energy.dart'; import 'package:diet_guard_app/services/week_plan.dart'; +import 'package:diet_guard_app/ui/cues.dart'; +import 'package:diet_guard_app/ui/macro_kind.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:flutter/material.dart'; @@ -53,8 +56,7 @@ class _WeekPlanCardState extends State { Widget build(BuildContext context) { final target = int.tryParse(_target.text) ?? widget.defaultTarget; final typed = { - for (var i = 0; i < 7; i++) - i: ?int.tryParse(_days[i].text), + for (var i = 0; i < 7; i++) i: ?int.tryParse(_days[i].text), }; final plan = planWeek( widget.today ?? DateTime.now(), @@ -64,41 +66,39 @@ class _WeekPlanCardState extends State { ); final scheme = Theme.of(context).colorScheme; return BodySection( - title: 'Week planner (info only)', + semanticLabel: 'Week planner', children: [ - TextField( - controller: _target, - decoration: InputDecoration( - labelText: 'Weekly average target (kcal/day)', - hintText: '${widget.defaultTarget}', + SpokenLabel( + semanticLabel: 'Weekly average target (kcal/day)', + child: TextField( + controller: _target, + decoration: InputDecoration( + prefixIcon: ExcludeSemantics( + child: Icon(MacroKind.kcal.icon, color: MacroKind.kcal.color), + ), + hintText: '${widget.defaultTarget}', + ), + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + onChanged: (_) => setState(() {}), ), - keyboardType: TextInputType.number, - inputFormatters: [FilteringTextInputFormatter.digitsOnly], - onChanged: (_) => setState(() {}), ), const SizedBox(height: AppSpacing.sm), for (var i = 0; i < 7; i++) Row( children: [ - SizedBox(width: 48, child: Text(plan.days[i].weekday)), + // Day of month, not a weekday word: rows run Monday..Sunday. + SizedBox(width: 32, child: Text(plan.days[i].day.substring(8))), Expanded( - child: Text( - '${plan.days[i].kcal} kcal ${_sourceLabel(plan.days[i])}', - style: TextStyle( - color: plan.days[i].source == 'plan' && plan.belowFloor - ? scheme.error - : null, - ), - ), + child: _DayFigure(plan.days[i], belowFloor: plan.belowFloor), ), SizedBox( width: 96, - child: TextField( + child: IconField( + icon: Icons.rice_bowl, + semanticLabel: 'ate…', controller: _days[i], - decoration: const InputDecoration( - hintText: 'ate…', - isDense: true, - ), + dense: true, keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly], onChanged: (_) => setState(() {}), @@ -107,26 +107,86 @@ class _WeekPlanCardState extends State { ], ), const SizedBox(height: AppSpacing.sm), - BodyNote(_summary(plan)), + _Summary(plan, scheme), ], ); } } -String _sourceLabel(DayPlan day) => switch (day.source) { - 'typed' => '(typed)', - 'logged' => '(logged)', - 'unlogged' => '(not logged -- type it)', - _ => '(plan)', -}; +/// A day's kcal with a glyph for where the number came from. +class _DayFigure extends StatelessWidget { + const _DayFigure(this.day, {required this.belowFloor}); -String _summary(WeekPlan plan) { - final per = plan.perRemaining; - if (per == null) { - return 'Every day is known: week average ' - '${whole(plan.weekAvg)} kcal.'; + final DayPlan day; + final bool belowFloor; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (icon, spoken) = switch (day.source) { + 'typed' => (Icons.edit, '(typed)'), + 'logged' => (Icons.check, '(logged)'), + 'unlogged' => (Icons.help_outline, '(not logged -- type it)'), + _ => (Icons.insights, '(plan)'), + }; + final bad = day.source == 'plan' && belowFloor; + final unlogged = day.source == 'unlogged'; + final tint = bad + ? scheme.error + : unlogged + ? CueKind.warn.tint(context) + : null; + return Row( + children: [ + MacroFigure(kind: MacroKind.kcal, value: '${day.kcal}', size: 16), + const SizedBox(width: AppSpacing.sm), + Icon(icon, size: 16, color: tint, semanticLabel: spoken), + ], + ); + } +} + +/// What to eat on the open days, or the finished week's average. +class _Summary extends StatelessWidget { + const _Summary(this.plan, this.scheme); + + final WeekPlan plan; + final ColorScheme scheme; + + @override + Widget build(BuildContext context) { + final per = plan.perRemaining; + if (per == null) { + return Row( + children: [ + Icon( + Icons.check_circle, + color: CueKind.ok.tint(context), + semanticLabel: 'Every day is known: week average', + ), + const SizedBox(width: AppSpacing.xs), + MacroFigure(kind: MacroKind.kcal, value: whole(plan.weekAvg)), + ], + ); + } + return Row( + children: [ + const Icon(Icons.restaurant, size: 18, semanticLabel: 'Eat'), + const SizedBox(width: AppSpacing.xs), + MacroFigure(kind: MacroKind.kcal, value: '$per'), + const SizedBox(width: AppSpacing.md), + const Icon(Icons.flag_outlined, size: 18, semanticLabel: 'average'), + const SizedBox(width: AppSpacing.xs), + Text('${plan.targetAvg}'), + if (plan.belowFloor) ...[ + const SizedBox(width: AppSpacing.md), + const StatusCue( + kind: CueKind.error, + icon: Icons.vertical_align_bottom, + semanticLabel: 'below the $minTargetKcal kcal floor', + ), + ], + ], + ); } - final floor = plan.belowFloor ? ' -- below the 1200 kcal floor!' : ''; - return 'Eat $per kcal on each open day to average ' - '${plan.targetAvg}$floor'; } diff --git a/app/lib/widgets/body/weight_card.dart b/app/lib/widgets/body/weight_card.dart index 10f6171..5e51b00 100644 --- a/app/lib/widgets/body/weight_card.dart +++ b/app/lib/widgets/body/weight_card.dart @@ -5,12 +5,11 @@ library; import 'package:diet_guard_app/models/body_document.dart'; -import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/services/body_service.dart'; -import 'package:diet_guard_app/widgets/body/body_section.dart'; -import 'package:diet_guard_app/widgets/body/weight_chart.dart'; +import 'package:diet_guard_app/widgets/body/dated_value_card.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; + +export 'package:diet_guard_app/widgets/body/dated_value_card.dart'; /// Weight: 20-400 kg; wake-alarm weigh-ins land here too. class WeightCard extends StatelessWidget { @@ -24,12 +23,12 @@ class WeightCard extends StatelessWidget { Widget build(BuildContext context) { final body = BodyService.instance; return DatedValueCard( - title: 'Weight', - fieldLabel: 'Weight (kg)', + semanticLabel: 'Weight', + fieldSemanticLabel: 'Weight (kg)', + icon: Icons.monitor_weight, unit: 'kg', min: 20, max: 400, - hint: 'Morning weigh-ins from wake-alarm appear here.', latest: body.latestWeight, series: body.weightSeries, onSave: body.setWeight, @@ -51,12 +50,12 @@ class BodyFatCard extends StatelessWidget { Widget build(BuildContext context) { final body = BodyService.instance; return DatedValueCard( - title: 'Body fat', - fieldLabel: 'Body fat (%)', + semanticLabel: 'Body fat', + fieldSemanticLabel: 'Body fat (%)', + icon: Icons.percent, unit: '%', min: minBodyFat, max: maxBodyFat, - hint: 'With a body fat %, targets use the lean-mass (Katch-McArdle) BMR.', latest: body.latestBodyFat, series: body.bodyFatSeries, onSave: body.setBodyFat, @@ -65,150 +64,3 @@ class BodyFatCard extends StatelessWidget { ); } } - -/// Enters/deletes a day's value and charts the history. -class DatedValueCard extends StatefulWidget { - /// Creates the card. - const DatedValueCard({ - required this.title, - required this.fieldLabel, - required this.unit, - required this.min, - required this.max, - required this.hint, - required this.latest, - required this.series, - required this.onSave, - required this.onDelete, - required this.onChanged, - super.key, - }); - - /// Section heading. - final String title; - - /// Input label. - final String fieldLabel; - - /// Unit suffix (`kg`, `%`). - final String unit; - - /// Smallest accepted value. - final double min; - - /// Largest accepted value. - final double max; - - /// Note shown until something is saved. - final String hint; - - /// Newest `(day, value)`, or null. - final (String, double)? latest; - - /// Every live `(day, value)`, oldest first. - final List<(String, double)> series; - - /// Writes a value for a day. - final Future Function(String day, double value) onSave; - - /// Deletes a day. - final Future Function(String day) onDelete; - - /// Called once a value has been written or deleted. - final VoidCallback onChanged; - - @override - State createState() => _DatedValueCardState(); -} - -class _DatedValueCardState extends State { - final _value = TextEditingController(); - String _day = localDateKey(DateTime.now()); - String? _status; - - @override - void dispose() { - _value.dispose(); - super.dispose(); - } - - String _fmt(double value) => '${oneDecimal(value)} ${widget.unit}'; - - Future _pickDay() async { - final picked = await showDatePicker( - context: context, - firstDate: DateTime(2000), - lastDate: DateTime.now(), - initialDate: DateTime.parse(_day), - ); - if (picked == null || !mounted) return; - setState(() => _day = localDateKey(picked)); - } - - Future _save() async { - final value = double.tryParse(_value.text.replaceAll(',', '.')); - if (value == null || value < widget.min || value > widget.max) { - setState( - () => _status = - '${widget.title} must be ${whole(widget.min)}-' - '${whole(widget.max)} ${widget.unit}.', - ); - return; - } - await widget.onSave(_day, value); - if (!mounted) return; - _value.clear(); - setState(() => _status = 'Saved ${_fmt(value)} for $_day.'); - widget.onChanged(); - } - - Future _delete() async { - await widget.onDelete(_day); - if (!mounted) return; - setState(() => _status = 'Deleted $_day.'); - widget.onChanged(); - } - - @override - Widget build(BuildContext context) { - final latest = widget.latest; - return BodySection( - title: widget.title, - children: [ - BodyStatRow( - 'Latest', - latest == null ? 'none yet' : '${_fmt(latest.$2)} (${latest.$1})', - ), - Row( - children: [ - Expanded( - child: TextField( - controller: _value, - decoration: InputDecoration(labelText: widget.fieldLabel), - keyboardType: const TextInputType.numberWithOptions( - decimal: true, - ), - inputFormatters: [ - FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), - ], - ), - ), - TextButton(onPressed: _pickDay, child: Text(_day)), - ], - ), - Row( - children: [ - Expanded(child: BodyNote(_status ?? widget.hint)), - IconButton( - icon: const Icon(Icons.delete_outline), - tooltip: 'Delete this day', - onPressed: _delete, - ), - FilledButton(onPressed: _save, child: const Text('Save')), - ], - ), - WeightChart(series: widget.series), - ], - ); - } -} diff --git a/app/lib/widgets/body/weight_chart.dart b/app/lib/widgets/body/weight_chart.dart index 4d84e98..c17937c 100644 --- a/app/lib/widgets/body/weight_chart.dart +++ b/app/lib/widgets/body/weight_chart.dart @@ -4,11 +4,12 @@ /// drawn to scale rather than evenly spaced. library; +import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; -/// Selectable chart ranges, `(label, days)`; null days = everything. +/// Selectable chart ranges, `(spoken name, days)`; null days = everything. const List<(String, int?)> weightChartRanges = [ ('30d', 30), ('90d', 90), @@ -61,11 +62,19 @@ class _WeightChartState extends State { Wrap( spacing: AppSpacing.sm, children: [ - for (final (label, days) in weightChartRanges) - ChoiceChip( - label: Text(label), - selected: _days == days, - onSelected: (_) => setState(() => _days = days), + for (final (spoken, days) in weightChartRanges) + SpokenLabel( + semanticLabel: spoken, + child: ChoiceChip( + // Days as a bare numeral; "everything" as the infinity glyph. + label: ExcludeSemantics( + child: days == null + ? const Icon(Icons.all_inclusive, size: 18) + : Text('$days'), + ), + selected: _days == days, + onSelected: (_) => setState(() => _days = days), + ), ), ], ), @@ -73,7 +82,14 @@ class _WeightChartState extends State { SizedBox( height: 200, child: points.length < 2 - ? const Center(child: Text('Need two readings for a graph.')) + ? Center( + child: Icon( + Icons.show_chart, + size: 64, + color: Theme.of(context).colorScheme.outline, + semanticLabel: 'Need two readings for a graph.', + ), + ) : _chart(context, points), ), ], diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 626a5cb..047d9d1 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.142+1 +version: 1.0.143+1 environment: sdk: ^3.12.2 diff --git a/app/test/screens/body_screen_goal_test.dart b/app/test/screens/body_screen_goal_test.dart index 34c0075..6a87d74 100644 --- a/app/test/screens/body_screen_goal_test.dart +++ b/app/test/screens/body_screen_goal_test.dart @@ -2,9 +2,11 @@ import 'package:diet_guard_app/models/body_document.dart'; import 'package:diet_guard_app/services/body_energy.dart'; import 'package:diet_guard_app/services/body_prefs.dart'; import 'package:diet_guard_app/services/body_service.dart'; +import 'package:diet_guard_app/ui/cues.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../label_finders.dart'; import 'body_screen_support.dart'; void main() { @@ -22,10 +24,12 @@ void main() { await seedPerson(store); await pumpBody(tester); await openTile(tester, 'Daily calorie target'); + // Each mark of the goal row is spoken as its value; so is its picker + // option, hence `.last` for the option (the row stays mounted behind). Future choose(String word, String option) async { - await tester.tap(find.text(word).first); + await tester.tap(bySemLabel(word).first); await tester.pumpAndSettle(); - await tester.tap(find.text(option).last); + await tester.tap(bySemLabel(option).last); await tester.pumpAndSettle(); } @@ -50,24 +54,25 @@ void main() { ); // A typed amount; junk is refused and the dialog stays open. - final other = find.widgetWithText(TextField, 'Other amount'); + final other = fieldByLabel('Other amount'); await tester.tap(find.text('1')); await tester.pumpAndSettle(); await tester.enterText(other, ''); - await tester.tap(find.text('OK')); + await tester.tap(byIconLabel('OK')); await tester.pumpAndSettle(); - expect(find.text('OK'), findsOneWidget); + expect(byIconLabel('OK'), findsOneWidget); + expect(cueOfKind(CueKind.error), findsOneWidget); await tester.enterText(other, '2,5'); - await tester.tap(find.text('OK')); + await tester.tap(byIconLabel('OK')); await tester.pumpAndSettle(); expect(savedGoal(BodyService.instance).amount, 2.5); // Cancel changes nothing; neither does dismissing a sheet. await tester.tap(find.text('2.5')); await tester.pumpAndSettle(); - await tester.tap(find.text('Cancel')); + await tester.tap(byIconLabel('Cancel')); await tester.pumpAndSettle(); - await tester.tap(find.text('gain')); + await tester.tap(bySemLabel('gain').first); await tester.pumpAndSettle(); await tester.tapAt(const Offset(5, 5)); await tester.pumpAndSettle(); @@ -86,16 +91,19 @@ void main() { await setGoal(body, const Goal('lose', 1, 'kg', 'week', 'measured:MET')); await pumpBody(tester); await openTile(tester, 'Daily calorie target'); - expect(find.textContaining('no workouts published yet'), findsOneWidget); - await tester.tap(find.text('Measured (MET)')); + expect( + cueLabelled('no workouts published yet (the PC publishes them).'), + findsOneWidget, + ); + await tester.tap(bySemLabel('Measured (MET)').first); await tester.pumpAndSettle(); - await tester.tap(find.text('Sedentary').last); + await tester.tap(bySemLabel('Sedentary').last); await tester.pumpAndSettle(); await tester.tap(find.text('1')); await tester.pumpAndSettle(); - await tester.enterText(find.widgetWithText(TextField, 'Other amount'), '3'); - await tester.tap(find.text('OK')); + await tester.enterText(fieldByLabel('Other amount'), '3'); + await tester.tap(byIconLabel('OK')); await tester.pumpAndSettle(); - expect(find.textContaining('below the 1200 kcal floor'), findsOneWidget); + expect(cueLabelled('That is below the 1200 kcal floor.'), findsOneWidget); }); } diff --git a/app/test/screens/body_screen_steps_test.dart b/app/test/screens/body_screen_steps_test.dart index f9937ee..bbe51a3 100644 --- a/app/test/screens/body_screen_steps_test.dart +++ b/app/test/screens/body_screen_steps_test.dart @@ -1,11 +1,11 @@ import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/services/body_service.dart'; import 'package:diet_guard_app/services/health_steps.dart'; -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'body_screen_support.dart'; +import '../label_finders.dart'; import '../services/health_steps_test.dart' show FakeStepsSource; +import 'body_screen_support.dart'; void main() { final original = stepsSource; @@ -36,14 +36,14 @@ void main() { expect(fake.lastRead, isNull, reason: 'never reads before permission'); await openTile(tester, 'Activity'); - await tester.tap(find.text('Connect Health Connect steps')); + await tester.tap(byIconLabel('Connect Health Connect steps')); await tester.pumpAndSettle(); - expect(find.text('Connect Health Connect steps'), findsOneWidget); + expect(byIconLabel('Connect Health Connect steps'), findsOneWidget); fake.grantOnRequest = true; - await tester.tap(find.text('Connect Health Connect steps')); + await tester.tap(byIconLabel('Connect Health Connect steps')); await tester.pumpAndSettle(); - expect(find.text('Connect Health Connect steps'), findsNothing); + expect(byIconLabel('Connect Health Connect steps'), findsNothing); expect( BodyService.instance.document.steps[localDateKey(yesterday)]!.n, 6500, @@ -56,13 +56,13 @@ void main() { await pumpBody(tester); await openTile(tester, 'Activity'); expect(fake.lastRead, isNotNull); - expect(find.text('Connect Health Connect steps'), findsNothing); + expect(byIconLabel('Connect Health Connect steps'), findsNothing); }); testWidgets('a Health Connect error just hides nothing', (tester) async { stepsSource = FakeStepsSource()..failWith = StateError('gone'); await pumpBody(tester); await openTile(tester, 'Activity'); - expect(find.text('Connect Health Connect steps'), findsOneWidget); + expect(byIconLabel('Connect Health Connect steps'), findsOneWidget); }); } diff --git a/app/test/screens/body_screen_support.dart b/app/test/screens/body_screen_support.dart index e82870a..c76e028 100644 --- a/app/test/screens/body_screen_support.dart +++ b/app/test/screens/body_screen_support.dart @@ -11,6 +11,7 @@ import 'package:diet_guard_app/widgets/body/body_tile_grid.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../label_finders.dart'; import '../services/body_test_support.dart'; export '../services/body_test_support.dart'; @@ -89,11 +90,11 @@ Future seedPerson(MemoryDocStore store, {Object? goal}) async { double topOf(WidgetTester tester, Finder finder) => tester.getTopLeft(finder.first).dy; -/// The overview tile titled [title]. +/// The overview tile spoken as [title]. Finder tile(String title) => - find.descendant(of: find.byType(BodyTileGrid), matching: find.text(title)); + find.descendant(of: find.byType(BodyTileGrid), matching: bySemLabel(title)); -/// Opens the sheet behind the tile titled [title]. +/// Opens the sheet behind the tile spoken as [title]. Future openTile(WidgetTester tester, String title) async { await tester.tap(tile(title)); await tester.pumpAndSettle(); @@ -109,9 +110,9 @@ Future closeSheet(WidgetTester tester) async { Finder inSheet(Finder finder) => find.descendant(of: find.byType(BottomSheet), matching: finder); -/// Titles of the overview tiles, in display order. +/// Spoken names of the overview tiles, in display order. List tileTitles(WidgetTester tester) => tester .widget(find.byType(BodyTileGrid)) .tiles - .map((t) => t.title) + .map((t) => t.semanticLabel) .toList(); diff --git a/app/test/screens/body_screen_test.dart b/app/test/screens/body_screen_test.dart index bbe2eab..7ef8160 100644 --- a/app/test/screens/body_screen_test.dart +++ b/app/test/screens/body_screen_test.dart @@ -1,9 +1,11 @@ import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/screens/body_screen.dart'; import 'package:diet_guard_app/services/body_service.dart'; +import 'package:diet_guard_app/ui/cues.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../label_finders.dart'; import 'body_screen_support.dart'; void main() { @@ -20,18 +22,30 @@ void main() { ) async { await pumpBody(tester); expect(tileTitles(tester).first, 'Profile'); - expect(find.textContaining('Age unknown'), findsOneWidget); + // Unknown age: the profile tile carries no number and no cake. + expect( + find.descendant(of: tile('Profile'), matching: find.byIcon(Icons.cake)), + findsNothing, + ); await openTile(tester, 'Daily calorie target'); - expect(find.textContaining('Set your profile and enter'), findsOneWidget); + // Both inputs missing: one warning glyph each (profile, weight). + expect(cueOfKind(CueKind.warn), findsNWidgets(2)); + expect( + cueLabelled(bodyMissingNote(BodyService.instance)), + findsNWidgets(2), + ); await closeSheet(tester); await openTile(tester, 'Activity'); - expect(find.textContaining('No activity data yet'), findsOneWidget); + expect( + cueLabelled('No activity data yet -- published by the PC.'), + findsOneWidget, + ); await closeSheet(tester); await openTile(tester, 'Weight'); - expect(find.text('Need two readings for a graph.'), findsOneWidget); + expect(byIconLabel('Need two readings for a graph.'), findsOneWidget); await closeSheet(tester); await openTile(tester, 'Body fat'); - expect(find.text('Need two readings for a graph.'), findsOneWidget); + expect(byIconLabel('Need two readings for a graph.'), findsOneWidget); }); testWidgets('a weight without a profile asks for the profile', ( @@ -40,7 +54,12 @@ void main() { await BodyService.instance.setWeight('2026-09-20', 80); await pumpBody(tester); await openTile(tester, 'Daily calorie target'); - expect(find.textContaining('Set your profile (birth'), findsOneWidget); + expect( + cueLabelled( + 'Set your profile (birth date, height, sex) to see the numbers.', + ), + findsOneWidget, + ); }); testWidgets('a profile without a weight asks for the weight', (tester) async { @@ -51,7 +70,10 @@ void main() { ); await pumpBody(tester); await openTile(tester, 'Daily calorie target'); - expect(find.text('Enter your weight to see the numbers.'), findsOneWidget); + expect( + cueLabelled('Enter your weight to see the numbers.'), + findsOneWidget, + ); }); testWidgets('a full profile: goal first, profile then body fat last', ( @@ -68,44 +90,52 @@ void main() { ); expect(titles.last, 'Body fat'); // Headline numbers on the tiles themselves. - expect(find.text('2209 kcal'), findsOneWidget); + expect( + find.descendant( + of: tile('Daily calorie target'), + matching: find.text('2209'), + ), + findsOneWidget, + ); expect(find.text('80.0 kg'), findsOneWidget); expect(find.text('24.7'), findsOneWidget); - expect(find.textContaining('Age 30'), findsOneWidget); + expect( + find.descendant(of: tile('Profile'), matching: find.text('30')), + findsOneWidget, + ); // 80 kg, 180 cm, 30 y, male, lose 0.5 kg/week on Moderate: // 1780 x 1.55 - 550 = 2209. await openTile(tester, 'Daily calorie target'); - expect(find.text('2209'), findsOneWidget); - expect( - find.textContaining('Maintenance 2759 kcal (Mifflin-St Jeor'), - findsOneWidget, - ); + expect(inSheet(find.text('2209')), findsOneWidget); + expect(inSheet(find.text('2759')), findsOneWidget); + expect(inSheet(find.text('Mifflin-St Jeor')), findsOneWidget); await closeSheet(tester); await openTile(tester, 'BMI'); expect(inSheet(find.text('24.7')), findsOneWidget); expect(find.text('59.9-80.7 kg'), findsOneWidget); + expect(byIconLabel('normal'), findsOneWidget); await closeSheet(tester); await openTile(tester, 'Ideal weight'); - expect(find.text('Average of all'), findsOneWidget); + expect(byIconLabel('Average of all'), findsOneWidget); expect(find.textContaining('Broca'), findsNothing); await closeSheet(tester); await openTile(tester, 'Resting metabolism (BMR)'); - expect(inSheet(find.text('1780 kcal')), findsOneWidget); - expect(find.text('n/a -- log a body-fat %'), findsNWidgets(2)); + expect(inSheet(find.text('1780')), findsOneWidget); + expect(byIconLabel('n/a -- log a body-fat %'), findsNWidgets(2)); await closeSheet(tester); // 5000 steps over baseline x 0.747 m x 0.5 x 80 kg = 149.4 kcal, and // all the data is from yesterday, so the window is that one day. await openTile(tester, 'Activity'); + expect(find.text('9000 ${yesterdayKey()}'), findsOneWidget); + expect(inSheet(find.text('149')), findsOneWidget); expect( - find.textContaining('Steps outside workouts: 9000 on ${yesterdayKey()}'), + byIconLabel('Mean daily exercise, last 1 full days:'), findsOneWidget, ); - expect(find.textContaining('add 149 kcal/day'), findsOneWidget); - expect(find.text('Mean daily exercise, last 1 full days:'), findsOneWidget); expect(find.textContaining('Evening run'), findsOneWidget); expect(find.textContaining('StrongLifts A'), findsOneWidget); - expect(find.text('Connect Health Connect steps'), findsNothing); + expect(byIconLabel('Connect Health Connect steps'), findsNothing); }); testWidgets('a body fat switches the target to Katch-McArdle', ( @@ -114,24 +144,25 @@ void main() { await seedPerson(store); await pumpBody(tester); await openTile(tester, 'Body fat'); - final field = find.widgetWithText(TextField, 'Body fat (%)'); + final field = fieldByLabel('Body fat (%)'); await tester.enterText(field, '99'); - await tester.tap(find.text('Save')); + await tester.tap(byIconLabel('Save')); await tester.pumpAndSettle(); - expect(find.text('Body fat must be 3-70 %.'), findsOneWidget); + expect(cueLabelled('Body fat must be 3-70 %.'), findsOneWidget); + expect(cueOfKind(CueKind.error), findsOneWidget); await tester.enterText(field, '18,5'); - await tester.tap(find.text('Save')); + await tester.tap(byIconLabel('Save')); await tester.pumpAndSettle(); expect(BodyService.instance.latestBodyFat?.$2, 18.5); await closeSheet(tester); expect(find.text('18.5 %'), findsOneWidget); await openTile(tester, 'Daily calorie target'); - expect(find.textContaining('(Katch-McArdle resting'), findsOneWidget); - expect(find.text('2206'), findsOneWidget); + expect(inSheet(find.text('Katch-McArdle')), findsOneWidget); + expect(inSheet(find.text('2206')), findsOneWidget); await closeSheet(tester); await openTile(tester, 'Resting metabolism (BMR)'); - expect(inSheet(find.text('1778 kcal')), findsOneWidget); + expect(inSheet(find.text('1778')), findsOneWidget); }); testWidgets('saving and deleting a weight updates the numbers', ( @@ -140,14 +171,14 @@ void main() { await seedPerson(store); await pumpBody(tester); await openTile(tester, 'Weight'); - final field = find.widgetWithText(TextField, 'Weight (kg)'); + final field = fieldByLabel('Weight (kg)'); await tester.enterText(field, '5'); - await tester.tap(find.text('Save')); + await tester.tap(byIconLabel('Save')); await tester.pumpAndSettle(); - expect(find.text('Weight must be 20-400 kg.'), findsOneWidget); + expect(cueLabelled('Weight must be 20-400 kg.'), findsOneWidget); await tester.enterText(field, '90,5'); - await tester.tap(find.text('Save')); + await tester.tap(byIconLabel('Save')); await tester.pumpAndSettle(); final today = localDateKey(DateTime.now()); expect(BodyService.instance.latestWeight, (today, 90.5)); @@ -155,27 +186,32 @@ void main() { expect(find.text('27.9'), findsOneWidget); // 90.5 / 1.8^2 on the BMI tile await openTile(tester, 'Weight'); - await tester.tap(find.byTooltip('Delete this day').first); + await tester.tap(byIconLabel('Delete this day').first); await tester.pumpAndSettle(); expect(BodyService.instance.latestWeight?.$1, yesterdayKey()); + + // The undo arrow brings the deleted day back, value and all. + await tester.tap(byIconLabel('Undo')); + await tester.pumpAndSettle(); + expect(BodyService.instance.latestWeight, (today, 90.5)); }); testWidgets('the profile form validates height and saves', (tester) async { await pumpBody(tester); await openTile(tester, 'Profile'); - final field = find.widgetWithText(TextField, 'Height (cm)'); + final field = fieldByLabel('Height (cm)'); await tester.enterText(field, '9'); - await tester.tap(find.text('Save profile')); + await tester.tap(byIconLabel('Save profile')); await tester.pumpAndSettle(); - expect(find.text('Height must be 50-260 cm.'), findsOneWidget); + expect(cueLabelled('Height must be 50-260 cm.'), findsOneWidget); await tester.enterText(field, '172.5'); - await tester.tap(find.text('Female')); - await tester.tap(find.text('Save profile')); + await tester.tap(byIconLabel('Female')); + await tester.tap(byIconLabel('Save profile')); await tester.pumpAndSettle(); expect(BodyService.instance.heightCm, 172.5); expect(BodyService.instance.sex, 'f'); - expect(find.text('Saved.'), findsOneWidget); + expect(cueLabelled('Saved.'), findsOneWidget); }); test('kcalByDay of an empty log is empty', () { diff --git a/app/test/widgets/body/body_widgets_test.dart b/app/test/widgets/body/body_widgets_test.dart index f012085..af4ac9d 100644 --- a/app/test/widgets/body/body_widgets_test.dart +++ b/app/test/widgets/body/body_widgets_test.dart @@ -9,6 +9,7 @@ import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../../label_finders.dart'; Future _pump(WidgetTester tester, Widget child) async { tester.view.physicalSize = const Size(1200, 4000); @@ -29,6 +30,12 @@ const _short = Biometrics( isMale: false, ); +/// [text] inside the planner's summary row (the one led by the fork glyph). +Finder inSummary(String text) => find.descendant( + of: find.ancestor(of: byIconLabel('Eat'), matching: find.byType(Row)).first, + matching: find.text(text), +); + void main() { group('helpers', () { test('halfUp rounds half away from banker', () { @@ -68,18 +75,21 @@ void main() { }); }); - testWidgets('a short teenager sees n/a formulas and the age note', ( - tester, - ) async { + testWidgets('a short teenager sees dashes and the age band', (tester) async { await _pump( tester, const Column( - children: [BmiCard(bio: _short), IdealWeightCard(bio: _short)], + children: [ + BmiCard(bio: _short), + IdealWeightCard(bio: _short), + ], ), ); - expect(find.text('n/a'), findsNWidgets(3)); - expect(find.textContaining('undefined below 152.4 cm'), findsOneWidget); - expect(find.text('adult categories do not apply under 20'), findsOneWidget); + expect(find.text('—'), findsNWidgets(3)); + expect( + byIconLabel('adult categories do not apply under 20'), + findsOneWidget, + ); }); testWidgets('activity card states', (tester) async { @@ -87,7 +97,10 @@ void main() { tester, const ActivityCard(sessions: [], weightKg: null, exercise: null), ); - expect(find.textContaining('Enter your weight'), findsOneWidget); + expect( + cueLabelled('Enter your weight to estimate exercise kcal.'), + findsOneWidget, + ); await _pump( tester, const ActivityCard( @@ -96,8 +109,8 @@ void main() { exercise: {'MET': 0, 'ACSM': 0, 'Per-km': 0}, ), ); - expect(find.textContaining('No workouts in the last 28 days'), findsOne); - expect(find.text('0 kcal/day'), findsNWidgets(3)); + expect(cueLabelled('No workouts in the last 28 days.'), findsOneWidget); + expect(find.text('0'), findsNWidgets(3)); var tapped = false; await _pump( tester, @@ -110,12 +123,13 @@ void main() { onConnectSteps: () => tapped = true, ), ); - expect(find.textContaining('No activity data yet'), findsNothing); expect( - find.textContaining('12000 on 2026-09-27; above 4000/day they add 20'), - findsOneWidget, + cueLabelled('No activity data yet -- published by the PC.'), + findsNothing, ); - await tester.tap(find.text('Connect Health Connect steps')); + expect(find.text('12000 2026-09-27'), findsOneWidget); + expect(find.text('20'), findsOneWidget); + await tester.tap(byIconLabel('Connect Health Connect steps')); expect(tapped, isTrue); }); @@ -129,8 +143,8 @@ void main() { today: DateTime(2026, 9, 27), ), ); - expect(find.text('Need two readings for a graph.'), findsOneWidget); - await tester.tap(find.text('All')); + expect(byIconLabel('Need two readings for a graph.'), findsOneWidget); + await tester.tap(bySemLabel('All')); await tester.pumpAndSettle(); expect(find.byType(LineChart), findsOneWidget); }); @@ -147,27 +161,35 @@ void main() { ), ); // Mon logged, Tue unlogged: (14000 - 2500) / 6 = 1917. - expect(find.textContaining('2500 kcal (logged)'), findsOneWidget); - expect(find.textContaining('(not logged -- type it)'), findsOneWidget); - expect(find.textContaining('Eat 1917 kcal'), findsOneWidget); + expect(byIconLabel('(logged)'), findsOneWidget); + expect(find.text('2500'), findsOneWidget); + expect(byIconLabel('(not logged -- type it)'), findsOneWidget); + expect(inSummary('1917'), findsOneWidget); - final dayFields = find.widgetWithText(TextField, 'ate…'); + final dayFields = fieldByLabel('ate…'); await tester.enterText(dayFields.at(1), '1800'); await tester.pumpAndSettle(); - expect(find.textContaining('1800 kcal (typed)'), findsOneWidget); - expect(find.textContaining('Eat 1940 kcal'), findsOneWidget); + expect(byIconLabel('(typed)'), findsOneWidget); + expect( + find + .byType(Text) + .evaluate() + .where((e) => (e.widget as Text).data == '1800'), + hasLength(1), + ); + expect(inSummary('1940'), findsOneWidget); await tester.enterText( - find.widgetWithText(TextField, 'Weekly average target (kcal/day)'), + fieldByLabel('Weekly average target (kcal/day)'), '900', ); await tester.pumpAndSettle(); - expect(find.textContaining('below the 1200 kcal floor'), findsOneWidget); + expect(cueLabelled('below the 1200 kcal floor'), findsOneWidget); for (var i = 0; i < 7; i++) { await tester.enterText(dayFields.at(i), '2000'); } await tester.pumpAndSettle(); - expect(find.textContaining('Every day is known'), findsOneWidget); + expect(byIconLabel('Every day is known: week average'), findsOneWidget); }); }