Compare commits

..

No commits in common. "45627f70751efb0cf80e38cd508f5c7874e04ed4" and "832f9ab7da213612d22a7d12ba669d42aa7f28ae" have entirely different histories.

110 changed files with 2059 additions and 3857 deletions

View File

@ -18,8 +18,6 @@ import 'package:diet_guard_app/services/body_prefs.dart';
import 'package:diet_guard_app/services/body_service.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/health_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.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/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/activity_card.dart'; import 'package:diet_guard_app/widgets/body/activity_card.dart';
import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart';
@ -111,13 +109,22 @@ class _BodyScreenState extends State<BodyScreen> {
final (exercise, _, _) = bodyExercise(body, bio, today); final (exercise, _, _) = bodyExercise(body, bio, today);
final tiles = _tiles(body, bio, exercise); final tiles = _tiles(body, bio, exercise);
return Scaffold( return Scaffold(
appBar: AppBar(), appBar: AppBar(title: const Text('Body')),
body: Padding( body: Padding(
padding: const EdgeInsets.all(AppSpacing.md), padding: const EdgeInsets.all(AppSpacing.md),
child: Center( child: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose), constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: BodyTileGrid(tiles: tiles), child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
BodyTileGrid(tiles: tiles),
const SizedBox(height: AppSpacing.sm),
BodyNote(
'Age ${bodyAgeText(body, today)} · synced with the PC.',
),
],
),
), ),
), ),
), ),
@ -152,12 +159,8 @@ class _BodyScreenState extends State<BodyScreen> {
) { ) {
final weight = body.latestWeight?.$2; final weight = body.latestWeight?.$2;
final bodyFat = body.latestBodyFat?.$2; final bodyFat = body.latestBodyFat?.$2;
final age = bodyAgeText(body, DateTime.now());
final profile = BodyTileSpec( final profile = BodyTileSpec(
semanticLabel: 'Profile', title: 'Profile',
icon: Icons.person,
value: age,
valueIcon: age == null ? null : Icons.cake,
builder: (_) => ProfileCard(onSaved: _onChanged), builder: (_) => ProfileCard(onSaved: _onChanged),
); );
final goal = bio == null final goal = bio == null
@ -171,65 +174,45 @@ class _BodyScreenState extends State<BodyScreen> {
return [ return [
if (_profileAtTop) profile, if (_profileAtTop) profile,
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Daily calorie target', title: 'Daily calorie target',
icon: Icons.flag, value: goal == null ? null : '$goal kcal',
value: goal == null ? null : '$goal',
valueIcon: goal == null ? null : MacroKind.kcal.icon,
builder: (_) => bio == null builder: (_) => bio == null
? BodySection( ? BodySection(
semanticLabel: 'Daily calorie target', title: 'Daily calorie target',
children: [ children: [BodyNote(bodyMissingNote(body))],
Row(
children: [
for (final icon in bodyMissingIcons(body))
StatusCue(
kind: CueKind.warn,
icon: icon,
semanticLabel: bodyMissingNote(body),
),
],
),
],
) )
: GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat), : GoalCard(bio: bio, exercise: exercise, bodyFatPct: bodyFat),
), ),
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Weight', title: 'Weight',
icon: Icons.monitor_weight,
value: weight == null ? null : formatKg(weight), value: weight == null ? null : formatKg(weight),
builder: (_) => WeightCard(onChanged: _onChanged), builder: (_) => WeightCard(onChanged: _onChanged),
), ),
if (bio != null) ...[ if (bio != null) ...[
BodyTileSpec( BodyTileSpec(
semanticLabel: 'BMI', title: 'BMI',
icon: Icons.accessibility_new,
value: oneDecimal(bmiReport(bio).bmi), value: oneDecimal(bmiReport(bio).bmi),
builder: (_) => BmiCard(bio: bio), builder: (_) => BmiCard(bio: bio),
), ),
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Ideal weight', title: 'Ideal weight',
icon: Icons.balance,
builder: (_) => IdealWeightCard(bio: bio), builder: (_) => IdealWeightCard(bio: bio),
), ),
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Resting metabolism (BMR)', title: 'Resting metabolism (BMR)',
icon: Icons.bedtime, value: '${whole(tableBmr(bio, bodyFat).value!)} kcal',
value: whole(tableBmr(bio, bodyFat).value!),
valueIcon: MacroKind.kcal.icon,
builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat), builder: (_) => BmrCard(bio: bio, bodyFatPct: bodyFat),
), ),
], ],
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Activity', title: 'Activity',
icon: Icons.directions_run,
builder: (_) => ValueListenableBuilder<bool>( builder: (_) => ValueListenableBuilder<bool>(
valueListenable: _canConnectSteps, valueListenable: _canConnectSteps,
builder: (_, canConnect, _) => _activityCard(canConnect: canConnect), builder: (_, canConnect, _) => _activityCard(canConnect: canConnect),
), ),
), ),
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Week planner', title: 'Week planner (info only)',
icon: Icons.calendar_view_week,
builder: (_) => WeekPlanCard( builder: (_) => WeekPlanCard(
defaultTarget: AppSettingsService.dailyKcalGoal, defaultTarget: AppSettingsService.dailyKcalGoal,
logged: _logged, logged: _logged,
@ -237,8 +220,7 @@ class _BodyScreenState extends State<BodyScreen> {
), ),
if (!_profileAtTop) profile, if (!_profileAtTop) profile,
BodyTileSpec( BodyTileSpec(
semanticLabel: 'Body fat', title: 'Body fat',
icon: Icons.percent,
value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %', value: bodyFat == null ? null : '${oneDecimal(bodyFat)} %',
builder: (_) => BodyFatCard(onChanged: _onChanged), builder: (_) => BodyFatCard(onChanged: _onChanged),
), ),

View File

@ -6,7 +6,6 @@ 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_service.dart';
import 'package:diet_guard_app/services/body_steps.dart'; import 'package:diet_guard_app/services/body_steps.dart';
import 'package:diet_guard_app/services/log_storage_service.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 /// Builds the person from the stored profile and newest weight, or null
/// when anything the formulas need is missing. /// when anything the formulas need is missing.
@ -62,16 +61,7 @@ Map<String, double> kcalByDay(DayLog log) => {
.fold<double>(0, (sum, food) => sum + food.kcal), .fold<double>(0, (sum, food) => sum + food.kcal),
}; };
/// Glyphs of the inputs still missing (profile, weight), in the order the /// Why the numbers are missing.
/// user should supply them; the visible counterpart of [bodyMissingNote].
List<IconData> 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) { String bodyMissingNote(BodyService body) {
if (body.latestWeight == null && body.birth == null) { if (body.latestWeight == null && body.birth == null) {
return 'Set your profile and enter your weight to see BMI, ideal ' return 'Set your profile and enter your weight to see BMI, ideal '
@ -81,8 +71,8 @@ String bodyMissingNote(BodyService body) {
return 'Set your profile (birth date, height, sex) to see the numbers.'; return 'Set your profile (birth date, height, sex) to see the numbers.';
} }
/// The age in whole years, or null while no birth date is stored. /// The age line value.
String? bodyAgeText(BodyService body, DateTime today) { String bodyAgeText(BodyService body, DateTime today) {
final birth = DateTime.tryParse(body.birth ?? ''); final birth = DateTime.tryParse(body.birth ?? '');
return birth == null ? null : '${ageOn(birth, today)}'; return birth == null ? 'unknown' : '${ageOn(birth, today)}';
} }

View File

@ -17,8 +17,6 @@ import 'package:diet_guard_app/services/average_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/day_status_service.dart'; import 'package:diet_guard_app/services/day_status_service.dart';
import 'package:diet_guard_app/services/log_storage_service.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/widgets/average_summary_row.dart'; import 'package:diet_guard_app/widgets/average_summary_row.dart';
import 'package:diet_guard_app/widgets/day_status_calendar.dart'; import 'package:diet_guard_app/widgets/day_status_calendar.dart';
import 'package:diet_guard_app/widgets/streak_summary_row.dart'; import 'package:diet_guard_app/widgets/streak_summary_row.dart';
@ -155,8 +153,9 @@ class _CalendarScreenState extends State<CalendarScreen> {
if (_loading) { if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator())); return const Scaffold(body: Center(child: CircularProgressIndicator()));
} }
final theme = Theme.of(context);
return Scaffold( return Scaffold(
appBar: AppBar(), appBar: AppBar(title: const Text('Calendar')),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(
@ -169,10 +168,11 @@ class _CalendarScreenState extends State<CalendarScreen> {
if (_budgetStatus != null) if (_budgetStatus != null)
Padding( Padding(
padding: const EdgeInsets.only(top: 4), padding: const EdgeInsets.only(top: 4),
child: StatusCue( child: Text(
key: ValueKey(_budgetStatus), _budgetStatus!,
kind: _budgetError ? CueKind.error : CueKind.ok, style: TextStyle(
semanticLabel: _budgetStatus!, color: _budgetError ? theme.colorScheme.error : null,
),
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@ -215,11 +215,7 @@ class _BudgetRow extends StatelessWidget {
return Row( return Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon( const Text('Daily budget (kcal):'),
MacroKind.kcal.icon,
color: MacroKind.kcal.color,
semanticLabel: 'Daily budget (kcal)',
),
const SizedBox(width: 8), const SizedBox(width: 8),
SizedBox( SizedBox(
width: 90, width: 90,
@ -234,10 +230,7 @@ class _BudgetRow extends StatelessWidget {
const SizedBox(width: 8), const SizedBox(width: 8),
FilledButton( FilledButton(
onPressed: onEditOrSave, onPressed: onEditOrSave,
child: Icon( child: Text(editing ? 'Save' : 'Edit'),
editing ? Icons.check : Icons.edit,
semanticLabel: editing ? 'Save' : 'Edit',
),
), ),
], ],
); );

View File

@ -8,7 +8,6 @@ import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/models/nutrition.dart'; import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart'; import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart'; import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -36,7 +35,6 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
List<FoodSuggestion> _suggestions = const []; List<FoodSuggestion> _suggestions = const [];
String _source = 'manual'; String _source = 'manual';
String? _status; String? _status;
int _rejections = 0;
@override @override
void initState() { void initState() {
@ -82,7 +80,9 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
} }
Future<void> _onDescChanged() async { Future<void> _onDescChanged() async {
final matches = await FoodBankService.instance.search(_descController.text); final matches = await FoodBankService.instance.search(
_descController.text,
);
if (!mounted) return; if (!mounted) return;
setState(() => _suggestions = matches); setState(() => _suggestions = matches);
} }
@ -104,10 +104,7 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
Future<void> _onSave() async { Future<void> _onSave() async {
final desc = _descController.text.trim(); final desc = _descController.text.trim();
if (desc.isEmpty) { if (desc.isEmpty) {
setState(() { setState(() => _status = 'Description cannot be empty.');
_status = 'Description cannot be empty.';
_rejections++;
});
return; return;
} }
final nutrition = nutritionForPortion( final nutrition = nutritionForPortion(
@ -145,16 +142,17 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar(), appBar: AppBar(title: const Text('Edit meal')),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
IconField( TextField(
icon: Icons.restaurant,
semanticLabel: 'What did you eat?',
controller: _descController, controller: _descController,
decoration: const InputDecoration(
labelText: 'What did you eat?',
),
), ),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 240), constraints: const BoxConstraints(maxHeight: 240),
@ -170,20 +168,12 @@ class _EditEntryScreenState extends State<EditEntryScreen> {
width: double.infinity, width: double.infinity,
child: ElevatedButton( child: ElevatedButton(
onPressed: _onSave, onPressed: _onSave,
child: const Icon(Icons.check, semanticLabel: 'Save'), child: const Text('Save'),
), ),
), ),
if (_status != null) ...[ if (_status != null) ...[
const SizedBox(height: 12), const SizedBox(height: 12),
// New key per rejection so a repeat error shakes again. Text(_status!),
Align(
alignment: Alignment.centerLeft,
child: StatusCue(
key: ValueKey(_rejections),
kind: CueKind.error,
semanticLabel: _status!,
),
),
], ],
], ],
), ),

View File

@ -153,16 +153,15 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
final all = _allEntries; final all = _allEntries;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Food Bank'),
actions: [ actions: [
if (all != null) if (all != null)
Stack( Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
IconButton( IconButton(
icon: const Icon( icon: const Icon(Icons.filter_list),
Icons.filter_list, tooltip: 'Filter & sort',
semanticLabel: 'Filter & sort',
),
onPressed: _openFilterSheet, onPressed: _openFilterSheet,
), ),
if (_filter.isActive) if (_filter.isActive)
@ -186,19 +185,19 @@ class _FoodBankScreenState extends State<FoodBankScreen> {
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: _displayed.isEmpty : _displayed.isEmpty
? Center( ? Center(
child: Icon( child: Text(
all.isEmpty ? Icons.restaurant_menu : Icons.filter_list_off, all.isEmpty
size: 64, ? 'Food bank is empty.\n'
color: Theme.of(context).colorScheme.outline, 'Log meals to populate it, or add entries manually.'
semanticLabel: all.isEmpty
? 'Food bank is empty.'
: 'No entries match the current filter.', : 'No entries match the current filter.',
textAlign: TextAlign.center,
), ),
) )
: FbTileGrid(records: _displayed, onOpen: _openDetail), : FbTileGrid(records: _displayed, onOpen: _openDetail),
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: _openAddDialog, onPressed: _openAddDialog,
child: const Icon(Icons.add, semanticLabel: 'Add manual entry'), tooltip: 'Add manual entry',
child: const Icon(Icons.add),
), ),
); );
} }

View File

@ -28,27 +28,54 @@ class _ClientIdSetupDialogState extends State<_ClientIdSetupDialog> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Icon-only: the setup steps (open github.com/settings/developers, make
// an OAuth App with Device Flow, paste its client id) live in the repo
// docs, not on screen.
return AlertDialog( return AlertDialog(
content: IconField( title: const Text('One-time GitHub setup needed'),
icon: Icons.apps, content: SingleChildScrollView(
semanticLabel: 'Client ID', child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Diet Guard signs in via a GitHub OAuth App (no password '
'typed into this app). You only have to set this up once:',
),
const SizedBox(height: 12),
const Text(
'1. On any device, open '
'github.com/settings/developers → "New OAuth App".\n'
'2. Name/Homepage/Callback URL can be anything (device flow '
"doesn't use the callback) — e.g. "
'"Diet Guard" and your GitHub profile URL.\n'
'3. Check "Enable Device Flow", then click "Register '
'application".\n'
"4. Copy the Client ID shown on the app's page and paste it "
'below.',
),
const SizedBox(height: 12),
const Text(
'When you connect below, log in with the GitHub account that '
'has write access to kuhyx/syncs.',
),
const SizedBox(height: 16),
TextField(
controller: _controller, controller: _controller,
autofocus: true, autofocus: true,
decoration: const InputDecoration(labelText: 'Client ID'),
),
],
),
), ),
actions: [ actions: [
IconButton( TextButton(
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close, semanticLabel: 'Cancel'), child: const Text('Cancel'),
), ),
IconButton.filled( FilledButton(
onPressed: () { onPressed: () {
final id = _controller.text.trim(); final id = _controller.text.trim();
if (id.isNotEmpty) Navigator.of(context).pop(id); if (id.isNotEmpty) Navigator.of(context).pop(id);
}, },
icon: const Icon(Icons.arrow_forward, semanticLabel: 'Continue'), child: const Text('Continue'),
), ),
], ],
); );

View File

@ -21,7 +21,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
TextEditingController get _clientIdController; TextEditingController get _clientIdController;
bool _busy = false; bool _busy = false;
Widget? _status; String? _status;
String _storedToken = ''; String _storedToken = '';
SyncSettings _currentSettings() { SyncSettings _currentSettings() {
final typed = _tokenController.text.trim(); final typed = _tokenController.text.trim();
@ -37,18 +37,9 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
clientId: _clientIdController.text.trim(), clientId: _clientIdController.text.trim(),
); );
} }
void _showMessage(String message) {
/// Shows the outcome as an icon cue; [semanticLabel] is spoken, never
/// painted.
void _showCue(CueKind kind, String semanticLabel) {
if (!mounted) return; if (!mounted) return;
setState( setState(() => _status = message);
() => _status = StatusCue(
key: UniqueKey(),
kind: kind,
semanticLabel: semanticLabel,
),
);
} }
Future<void> _connectGitHub() async { Future<void> _connectGitHub() async {
@ -78,12 +69,12 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
_storedToken = token; _storedToken = token;
if (SyncSettings.exposesTokenValue) _tokenController.text = token; if (SyncSettings.exposesTokenValue) _tokenController.text = token;
}); });
_showCue(CueKind.info, 'Connected — syncing…'); _showMessage('Connected — syncing…');
await _currentSettings().save(); await _currentSettings().save();
await _syncAfterConnect(); await _syncAfterConnect();
} }
} on Exception catch (e) { } on Exception catch (e) {
_showCue(CueKind.error, 'Could not start device flow: $e'); _showMessage('Could not start device flow: $e');
} finally { } finally {
auth.close(); auth.close();
} }
@ -97,10 +88,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
try { try {
await runSync(await syncBackend(client)); await runSync(await syncBackend(client));
await SyncHealth.recordSuccess(); await SyncHealth.recordSuccess();
_showCue(CueKind.ok, 'Connected and synced.'); _showMessage('Connected and synced.');
} on Exception catch (e) { } on Exception catch (e) {
await SyncHealth.recordFailure(); await SyncHealth.recordFailure();
_showCue(CueKind.error, 'Connected, but sync failed: $e'); _showMessage('Connected, but sync failed: $e');
} finally { } finally {
client.close(); client.close();
} }
@ -111,7 +102,7 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
await _currentSettings().save(); await _currentSettings().save();
if (!mounted) return; if (!mounted) return;
setState(() => _busy = false); setState(() => _busy = false);
_showCue(CueKind.ok, 'Saved.'); _showMessage('Saved.');
} }
Future<void> _testConnection() async { Future<void> _testConnection() async {
@ -120,13 +111,11 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
final client = createGitHubClient(settings, httpClient: widget.httpClient); final client = createGitHubClient(settings, httpClient: widget.httpClient);
try { try {
final ok = await client.canAccessRepo(); final ok = await client.canAccessRepo();
if (ok) { _showMessage(
_showCue(CueKind.ok, 'GitHub connection OK.'); ok ? 'GitHub connection OK.' : 'GitHub connection failed.',
} else { );
_showCue(CueKind.error, 'GitHub connection failed.');
}
} on Exception catch (e) { } on Exception catch (e) {
_showCue(CueKind.error, 'GitHub connection failed: $e'); _showMessage('GitHub connection failed: $e');
} finally { } finally {
client.close(); client.close();
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);
@ -144,10 +133,10 @@ mixin _GitHubMirrorActions on State<GitHubMirrorScreen> {
// *because* the banner told them syncing had stopped, so a successful // *because* the banner told them syncing had stopped, so a successful
// run here must dismiss the warning it caused. // run here must dismiss the warning it caused.
await SyncHealth.recordSuccess(); await SyncHealth.recordSuccess();
_showCue(CueKind.ok, 'Synced.'); _showMessage('Synced.');
} on Exception catch (e) { } on Exception catch (e) {
await SyncHealth.recordFailure(); await SyncHealth.recordFailure();
_showCue(CueKind.error, 'Sync failed: $e'); _showMessage('Sync failed: $e');
} finally { } finally {
client.close(); client.close();
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);

View File

@ -13,7 +13,6 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/sync_health.dart'; import 'package:diet_guard_app/services/sync_health.dart';
import 'package:diet_guard_app/services/sync_service.dart'; import 'package:diet_guard_app/services/sync_service.dart';
import 'package:diet_guard_app/services/sync_settings.dart'; import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:github_device_auth/github_device_auth.dart'; import 'package:github_device_auth/github_device_auth.dart';
@ -95,86 +94,107 @@ class _GitHubMirrorScreenState extends State<GitHubMirrorScreen>
/// The token as loaded, so a platform that cannot display it (web) still /// The token as loaded, so a platform that cannot display it (web) still
/// round-trips it instead of blanking it on the next save. /// round-trips it instead of blanking it on the next save.
/// Runs the OAuth device flow and, on success, fills in the token field. /// Runs the OAuth device flow and, on success, fills in the token field.
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (_loading) { if (_loading) {
return const Scaffold(body: Center(child: CircularProgressIndicator())); return const Scaffold(body: Center(child: CircularProgressIndicator()));
} }
return Scaffold( return Scaffold(
// No title and no explanatory paragraph: the code glyph that opened this appBar: AppBar(title: const Text('Advanced sync (GitHub)')),
// screen names it, and the connect button is self-evident. // Centred and capped at the prose width -- see settings_screen.dart's
appBar: AppBar(), // note on why: on the desktop surface an uncapped ListView spanned the
// Centred and capped at the prose width so fields do not span the // full window, so explanatory paragraphs ran far past the readable
// whole window on the desktop surface. // line-length limit.
body: Center( body: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose), constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: ListView( child: ListView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
children: [ children: [
Text(
'Syncs still mirror to GitHub until every device has moved '
'to Firebase. Authorize in your browser — no token to '
'paste.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
Align( Align(
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
child: IconButton.filled( child: FilledButton.icon(
onPressed: _connectGitHub, onPressed: _connectGitHub,
icon: const Icon( icon: const Icon(Icons.login),
Icons.login, label: const Text('Connect GitHub'),
semanticLabel: 'Connect GitHub',
),
), ),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
IconField( TextField(
icon: Icons.person_outline,
semanticLabel: 'GitHub owner',
controller: _ownerController, controller: _ownerController,
decoration: const InputDecoration(labelText: 'GitHub owner'),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
IconField( TextField(
icon: Icons.folder_outlined,
semanticLabel: 'Repo',
controller: _repoController, controller: _repoController,
decoration: const InputDecoration(labelText: 'Repo'),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
IconField( TextField(
icon: Icons.apps,
semanticLabel: 'OAuth App client id',
controller: _clientIdController, controller: _clientIdController,
decoration: const InputDecoration(
labelText: 'OAuth App client id',
helperText: 'Needed for the Connect GitHub button',
),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
IconField( TextField(
icon: Icons.key,
semanticLabel: 'Personal access token (fallback)',
controller: _tokenController, controller: _tokenController,
obscure: true, obscureText: true,
decoration: InputDecoration(
labelText: 'Personal access token (fallback)',
// Both wrapper hints are web-only; a VM test always takes
// the null branch.
// coverage:ignore-start
helperText: SyncSettings.exposesTokenValue
? null
: _storedToken.isEmpty
? 'Stored by the desktop wrapper, never by the browser'
: 'A token is stored by the desktop wrapper; type '
'here only to replace it',
// coverage:ignore-end
helperMaxLines: 2,
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Wrap( Wrap(
spacing: 8, spacing: 8,
children: [ children: [
IconButton.filled( ElevatedButton(
onPressed: _busy ? null : _save, onPressed: _busy ? null : _save,
icon: const Icon(Icons.check, semanticLabel: 'Save'), child: const Text('Save'),
), ),
// Tests the GitHub connection only (a canAccessRepo call); OutlinedButton(
// it says nothing about Firebase.
IconButton.outlined(
onPressed: _busy ? null : _testConnection, onPressed: _busy ? null : _testConnection,
icon: const Icon( // Named for what it actually does: _testConnection builds
Icons.network_check, // a GitHub client and calls canAccessRepo(). It says
semanticLabel: 'Test GitHub connection', // nothing about Firebase, and the bare label implied
// otherwise.
child: const Text('Test GitHub connection'),
), ),
), ElevatedButton(
IconButton.filled(
onPressed: _busy ? null : _syncNow, onPressed: _busy ? null : _syncNow,
icon: const Icon(Icons.sync, semanticLabel: 'Sync now'), child: const Text('Sync now'),
), ),
], ],
), ),
if (_status != null) ...[ if (_status != null) ...[
const SizedBox(height: 16), const SizedBox(height: 16),
Align(alignment: Alignment.centerLeft, child: _status), Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
], ],
], ],
), ),

View File

@ -159,16 +159,15 @@ class _HistoryScreenState extends State<HistoryScreen> {
final allEntries = _allEntries; final allEntries = _allEntries;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('History'),
actions: [ actions: [
if (allEntries != null) if (allEntries != null)
Stack( Stack(
alignment: Alignment.center, alignment: Alignment.center,
children: [ children: [
IconButton( IconButton(
icon: const Icon( icon: const Icon(Icons.filter_list),
Icons.filter_list, tooltip: 'Filter & sort',
semanticLabel: 'Filter & sort',
),
onPressed: _openFilterSheet, onPressed: _openFilterSheet,
), ),
if (_filter.isActive) if (_filter.isActive)
@ -192,11 +191,8 @@ class _HistoryScreenState extends State<HistoryScreen> {
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: _displayed.isEmpty : _displayed.isEmpty
? Center( ? Center(
child: Icon( child: Text(
allEntries.isEmpty ? Icons.restaurant : Icons.filter_list_off, allEntries.isEmpty
size: 64,
color: Theme.of(context).colorScheme.outline,
semanticLabel: allEntries.isEmpty
? 'Nothing logged yet.' ? 'Nothing logged yet.'
: 'No entries match the current filter.', : 'No entries match the current filter.',
), ),

View File

@ -45,23 +45,28 @@ List<Widget> logMealAppBarActions({
required VoidCallback onBody, required VoidCallback onBody,
}) => [ }) => [
IconButton( IconButton(
icon: const Icon(Icons.monitor_weight, semanticLabel: 'Body'), icon: const Icon(Icons.monitor_weight),
tooltip: 'Body',
onPressed: onBody, onPressed: onBody,
), ),
IconButton( IconButton(
icon: const Icon(Icons.restaurant_menu, semanticLabel: 'Food bank'), icon: const Icon(Icons.restaurant_menu),
tooltip: 'Food bank',
onPressed: onFoodBank, onPressed: onFoodBank,
), ),
IconButton( IconButton(
icon: const Icon(Icons.history, semanticLabel: 'History'), icon: const Icon(Icons.history),
tooltip: 'History',
onPressed: onHistory, onPressed: onHistory,
), ),
IconButton( IconButton(
icon: const Icon(Icons.calendar_month, semanticLabel: 'Calendar'), icon: const Icon(Icons.calendar_month),
tooltip: 'Calendar',
onPressed: onCalendar, onPressed: onCalendar,
), ),
IconButton( IconButton(
icon: const Icon(Icons.settings, semanticLabel: 'Sync settings'), icon: const Icon(Icons.settings),
tooltip: 'Sync settings',
onPressed: onSettings, onPressed: onSettings,
), ),
]; ];

View File

@ -12,7 +12,6 @@ import 'package:diet_guard_app/screens/log_meal_sync_mixin.dart';
import 'package:diet_guard_app/services/kuchnia_fill_flow.dart'; import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart'; import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart'; import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Drives the screen's [FillAllFlow] and tidies the screen after a fill. /// Drives the screen's [FillAllFlow] and tidies the screen after a fill.
@ -22,9 +21,8 @@ mixin LogMealFillMixin<T extends StatefulWidget>
/// armed proposal along with it. /// armed proposal along with it.
FillAllFlow fillFlow = FillAllFlow(); FillAllFlow fillFlow = FillAllFlow();
/// Shows [message] as a status cue of [kind] (its words are only spoken). /// Shows [message] in the form's status line. Supplied by the screen.
/// Supplied by the screen. void showFillStatus(String message);
void showFillStatus(String message, {CueKind kind = CueKind.info});
/// A proposal belongs to the date it was fetched for; picking another (or /// A proposal belongs to the date it was fetched for; picking another (or
/// going back to today) must not leave "Confirm (N)" offering it. /// going back to today) must not leave "Confirm (N)" offering it.
@ -51,9 +49,7 @@ mixin LogMealFillMixin<T extends StatefulWidget>
// for the next tick, and the user is told the batch did not finish. // for the next tick, and the user is told the batch did not finish.
await publishAfterLog(); await publishAfterLog();
await refreshSlots(); await refreshSlots();
if (mounted) { if (mounted) showFillStatus('Fill all failed: $error');
showFillStatus('Fill all failed: $error', kind: CueKind.error);
}
return; return;
} }
if (!mounted) return; if (!mounted) return;
@ -63,10 +59,7 @@ mixin LogMealFillMixin<T extends StatefulWidget>
await _afterFill(outcome.written, later: day != null); await _afterFill(outcome.written, later: day != null);
} }
if (!mounted) return; if (!mounted) return;
showFillStatus( showFillStatus(outcome.message);
outcome.message,
kind: outcome.written.isNotEmpty ? CueKind.ok : CueKind.warn,
);
} }
/// Disarms a proposal without writing anything. /// Disarms a proposal without writing anything.

View File

@ -91,34 +91,21 @@ mixin LogMealFutureMixin<T extends StatefulWidget> on State<T> {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return Row( return Row(
children: [ children: [
// Today is the default and shows nothing; only a picked date (data) Icon(Icons.event, size: 18, color: scheme.onSurfaceVariant),
// is shown, marked by the calendar glyph.
if (date != null) ...[
Icon(
Icons.event,
size: 18,
color: scheme.onSurfaceVariant,
semanticLabel: 'Log date',
),
const SizedBox(width: AppSpacing.xs), const SizedBox(width: AppSpacing.xs),
], Expanded(child: Text(date == null ? 'Today' : localDateKey(date))),
Expanded( TextButton.icon(
child: date == null ? const SizedBox() : Text(localDateKey(date)),
),
IconButton(
// Not Icons.calendar_month: the app bar's own "Calendar" nav button // Not Icons.calendar_month: the app bar's own "Calendar" nav button
// already uses that, and a second one on screen makes // already uses that, and a second one on screen makes
// `find.byIcon` ambiguous for widget tests (and taps) alike. // `find.byIcon` ambiguous for widget tests (and taps) alike.
icon: Icon( icon: const Icon(Icons.date_range, size: 18),
Icons.date_range, label: Text(date == null ? 'Log for later' : 'Change date'),
size: 18,
semanticLabel: date == null ? 'Log for later' : 'Change date',
),
onPressed: _pickFutureDate, onPressed: _pickFutureDate,
), ),
if (date != null) if (date != null)
IconButton( IconButton(
icon: const Icon(Icons.close, semanticLabel: 'Back to today'), icon: const Icon(Icons.close),
tooltip: 'Back to today',
onPressed: resetFutureLog, onPressed: resetFutureLog,
), ),
], ],

View File

@ -25,7 +25,6 @@ import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/kuchnia_spread.dart'; import 'package:diet_guard_app/services/kuchnia_spread.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart'; import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -187,14 +186,9 @@ mixin LogMealKuchniaMixin<T extends StatefulWidget> on State<T> {
if (mounted) setState(() => deliveryBusy = false); if (mounted) setState(() => deliveryBusy = false);
} }
if (!mounted || message == null) return; if (!mounted || message == null) return;
// The outcome sentence stays as the spoken label; the snackbar paints ScaffoldMessenger.of(
// only a warning glyph (no delivery / not ready / fetch failed).
showCueSnack(
context, context,
kind: CueKind.warn, ).showSnackBar(SnackBar(content: Text(message)));
semanticLabel: message,
icon: Icons.restaurant,
);
} }
/// Prefills the form with the next queued dish, if there is one. /// Prefills the form with the next queued dish, if there is one.

View File

@ -18,7 +18,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_feedback.dart'; import 'package:diet_guard_app/services/log_feedback.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart'; import 'package:diet_guard_app/widgets/autocomplete_suggestion_list.dart';
import 'package:diet_guard_app/widgets/fill_all_row.dart'; import 'package:diet_guard_app/widgets/fill_all_row.dart';
@ -60,14 +59,9 @@ class _LogMealScreenState extends State<LogMealScreen>
@override @override
int? selectedSlot; int? selectedSlot;
String _source = 'manual'; String _source = 'manual';
CueState? _cue; // painted as a tinted icon, never as text String? _status;
TodayProgress? _progress; TodayProgress? _progress;
void _setCue(CueKind kind, String? label) {
_cue = label == null ? null : CueState.next(_cue, kind, label);
_progress = null;
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@ -123,8 +117,10 @@ class _LogMealScreenState extends State<LogMealScreen>
@override @override
void onDishPrefilled() => setState(() => _source = 'catering'); void onDishPrefilled() => setState(() => _source = 'catering');
@override @override
void showFillStatus(String message, {CueKind kind = CueKind.info}) => void showFillStatus(String message) => setState(() {
setState(() => _setCue(kind, message)); _status = message;
_progress = null;
});
void _onSuggestionSelected(FoodSuggestion suggestion) { void _onSuggestionSelected(FoodSuggestion suggestion) {
fillControllersFromSuggestion(suggestion, _descController, _macros); fillControllersFromSuggestion(suggestion, _descController, _macros);
@ -137,12 +133,18 @@ class _LogMealScreenState extends State<LogMealScreen>
Future<void> _onLogMeal() async { Future<void> _onLogMeal() async {
final desc = _descController.text.trim(); final desc = _descController.text.trim();
if (desc.isEmpty) { if (desc.isEmpty) {
setState(() => _setCue(CueKind.error, 'Type what you ate first.')); setState(() {
_status = 'Type what you ate first.';
_progress = null;
});
return; return;
} }
final target = resolveLogTarget(selectedSlot); final target = resolveLogTarget(selectedSlot);
if (target.error != null) { if (target.error != null) {
setState(() => _setCue(CueKind.error, target.error)); setState(() {
_status = target.error;
_progress = null;
});
return; return;
} }
// On the tap, before the write/sync: waiting for them is just latency. // On the tap, before the write/sync: waiting for them is just latency.
@ -169,7 +171,7 @@ class _LogMealScreenState extends State<LogMealScreen>
// becomes a dead letter -- the exact regression the PC gate once shipped. // becomes a dead letter -- the exact regression the PC gate once shipped.
advanceQueueAfterLog(desc); advanceQueueAfterLog(desc);
setState(() { setState(() {
_setCue(CueKind.info, queueStatusLine); _status = queueStatusLine;
_progress = buildTodayProgress(log, logged: entry); _progress = buildTodayProgress(log, logged: entry);
}); });
} }
@ -178,8 +180,7 @@ class _LogMealScreenState extends State<LogMealScreen>
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
// No title: the app's identity is the launcher icon, and the five title: const Text('Diet Guard'),
// destination glyphs fill the bar.
actions: [ actions: [
...logMealAppBarActions( ...logMealAppBarActions(
onFoodBank: onOpenFoodBank, onFoodBank: onOpenFoodBank,
@ -205,10 +206,9 @@ class _LogMealScreenState extends State<LogMealScreen>
setState(() => selectedSlot = slot), setState(() => selectedSlot = slot),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
IconField( TextField(
controller: _descController, controller: _descController,
icon: Icons.fastfood, decoration: const InputDecoration(labelText: 'What did you eat?'),
semanticLabel: 'What did you eat?',
), ),
AutocompleteSuggestionList( AutocompleteSuggestionList(
suggestions: _suggestions, suggestions: _suggestions,
@ -231,12 +231,12 @@ class _LogMealScreenState extends State<LogMealScreen>
busy: fillFlow.busy || deliveryBusy, busy: fillFlow.busy || deliveryBusy,
armedCount: fillFlow.armedCount, armedCount: fillFlow.armedCount,
), ),
// Mutually exclusive: _cue carries a validation complaint or // Mutually exclusive: _status carries a validation complaint,
// queue note, _progress the post-log summary; the two may stack // _progress the post-log summary. A successful log clears one
// only after a log that leaves dishes queued. // and sets the other, so the two never stack.
if (_cue != null) ...[ if (_status != null) ...[
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
_cue!.widget, Text(_status!),
], ],
if (_progress != null) ...[ if (_progress != null) ...[
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),

View File

@ -7,18 +7,11 @@
part of 'settings_screen.dart'; part of 'settings_screen.dart';
mixin _SettingsKcalGoal on State<SettingsScreen> { mixin _SettingsKcalGoal on State<SettingsScreen> {
/// The latest outcome as an icon cue; null until something happened. String? _status;
Widget? _status;
void _showCue(CueKind kind, String semanticLabel) { void _showMessage(String message) {
if (!mounted) return; if (!mounted) return;
setState( setState(() => _status = message);
() => _status = StatusCue(
key: UniqueKey(),
kind: kind,
semanticLabel: semanticLabel,
),
);
} }
Timer? _kcalGoalDebounce; Timer? _kcalGoalDebounce;
@ -57,13 +50,13 @@ mixin _SettingsKcalGoal on State<SettingsScreen> {
() => Permission.ignoreBatteryOptimizations.request(); () => Permission.ignoreBatteryOptimizations.request();
try { try {
final status = await request(); final status = await request();
if (status.isGranted) { _showMessage(
_showCue(CueKind.ok, 'Battery optimization exemption granted.'); status.isGranted
} else { ? 'Battery optimization exemption granted.'
_showCue(CueKind.warn, 'Exemption not granted.'); : 'Exemption not granted -- notifications may be delayed.',
} );
} on Exception catch (e) { } on Exception catch (e) {
_showCue(CueKind.error, 'Could not request exemption: $e'); _showMessage('Could not request exemption: $e');
} }
} }
} }

View File

@ -18,39 +18,21 @@ library;
import 'package:diet_guard_app/services/kuchnia_client.dart'; import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart'; import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart'; import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// What a delivery fetch reports: a cue [kind], a spoken [label] (never
/// painted) and, when dishes were banked, their [count] (painted as a number).
class FetchOutcome {
/// Creates an outcome.
const FetchOutcome(this.kind, this.label, {this.count});
/// Icon/colour of the cue.
final CueKind kind;
/// Spoken description; never painted.
final String label;
/// Dishes banked, shown as a bare number next to the cue.
final int? count;
}
/// Fetches today's delivery and reports what was banked. /// Fetches today's delivery and reports what was banked.
/// ///
/// Deliberately "banked", not "logged": a delivered meal is not an eaten /// Deliberately says "banked", not "logged": a delivered meal is not an eaten
/// meal, so the dishes land in the food bank and the user still taps to log /// meal, so the dishes land in the food bank and the user still taps to log
/// each one. Top-level so the settings screen can pass it without growing. /// each one. Top-level so the settings screen can pass it without growing.
Future<FetchOutcome> fetchTodaysDelivery() async { Future<String> fetchTodaysDelivery() async {
final result = await refreshDelivery(DateTime.now()); final result = await refreshDelivery(DateTime.now());
if (!result.ok) return FetchOutcome(CueKind.error, result.reason!); if (!result.ok) return result.reason!;
if (result.dishes.isEmpty) { if (result.dishes.isEmpty) return 'No delivery found for today.';
return const FetchOutcome(CueKind.warn, 'No delivery found for today.');
}
final count = result.dishes.length; final count = result.dishes.length;
return FetchOutcome(CueKind.ok, '$count dishes added', count: count); return '$count ${count == 1 ? 'dish' : 'dishes'} added to your food bank. '
'Log them from the meal screen when you eat them.';
} }
/// Credential fields plus, on Android, a "fetch today's delivery" action. /// Credential fields plus, on Android, a "fetch today's delivery" action.
@ -61,14 +43,18 @@ class KuchniaSettingsSection extends StatefulWidget {
/// button is replaced by a one-line explanation rather than silently /// button is replaced by a one-line explanation rather than silently
/// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a /// vanishing. [onFetch] defaults to the real fetch. Both are injectable so a
/// widget test can drive the section without a network or a platform check. /// widget test can drive the section without a network or a platform check.
const KuchniaSettingsSection({this.canFetch, this.onFetch, super.key}); const KuchniaSettingsSection({
this.canFetch,
this.onFetch,
super.key,
});
/// Whether this platform can reach the catering panel; null means ask. /// Whether this platform can reach the catering panel; null means ask.
final bool? canFetch; final bool? canFetch;
/// Fetches today's delivery and returns a status line; null means the real /// Fetches today's delivery and returns a status line; null means the real
/// one. /// one.
final Future<FetchOutcome> Function()? onFetch; final Future<String> Function()? onFetch;
@override @override
State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState(); State<KuchniaSettingsSection> createState() => _KuchniaSettingsSectionState();
@ -83,7 +69,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
); );
bool _obscured = true; bool _obscured = true;
bool _busy = false; bool _busy = false;
Widget? _status; String? _status;
@override @override
void dispose() { void dispose() {
@ -99,13 +85,7 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
_password.text, _password.text,
); );
if (!mounted) return; if (!mounted) return;
setState( setState(() => _status = 'Saved. It will sync to your other devices.');
() => _status = StatusCue(
key: UniqueKey(),
kind: CueKind.ok,
semanticLabel: 'Saved. It will sync to your other devices.',
),
);
} }
Future<void> _fetch() async { Future<void> _fetch() async {
@ -113,93 +93,92 @@ class _KuchniaSettingsSectionState extends State<KuchniaSettingsSection> {
_busy = true; _busy = true;
_status = null; _status = null;
}); });
final outcome = await (widget.onFetch ?? fetchTodaysDelivery)(); final message = await (widget.onFetch ?? fetchTodaysDelivery)();
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_busy = false; _busy = false;
_status = Row( _status = message;
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.sm,
children: [
StatusCue(
key: UniqueKey(),
kind: outcome.kind,
semanticLabel: outcome.label,
),
if (outcome.count != null) Text('${outcome.count}'),
],
);
}); });
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context);
final canFetch = widget.canFetch ?? kuchniaFetchSupported; final canFetch = widget.canFetch ?? kuchniaFetchSupported;
// The section owns its own leading divider so the settings screen needs a // The section owns its own leading divider so the settings screen needs a
// single line for it -- that file sits on the repo's 250-line ceiling. // single line for it -- that file sits on the repo's 250-line ceiling.
// No heading or blurb: the delivery truck on the fetch button names it.
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const SizedBox(height: 24), const SizedBox(height: 24),
const Divider(), const Divider(),
const SizedBox(height: 8), const SizedBox(height: 8),
Text('Kuchnia Wikinga', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
"Your catering panel login, so this device can look up the day's "
'delivered dishes and their macros. Stored and synced in plain '
'text, like the rest of your synced data.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field), constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: IconField( child: TextField(
icon: Icons.alternate_email,
semanticLabel: 'Panel e-mail',
controller: _username, controller: _username,
keyboardType: TextInputType.emailAddress, keyboardType: TextInputType.emailAddress,
autocorrect: false, autocorrect: false,
decoration: const InputDecoration(labelText: 'Panel e-mail'),
onSubmitted: (_) => _save(), onSubmitted: (_) => _save(),
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field), constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: IconField( child: TextField(
icon: Icons.key,
semanticLabel: 'Panel password',
controller: _password, controller: _password,
obscure: _obscured, obscureText: _obscured,
autocorrect: false, autocorrect: false,
onSubmitted: (_) => _save(), enableSuggestions: false,
suffix: IconButton( decoration: InputDecoration(
icon: Icon( labelText: 'Panel password',
_obscured ? Icons.visibility : Icons.visibility_off, suffixIcon: IconButton(
semanticLabel: _obscured ? 'Show password' : 'Hide password', icon: Icon(_obscured ? Icons.visibility : Icons.visibility_off),
), tooltip: _obscured ? 'Show password' : 'Hide password',
onPressed: () => setState(() => _obscured = !_obscured), onPressed: () => setState(() => _obscured = !_obscured),
), ),
), ),
onSubmitted: (_) => _save(),
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
Wrap( Wrap(
spacing: 8, spacing: 8,
runSpacing: 8, runSpacing: 8,
children: [ children: [
IconButton.filled( FilledButton(onPressed: _save, child: const Text('Save login')),
onPressed: _save, if (canFetch)
icon: const Icon(Icons.check, semanticLabel: 'Save login'), OutlinedButton.icon(
), onPressed: _busy ? null : _fetch,
// Browser builds show the button greyed out: the panel blocks icon: const Icon(Icons.restaurant),
// browser requests, and the disabled state is the cue. label: Text(
IconButton.outlined( _busy ? 'Fetching…' : "Fetch today's delivery",
onPressed: canFetch && !_busy ? _fetch : null,
icon: _busy
? const SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(
Icons.local_shipping_outlined,
semanticLabel: "Fetch today's delivery",
), ),
), ),
], ],
), ),
if (_status != null) ...[const SizedBox(height: 8), _status!], if (!canFetch) ...[
const SizedBox(height: 8),
Text(
'Android only — the catering panel blocks browser requests. Your '
'login still syncs to your phone from here.',
style: theme.textTheme.bodySmall,
),
],
if (_status != null) ...[
const SizedBox(height: 8),
Text(_status!, style: theme.textTheme.bodyMedium),
],
], ],
); );
} }

View File

@ -15,8 +15,6 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/firebase_client.dart'; import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart'; import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_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/ui/theme.dart';
import 'package:diet_guard_app/widgets/data_backup_row.dart'; import 'package:diet_guard_app/widgets/data_backup_row.dart';
import 'package:diet_guard_app/widgets/log_sound_tile.dart'; import 'package:diet_guard_app/widgets/log_sound_tile.dart';
@ -151,26 +149,30 @@ class _SettingsScreenState extends State<SettingsScreen>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
// No title: the gear that opened this screen already names it. appBar: AppBar(title: const Text('Settings')),
appBar: AppBar(), // Capped at the prose width: on the ~1366px desktop window the
// Capped at the prose width so fields do not span a ~1366px window. // paragraphs below ran ~180 chars/line, twice tokens.md rule 21's limit.
body: Center( body: Center(
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.prose), constraints: const BoxConstraints(maxWidth: AppWidth.prose),
child: ListView( child: ListView(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
children: [ children: [
Text('Nutrition', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
// A four-digit number: capped so the field does not read as a // A four-digit number: capped so the field does not read as a
// layout error by spanning the whole column. // layout error by spanning the whole column.
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field), constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: IconField( child: TextField(
icon: MacroKind.kcal.icon,
iconColor: MacroKind.kcal.color,
semanticLabel: 'Daily kcal goal',
controller: _kcalGoalController, controller: _kcalGoalController,
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
decoration: const InputDecoration(
labelText: 'Daily kcal goal',
helperText: 'Shown in the history day summary',
suffixText: 'kcal',
),
onChanged: _onKcalGoalChanged, onChanged: _onKcalGoalChanged,
), ),
), ),
@ -184,21 +186,15 @@ class _SettingsScreenState extends State<SettingsScreen>
const Divider(), const Divider(),
ListTile( ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
leading: const Icon( title: const Text('Sync settings'),
Icons.cloud_sync_outlined, subtitle: const Text('Firebase sync'),
semanticLabel: 'Sync settings',
),
trailing: const Icon(Icons.chevron_right), trailing: const Icon(Icons.chevron_right),
onTap: () => unawaited(_openSyncSettings()), onTap: () => unawaited(_openSyncSettings()),
), ),
// Legacy mirror: muted tint marks it as the secondary path.
ListTile( ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
leading: Icon( title: const Text('Advanced sync (GitHub)'),
Icons.code, subtitle: const Text('Cutover mirror — not recommended'),
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: 'Advanced sync (GitHub)',
),
trailing: const Icon(Icons.chevron_right), trailing: const Icon(Icons.chevron_right),
onTap: () => unawaited(_openGitHubMirror()), onTap: () => unawaited(_openGitHubMirror()),
), ),
@ -207,27 +203,42 @@ class _SettingsScreenState extends State<SettingsScreen>
.dailyKcalGoal .dailyKcalGoal
.toString(), .toString(),
), ),
const SizedBox(height: 24),
const Divider(),
const SizedBox(height: 8),
Text(
'Notifications',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 4),
Text(
_isAndroid
? 'A background check nags you every ~15 min if a '
'meal slot is overdue. Aggressive OEM battery '
'optimization (MIUI, some Samsung configs) can '
'delay this well past 15 min -- request an '
'exemption for reliable nagging.'
: 'A check runs every 5 min while this window is open and '
'notifies you about an overdue meal slot. A browser '
'cannot run anything once the window is closed -- on '
'the PC the real backstop is the diet_guard gate, '
'which locks the screen instead.',
style: Theme.of(context).textTheme.bodySmall,
),
// Battery-optimization exemption is Android-only, and // Battery-optimization exemption is Android-only, and
// `permission_handler` has no web implementation at all; // `permission_handler` has no web implementation at all;
// the row would throw rather than degrade in the browser. // the row would throw rather than degrade in the browser.
if (_isAndroid) ...[ if (_isAndroid) ...[
const SizedBox(height: 24), const SizedBox(height: 12),
const Divider(), OutlinedButton.icon(
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: IconButton.outlined(
onPressed: _requestBatteryExemption, onPressed: _requestBatteryExemption,
icon: const Icon( icon: const Icon(Icons.battery_alert),
Icons.battery_alert, label: const Text('Disable battery optimization'),
semanticLabel: 'Disable battery optimization',
),
),
), ),
], ],
if (_status != null) ...[ if (_status != null) ...[
const SizedBox(height: 16), const SizedBox(height: 16),
Align(alignment: Alignment.centerLeft, child: _status), Text(_status!, style: Theme.of(context).textTheme.bodyMedium),
], ],
], ],
), ),

View File

@ -22,6 +22,13 @@ export 'package:diet_guard_app/models/workout_session.dart';
/// Formula names, in display order. /// Formula names, in display order.
const List<String> activityFormulas = ['MET', 'ACSM', 'Per-km']; const List<String> 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. /// Measured activity averages at most the last two full weeks.
const int maxWindowDays = 14; const int maxWindowDays = 14;

View File

@ -31,6 +31,16 @@ const List<(double, String)> _bmiBands = [
]; ];
const String _topBand = 'obese class III'; 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 %. /// The lean-mass formula the calorie table switches to with a body fat %.
const String katchMcArdle = 'Katch-McArdle'; const String katchMcArdle = 'Katch-McArdle';

View File

@ -20,9 +20,8 @@ abstract class NotificationBackend {
/// of the app. /// of the app.
Future<bool?> requestPermission(); Future<bool?> requestPermission();
/// Posts (or replaces) the notification for [slot], titled with the slot's /// Posts (or replaces) the notification for [slot].
/// clock time and carrying no body text. Future<void> show(int slot, String title, String body);
Future<void> show(int slot, String title);
/// Removes the notification for [slot], if one is showing. /// Removes the notification for [slot], if one is showing.
Future<void> cancel(int slot); Future<void> cancel(int slot);

View File

@ -15,8 +15,7 @@ class LocalNotificationsBackend implements NotificationBackend {
final FlutterLocalNotificationsPlugin plugin; final FlutterLocalNotificationsPlugin plugin;
static const _channelId = 'diet_guard_due_slot'; static const _channelId = 'diet_guard_due_slot';
// The app's proper name, same as the launcher label (no descriptive text). static const _channelName = 'Meal reminders';
static const _channelName = 'DietGuard';
@override @override
Future<void> initialize() async { Future<void> initialize() async {
@ -48,7 +47,7 @@ class LocalNotificationsBackend implements NotificationBackend {
Future.value(); Future.value();
@override @override
Future<void> show(int slot, String title) async { Future<void> show(int slot, String title, String body) async {
const details = NotificationDetails( const details = NotificationDetails(
android: AndroidNotificationDetails( android: AndroidNotificationDetails(
_channelId, _channelId,
@ -57,7 +56,12 @@ class LocalNotificationsBackend implements NotificationBackend {
priority: Priority.high, priority: Priority.high,
), ),
); );
await plugin.show(id: slot, title: title, notificationDetails: details); await plugin.show(
id: slot,
title: title,
body: body,
notificationDetails: details,
);
} }
@override @override

View File

@ -36,13 +36,13 @@ class WebNotificationBackend implements NotificationBackend {
} }
@override @override
Future<void> show(int slot, String title) async { Future<void> show(int slot, String title, String body) async {
// Posting without permission throws; a silent no-op matches this // Posting without permission throws; a silent no-op matches this
// service's degrade-quietly stance everywhere else. // service's degrade-quietly stance everywhere else.
if (!_granted) return; if (!_granted) return;
_shown[slot] = web.Notification( _shown[slot] = web.Notification(
title, title,
web.NotificationOptions(tag: 'diet_guard_slot_$slot'), web.NotificationOptions(body: body, tag: 'diet_guard_slot_$slot'),
); );
} }

View File

@ -86,9 +86,11 @@ class NotificationService {
await _backend.cancel(id); await _backend.cancel(id);
} }
for (final slot in due) { for (final slot in due) {
// The title is only the overdue slot's clock time (a number from the await _backend.show(
// user's own schedule); the launcher icon is the second channel. slot,
await _backend.show(slot, slotLabel(slot)); 'Meal not logged',
"You haven't logged your ${slotLabel(slot)} meal yet.",
);
} }
} }
} }

View File

@ -53,7 +53,8 @@ abstract final class SyncHealth {
_recordFailure(SyncFailureKind.unconfigured); _recordFailure(SyncFailureKind.unconfigured);
/// Marks a tick that had a backend but failed to publish. /// Marks a tick that had a backend but failed to publish.
static Future<void> recordFailure() => _recordFailure(SyncFailureKind.failed); static Future<void> recordFailure() =>
_recordFailure(SyncFailureKind.failed);
static Future<void> _recordFailure(SyncFailureKind kind) => static Future<void> _recordFailure(SyncFailureKind kind) =>
_withPrefs((prefs) => prefs.setString(_kFailureKind, kind.name)); _withPrefs((prefs) => prefs.setString(_kFailureKind, kind.name));
@ -154,16 +155,6 @@ class SyncHealthStatus {
return 'Not syncing since ${_ago(since)}. Meals stay on this device.'; return 'Not syncing since ${_ago(since)}. Meals stay on this device.';
} }
/// Compact elapsed time (`5h`, `2d`) for a numeral beside the banner's
/// glyph; null when it has not been at least an hour or never succeeded.
String? get agoShort {
final last = lastSuccess;
if (last == null) return null;
final since = now.difference(last);
if (since < const Duration(hours: 1)) return null;
return since.inDays >= 1 ? '${since.inDays}d' : '${since.inHours}h';
}
static String _ago(Duration since) { static String _ago(Duration since) {
if (since.inDays >= 1) { if (since.inDays >= 1) {
return '${since.inDays}d ago'; return '${since.inDays}d ago';

View File

@ -1,197 +0,0 @@
/// Text-free status cues: tinted icon + shake + haptic instead of sentences.
///
/// Every cue carries its meaning twice (icon shape AND colour) and exposes
/// the old sentence only as a screen-reader label, never as visible text.
library;
import 'dart:async';
import 'dart:math' as math;
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
export 'package:diet_guard_app/ui/icon_field.dart';
/// What a [StatusCue] reports.
enum CueKind {
/// Something worked.
ok(Icons.check_circle),
/// Neutral information.
info(Icons.info),
/// Caution, e.g. nothing to do or only partly done.
warn(Icons.warning_amber_rounded),
/// Something failed or the input was rejected.
error(Icons.error);
const CueKind(this.icon);
/// Default glyph for this kind.
final IconData icon;
/// Tint for this kind from the active theme.
Color tint(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final status =
Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark;
return switch (this) {
CueKind.ok => status.success,
CueKind.info => scheme.onSurfaceVariant,
CueKind.warn => status.warning,
CueKind.error => scheme.error,
};
}
}
/// A tinted icon chip that replaces a status sentence.
///
/// [CueKind.error] shakes (~3 swings, skipped when the platform asks for
/// reduced motion) and fires a heavy haptic; [CueKind.ok] fires a light one.
/// [semanticLabel] is announced as a live region and is never painted.
class StatusCue extends StatefulWidget {
/// Creates a cue of [kind]; [icon] overrides the kind's default glyph.
const StatusCue({
required this.kind,
required this.semanticLabel,
this.icon,
super.key,
});
/// Meaning of the cue.
final CueKind kind;
/// Spoken description (screen readers, tests); never painted.
final String semanticLabel;
/// Optional glyph replacing [CueKind.icon].
final IconData? icon;
@override
State<StatusCue> createState() => _StatusCueState();
}
class _StatusCueState extends State<StatusCue>
with SingleTickerProviderStateMixin {
late final AnimationController _shake = AnimationController(
vsync: this,
duration: AppDuration.slow * 2,
);
@override
void initState() {
super.initState();
unawaited(_announce());
}
Future<void> _announce() async {
switch (widget.kind) {
case CueKind.error:
await HapticFeedback.heavyImpact();
if (mounted && !MediaQuery.disableAnimationsOf(context)) {
await _shake.forward();
}
case CueKind.ok:
await HapticFeedback.lightImpact();
case CueKind.info || CueKind.warn:
break;
}
}
@override
void dispose() {
_shake.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final tint = widget.kind.tint(context);
return Semantics(
liveRegion: true,
label: widget.semanticLabel,
child: ExcludeSemantics(
child: AnimatedBuilder(
animation: _shake,
builder: (context, child) => Transform.translate(
offset: Offset(math.sin(_shake.value * 6 * math.pi) * 8, 0),
child: child,
),
child: DecoratedBox(
decoration: BoxDecoration(
color: tint.withValues(alpha: 0.16),
borderRadius: BorderRadius.circular(AppRadius.md),
border: Border.all(color: tint),
),
child: Padding(
padding: const EdgeInsets.all(AppSpacing.sm),
child: Icon(widget.icon ?? widget.kind.icon, color: tint),
),
),
),
),
);
}
}
/// Shows an icon-only snackbar; [onUndo] adds an undo arrow inside it.
///
/// `SnackBarAction` can only carry text, so the undo is an [IconButton].
void showCueSnack(
BuildContext context, {
required CueKind kind,
required String semanticLabel,
IconData? icon,
VoidCallback? onUndo,
}) {
final messenger = ScaffoldMessenger.of(context)..hideCurrentSnackBar();
final tint = kind.tint(context);
messenger.showSnackBar(
SnackBar(
content: Semantics(
liveRegion: true,
label: semanticLabel,
child: Row(
children: [
Icon(icon ?? kind.icon, color: tint),
const Spacer(),
if (onUndo != null)
IconButton(
icon: const Icon(Icons.undo, semanticLabel: 'Undo'),
onPressed: () {
messenger.hideCurrentSnackBar();
onUndo();
},
),
],
),
),
),
);
}
/// One screen's current status cue; [seq] re-keys the widget so an identical
/// consecutive status still shakes/pulses again.
@immutable
class CueState {
/// Creates the successor of [previous] carrying [kind] and [label].
CueState.next(CueState? previous, this.kind, this.label)
: seq = (previous?.seq ?? 0) + 1;
/// Meaning.
final CueKind kind;
/// Spoken description; never painted.
final String label;
/// Monotonic counter used as the widget key.
final int seq;
/// The left-aligned cue widget for this state.
Widget get widget => Align(
alignment: Alignment.centerLeft,
child: StatusCue(key: ValueKey(seq), kind: kind, semanticLabel: label),
);
}

View File

@ -1,129 +0,0 @@
/// An icon-captioned text field: the glyph is painted, the words are only a
/// spoken label (see [IconField]).
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// A bordered text field whose caption is an icon plus a spoken label.
///
/// Replaces `InputDecoration(labelText: ...)`: the glyph is painted, the
/// words exist only for screen readers, tests and flutter-web-drive.
class IconField extends StatelessWidget {
/// Creates a field captioned by [icon].
const IconField({
required this.icon,
required this.semanticLabel,
this.controller,
this.keyboardType,
this.obscure = false,
this.suffix,
this.onChanged,
this.dense = false,
this.fieldKey,
this.iconColor,
this.inputFormatters,
this.onSubmitted,
this.autofocus = false,
this.autocorrect = true,
super.key,
});
/// Input formatters, e.g. digits only.
final List<TextInputFormatter>? inputFormatters;
/// Called when the user submits from the keyboard.
final ValueChanged<String>? onSubmitted;
/// Whether the field grabs focus when it first appears.
final bool autofocus;
/// Whether the keyboard may autocorrect (false for e-mails and secrets).
final bool autocorrect;
/// Painted caption.
final IconData icon;
/// Tint of [icon]; the theme's default when null.
final Color? iconColor;
/// Spoken caption; never painted.
final String semanticLabel;
/// Backing controller.
final TextEditingController? controller;
/// Keyboard type.
final TextInputType? keyboardType;
/// Hides the typed characters.
final bool obscure;
/// Trailing widget, e.g. a visibility toggle.
final Widget? suffix;
/// Change callback.
final ValueChanged<String>? onChanged;
/// Compact vertical padding.
final bool dense;
/// Key given to the inner [TextField].
final Key? fieldKey;
@override
Widget build(BuildContext context) {
// MergeSemantics folds the spoken label into the TextField's own node:
// a bare `Semantics(textField: true)` wrapper produced a second,
// disabled textbox beside the real one, so drivers tapped the dead one.
return MergeSemantics(
child: Semantics(
label: semanticLabel,
child: TextField(
key: fieldKey,
controller: controller,
keyboardType: keyboardType,
obscureText: obscure,
onChanged: onChanged,
onSubmitted: onSubmitted,
inputFormatters: inputFormatters,
autofocus: autofocus,
autocorrect: autocorrect,
enableSuggestions: autocorrect,
decoration: InputDecoration(
prefixIcon: ExcludeSemantics(child: Icon(icon, color: iconColor)),
prefixIconConstraints: dense
? const BoxConstraints(minWidth: 32, minHeight: 32)
: null,
suffixIcon: suffix,
isDense: dense,
),
),
),
);
}
}
/// Gives [child] a spoken name without painting any text.
///
/// Wraps `Semantics(label:)`; keeping the string on a `semanticLabel:` line
/// lets line-based text scanners recognise it as accessibility metadata even
/// after the formatter splits `Semantics(` from its arguments.
class SpokenLabel extends StatelessWidget {
/// Creates a labelled wrapper around [child].
const SpokenLabel({
required this.semanticLabel,
required this.child,
super.key,
});
/// Spoken name; never painted.
final String semanticLabel;
/// The widget being named.
final Widget child;
@override
Widget build(BuildContext context) =>
Semantics(label: semanticLabel, container: true, child: child);
}

View File

@ -1,80 +0,0 @@
/// Shape + colour vocabulary for the nutrition fields, so a field or figure
/// is recognised by its glyph instead of a "P"/"C"/"F"/"kcal" word.
///
/// Protein is a green circle, carbs an amber triangle, fat a blue square;
/// colour never carries the meaning alone (shape does too).
library;
import 'package:flutter/material.dart';
/// One nutrition field and its non-text identity.
enum MacroKind {
/// Reference weight the typed macros are stated for.
perGrams(Icons.scale, Color(0xFFAAA09A), 'per (g)', 'per'),
/// Energy.
kcal(Icons.bolt, Color(0xFFE08A3C), 'kcal', 'kcal'),
/// Protein.
protein(Icons.circle, Color(0xFF8A9A3C), 'protein g', 'P'),
/// Carbohydrate.
carbs(Icons.change_history, Color(0xFFE0A63C), 'carbs g', 'C'),
/// Fat.
fat(Icons.square, Color(0xFF6C9BD1), 'fat g', 'F'),
/// Portion weight actually eaten.
eaten(Icons.rice_bowl, Color(0xFFAAA09A), 'eaten (g)', 'eaten');
const MacroKind(this.icon, this.color, this._long, this._short);
/// Painted glyph.
final IconData icon;
/// Glyph tint.
final Color color;
final String _long;
final String _short;
/// Spoken name; the long form unless [compact].
String semanticLabel({required bool compact}) => compact ? _short : _long;
}
/// A glyph + number pair, e.g. a green circle and `12`.
class MacroFigure extends StatelessWidget {
/// Creates a figure for [kind] showing [grams] (or [value] verbatim).
const MacroFigure({
required this.kind,
required this.value,
this.size = 12,
super.key,
});
/// Which nutrient.
final MacroKind kind;
/// The number to show, already formatted.
final String value;
/// Glyph size.
final double size;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
kind.icon,
color: kind.color,
size: size,
semanticLabel: kind.semanticLabel(compact: false),
),
const SizedBox(width: 3),
Text(value),
],
);
}
}

View File

@ -1,33 +0,0 @@
/// Glyph for where a log entry came from, replacing the stored source word
/// (`manual`, `food bank`, `catering`) that used to be printed on screen.
library;
import 'package:flutter/material.dart';
/// Icon for a stored entry `source` value; unknown values get a neutral dot.
IconData sourceIcon(String source) => switch (source) {
'manual' => Icons.edit,
'food bank' => Icons.restaurant_menu,
'catering' => Icons.local_shipping,
_ => Icons.circle_outlined,
};
/// A small painted [sourceIcon] that still speaks the stored source value.
class SourceMark extends StatelessWidget {
/// Creates a mark for [source].
const SourceMark(this.source, {this.size = 14, super.key});
/// Stored source value.
final String source;
/// Glyph size.
final double size;
@override
Widget build(BuildContext context) => Icon(
sourceIcon(source),
size: size,
color: Theme.of(context).colorScheme.onSurfaceVariant,
semanticLabel: source,
);
}

View File

@ -2,7 +2,6 @@
library; library;
import 'package:diet_guard_app/models/food_suggestion.dart'; import 'package:diet_guard_app/models/food_suggestion.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// A tappable list of [FoodSuggestion]s, each filling the form on tap. /// A tappable list of [FoodSuggestion]s, each filling the form on tap.
@ -58,12 +57,8 @@ class AutocompleteSuggestionList extends StatelessWidget {
return ListTile( return ListTile(
dense: true, dense: true,
title: Text(suggestion.name), title: Text(suggestion.name),
subtitle: Align( subtitle: Text(
alignment: Alignment.centerLeft, '${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
child: MacroFigure(
kind: MacroKind.kcal,
value: suggestion.nutrition.kcal.toStringAsFixed(0),
),
), ),
onTap: () => onSelected(suggestion), onTap: () => onSelected(suggestion),
); );
@ -81,34 +76,17 @@ class AutocompleteSuggestionList extends StatelessWidget {
onTap: () => onSelected(suggestion), onTap: () => onSelected(suggestion),
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4), padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
Flexible(
child: Text( child: Text(
suggestion.name, '${suggestion.name} · '
'${suggestion.nutrition.kcal.toStringAsFixed(0)} kcal',
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
), ),
const SizedBox(width: 8),
MacroFigure(
kind: MacroKind.kcal,
value: suggestion.nutrition.kcal.toStringAsFixed(0),
),
],
),
),
), ),
if (remaining > 0) if (remaining > 0)
TextButton( TextButton(
onPressed: () => _showMore(context), onPressed: () => _showMore(context),
child: Row( child: Text('$remaining more'),
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.more_horiz, semanticLabel: 'More'),
const SizedBox(width: 4),
Text('+$remaining'),
],
),
), ),
], ],
); );

View File

@ -2,23 +2,23 @@
library; library;
import 'package:diet_guard_app/models/period_average.dart'; import 'package:diet_guard_app/models/period_average.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Displays this week's and this month's average kcal/day and their bands. /// Displays this week's and this month's average kcal/day and their bands.
/// ///
/// Mirrors `_calendar_view.py`'s `averages_text`, minus the words: each period /// Mirrors `_calendar_view.py`'s `averages_text`: "Avg/day (to yesterday):
/// is a calendar glyph, the average as a number, and the band as a tinted /// week NNNN kcal (band) · month NNNN kcal (band)".
/// icon (check = under, warning = slightly over, error = very over, dash =
/// no data) so colour is never the only channel.
/// ///
/// Both periods stop at yesterday, so this line does not swing every time a /// Both periods stop at yesterday, so this line does not swing every time a
/// meal is logged today -- it answers "how has this week gone", not "how am I /// meal is logged today -- it answers "how has this week gone", not "how am I
/// doing right now", which is what the Today progress card is for. /// doing right now", which is what the Today progress card is for.
class AverageSummaryRow extends StatelessWidget { class AverageSummaryRow extends StatelessWidget {
/// Creates an [AverageSummaryRow]. /// Creates an [AverageSummaryRow].
const AverageSummaryRow({required this.week, required this.month, super.key}); const AverageSummaryRow({
required this.week,
required this.month,
super.key,
});
/// The current ISO week's average, through yesterday. /// The current ISO week's average, through yesterday.
final PeriodAverage week; final PeriodAverage week;
@ -26,72 +26,18 @@ class AverageSummaryRow extends StatelessWidget {
/// The current calendar month's average, through yesterday. /// The current calendar month's average, through yesterday.
final PeriodAverage month; final PeriodAverage month;
@override static String _part(PeriodAverage period) {
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_PeriodFigure(
period: week,
icon: Icons.calendar_view_week,
semanticLabel: 'week',
),
const SizedBox(width: 24),
_PeriodFigure(
period: month,
icon: Icons.calendar_view_month,
semanticLabel: 'month',
),
],
);
}
}
class _PeriodFigure extends StatelessWidget {
const _PeriodFigure({
required this.period,
required this.icon,
required this.semanticLabel,
});
final PeriodAverage period;
final IconData icon;
final String semanticLabel;
(CueKind, IconData) get _band => switch (period.band) {
null => (CueKind.info, Icons.remove_circle_outline),
AverageBand.under => (CueKind.ok, Icons.check_circle),
AverageBand.slightlyOver => (CueKind.warn, Icons.warning_amber_rounded),
AverageBand.veryOver => (CueKind.error, Icons.error),
};
@override
Widget build(BuildContext context) {
final (kind, bandIcon) = _band;
final avg = period.avgKcal; final avg = period.avgKcal;
final style = Theme.of(context).textTheme.bodySmall; if (avg == null) return bandLabel(period.band);
return Row( return '${avg.round()} kcal (${bandLabel(period.band)})';
mainAxisSize: MainAxisSize.min, }
children: [
Icon(icon, size: 16, semanticLabel: semanticLabel), @override
const SizedBox(width: 4), Widget build(BuildContext context) {
Icon( return Text(
bandIcon, 'Avg/day (to yesterday): week ${_part(week)} · month ${_part(month)}',
size: 16, textAlign: TextAlign.center,
color: kind.tint(context), style: Theme.of(context).textTheme.bodySmall,
semanticLabel: bandLabel(period.band),
),
if (avg != null) ...[
const SizedBox(width: 4),
Icon(
MacroKind.kcal.icon,
size: 14,
color: MacroKind.kcal.color,
semanticLabel: 'kcal',
),
Text('${avg.round()}', style: style),
],
],
); );
} }
} }

View File

@ -2,11 +2,8 @@
library; library;
import 'package:diet_guard_app/services/activity_kcal.dart'; import 'package:diet_guard_app/services/activity_kcal.dart';
import 'package:diet_guard_app/ui/cues.dart'; import 'package:diet_guard_app/services/body_steps.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/body_section.dart';
import 'package:diet_guard_app/widgets/body/formula_figure.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// How many of the newest sessions to list. /// How many of the newest sessions to list.
@ -58,118 +55,48 @@ class ActivityCard extends StatelessWidget {
final lastDay = steps.isEmpty final lastDay = steps.isEmpty
? null ? null
: steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b); : steps.keys.reduce((a, b) => a.compareTo(b) > 0 ? a : b);
final muted = Theme.of(context).colorScheme.onSurfaceVariant;
return BodySection( return BodySection(
semanticLabel: 'Activity', title: 'Activity',
children: [ children: [
if (sessions == null && steps.isEmpty) if (sessions == null && steps.isEmpty)
const StatusCue( const BodyNote('No activity data yet -- published by the PC.'),
kind: CueKind.info,
icon: Icons.directions_run,
semanticLabel: 'No activity data yet -- published by the PC.',
),
if (means != null) ...[ if (means != null) ...[
Row( BodyNote('Mean daily exercise, last $window full days:'),
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) for (final name in activityFormulas)
_FormulaRow(name, whole(means[name] ?? 0)), BodyStatRow(name, '${whole(means[name] ?? 0)} kcal/day'),
], ],
if (lastDay != null && stepKcal != null) if (lastDay != null && stepKcal != null)
Padding( BodyNote(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs), 'Steps outside workouts: ${steps[lastDay]} on $lastDay; above '
child: Row( '$stepBaseline/day they add ${whole(stepKcal)} kcal/day '
children: [ '(included above).',
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) if (onConnectSteps != null)
Align( Align(
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
child: OutlinedButton( child: OutlinedButton.icon(
icon: const Icon(Icons.directions_walk),
label: const Text('Connect Health Connect steps'),
onPressed: onConnectSteps, 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) if (sessions != null && kg == null)
const StatusCue( const BodyNote('Enter your weight to estimate exercise kcal.'),
kind: CueKind.warn,
icon: Icons.monitor_weight,
semanticLabel: 'Enter your weight to estimate exercise kcal.',
),
if (sessions != null && kg != null) ...[ if (sessions != null && kg != null) ...[
const Divider(), const Divider(),
if (newest.isEmpty) if (newest.isEmpty)
const StatusCue( const BodyNote('No workouts in the last 28 days.'),
kind: CueKind.info,
icon: Icons.event_busy,
semanticLabel: 'No workouts in the last 28 days.',
),
for (final session in newest.take(activityListLimit)) for (final session in newest.take(activityListLimit))
_SessionTile(result: sessionKcal(session, kg)), _SessionTile(result: sessionKcal(session, kg)),
if (newest.isNotEmpty)
const BodyNote('~ = no distance, MET estimate used instead.'),
const BodyNote(methodsNote),
], ],
], ],
); );
} }
} }
/// A formula's glyph 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: Align(
alignment: Alignment.centerLeft,
child: FormulaGlyph(name),
),
),
MacroFigure(kind: MacroKind.kcal, value: value, size: 16),
],
),
);
}
class _SessionTile extends StatelessWidget { class _SessionTile extends StatelessWidget {
const _SessionTile({required this.result}); const _SessionTile({required this.result});
@ -179,52 +106,22 @@ class _SessionTile extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final session = result.session; final session = result.session;
final km = session.km; final km = session.km;
final muted = Theme.of(context).colorScheme.onSurfaceVariant; final distance = km == null ? '' : ', ${oneDecimal(km)} km';
return Padding( final kcal = [
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',
),
const SizedBox(width: AppSpacing.xs),
Expanded(
child: Wrap(
spacing: AppSpacing.sm,
children: [
for (final name in activityFormulas) for (final name in activityFormulas)
FormulaFigure( _formulaKcal(name, result.kcal[name]!, result.fallback.contains(name)),
name, ].join(' · ');
whole(result.kcal[name]!), return ListTile(
fallback: result.fallback.contains(name), dense: true,
), contentPadding: EdgeInsets.zero,
], title: Text('${session.day} ${session.label}'),
), subtitle: Text(
), '${whole(session.minutes)} min$distance\n$kcal kcal',
],
),
],
), ),
isThreeLine: true,
); );
} }
} }
String _formulaKcal(String name, double kcal, bool fallback) =>
'$name ${whole(kcal)}${fallback ? '~' : ''}';

View File

@ -1,74 +1,52 @@
/// A card, the building block of every Body screen section, plus the /// A titled card, the building block of every Body screen section.
/// icon-led stat rows the cards are made of. No headings: the overview tile
/// that opened the sheet already says what it is.
library; library;
import 'package:diet_guard_app/services/body_calc.dart'; import 'package:diet_guard_app/services/body_calc.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// A card with [children] stacked in it; [semanticLabel] names it for screen /// A card with a title row and [children] stacked below it.
/// readers and tests and is never painted.
class BodySection extends StatelessWidget { class BodySection extends StatelessWidget {
/// Creates a section. /// Creates a section.
const BodySection({ const BodySection({
required this.semanticLabel, required this.title,
required this.children, required this.children,
super.key, super.key,
}); });
/// Spoken name of the section. /// Section heading.
final String semanticLabel; final String title;
/// Section content. /// Section content.
final List<Widget> children; final List<Widget> children;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Semantics( final theme = Theme.of(context);
container: true, return Card(
label: semanticLabel,
child: Card(
margin: const EdgeInsets.only(bottom: AppSpacing.md), margin: const EdgeInsets.only(bottom: AppSpacing.md),
child: Padding( child: Padding(
padding: const EdgeInsets.all(AppSpacing.md), padding: const EdgeInsets.all(AppSpacing.md),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: children, children: [
), Text(title, style: theme.textTheme.titleMedium),
const SizedBox(height: AppSpacing.sm),
...children,
],
), ),
), ),
); );
} }
} }
/// One line of a stats card: a leading mark on the left, a value on the right. /// A label on the left, a value on the right; one line of a stats card.
///
/// 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 { class BodyStatRow extends StatelessWidget {
/// A row led by a formula's proper name. /// Creates a row.
const BodyStatRow.named(this.name, this.value, {this.color, super.key}) const BodyStatRow(this.label, this.value, {this.color, super.key});
: icon = null,
semanticLabel = null;
/// A row led by [icon], spoken as [semanticLabel]. /// What the value is.
const BodyStatRow.icon( final String label;
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. /// The formatted value.
final String value; final String value;
@ -78,19 +56,11 @@ class BodyStatRow extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final lead = icon;
return Padding( return Padding(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2), padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2),
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(child: Text(label)),
child: lead == null
? Text(name!)
: Align(
alignment: Alignment.centerLeft,
child: Icon(lead, size: 20, semanticLabel: semanticLabel),
),
),
Text( Text(
value, value,
style: TextStyle( style: TextStyle(
@ -104,8 +74,28 @@ class BodyStatRow extends StatelessWidget {
} }
} }
/// `74.99` -> `"75.0 kg"`, null -> a dash. Half-up, like the PC. /// A muted one-line explanation (missing data, notes).
String formatKg(double? kg) => kg == null ? '—' : '${oneDecimal(kg)} kg'; 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';
/// [value] to one decimal, rounded half-up like the PC prints it. /// [value] to one decimal, rounded half-up like the PC prints it.
String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1); String oneDecimal(double value) => halfUp(value, 1).toStringAsFixed(1);

View File

@ -2,26 +2,9 @@
library; library;
import 'package:diet_guard_app/services/body_calc.dart'; 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:diet_guard_app/widgets/body/body_section.dart';
import 'package:flutter/material.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. /// BMI, BMI Prime, Trefethen's BMI and the WHO category.
class BmiCard extends StatelessWidget { class BmiCard extends StatelessWidget {
/// Creates the card for [bio]. /// Creates the card for [bio].
@ -34,40 +17,30 @@ class BmiCard extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final report = bmiReport(bio); final report = bmiReport(bio);
final (low, high) = healthyRange(bio); final (low, high) = healthyRange(bio);
final (icon, kind) = bmiBandCue(report.category); final normal = report.category == 'normal';
final tint = kind.tint(context);
return BodySection( return BodySection(
semanticLabel: 'BMI', title: 'BMI',
children: [ children: [
Row( BodyStatRow(
children: [ 'BMI',
Icon(icon, color: tint, semanticLabel: report.category),
const SizedBox(width: AppSpacing.sm),
Text(
oneDecimal(report.bmi), oneDecimal(report.bmi),
style: Theme.of( color: normal ? null : Theme.of(context).colorScheme.error,
context,
).textTheme.headlineMedium?.copyWith(color: tint),
), ),
], BodyStatRow('Category', report.category),
), BodyStatRow('BMI Prime', halfUp(report.prime, 2).toStringAsFixed(2)),
const SizedBox(height: AppSpacing.sm), BodyStatRow('Trefethen (new BMI)', oneDecimal(report.trefethen)),
BodyStatRow.named( BodyStatRow(
'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)', 'Healthy weight for your height (BMI 18.5-24.9)',
'${oneDecimal(low)}-${oneDecimal(high)} kg', '${oneDecimal(low)}-${oneDecimal(high)} kg',
), ),
const BodyNote(bmiPrimeNote),
const BodyNote(trefethenNote),
], ],
); );
} }
} }
/// Every ideal-weight formula; a dash where one is undefined. /// Every ideal-weight formula; `n/a` where one is undefined.
class IdealWeightCard extends StatelessWidget { class IdealWeightCard extends StatelessWidget {
/// Creates the card for [bio]. /// Creates the card for [bio].
const IdealWeightCard({required this.bio, super.key}); const IdealWeightCard({required this.bio, super.key});
@ -78,25 +51,25 @@ class IdealWeightCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final formulas = idealWeights(bio); final formulas = idealWeights(bio);
final undefined = formulas.any((f) => f.value == null);
final summary = idealSummary(formulas); final summary = idealSummary(formulas);
return BodySection( return BodySection(
semanticLabel: 'Ideal weight', title: 'Ideal weight',
children: [ children: [
for (final formula in formulas) for (final formula in formulas)
BodyStatRow.named(formula.name, formatKg(formula.value)), BodyStatRow(formula.name, formatKg(formula.value)),
if (summary != null) ...[ if (summary != null) ...[
const Divider(), const Divider(),
BodyStatRow.icon( BodyStatRow('Average of all', formatKg(summary.$1)),
Icons.functions, BodyStatRow(
'Average of all',
formatKg(summary.$1),
),
BodyStatRow.icon(
Icons.swap_horiz,
'Ideal range', 'Ideal range',
'${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg', '${oneDecimal(summary.$2)}-${oneDecimal(summary.$3)} kg',
), ),
], ],
if (undefined)
const BodyNote(
'Devine, Robinson and Miller are undefined below 152.4 cm.',
),
], ],
); );
} }
@ -116,29 +89,14 @@ class BmrCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BodySection( return BodySection(
semanticLabel: 'Resting metabolism (BMR)', title: 'Resting metabolism (BMR)',
children: [ children: [
for (final formula in bmrFormulas(bio, bodyFatPct)) for (final formula in bmrFormulas(bio, bodyFatPct))
Padding( BodyStatRow(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.xs / 2), formula.name,
child: Row( formula.value == null
children: [ ? 'n/a -- log a body-fat %'
Expanded(child: Text(formula.name)), : '${whole(formula.value!)} kcal',
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,
),
],
),
), ),
], ],
); );

View File

@ -1,34 +1,22 @@
/// The Body screen's overview: two-column icon tiles that fit one phone /// The Body screen's overview: two-column metric tiles that fit one phone
/// screen. Tapping a tile opens the section's full card in a bottom sheet. /// screen. Tapping a tile opens the section's full card in a bottom sheet.
library; library;
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// One tile: a big [icon] (spoken as [semanticLabel]), an optional headline /// One tile: a section [title], an optional headline [value], and the
/// [value] and the [builder] of the full card shown in the sheet. /// [builder] of the full card shown in the sheet.
class BodyTileSpec { class BodyTileSpec {
/// Creates a tile spec. /// Creates a tile spec.
const BodyTileSpec({ const BodyTileSpec({required this.title, required this.builder, this.value});
required this.semanticLabel,
required this.icon,
required this.builder,
this.value,
this.valueIcon,
});
/// Spoken name of the section; never painted. /// Section name, the same text the full card carries.
final String semanticLabel; final String title;
/// The section's glyph.
final IconData icon;
/// Headline number for the tile (null when the section has none). /// Headline number for the tile (null when the section has none).
final String? value; 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. /// Builds the full card for the sheet.
final WidgetBuilder builder; final WidgetBuilder builder;
} }
@ -88,47 +76,28 @@ class _Tile extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final value = spec.value;
final valueIcon = spec.valueIcon;
return Card( return Card(
margin: EdgeInsets.zero, margin: EdgeInsets.zero,
child: Semantics(
button: true,
label: spec.semanticLabel,
child: InkWell( child: InkWell(
onTap: () => _open(context), onTap: () => _open(context),
borderRadius: BorderRadius.circular(AppRadius.md), borderRadius: BorderRadius.circular(AppRadius.md),
child: Padding( child: Padding(
padding: const EdgeInsets.all(AppSpacing.sm), padding: const EdgeInsets.all(AppSpacing.sm),
child: Row( child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
ExcludeSemantics(
child: Icon(
spec.icon,
size: 36,
color: theme.colorScheme.onSurfaceVariant,
),
),
// The whole space beside the glyph goes to the value; it
// scales down instead of ellipsizing ("70.0 kg" must show).
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: FittedBox(
fit: BoxFit.scaleDown,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (valueIcon != null)
Icon(
valueIcon,
size: 18,
color: theme.colorScheme.primary,
),
if (value != null)
Text( Text(
value, spec.title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodyMedium,
),
if (spec.value != null)
Text(
spec.value!,
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleMedium?.copyWith( style: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.primary, color: theme.colorScheme.primary,
), ),
@ -137,12 +106,6 @@ class _Tile extends StatelessWidget {
), ),
), ),
), ),
),
],
),
),
),
),
); );
} }
} }

View File

@ -1,223 +0,0 @@
/// 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<void> Function(String day, double value) onSave;
/// Deletes a day.
final Future<void> Function(String day) onDelete;
/// Called once a value has been written or deleted.
final VoidCallback onChanged;
@override
State<DatedValueCard> createState() => _DatedValueCardState();
}
class _DatedValueCardState extends State<DatedValueCard> {
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<void> _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<void> _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<void> _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<void> _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),
],
);
}
}

View File

@ -1,66 +0,0 @@
/// A kcal formula shown as a glyph + number; its proper name is only a
/// long-press tooltip.
library;
import 'package:diet_guard_app/services/activity_kcal.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
/// One distinct glyph per entry of [activityFormulas].
const Map<String, IconData> formulaIcons = {
'MET': Icons.speed,
'ACSM': Icons.functions,
'Per-km': Icons.straighten,
};
/// The glyph for formula [name], tooltipped with the formula's proper name.
class FormulaGlyph extends StatelessWidget {
/// Creates a glyph for [name].
const FormulaGlyph(this.name, {this.size = 16, super.key});
/// The formula's proper name (a key of [formulaIcons]).
final String name;
/// Glyph size.
final double size;
@override
Widget build(BuildContext context) => Tooltip(
message: name,
child: Icon(
formulaIcons[name],
size: size,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
);
}
/// Glyph + number (a trailing `~` marks a figure that reuses the MET value).
class FormulaFigure extends StatelessWidget {
/// Creates a figure.
const FormulaFigure(
this.name,
this.value, {
this.fallback = false,
super.key,
});
/// The formula's proper name.
final String name;
/// The formatted kcal number.
final String value;
/// Whether the figure is a fallback to the MET value.
final bool fallback;
@override
Widget build(BuildContext context) => Row(
mainAxisSize: MainAxisSize.min,
children: [
FormulaGlyph(name),
const SizedBox(width: AppSpacing.xs),
Text(fallback ? '$value~' : value),
],
);
}

View File

@ -1,7 +1,6 @@
/// The Body screen's top line as marks instead of a sentence: direction /// The Body screen's top line: "To [lose] [0.5] [kg] / [week] on
/// arrow, amount, unit, per-period calendar, activity glyph, then a bolt and /// [Moderate] eat 2019 kcal". Every bracket is tappable and opens a picker;
/// the daily kcal answer. Every mark is tappable and opens a picker; the /// the choice is saved (and synced) immediately. Informational only.
/// choice is saved (and synced) immediately. Informational only.
library; library;
import 'dart:async'; import 'dart:async';
@ -10,15 +9,12 @@ 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_energy.dart';
import 'package:diet_guard_app/services/body_prefs.dart'; import 'package:diet_guard_app/services/body_prefs.dart';
import 'package:diet_guard_app/services/body_service.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/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/body_section.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:diet_guard_app/widgets/body/goal_pickers.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// The goal row and its answer. /// The goal sentence and its answer.
class GoalCard extends StatefulWidget { class GoalCard extends StatefulWidget {
/// Creates the card. /// Creates the card.
const GoalCard({ const GoalCard({
@ -51,59 +47,26 @@ class _GoalCardState extends State<GoalCard> {
await setGoal(BodyService.instance, picked); await setGoal(BodyService.instance, picked);
} }
/// A bordered, tappable mark spoken as [spoken]; [child] is its look. Widget _choice(String text, Future<Goal?> Function(BuildContext, Goal) p) {
Widget _choice(
String spoken,
Widget child,
Future<Goal?> Function(BuildContext, Goal) picker,
) {
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return Semantics( return InkWell(
button: true, onTap: () => unawaited(_pick(p)),
label: spoken,
child: InkWell(
onTap: () => unawaited(_pick(picker)),
borderRadius: BorderRadius.circular(AppRadius.sm), borderRadius: BorderRadius.circular(AppRadius.sm),
child: Container( child: Padding(
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs),
horizontal: AppSpacing.sm, child: Text(
vertical: AppSpacing.xs, text,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppRadius.sm),
border: Border.all(color: scheme.outline),
),
child: ExcludeSemantics(
child: DefaultTextStyle.merge(
style: TextStyle( style: TextStyle(
color: scheme.primary, color: scheme.primary,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), decoration: TextDecoration.underline,
child: IconTheme.merge( decorationColor: scheme.primary,
data: IconThemeData(color: scheme.primary),
child: child,
),
),
), ),
), ),
), ),
); );
} }
Widget _iconChoice(
String spoken,
IconData icon,
Future<Goal?> Function(BuildContext, Goal) picker, {
String? caption,
}) => _choice(
spoken,
Row(
mainAxisSize: MainAxisSize.min,
children: [Icon(icon), if (caption != null) Text(caption)],
),
picker,
);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
@ -113,42 +76,24 @@ class _GoalCardState extends State<GoalCard> {
final tdee = target.tdee; final tdee = target.tdee;
final maintain = _goal.direction == 'maintain'; final maintain = _goal.direction == 'maintain';
return BodySection( return BodySection(
semanticLabel: 'Daily calorie target', title: 'Daily calorie target',
children: [ children: [
Wrap( Wrap(
crossAxisAlignment: WrapCrossAlignment.center, crossAxisAlignment: WrapCrossAlignment.center,
spacing: AppSpacing.sm, runSpacing: AppSpacing.xs,
runSpacing: AppSpacing.sm,
children: [ children: [
_iconChoice( const Text('To'),
_goal.direction, _choice(_goal.direction, pickDirection),
directionIcon(_goal.direction),
pickDirection,
),
if (!maintain) ...[ if (!maintain) ...[
_choice( _choice(formatG(_goal.amount), pickAmount),
formatG(_goal.amount), _choice(_goal.weightUnit, pickWeightUnit),
Text(formatG(_goal.amount)), const Text('/'),
pickAmount, _choice(_goal.timeUnit, pickTimeUnit),
),
_choice(_goal.weightUnit, Text(_goal.weightUnit), pickWeightUnit),
_iconChoice(
_goal.timeUnit,
timeUnitIcon(_goal.timeUnit),
pickTimeUnit,
),
], ],
_iconChoice( const Text('on'),
activityLabel(_goal.activity), _choice(activityLabel(_goal.activity), pickActivity),
activityIcon(_goal.activity), if (kcal != null) ...[
pickActivity, const Text('eat '),
caption: activityCaption(_goal.activity),
),
if (kcal != null)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(MacroKind.kcal.icon, color: theme.colorScheme.primary),
Text( Text(
'$kcal', '$kcal',
style: theme.textTheme.headlineMedium?.copyWith( style: theme.textTheme.headlineMedium?.copyWith(
@ -156,37 +101,25 @@ class _GoalCardState extends State<GoalCard> {
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
), ),
), ),
const Text(' kcal'),
], ],
),
], ],
), ),
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
if (kcal == null) if (kcal == null)
const StatusCue( const BodyNote('no workouts published yet (the PC publishes them).'),
kind: CueKind.warn,
icon: Icons.directions_run,
semanticLabel: 'no workouts published yet (the PC publishes them).',
),
if (target.belowFloor) if (target.belowFloor)
const StatusCue( Text(
kind: CueKind.error, 'That is below the $minTargetKcal kcal floor.',
icon: Icons.vertical_align_bottom, style: TextStyle(color: theme.colorScheme.error),
semanticLabel: 'That is below the $minTargetKcal kcal floor.',
), ),
if (tdee != null) if (tdee != null)
Row( BodyNote(
children: [ 'Maintenance ${whole(tdee)} kcal (${target.bmrName} resting '
Icon( 'burn x activity); 1 kg of fat = ${formatG(kcalPerKg)} kcal.',
Icons.balance,
size: 18,
color: theme.colorScheme.onSurfaceVariant,
semanticLabel: 'Maintenance',
), ),
const SizedBox(width: AppSpacing.xs), const BodyNote(
MacroFigure(kind: MacroKind.kcal, value: whole(tdee), size: 16), 'Informational only — the budget is never changed from here.',
const SizedBox(width: AppSpacing.sm),
Text(target.bmrName),
],
), ),
], ],
); );

View File

@ -1,43 +0,0 @@
/// 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;
}

View File

@ -1,141 +1,71 @@
/// The pickers behind each tappable mark of the goal row. /// The pickers behind each tappable word of the goal sentence.
/// ///
/// Each returns the edited [Goal], or null when dismissed. Options are icons /// Each returns the edited [Goal], or null when dismissed.
/// (plus a number or proper name where one exists); the spoken name of every
/// option is its semantic label.
library; library;
import 'package:diet_guard_app/services/body_energy.dart'; 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/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/goal_icons.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
/// One choice in a picker sheet.
typedef PickerOption = ({
String value,
String spoken,
IconData icon,
String? caption,
});
Future<String?> _sheet( Future<String?> _sheet(
BuildContext context, BuildContext context,
List<PickerOption> options, String title,
List<(String, String, String?)> options,
String selected, String selected,
) => showModalBottomSheet<String>( ) => showModalBottomSheet<String>(
context: context, context: context,
builder: (context) => SafeArea( builder: (context) => SafeArea(
child: Padding( child: ListView(
padding: const EdgeInsets.all(AppSpacing.md), shrinkWrap: true,
child: Wrap(
spacing: AppSpacing.sm,
runSpacing: AppSpacing.sm,
children: [ children: [
for (final option in options) ListTile(title: Text(title)),
_OptionButton( for (final (value, label, subtitle) in options)
option: option, ListTile(
selected: option.value == selected, title: Text(label),
onTap: () => Navigator.of(context).pop(option.value), subtitle: subtitle == null ? null : Text(subtitle),
selected: value == selected,
trailing: value == selected ? const Icon(Icons.check) : null,
onTap: () => Navigator.of(context).pop(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. /// Lose / maintain / gain.
Future<Goal?> pickDirection(BuildContext context, Goal goal) async { Future<Goal?> pickDirection(BuildContext context, Goal goal) async {
final value = await _sheet(context, [ final value = await _sheet(context, 'Direction', [
for (final d in directions) for (final d in directions) (d, d, null),
(value: d, spoken: d, icon: directionIcon(d), caption: null),
], goal.direction); ], goal.direction);
return value == null ? null : goal.copyWith(direction: value); return value == null ? null : goal.copyWith(direction: value);
} }
/// Kilograms, pounds, grams or stones (the unit symbols are the captions). /// Kilograms, pounds, grams or stones.
Future<Goal?> pickWeightUnit(BuildContext context, Goal goal) async { Future<Goal?> pickWeightUnit(BuildContext context, Goal goal) async {
final value = await _sheet(context, [ final value = await _sheet(context, 'Weight unit', [
for (final u in weightUnits.keys) for (final u in weightUnits.keys) (u, u, null),
(value: u, spoken: u, icon: Icons.scale, caption: u),
], goal.weightUnit); ], goal.weightUnit);
return value == null ? null : goal.copyWith(weightUnit: value); return value == null ? null : goal.copyWith(weightUnit: value);
} }
/// Per day, week, month or year. /// Per day, week, month or year.
Future<Goal?> pickTimeUnit(BuildContext context, Goal goal) async { Future<Goal?> pickTimeUnit(BuildContext context, Goal goal) async {
final value = await _sheet(context, [ final value = await _sheet(context, 'Per', [
for (final u in timeUnits.keys) for (final u in timeUnits.keys) (u, u, null),
(value: u, spoken: u, icon: timeUnitIcon(u), caption: null),
], goal.timeUnit); ], goal.timeUnit);
return value == null ? null : goal.copyWith(timeUnit: value); return value == null ? null : goal.copyWith(timeUnit: value);
} }
/// The five levels, then the three measured formulas. /// The five levels, then the three measured formulas.
Future<Goal?> pickActivity(BuildContext context, Goal goal) async { Future<Goal?> pickActivity(BuildContext context, Goal goal) async {
final value = await _sheet(context, [ final meaning = {for (final l in activityLevels) l.key: l.meaning};
final value = await _sheet(context, 'Activity', [
for (final key in activityChoices) for (final key in activityChoices)
( (
value: key, key,
spoken: activityLabel(key), activityLabel(key),
icon: activityIcon(key), meaning[key] ?? 'BMR x 1.2 + your real workouts and steps',
caption: activityCaption(key),
), ),
], goal.activity); ], goal.activity);
return value == null ? null : goal.copyWith(activity: value); return value == null ? null : goal.copyWith(activity: value);
@ -165,7 +95,6 @@ class _AmountDialogState extends State<_AmountDialog> {
late final _controller = TextEditingController( late final _controller = TextEditingController(
text: formatG(widget.goal.amount), text: formatG(widget.goal.amount),
); );
bool _rejected = false;
@override @override
void dispose() { void dispose() {
@ -175,17 +104,14 @@ class _AmountDialogState extends State<_AmountDialog> {
void _submit() { void _submit() {
final typed = double.tryParse(_controller.text.replaceAll(',', '.')); final typed = double.tryParse(_controller.text.replaceAll(',', '.'));
if (typed != null && typed >= 0) { if (typed != null && typed >= 0) Navigator.of(context).pop(typed);
Navigator.of(context).pop(typed);
return;
}
setState(() => _rejected = true);
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final goal = widget.goal; final goal = widget.goal;
return AlertDialog( return AlertDialog(
title: Text('How much (${goal.weightUnit} / ${goal.timeUnit})'),
content: Column( content: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
@ -200,29 +126,23 @@ class _AmountDialogState extends State<_AmountDialog> {
), ),
], ],
), ),
IconField( TextField(
icon: Icons.edit,
semanticLabel: 'Other amount',
controller: _controller, controller: _controller,
decoration: const InputDecoration(labelText: 'Other amount'),
keyboardType: const TextInputType.numberWithOptions(decimal: true), keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [ inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
], ],
onSubmitted: (_) => _submit(), onSubmitted: (_) => _submit(),
), ),
if (_rejected)
const StatusCue(kind: CueKind.error, semanticLabel: 'not a number'),
], ],
), ),
actions: [ actions: [
IconButton( TextButton(
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close, semanticLabel: 'Cancel'), child: const Text('Cancel'),
),
IconButton.filled(
onPressed: _submit,
icon: const Icon(Icons.check, semanticLabel: 'OK'),
), ),
FilledButton(onPressed: _submit, child: const Text('OK')),
], ],
); );
} }

View File

@ -3,7 +3,6 @@ library;
import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/body_service.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/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -25,7 +24,7 @@ class _ProfileCardState extends State<ProfileCard> {
final _height = TextEditingController(); final _height = TextEditingController();
String? _birth; String? _birth;
String? _sex; String? _sex;
Widget? _status; String? _status;
@override @override
void initState() { void initState() {
@ -60,14 +59,7 @@ class _ProfileCardState extends State<ProfileCard> {
Future<void> _save() async { Future<void> _save() async {
final height = double.tryParse(_height.text.replaceAll(',', '.')); final height = double.tryParse(_height.text.replaceAll(',', '.'));
if (height == null || height < 50 || height > 260) { if (height == null || height < 50 || height > 260) {
setState( setState(() => _status = 'Height must be 50-260 cm.');
() => _status = StatusCue(
key: UniqueKey(),
kind: CueKind.error,
icon: Icons.height,
semanticLabel: 'Height must be 50-260 cm.',
),
);
return; return;
} }
await BodyService.instance.setProfile( await BodyService.instance.setProfile(
@ -76,45 +68,28 @@ class _ProfileCardState extends State<ProfileCard> {
sex: _sex, sex: _sex,
); );
if (!mounted) return; if (!mounted) return;
setState( setState(() => _status = 'Saved.');
() => _status = StatusCue(
key: UniqueKey(),
kind: CueKind.ok,
semanticLabel: 'Saved.',
),
);
widget.onSaved(); widget.onSaved();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final birth = _birth;
final status = _status;
return BodySection( return BodySection(
semanticLabel: 'Profile', title: 'Profile',
children: [ children: [
Align( Row(
alignment: Alignment.centerLeft, children: [
child: TextButton( Expanded(child: Text('Born: ${_birth ?? 'not set'}')),
TextButton.icon(
icon: const Icon(Icons.cake),
label: const Text('Birth date'),
onPressed: _pickBirth, 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, controller: _height,
decoration: const InputDecoration(labelText: 'Height (cm)'),
keyboardType: const TextInputType.numberWithOptions(decimal: true), keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [ inputFormatters: [
FilteringTextInputFormatter.allow(RegExp('[0-9.,]')), FilteringTextInputFormatter.allow(RegExp('[0-9.,]')),
@ -122,16 +97,9 @@ class _ProfileCardState extends State<ProfileCard> {
), ),
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
SegmentedButton<String>( SegmentedButton<String>(
showSelectedIcon: false,
segments: const [ segments: const [
ButtonSegment( ButtonSegment(value: 'm', label: Text('Male')),
value: 'm', ButtonSegment(value: 'f', label: Text('Female')),
icon: Icon(Icons.male, semanticLabel: 'Male'),
),
ButtonSegment(
value: 'f',
icon: Icon(Icons.female, semanticLabel: 'Female'),
),
], ],
selected: {?_sex}, selected: {?_sex},
emptySelectionAllowed: true, emptySelectionAllowed: true,
@ -141,11 +109,8 @@ class _ProfileCardState extends State<ProfileCard> {
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
Row( Row(
children: [ children: [
if (status != null) Expanded(child: status) else const Spacer(), Expanded(child: BodyNote(_status ?? 'Syncs to the PC.')),
IconButton.filled( FilledButton(onPressed: _save, child: const Text('Save profile')),
onPressed: _save,
icon: const Icon(Icons.check, semanticLabel: 'Save profile'),
),
], ],
), ),
], ],

View File

@ -4,10 +4,7 @@
/// day overrides it (a planned feast on Saturday too). /// day overrides it (a planned feast on Saturday too).
library; library;
import 'package:diet_guard_app/services/body_energy.dart';
import 'package:diet_guard_app/services/week_plan.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/ui/theme.dart';
import 'package:diet_guard_app/widgets/body/body_section.dart'; import 'package:diet_guard_app/widgets/body/body_section.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -56,7 +53,8 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final target = int.tryParse(_target.text) ?? widget.defaultTarget; final target = int.tryParse(_target.text) ?? widget.defaultTarget;
final typed = <int, int>{ final typed = <int, int>{
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( final plan = planWeek(
widget.today ?? DateTime.now(), widget.today ?? DateTime.now(),
@ -66,39 +64,41 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
); );
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return BodySection( return BodySection(
semanticLabel: 'Week planner', title: 'Week planner (info only)',
children: [ children: [
SpokenLabel( TextField(
semanticLabel: 'Weekly average target (kcal/day)',
child: TextField(
controller: _target, controller: _target,
decoration: InputDecoration( decoration: InputDecoration(
prefixIcon: ExcludeSemantics( labelText: 'Weekly average target (kcal/day)',
child: Icon(MacroKind.kcal.icon, color: MacroKind.kcal.color),
),
hintText: '${widget.defaultTarget}', hintText: '${widget.defaultTarget}',
), ),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (_) => setState(() {}), onChanged: (_) => setState(() {}),
), ),
),
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
for (var i = 0; i < 7; i++) for (var i = 0; i < 7; i++)
Row( Row(
children: [ children: [
// Day of month, not a weekday word: rows run Monday..Sunday. SizedBox(width: 48, child: Text(plan.days[i].weekday)),
SizedBox(width: 32, child: Text(plan.days[i].day.substring(8))),
Expanded( Expanded(
child: _DayFigure(plan.days[i], belowFloor: plan.belowFloor), child: Text(
'${plan.days[i].kcal} kcal ${_sourceLabel(plan.days[i])}',
style: TextStyle(
color: plan.days[i].source == 'plan' && plan.belowFloor
? scheme.error
: null,
),
),
), ),
SizedBox( SizedBox(
width: 96, width: 96,
child: IconField( child: TextField(
icon: Icons.rice_bowl,
semanticLabel: 'ate…',
controller: _days[i], controller: _days[i],
dense: true, decoration: const InputDecoration(
hintText: 'ate…',
isDense: true,
),
keyboardType: TextInputType.number, keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly], inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (_) => setState(() {}), onChanged: (_) => setState(() {}),
@ -107,86 +107,26 @@ class _WeekPlanCardState extends State<WeekPlanCard> {
], ],
), ),
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
_Summary(plan, scheme), BodyNote(_summary(plan)),
], ],
); );
} }
} }
/// A day's kcal with a glyph for where the number came from. String _sourceLabel(DayPlan day) => switch (day.source) {
class _DayFigure extends StatelessWidget { 'typed' => '(typed)',
const _DayFigure(this.day, {required this.belowFloor}); 'logged' => '(logged)',
'unlogged' => '(not logged -- type it)',
final DayPlan day; _ => '(plan)',
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. String _summary(WeekPlan plan) {
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; final per = plan.perRemaining;
if (per == null) { if (per == null) {
return Row( return 'Every day is known: week average '
children: [ '${whole(plan.weekAvg)} kcal.';
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';
} }

View File

@ -5,11 +5,12 @@
library; library;
import 'package:diet_guard_app/models/body_document.dart'; 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/services/body_service.dart';
import 'package:diet_guard_app/widgets/body/dated_value_card.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/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. /// Weight: 20-400 kg; wake-alarm weigh-ins land here too.
class WeightCard extends StatelessWidget { class WeightCard extends StatelessWidget {
@ -23,12 +24,12 @@ class WeightCard extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final body = BodyService.instance; final body = BodyService.instance;
return DatedValueCard( return DatedValueCard(
semanticLabel: 'Weight', title: 'Weight',
fieldSemanticLabel: 'Weight (kg)', fieldLabel: 'Weight (kg)',
icon: Icons.monitor_weight,
unit: 'kg', unit: 'kg',
min: 20, min: 20,
max: 400, max: 400,
hint: 'Morning weigh-ins from wake-alarm appear here.',
latest: body.latestWeight, latest: body.latestWeight,
series: body.weightSeries, series: body.weightSeries,
onSave: body.setWeight, onSave: body.setWeight,
@ -50,12 +51,12 @@ class BodyFatCard extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final body = BodyService.instance; final body = BodyService.instance;
return DatedValueCard( return DatedValueCard(
semanticLabel: 'Body fat', title: 'Body fat',
fieldSemanticLabel: 'Body fat (%)', fieldLabel: 'Body fat (%)',
icon: Icons.percent,
unit: '%', unit: '%',
min: minBodyFat, min: minBodyFat,
max: maxBodyFat, max: maxBodyFat,
hint: 'With a body fat %, targets use the lean-mass (Katch-McArdle) BMR.',
latest: body.latestBodyFat, latest: body.latestBodyFat,
series: body.bodyFatSeries, series: body.bodyFatSeries,
onSave: body.setBodyFat, onSave: body.setBodyFat,
@ -64,3 +65,150 @@ 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<void> Function(String day, double value) onSave;
/// Deletes a day.
final Future<void> Function(String day) onDelete;
/// Called once a value has been written or deleted.
final VoidCallback onChanged;
@override
State<DatedValueCard> createState() => _DatedValueCardState();
}
class _DatedValueCardState extends State<DatedValueCard> {
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<void> _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<void> _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<void> _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),
],
);
}
}

View File

@ -4,12 +4,11 @@
/// drawn to scale rather than evenly spaced. /// drawn to scale rather than evenly spaced.
library; library;
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:fl_chart/fl_chart.dart'; import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Selectable chart ranges, `(spoken name, days)`; null days = everything. /// Selectable chart ranges, `(label, days)`; null days = everything.
const List<(String, int?)> weightChartRanges = [ const List<(String, int?)> weightChartRanges = [
('30d', 30), ('30d', 30),
('90d', 90), ('90d', 90),
@ -62,34 +61,19 @@ class _WeightChartState extends State<WeightChart> {
Wrap( Wrap(
spacing: AppSpacing.sm, spacing: AppSpacing.sm,
children: [ children: [
for (final (spoken, days) in weightChartRanges) for (final (label, days) in weightChartRanges)
SpokenLabel( ChoiceChip(
semanticLabel: spoken, label: Text(label),
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, selected: _days == days,
onSelected: (_) => setState(() => _days = days), onSelected: (_) => setState(() => _days = days),
), ),
),
], ],
), ),
const SizedBox(height: AppSpacing.sm), const SizedBox(height: AppSpacing.sm),
SizedBox( SizedBox(
height: 200, height: 200,
child: points.length < 2 child: points.length < 2
? Center( ? const Center(child: Text('Need two readings for a graph.'))
child: Icon(
Icons.show_chart,
size: 64,
color: Theme.of(context).colorScheme.outline,
semanticLabel: 'Need two readings for a graph.',
),
)
: _chart(context, points), : _chart(context, points),
), ),
], ],

View File

@ -46,6 +46,23 @@ class DayStatusCalendar extends StatelessWidget {
/// outside the displayed month is never tappable regardless. /// outside the displayed month is never tappable regardless.
final void Function(DateTime day)? onDaySelected; final void Function(DateTime day)? onDaySelected;
static const _weekHeaders = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
static const _monthNames = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
String _dateKey(int year, int m, int day) => String _dateKey(int year, int m, int day) =>
'$year-${m.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}'; '$year-${m.toString().padLeft(2, '0')}-${day.toString().padLeft(2, '0')}';
@ -112,18 +129,13 @@ class DayStatusCalendar extends StatelessWidget {
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
IconButton( IconButton(
icon: Icon( icon: Icon(Icons.chevron_left, color: scheme.onSurfaceVariant),
Icons.chevron_left,
color: scheme.onSurfaceVariant,
semanticLabel: 'Previous month',
),
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
onPressed: onPrevMonth, onPressed: onPrevMonth,
), ),
// Numeric month/year: a month name would be written chrome.
Text( Text(
'${m.toString().padLeft(2, '0')} · $year', '${_monthNames[m - 1]} $year',
style: TextStyle( style: TextStyle(
color: scheme.onSurface, color: scheme.onSurface,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
@ -131,11 +143,7 @@ class DayStatusCalendar extends StatelessWidget {
), ),
), ),
IconButton( IconButton(
icon: Icon( icon: Icon(Icons.chevron_right, color: scheme.onSurfaceVariant),
Icons.chevron_right,
color: scheme.onSurfaceVariant,
semanticLabel: 'Next month',
),
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
onPressed: onNextMonth, onPressed: onNextMonth,
@ -145,23 +153,25 @@ class DayStatusCalendar extends StatelessWidget {
const SizedBox(height: AppSpacing.xs + 2), const SizedBox(height: AppSpacing.xs + 2),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisAlignment: MainAxisAlignment.spaceAround,
// Weekday names are gone: seven dots mark the Monday-first children: _weekHeaders
// columns, the two weekend ones in the accent colour. .map(
children: [ (h) => SizedBox(
for (var col = 0; col < 7; col++)
SizedBox(
width: 30, width: 30,
child: Center( child: Text(
child: Icon( h,
Icons.circle, textAlign: TextAlign.center,
size: col >= 5 ? 8 : 5, // Two-letter day abbreviations are UI chrome (like a
color: col >= 5 // badge/tag), deliberately kept below the 16px body
? scheme.primary // floor rather than forced to grow past their slot.
: scheme.onSurfaceVariant, style: TextStyle(
color: scheme.onSurfaceVariant,
fontSize: AppTextSize.label - 2,
fontWeight: FontWeight.bold,
), ),
), ),
), ),
], )
.toList(),
), ),
const SizedBox(height: AppSpacing.xs), const SizedBox(height: AppSpacing.xs),
...List.generate(rows, (row) { ...List.generate(rows, (row) {
@ -208,10 +218,9 @@ class DayStatusCalendar extends StatelessWidget {
// and no semantics for a screen reader. InkWell is a focus // and no semantics for a screen reader. InkWell is a focus
// stop and is activated by Enter/Space. // stop and is activated by Enter/Space.
final date = DateTime(year, m, day); final date = DateTime(year, m, day);
final semanticLabel = 'View $day/$m/$year';
return Semantics( return Semantics(
button: true, button: true,
label: semanticLabel, label: 'View $day/$m/$year',
child: InkWell( child: InkWell(
onTap: () => onDaySelected!(date), onTap: () => onDaySelected!(date),
customBorder: const CircleBorder(), customBorder: const CircleBorder(),

View File

@ -9,8 +9,8 @@ import 'package:diet_guard_app/services/kuchnia_client.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Spoken name of the resting button (never painted). /// Resting label, mirroring the PC gate's "🍱 Fill all".
const fillAllLabel = 'Fill all with catering'; const fillAllLabel = '🍱 Fill all with catering';
/// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed. /// Fill-all button; relabels to "✓ Confirm (N)" once a proposal is armed.
class FillAllRow extends StatelessWidget { class FillAllRow extends StatelessWidget {
@ -52,42 +52,26 @@ class FillAllRow extends StatelessWidget {
Expanded( Expanded(
child: OutlinedButton( child: OutlinedButton(
onPressed: busy ? null : onFill, onPressed: busy ? null : onFill,
child: _face(context, armed), child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(_label(armed), maxLines: 1),
),
), ),
), ),
if (armed) ...[ if (armed) ...[
const SizedBox(width: AppSpacing.sm), const SizedBox(width: AppSpacing.sm),
IconButton( TextButton(
onPressed: busy ? null : onCancel, onPressed: busy ? null : onCancel,
icon: const Icon(Icons.close, semanticLabel: 'Cancel'), child: const Text('Cancel'),
), ),
], ],
], ],
); );
} }
/// Resting glyph; spinner while busy; double check + count once armed. String _label(bool armed) {
Widget _face(BuildContext context, bool armed) { if (busy) return 'Working…';
if (busy) { if (armed) return '✓ Confirm ($armedCount)';
return const SizedBox( return fillAllLabel;
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
);
}
if (!armed) {
return const Icon(Icons.playlist_add_check, semanticLabel: fillAllLabel);
}
final success =
(Theme.of(context).extension<AppStatusColors>() ?? AppStatusColors.dark)
.success;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.done_all, color: success, semanticLabel: 'Confirm'),
const SizedBox(width: AppSpacing.xs),
Text('$armedCount'),
],
);
} }
} }

View File

@ -1,124 +0,0 @@
/// Icon-only chrome shared by the history and food-bank filter sheets: the
/// clear control, the apply bar and the sort chooser. Each control paints a
/// glyph and speaks its old caption only through its semantic label.
library;
import 'package:flutter/material.dart';
/// Top row of a filter sheet: one clear-everything icon, right-aligned.
class FilterSheetHeader extends StatelessWidget {
/// Creates a header whose clear icon calls [onClear].
const FilterSheetHeader({required this.onClear, super.key});
/// Called when the clear icon is pressed.
final VoidCallback onClear;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 8, 0),
child: Align(
alignment: Alignment.centerRight,
child: IconButton(
icon: const Icon(Icons.filter_list_off, semanticLabel: 'Clear all'),
onPressed: onClear,
),
),
);
}
/// Bottom bar of a filter sheet: one full-width check button.
class FilterApplyBar extends StatelessWidget {
/// Creates an apply bar that calls [onApply].
const FilterApplyBar({required this.onApply, super.key});
/// Called when the check is pressed.
final VoidCallback onApply;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: onApply,
child: const Icon(Icons.check, semanticLabel: 'Apply'),
),
),
);
}
/// One choice in a [SortChoiceRow]: a glyph, its tint and its spoken name.
class SortOption<T> {
/// Creates an option selecting [value].
const SortOption(this.value, this.icon, this.semanticLabel, {this.color});
/// The value reported when chosen.
final T value;
/// Painted glyph.
final IconData icon;
/// Spoken name; never painted.
final String semanticLabel;
/// Glyph tint; the theme default when null.
final Color? color;
}
/// Icon chips for the sort field plus an arrow for the direction.
class SortChoiceRow<T> extends StatelessWidget {
/// Creates a chooser over [options] with [selected] active.
const SortChoiceRow({
required this.options,
required this.selected,
required this.ascending,
required this.onChanged,
super.key,
});
/// Choices in display order.
final List<SortOption<T>> options;
/// The active choice.
final T selected;
/// Whether the sort runs ascending.
final bool ascending;
/// Called with the new field and direction.
final void Function({required T field, required bool asc}) onChanged;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [
for (final o in options)
ChoiceChip(
label: Icon(
o.icon,
size: 18,
color: o.color,
semanticLabel: o.semanticLabel,
),
selected: selected == o.value,
onSelected: (_) => onChanged(field: o.value, asc: ascending),
),
],
),
),
IconButton(
icon: Icon(
ascending ? Icons.arrow_upward : Icons.arrow_downward,
semanticLabel: ascending ? 'Ascending' : 'Descending',
),
onPressed: () => onChanged(field: selected, asc: !ascending),
),
],
);
}
}

View File

@ -6,11 +6,9 @@
/// screen owns the other's controls. /// screen owns the other's controls.
library; library;
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// The free-text search-by-name field in the filter sheet. /// The free-text "search by name" field in the filter sheet.
/// ///
/// Stateful only to own its [TextEditingController]; the query itself lives in /// Stateful only to own its [TextEditingController]; the query itself lives in
/// the screen's [HistoryFilter]. /// the screen's [HistoryFilter].
@ -46,11 +44,13 @@ class NameSearchFieldState extends State<NameSearchField> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IconField( return TextField(
icon: Icons.search,
semanticLabel: 'Search by name',
controller: _controller, controller: _controller,
dense: true, decoration: const InputDecoration(
labelText: 'Search by name',
prefixIcon: Icon(Icons.search),
isDense: true,
),
onChanged: widget.onChanged, onChanged: widget.onChanged,
); );
} }
@ -112,7 +112,7 @@ class SliderSelectedLabel extends StatelessWidget {
class FilterRangeRow extends StatelessWidget { class FilterRangeRow extends StatelessWidget {
/// Creates a range row bounded by [maxValue]. /// Creates a range row bounded by [maxValue].
const FilterRangeRow({ const FilterRangeRow({
required this.kind, required this.label,
required this.sliderKey, required this.sliderKey,
required this.maxValue, required this.maxValue,
required this.min, required this.min,
@ -123,8 +123,8 @@ class FilterRangeRow extends StatelessWidget {
super.key, super.key,
}); });
/// Which nutrient this range filters; its glyph heads the row. /// Section heading, e.g. `Protein range (g)`.
final MacroKind kind; final String label;
/// Widget key on the slider itself, so tests can drive one row. /// Widget key on the slider itself, so tests can drive one row.
final Key sliderKey; final Key sliderKey;
@ -158,14 +158,7 @@ class FilterRangeRow extends StatelessWidget {
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Align( Text(label, style: Theme.of(context).textTheme.labelLarge),
alignment: Alignment.centerLeft,
child: Icon(
kind.icon,
color: kind.color,
semanticLabel: kind.semanticLabel(compact: false),
),
),
if (showEndpointLabels) if (showEndpointLabels)
SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'), SliderEndpointLabels(lo: '0', hi: '${maxValue.round()}$unit'),
RangeSlider( RangeSlider(

View File

@ -4,8 +4,6 @@
library; library;
import 'package:diet_guard_app/models/food_bank_record.dart'; import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Prompts for a new manually-curated food bank entry. /// Prompts for a new manually-curated food bank entry.
@ -55,50 +53,49 @@ class AddEntryDialogState extends State<AddEntryDialog> {
); );
} }
Widget _field(MacroKind kind, TextEditingController ctrl) => Padding( Widget _field(String label, TextEditingController ctrl) => Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: IconField( child: TextField(
icon: kind.icon,
iconColor: kind.color,
semanticLabel: kind.semanticLabel(compact: false),
controller: ctrl, controller: ctrl,
keyboardType: const TextInputType.numberWithOptions(decimal: true), keyboardType: const TextInputType.numberWithOptions(decimal: true),
dense: true, decoration: InputDecoration(labelText: label, isDense: true),
), ),
); );
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return AlertDialog( return AlertDialog(
title: const Text('Add to food bank'),
content: SingleChildScrollView( content: SingleChildScrollView(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.only(bottom: 8), padding: const EdgeInsets.only(bottom: 8),
child: IconField( child: TextField(
icon: Icons.restaurant,
semanticLabel: 'Name',
controller: _name, controller: _name,
dense: true, decoration: const InputDecoration(
labelText: 'Name',
isDense: true,
), ),
), ),
_field(MacroKind.perGrams, _grams), ),
_field(MacroKind.kcal, _kcal), _field('Reference grams', _grams),
_field(MacroKind.protein, _protein), _field('Kcal', _kcal),
_field(MacroKind.carbs, _carbs), _field('Protein (g)', _protein),
_field(MacroKind.fat, _fat), _field('Carbs (g)', _carbs),
_field('Fat (g)', _fat),
], ],
), ),
), ),
actions: [ actions: [
IconButton( TextButton(
onPressed: () => Navigator.of(context).pop(), onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close, semanticLabel: 'Cancel'), child: const Text('Cancel'),
), ),
ElevatedButton( ElevatedButton(
onPressed: _save, onPressed: _save,
child: const Icon(Icons.check, semanticLabel: 'Save to bank'), child: const Text('Save to bank'),
), ),
], ],
); );

View File

@ -4,9 +4,6 @@
/// range rows come from `widgets/filters/`, shared with the history sheet. /// range rows come from `widgets/filters/`, shared with the history sheet.
library; library;
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
import 'package:diet_guard_app/widgets/filters/filter_fields.dart'; import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart'; import 'package:diet_guard_app/widgets/food_bank/fb_filter.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -66,35 +63,6 @@ class FbFilterSheet extends StatelessWidget {
/// Called when the user clears every criterion. /// Called when the user clears every criterion.
final VoidCallback onClear; final VoidCallback onClear;
static final List<SortOption<FbSortField>> _sortOptions = [
const SortOption(FbSortField.count, Icons.repeat, 'Usage count'),
const SortOption(FbSortField.name, Icons.sort_by_alpha, 'Name'),
SortOption(
FbSortField.kcal,
MacroKind.kcal.icon,
'Kcal',
color: MacroKind.kcal.color,
),
SortOption(
FbSortField.protein,
MacroKind.protein.icon,
'Protein',
color: MacroKind.protein.color,
),
SortOption(
FbSortField.carbs,
MacroKind.carbs.icon,
'Carbs',
color: MacroKind.carbs.color,
),
SortOption(
FbSortField.fat,
MacroKind.fat.icon,
'Fat',
color: MacroKind.fat.color,
),
];
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return DraggableScrollableSheet( return DraggableScrollableSheet(
@ -103,17 +71,35 @@ class FbFilterSheet extends StatelessWidget {
maxChildSize: 0.95, maxChildSize: 0.95,
builder: (context, scroll) => Column( builder: (context, scroll) => Column(
children: [ children: [
FilterSheetHeader(onClear: onClear), Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
child: Row(
children: [
Expanded(
child: Text(
'Filter & Sort',
style: Theme.of(context).textTheme.titleMedium,
),
),
TextButton(
onPressed: onClear,
child: const Text('Clear all'),
),
],
),
),
const Divider(), const Divider(),
Expanded( Expanded(
child: ListView( child: ListView(
controller: scroll, controller: scroll,
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
children: [ children: [
IconField( TextField(
icon: Icons.search, decoration: const InputDecoration(
semanticLabel: 'Search by name', labelText: 'Search by name',
dense: true, prefixIcon: Icon(Icons.search),
isDense: true,
),
controller: TextEditingController(text: filter.nameQuery) controller: TextEditingController(text: filter.nameQuery)
..selection = TextSelection.collapsed( ..selection = TextSelection.collapsed(
offset: filter.nameQuery.length, offset: filter.nameQuery.length,
@ -125,7 +111,7 @@ class FbFilterSheet extends StatelessWidget {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.kcal, label: 'Kcal range',
sliderKey: const Key('fb-kcal-range-slider'), sliderKey: const Key('fb-kcal-range-slider'),
maxValue: maxKcal, maxValue: maxKcal,
min: filter.minKcal, min: filter.minKcal,
@ -138,7 +124,7 @@ class FbFilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.protein, label: 'Protein range (g)',
sliderKey: const Key('fb-protein-range-slider'), sliderKey: const Key('fb-protein-range-slider'),
maxValue: maxProtein, maxValue: maxProtein,
min: filter.minProtein, min: filter.minProtein,
@ -152,7 +138,7 @@ class FbFilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.carbs, label: 'Carbs range (g)',
sliderKey: const Key('fb-carbs-range-slider'), sliderKey: const Key('fb-carbs-range-slider'),
maxValue: maxCarbs, maxValue: maxCarbs,
min: filter.minCarbs, min: filter.minCarbs,
@ -166,7 +152,7 @@ class FbFilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.fat, label: 'Fat range (g)',
sliderKey: const Key('fb-fat-range-slider'), sliderKey: const Key('fb-fat-range-slider'),
maxValue: maxFat, maxValue: maxFat,
min: filter.minFat, min: filter.minFat,
@ -179,16 +165,74 @@ class FbFilterSheet extends StatelessWidget {
onFilterChanged(filter); onFilterChanged(filter);
}, },
), ),
SortChoiceRow<FbSortField>( Text(
options: _sortOptions, 'Sort by',
selected: sortField, style: Theme.of(context).textTheme.labelLarge,
ascending: ascending, ),
onChanged: onSortChanged, const SizedBox(height: 4),
Row(
children: [
Expanded(
child: DropdownButton<FbSortField>(
isExpanded: true,
value: sortField,
items: const [
DropdownMenuItem(
value: FbSortField.count,
child: Text('Usage count'),
),
DropdownMenuItem(
value: FbSortField.name,
child: Text('Name'),
),
DropdownMenuItem(
value: FbSortField.kcal,
child: Text('Kcal'),
),
DropdownMenuItem(
value: FbSortField.protein,
child: Text('Protein'),
),
DropdownMenuItem(
value: FbSortField.carbs,
child: Text('Carbs'),
),
DropdownMenuItem(
value: FbSortField.fat,
child: Text('Fat'),
),
],
onChanged: (v) {
if (v != null) {
onSortChanged(field: v, asc: ascending);
}
},
),
),
const SizedBox(width: 8),
IconButton(
icon: Icon(
ascending ? Icons.arrow_upward : Icons.arrow_downward,
),
tooltip: ascending ? 'Ascending' : 'Descending',
onPressed: () =>
onSortChanged(field: sortField, asc: !ascending),
),
],
), ),
], ],
), ),
), ),
FilterApplyBar(onApply: onApply), Padding(
padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: onApply,
child: const Text('Apply'),
),
),
),
], ],
), ),
); );

View File

@ -2,13 +2,9 @@
library; library;
import 'package:diet_guard_app/models/food_bank_record.dart'; import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// One banked food: its name, macros, and how often it has been logged. /// One banked food: its name, macros, and how often it has been logged.
///
/// Macros are glyph + number pairs; the reference weight carries the scale
/// glyph, the use count keeps its `×N` numeral.
class RecordTile extends StatelessWidget { class RecordTile extends StatelessWidget {
/// Creates a [RecordTile] for [record]. /// Creates a [RecordTile] for [record].
const RecordTile(this.record, {super.key}); const RecordTile(this.record, {super.key});
@ -18,23 +14,19 @@ class RecordTile extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
String n(double v) => v.toStringAsFixed(0); final macros =
'P ${record.proteinG.toStringAsFixed(0)} g '
'C ${record.carbsG.toStringAsFixed(0)} g '
'F ${record.fatG.toStringAsFixed(0)} g';
final per = record.grams > 0
? ' per ${record.grams.toStringAsFixed(0)} g'
: '';
return ListTile( return ListTile(
title: Text(record.desc), title: Text(record.desc),
subtitle: Wrap( subtitle: Text('${record.kcal.toStringAsFixed(0)} kcal$per · $macros'),
spacing: 12,
children: [
MacroFigure(kind: MacroKind.kcal, value: n(record.kcal)),
if (record.grams > 0)
MacroFigure(kind: MacroKind.perGrams, value: '${n(record.grams)}g'),
MacroFigure(kind: MacroKind.protein, value: '${n(record.proteinG)}g'),
MacroFigure(kind: MacroKind.carbs, value: '${n(record.carbsG)}g'),
MacroFigure(kind: MacroKind.fat, value: '${n(record.fatG)}g'),
],
),
trailing: record.count > 0 trailing: record.count > 0
? Text( ? Text(
'×${n(record.count)}', '×${record.count.toStringAsFixed(0)}',
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall,
) )
: null, : null,

View File

@ -4,7 +4,6 @@
library; library;
import 'package:diet_guard_app/models/food_bank_record.dart'; import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -60,13 +59,11 @@ class FbTile extends StatelessWidget {
Row( Row(
children: [ children: [
Expanded( Expanded(
child: Align( child: Text(
alignment: Alignment.centerLeft, '${record.kcal.toStringAsFixed(0)} kcal',
child: MacroFigure( maxLines: 1,
kind: MacroKind.kcal, overflow: TextOverflow.ellipsis,
value: record.kcal.toStringAsFixed(0), style: theme.textTheme.bodySmall,
size: 14,
),
), ),
), ),
if (record.count > 0) if (record.count > 0)

View File

@ -3,8 +3,6 @@
/// Split out of `history_screen.dart` to hold the repo's 250-line cap. /// Split out of `history_screen.dart` to hold the repo's 250-line cap.
library; library;
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
import 'package:diet_guard_app/widgets/filters/filter_fields.dart'; import 'package:diet_guard_app/widgets/filters/filter_fields.dart';
import 'package:diet_guard_app/widgets/history/history_filter.dart'; import 'package:diet_guard_app/widgets/history/history_filter.dart';
import 'package:diet_guard_app/widgets/history/history_filter_sort.dart'; import 'package:diet_guard_app/widgets/history/history_filter_sort.dart';
@ -75,7 +73,20 @@ class FilterSheet extends StatelessWidget {
maxChildSize: 0.95, maxChildSize: 0.95,
builder: (context, scroll) => Column( builder: (context, scroll) => Column(
children: [ children: [
FilterSheetHeader(onClear: onClear), Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 0),
child: Row(
children: [
Expanded(
child: Text(
'Filter & Sort',
style: Theme.of(context).textTheme.titleMedium,
),
),
TextButton(onPressed: onClear, child: const Text('Clear all')),
],
),
),
const Divider(), const Divider(),
Expanded( Expanded(
child: SingleChildScrollView( child: SingleChildScrollView(
@ -94,21 +105,18 @@ class FilterSheet extends StatelessWidget {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
// Date range: the glyph alone means "any date"; once a range // Date range
// is set its dates (data, not chrome) appear beside it. Text(
OutlinedButton( 'Date range',
child: Row( style: Theme.of(context).textTheme.labelLarge,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.date_range,
semanticLabel: 'Date range',
), ),
if (filter.dateRange != null) ...[ const SizedBox(height: 4),
const SizedBox(width: 8), OutlinedButton.icon(
Text(dateRangeLabel(filter.dateRange!)), icon: const Icon(Icons.date_range),
], label: Text(
], filter.dateRange == null
? 'Any date'
: dateRangeLabel(filter.dateRange!),
), ),
onPressed: () async { onPressed: () async {
final picked = await showDateRangePicker( final picked = await showDateRangePicker(
@ -124,20 +132,17 @@ class FilterSheet extends StatelessWidget {
}, },
), ),
if (filter.dateRange != null) if (filter.dateRange != null)
IconButton( TextButton(
onPressed: () { onPressed: () {
filter.dateRange = null; filter.dateRange = null;
onFilterChanged(filter); onFilterChanged(filter);
}, },
icon: const Icon( child: const Text('Clear date range'),
Icons.event_busy,
semanticLabel: 'Clear date range',
),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.kcal, label: 'Kcal range',
sliderKey: const Key('kcal-range-slider'), sliderKey: const Key('kcal-range-slider'),
maxValue: maxKcal, maxValue: maxKcal,
min: filter.minKcal, min: filter.minKcal,
@ -149,7 +154,7 @@ class FilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.protein, label: 'Protein range (g)',
sliderKey: const Key('protein-range-slider'), sliderKey: const Key('protein-range-slider'),
maxValue: maxProtein, maxValue: maxProtein,
min: filter.minProtein, min: filter.minProtein,
@ -162,7 +167,7 @@ class FilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.carbs, label: 'Carbs range (g)',
sliderKey: const Key('carbs-range-slider'), sliderKey: const Key('carbs-range-slider'),
maxValue: maxCarbs, maxValue: maxCarbs,
min: filter.minCarbs, min: filter.minCarbs,
@ -175,7 +180,7 @@ class FilterSheet extends StatelessWidget {
}, },
), ),
FilterRangeRow( FilterRangeRow(
kind: MacroKind.fat, label: 'Fat range (g)',
sliderKey: const Key('fat-range-slider'), sliderKey: const Key('fat-range-slider'),
maxValue: maxFat, maxValue: maxFat,
min: filter.minFat, min: filter.minFat,
@ -205,7 +210,16 @@ class FilterSheet extends StatelessWidget {
), ),
), ),
), ),
FilterApplyBar(onApply: onApply), Padding(
padding: const EdgeInsets.all(16),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: onApply,
child: const Text('Apply'),
),
),
),
], ],
), ),
); );

View File

@ -3,12 +3,8 @@
/// Split from `history_filter_sheet.dart` for the repo's 250-line cap. Both are /// Split from `history_filter_sheet.dart` for the repo's 250-line cap. Both are
/// stateless and report upward: the live filter and sort order belong to the /// stateless and report upward: the live filter and sort order belong to the
/// screen, so nothing here holds state that could disagree with what is shown. /// screen, so nothing here holds state that could disagree with what is shown.
/// Every control is a glyph; its old caption lives only in the semantic label.
library; library;
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/source_icon.dart';
import 'package:diet_guard_app/widgets/filters/filter_chrome.dart';
import 'package:diet_guard_app/widgets/history/history_filter.dart'; import 'package:diet_guard_app/widgets/history/history_filter.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -19,7 +15,7 @@ import 'package:flutter/material.dart';
/// a constraint on what `source` may contain. /// a constraint on what `source` may contain.
const _sources = ['manual', 'food bank']; const _sources = ['manual', 'food bank'];
/// Single-select chips filtering by entry source, with an "all" reset. /// Single-select chips filtering by entry source, with an "All" reset.
class FilterSourceChips extends StatelessWidget { class FilterSourceChips extends StatelessWidget {
/// Creates source chips with [selected] currently active. /// Creates source chips with [selected] currently active.
const FilterSourceChips({ const FilterSourceChips({
@ -28,38 +24,41 @@ class FilterSourceChips extends StatelessWidget {
super.key, super.key,
}); });
/// The active source, or null for "all". /// The active source, or null for "All".
final String? selected; final String? selected;
/// Called with the chosen source, or null when the reset chip is tapped. /// Called with the chosen source, or null when "All" is tapped.
final ValueChanged<String?> onSelected; final ValueChanged<String?> onSelected;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Wrap( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('Source', style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 4),
Wrap(
spacing: 8, spacing: 8,
children: [ children: [
FilterChip( FilterChip(
label: const Icon( label: const Text('All'),
Icons.all_inclusive,
size: 18,
semanticLabel: 'All',
),
selected: selected == null, selected: selected == null,
onSelected: (_) => onSelected(null), onSelected: (_) => onSelected(null),
), ),
for (final src in _sources) for (final src in _sources)
FilterChip( FilterChip(
label: SourceMark(src, size: 18), label: Text(src),
selected: selected == src, selected: selected == src,
onSelected: (_) => onSelected(src), onSelected: (_) => onSelected(src),
), ),
], ],
),
],
); );
} }
} }
/// The sort-field chips plus their ascending/descending toggle. /// The sort-field dropdown plus its ascending/descending toggle.
class FilterSortControls extends StatelessWidget { class FilterSortControls extends StatelessWidget {
/// Creates sort controls reflecting [sortField] and [ascending]. /// Creates sort controls reflecting [sortField] and [ascending].
const FilterSortControls({ const FilterSortControls({
@ -79,44 +78,63 @@ class FilterSortControls extends StatelessWidget {
final void Function({required HistorySortField field, required bool asc}) final void Function({required HistorySortField field, required bool asc})
onSortChanged; onSortChanged;
static final List<SortOption<HistorySortField>> _options = [
const SortOption(HistorySortField.date, Icons.calendar_today, 'Date'),
SortOption(
HistorySortField.kcal,
MacroKind.kcal.icon,
'Kcal',
color: MacroKind.kcal.color,
),
SortOption(
HistorySortField.protein,
MacroKind.protein.icon,
'Protein',
color: MacroKind.protein.color,
),
SortOption(
HistorySortField.carbs,
MacroKind.carbs.icon,
'Carbs',
color: MacroKind.carbs.color,
),
SortOption(
HistorySortField.fat,
MacroKind.fat.icon,
'Fat',
color: MacroKind.fat.color,
),
const SortOption(
HistorySortField.description,
Icons.sort_by_alpha,
'Description',
),
];
@override @override
Widget build(BuildContext context) => SortChoiceRow<HistorySortField>( Widget build(BuildContext context) {
options: _options, return Column(
selected: sortField, crossAxisAlignment: CrossAxisAlignment.stretch,
ascending: ascending, children: [
onChanged: onSortChanged, Text('Sort by', style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 4),
Row(
children: [
Expanded(
child: DropdownButton<HistorySortField>(
isExpanded: true,
value: sortField,
items: const [
DropdownMenuItem(
value: HistorySortField.date,
child: Text('Date'),
),
DropdownMenuItem(
value: HistorySortField.kcal,
child: Text('Kcal'),
),
DropdownMenuItem(
value: HistorySortField.protein,
child: Text('Protein'),
),
DropdownMenuItem(
value: HistorySortField.carbs,
child: Text('Carbs'),
),
DropdownMenuItem(
value: HistorySortField.fat,
child: Text('Fat'),
),
DropdownMenuItem(
value: HistorySortField.description,
child: Text('Description'),
),
],
onChanged: (v) {
if (v != null) {
onSortChanged(field: v, asc: ascending);
}
},
),
),
const SizedBox(width: 8),
IconButton(
icon: Icon(
ascending ? Icons.arrow_upward : Icons.arrow_downward,
),
tooltip: ascending ? 'Ascending' : 'Descending',
onPressed: () => onSortChanged(field: sortField, asc: !ascending),
),
],
),
],
); );
} }
}

View File

@ -170,17 +170,29 @@ String dateRangeLabel(DateTimeRange r) =>
'${r.start.toString().substring(0, 10)}' '${r.start.toString().substring(0, 10)}'
' – ${r.end.toString().substring(0, 10)}'; ' – ${r.end.toString().substring(0, 10)}';
/// Render a `YYYY-MM-DD` key as numeric `DD.MM.YYYY` (no weekday or month /// Render a `YYYY-MM-DD` key as a short `Wed 12 Aug`-style label.
/// names: those were written words, and a date is a number).
/// ///
/// Falls back to the raw key when it cannot be parsed, so a malformed date /// Falls back to the raw key when it cannot be parsed, so a malformed date
/// shows something rather than throwing inside a list build. /// shows something rather than throwing inside a list build.
String formatDay(String dateKey) { String formatDay(String dateKey) {
try { try {
final d = DateTime.parse(dateKey); final d = DateTime.parse(dateKey);
final day = d.day.toString().padLeft(2, '0'); const wd = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
final month = d.month.toString().padLeft(2, '0'); const mo = [
return '$day.$month.${d.year}'; 'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
return '${wd[d.weekday - 1]} ${d.day} ${mo[d.month - 1]} ${d.year}';
} on Exception { } on Exception {
return dateKey; return dateKey;
} }

View File

@ -3,14 +3,9 @@
/// Split out of `history_screen.dart` to hold the repo's 250-line cap. /// Split out of `history_screen.dart` to hold the repo's 250-line cap.
library; library;
import 'dart:async';
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/log_storage_service.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/source_icon.dart';
import 'package:diet_guard_app/widgets/history/history_grouping.dart'; import 'package:diet_guard_app/widgets/history/history_grouping.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -89,44 +84,28 @@ class DayHeaderTile extends StatelessWidget {
), ),
), ),
), ),
Icon( Text(
Icons.restaurant, '${header.entryCount}'
size: 14, ' ${header.entryCount == 1 ? 'entry' : 'entries'}',
color: colorScheme.onSurfaceVariant, style: textTheme.bodySmall,
semanticLabel: 'entries',
), ),
const SizedBox(width: 3),
Text('${header.entryCount}', style: textTheme.bodySmall),
], ],
), ),
const SizedBox(height: 2), const SizedBox(height: 2),
Row( Row(
children: [ children: [
Icon(
MacroKind.kcal.icon,
size: 14,
color: kcalColor,
semanticLabel: 'kcal',
),
const SizedBox(width: 3),
Text( Text(
'${header.totalKcal.round()} / $goal', '${header.totalKcal.round()} / $goal kcal',
style: textTheme.bodySmall?.copyWith(color: kcalColor), style: textTheme.bodySmall?.copyWith(color: kcalColor),
), ),
const SizedBox(width: 12),
MacroFigure(
kind: MacroKind.protein,
value: '${header.totalProtein.round()}g',
),
const SizedBox(width: 8), const SizedBox(width: 8),
MacroFigure( Text(
kind: MacroKind.carbs, 'P ${header.totalProtein.round()}g · '
value: '${header.totalCarbs.round()}g', 'C ${header.totalCarbs.round()}g · '
'F ${header.totalFat.round()}g',
style: textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
), ),
const SizedBox(width: 8),
MacroFigure(
kind: MacroKind.fat,
value: '${header.totalFat.round()}g',
), ),
], ],
), ),
@ -156,13 +135,7 @@ class EntryTile extends StatelessWidget {
return ListTile( return ListTile(
leading: const Icon(Icons.restaurant), leading: const Icon(Icons.restaurant),
title: Text(entry.desc), title: Text(entry.desc),
subtitle: Row( subtitle: Text('${entry.time} • ${entry.source}'),
children: [
Flexible(child: Text(entry.time, overflow: TextOverflow.ellipsis)),
const SizedBox(width: 8),
SourceMark(entry.source),
],
),
// Delete needs a focusable control, not just a long-press. Long-press has // Delete needs a focusable control, not just a long-press. Long-press has
// no keyboard equivalent at all, so on the desktop build (a Chrome --app // no keyboard equivalent at all, so on the desktop build (a Chrome --app
// window) deleting an entry was pointer-only: unreachable by keyboard and // window) deleting an entry was pointer-only: unreachable by keyboard and
@ -171,18 +144,12 @@ class EntryTile extends StatelessWidget {
trailing: Row( trailing: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
MacroFigure( Text('${entry.kcal.toStringAsFixed(0)} kcal'),
kind: MacroKind.kcal,
value: entry.kcal.toStringAsFixed(0),
size: 14,
),
if (canDelete) if (canDelete)
IconButton( IconButton(
icon: const Icon( icon: const Icon(Icons.delete_outline),
Icons.delete_outline, tooltip: 'Delete entry',
semanticLabel: 'Delete entry', onPressed: () => _confirmDelete(context),
),
onPressed: () => unawaited(_delete(context)),
), ),
], ],
), ),
@ -190,33 +157,35 @@ class EntryTile extends StatelessWidget {
// Delete remains id-only to avoid ambiguous time+desc matches. // Delete remains id-only to avoid ambiguous time+desc matches.
onTap: () => onEdit?.call(), onTap: () => onEdit?.call(),
// Retained as a redundant pointer shortcut, never the only route. // Retained as a redundant pointer shortcut, never the only route.
onLongPress: canDelete ? () => unawaited(_delete(context)) : null, onLongPress: canDelete ? () => _confirmDelete(context) : null,
); );
} }
/// Deletes at once and offers an icon-only undo instead of asking first. Future<void> _confirmDelete(BuildContext context) async {
/// final confirmed = await showDialog<bool>(
/// The snackbar is raised before the awaits because the reload that context: context,
/// follows rebuilds the list and may dispose this tile's context. Undo builder: (_) => AlertDialog(
/// writes the live copy back over the tombstone (same id), then reloads. title: const Text('Delete entry?'),
Future<void> _delete(BuildContext context) async { content: Text('Remove "${entry.desc}" from history?'),
showCueSnack( actions: [
context, TextButton(
kind: CueKind.ok, onPressed: () => Navigator.of(context).pop(false),
icon: Icons.delete_outline, child: const Text('Cancel'),
semanticLabel: 'Entry deleted', ),
onUndo: () => unawaited(_restore()), TextButton(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Delete'),
),
],
),
); );
if (confirmed == true) {
await LogStorageService.instance.deleteEntry(entry.id!); await LogStorageService.instance.deleteEntry(entry.id!);
await onDelete?.call(); await onDelete?.call();
} }
Future<void> _restore() async {
await LogStorageService.instance.updateEntry(
entry.copyWithDeleted(),
entry,
);
await onDelete?.call();
} }
} }

View File

@ -52,44 +52,44 @@ class LogMealActionsRow extends StatelessWidget {
final canFetch = canFetchDelivery ?? kuchniaFetchSupported; final canFetch = canFetchDelivery ?? kuchniaFetchSupported;
return Row( return Row(
children: [ children: [
// Expanded so the delivery button takes the slack and pushes the log // Flexible, not Spacer-and-hope: `OutlinedButton.icon` lays its label
// button right; the queue is a numeral next to the icon, so there is // out unbounded, so on a narrow phone the queue suffix renders wider
// no wide label to clip. While fetching the icon becomes a spinner. // than the row and is clipped without ever throwing an overflow. The
// Flexible caps the width and the FittedBox scales the text into it.
if (canFetch) if (canFetch)
Expanded( Expanded(
child: OutlinedButton( child: Tooltip(
message: "Load today's catering delivery",
child: OutlinedButton.icon(
onPressed: deliveryBusy ? null : onLoadDelivery, onPressed: deliveryBusy ? null : onLoadDelivery,
child: Row( icon: const Icon(Icons.restaurant),
mainAxisAlignment: MainAxisAlignment.center, label: FittedBox(
children: [ fit: BoxFit.scaleDown,
if (deliveryBusy) child: Text(_label, maxLines: 1),
const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
const Icon(
Icons.restaurant,
semanticLabel: "Load today's catering delivery",
),
if (dishesQueued > 0) ...[
const SizedBox(width: AppSpacing.xs),
Text('$dishesQueued'),
],
],
), ),
), ),
), ),
// No Spacer when the delivery button is present: it is a flex child ),
// too and would split the free space with the Expanded above. // No Spacer: it is a flex child too, so it would split the free space
// with the Flexible above and re-create the clipping this guards
// against. The Flexible takes the slack and pushes the log button
// right on its own.
if (!canFetch) const Spacer(), if (!canFetch) const Spacer(),
const SizedBox(width: AppSpacing.sm), const SizedBox(width: AppSpacing.sm),
FilledButton( Tooltip(
message: 'Log meal',
child: FilledButton(
onPressed: onLog, onPressed: onLog,
child: const Icon(Icons.check_circle, semanticLabel: 'Log meal'), child: const Icon(Icons.check_circle),
),
), ),
], ],
); );
} }
String get _label {
if (deliveryBusy) return 'Loading…';
if (dishesQueued > 0) return "Today's delivery ($dishesQueued more to go)";
return "Today's delivery";
}
} }

View File

@ -4,8 +4,6 @@
library; library;
import 'package:diet_guard_app/models/nutrition.dart'; import 'package:diet_guard_app/models/nutrition.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Text controllers for one macro-entry row, owned by the calling screen so /// Text controllers for one macro-entry row, owned by the calling screen so
@ -93,8 +91,7 @@ class MacroControllers {
} }
} }
/// A row of number-entry fields, each captioned by an icon: calories, /// A labeled row of number-entry fields for calories, macros, and the
/// macros, and the
/// optional reference-weight-vs-eaten-weight split. /// optional reference-weight-vs-eaten-weight split.
/// ///
/// Layout mirrors the Python gate's macro section: the reference weight /// Layout mirrors the Python gate's macro section: the reference weight
@ -119,59 +116,76 @@ class MacroInputRow extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final fields = [
_macroField(MacroKind.perGrams, controllers.perGrams),
_macroField(MacroKind.kcal, controllers.kcal),
_macroField(MacroKind.protein, controllers.protein),
_macroField(MacroKind.carbs, controllers.carbs),
_macroField(MacroKind.fat, controllers.fat),
_macroField(MacroKind.eaten, controllers.grams),
];
if (compact) { if (compact) {
return Row( return Row(
children: [ children: [
for (final (i, field) in fields.indexed) ...[ Expanded(child: _macroField('per', controllers.perGrams)),
if (i > 0) const SizedBox(width: 4), const SizedBox(width: 4),
Expanded(child: field), Expanded(child: _macroField('kcal', controllers.kcal)),
], const SizedBox(width: 4),
Expanded(child: _macroField('P', controllers.protein)),
const SizedBox(width: 4),
Expanded(child: _macroField('C', controllers.carbs)),
const SizedBox(width: 4),
Expanded(child: _macroField('F', controllers.fat)),
const SizedBox(width: 4),
Expanded(
child: Tooltip(
message: "blank = same as 'per (g)'",
child: _macroField('eaten', controllers.grams),
),
),
], ],
); );
} }
// Reference weight and kcal share a line, then the three macros, then the
// eaten weight: the same order the Python gate shows them in.
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// per-gram reference weight and kcal on the same line.
Row( Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
SizedBox(width: 96, child: fields[0]), SizedBox(
width: 72,
child: _macroField('per (g)', controllers.perGrams),
),
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded(child: fields[1]), Expanded(child: _macroField('kcal', controllers.kcal)),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( Row(
children: [ children: [
for (final (i, field) in fields.sublist(2, 5).indexed) ...[ Expanded(child: _macroField('protein g', controllers.protein)),
if (i > 0) const SizedBox(width: 8), const SizedBox(width: 8),
Expanded(child: field), Expanded(child: _macroField('carbs g', controllers.carbs)),
], const SizedBox(width: 8),
Expanded(child: _macroField('fat g', controllers.fat)),
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
fields[5], _macroField(
'eaten (g)',
controllers.grams,
helperText: "blank = same as 'per (g)'",
),
], ],
); );
} }
Widget _macroField(MacroKind kind, TextEditingController controller) { Widget _macroField(
return IconField( String label,
icon: kind.icon, TextEditingController controller, {
iconColor: kind.color, String? helperText,
semanticLabel: kind.semanticLabel(compact: compact), }) {
return TextField(
controller: controller, controller: controller,
keyboardType: const TextInputType.numberWithOptions(decimal: true), keyboardType: const TextInputType.numberWithOptions(decimal: true),
dense: true, decoration: InputDecoration(
labelText: label,
helperText: helperText,
isDense: true,
),
); );
} }
} }

View File

@ -4,7 +4,6 @@ library;
import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/ui/icon_field.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/meal_time_dropdown.dart'; import 'package:diet_guard_app/widgets/meal_time_dropdown.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -62,9 +61,15 @@ class MealScheduleEditor extends StatelessWidget {
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Text('Meal times', style: theme.textTheme.titleMedium),
const SizedBox(height: AppSpacing.xs),
Text(
'Checkpoints are spread evenly between your first and last meal.',
style: theme.textTheme.bodySmall,
),
const SizedBox(height: 12),
MealTimeDropdown( MealTimeDropdown(
icon: Icons.light_mode_outlined, label: 'First meal',
semanticLabel: 'First meal',
value: schedule.firstMinute, value: schedule.firstMinute,
minMinute: 0, minMinute: 0,
maxMinute: _firstMax, maxMinute: _firstMax,
@ -73,8 +78,7 @@ class MealScheduleEditor extends StatelessWidget {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
MealTimeDropdown( MealTimeDropdown(
icon: Icons.dark_mode_outlined, label: 'Last meal',
semanticLabel: 'Last meal',
value: schedule.lastMinute, value: schedule.lastMinute,
// At least one grid step after the first meal: the shortest window // At least one grid step after the first meal: the shortest window
// that still holds two distinct checkpoints. // that still holds two distinct checkpoints.
@ -85,12 +89,8 @@ class MealScheduleEditor extends StatelessWidget {
const SizedBox(height: 12), const SizedBox(height: 12),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: AppWidth.field), constraints: const BoxConstraints(maxWidth: AppWidth.field),
child: SpokenLabel(
semanticLabel: 'Meals per day',
child: InputDecorator( child: InputDecorator(
decoration: const InputDecoration( decoration: const InputDecoration(labelText: 'Meals per day'),
prefixIcon: ExcludeSemantics(child: Icon(Icons.restaurant)),
),
child: DropdownButtonHideUnderline( child: DropdownButtonHideUnderline(
child: DropdownButton<int>( child: DropdownButton<int>(
value: counts.contains(schedule.count) value: counts.contains(schedule.count)
@ -108,7 +108,6 @@ class MealScheduleEditor extends StatelessWidget {
), ),
), ),
), ),
),
const SizedBox(height: 12), const SizedBox(height: 12),
Text( Text(
schedule.slots().map(slotLabel).join(' · '), schedule.slots().map(slotLabel).join(' · '),

View File

@ -26,8 +26,7 @@ import 'package:flutter/material.dart';
class MealTimeDropdown extends StatelessWidget { class MealTimeDropdown extends StatelessWidget {
/// Creates a [MealTimeDropdown]. /// Creates a [MealTimeDropdown].
const MealTimeDropdown({ const MealTimeDropdown({
required this.icon, required this.label,
required this.semanticLabel,
required this.value, required this.value,
required this.minMinute, required this.minMinute,
required this.maxMinute, required this.maxMinute,
@ -36,11 +35,8 @@ class MealTimeDropdown extends StatelessWidget {
super.key, super.key,
}); });
/// The painted caption glyph, e.g. a sun for the first meal. /// The field label, e.g. "First meal".
final IconData icon; final String label;
/// The spoken caption, e.g. "First meal"; never painted.
final String semanticLabel;
/// The current minute of day. /// The current minute of day.
final int value; final int value;
@ -85,8 +81,7 @@ class MealTimeDropdown extends StatelessWidget {
final picked = await showTimePicker( final picked = await showTimePicker(
context: context, context: context,
initialTime: TimeOfDay(hour: value ~/ 60, minute: value % 60), initialTime: TimeOfDay(hour: value ~/ 60, minute: value % 60),
// Empty so the picker does not print its own heading over the clock. helpText: label,
helpText: '',
// The rest of the app writes times as HH:MM; an AM/PM dial here would // The rest of the app writes times as HH:MM; an AM/PM dial here would
// be the one place that reads differently. // be the one place that reads differently.
builder: (context, child) => MediaQuery( builder: (context, child) => MediaQuery(
@ -108,13 +103,8 @@ class MealTimeDropdown extends StatelessWidget {
spacing: AppSpacing.xs, spacing: AppSpacing.xs,
children: [ children: [
Expanded( Expanded(
child: Semantics(
label: semanticLabel,
container: true,
child: InputDecorator( child: InputDecorator(
decoration: InputDecoration( decoration: InputDecoration(labelText: label),
prefixIcon: ExcludeSemantics(child: Icon(icon)),
),
child: DropdownButtonHideUnderline( child: DropdownButtonHideUnderline(
child: DropdownButton<int>( child: DropdownButton<int>(
value: value, value: value,
@ -133,12 +123,9 @@ class MealTimeDropdown extends StatelessWidget {
), ),
), ),
), ),
),
IconButton( IconButton(
icon: const Icon( icon: const Icon(Icons.schedule),
Icons.schedule, tooltip: 'Type or pick an exact time',
semanticLabel: 'Type or pick an exact time',
),
onPressed: () => unawaited(_pickExact(context)), onPressed: () => unawaited(_pickExact(context)),
), ),
], ],

View File

@ -2,15 +2,13 @@
library; library;
import 'package:diet_guard_app/models/day_status.dart'; import 'package:diet_guard_app/models/day_status.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Displays the logging streak, adherence streak, and year-to-date tally. /// Displays the logging streak, adherence streak, and year-to-date tally.
/// ///
/// Mirrors `_calendar_view.py`'s `streaks_text`/`ytd_text` data, as glyphs and /// Mirrors `_calendar_view.py`'s `streaks_text`/`ytd_text` formatting:
/// numerals: pencil + N (logging streak), flame + N (adherence streak), /// "Logging streak: N day(s) · Adherence streak: N day(s)" and
/// calendar-check + X/Y (days logged of days elapsed), medal + Z (days within /// "This year: logged X/Y days · Z within budget".
/// budget).
class StreakSummaryRow extends StatelessWidget { class StreakSummaryRow extends StatelessWidget {
/// Creates a [StreakSummaryRow]. /// Creates a [StreakSummaryRow].
const StreakSummaryRow({ const StreakSummaryRow({
@ -29,80 +27,27 @@ class StreakSummaryRow extends StatelessWidget {
/// This year's logged/elapsed/adherent day counts. /// This year's logged/elapsed/adherent day counts.
final YtdTally tally; final YtdTally tally;
static String _plural(int count) => count == 1 ? 'day' : 'days';
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final status = theme.extension<AppStatusColors>() ?? AppStatusColors.dark;
return Column( return Column(
children: [ children: [
Wrap( Text(
alignment: WrapAlignment.center, 'Logging streak: $loggingStreak ${_plural(loggingStreak)} · '
spacing: AppSpacing.lg, 'Adherence streak: $adherenceStreak ${_plural(adherenceStreak)}',
children: [ textAlign: TextAlign.center,
_Figure(
icon: Icons.edit_note,
color: theme.colorScheme.primary,
semanticLabel: 'Logging streak',
value: '$loggingStreak',
style: theme.textTheme.titleSmall, style: theme.textTheme.titleSmall,
), ),
_Figure( const SizedBox(height: 4),
icon: Icons.local_fire_department, Text(
color: status.warning, 'This year: logged ${tally.loggedDays}/${tally.elapsedDays} days · '
semanticLabel: 'Adherence streak', '${tally.adherentDays} within budget',
value: '$adherenceStreak', textAlign: TextAlign.center,
style: theme.textTheme.titleSmall,
),
],
),
const SizedBox(height: AppSpacing.xs),
Wrap(
alignment: WrapAlignment.center,
spacing: AppSpacing.lg,
children: [
_Figure(
icon: Icons.event_available,
color: theme.colorScheme.onSurfaceVariant,
semanticLabel: 'Days logged this year',
value: '${tally.loggedDays}/${tally.elapsedDays}',
style: theme.textTheme.bodySmall, style: theme.textTheme.bodySmall,
), ),
_Figure(
icon: Icons.verified,
color: status.success,
semanticLabel: 'Days within budget',
value: '${tally.adherentDays}',
style: theme.textTheme.bodySmall,
),
],
),
], ],
); );
} }
} }
class _Figure extends StatelessWidget {
const _Figure({
required this.icon,
required this.color,
required this.semanticLabel,
required this.value,
required this.style,
});
final IconData icon;
final Color color;
final String semanticLabel;
final String value;
final TextStyle? style;
@override
Widget build(BuildContext context) => Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, color: color, size: 18, semanticLabel: semanticLabel),
const SizedBox(width: 4),
Text(value, style: style),
],
);
}

View File

@ -40,22 +40,16 @@ class SyncHealthBanner extends StatelessWidget {
border: Border.all(color: warning.withValues(alpha: 0.5)), border: Border.all(color: warning.withValues(alpha: 0.5)),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
// A glyph and, once an hour or more has passed, the elapsed time as a
// numeral (`2d`). The sentence survives only as the spoken label.
child: Row( child: Row(
children: [ children: [
Icon( Icon(Icons.cloud_off, size: 18, color: warning),
Icons.cloud_off,
size: 18,
color: warning,
semanticLabel: message,
),
const SizedBox(width: 8), const SizedBox(width: 8),
if (status?.agoShort case final ago?) Expanded(
Text( child: Text(
ago, message,
style: theme.textTheme.bodySmall?.copyWith(color: warning), style: theme.textTheme.bodySmall?.copyWith(color: warning),
), ),
),
], ],
), ),
); );

View File

@ -3,7 +3,6 @@
library; library;
import 'package:diet_guard_app/models/slot.dart'; import 'package:diet_guard_app/models/slot.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart'; import 'package:diet_guard_app/ui/theme.dart';
import 'package:diet_guard_app/widgets/progress_motion.dart'; import 'package:diet_guard_app/widgets/progress_motion.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -88,6 +87,8 @@ class TodayProgressCard extends StatelessWidget {
/// The values to display. /// The values to display.
final TodayProgress progress; final TodayProgress progress;
static String _plural(int count) => count == 1 ? 'day' : 'days';
static String _grams(double value) => '${value.round()}g'; static String _grams(double value) => '${value.round()}g';
/// Whole numbers without decimals; fractions exactly, never rounded. /// Whole numbers without decimals; fractions exactly, never rounded.
@ -97,7 +98,6 @@ class TodayProgressCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final status = theme.extension<AppStatusColors>() ?? AppStatusColors.dark;
final slot = progress.loggedSlotMinute; final slot = progress.loggedSlotMinute;
final logged = progress.loggedKcal; final logged = progress.loggedKcal;
final from = progress.previousKcal ?? progress.consumedKcal; final from = progress.previousKcal ?? progress.consumedKcal;
@ -118,55 +118,31 @@ class TodayProgressCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (slot != null && logged != null) ...[ if (slot != null && logged != null) ...[
Row( Text(
children: [ '✓ ${slotLabel(slot)} · ${_kcal(logged)} kcal',
Icon( style: theme.textTheme.labelMedium,
Icons.check_circle,
size: 16,
color: status.success,
semanticLabel: 'logged',
),
const SizedBox(width: AppSpacing.xs),
Text(slotLabel(slot), style: theme.textTheme.labelMedium),
const SizedBox(width: AppSpacing.sm),
MacroFigure(kind: MacroKind.kcal, value: _kcal(logged)),
],
), ),
const SizedBox(height: AppSpacing.xs), const SizedBox(height: AppSpacing.xs),
], ],
CountUp(from: from, to: progress.consumedKcal, builder: _kcalRow), CountUp(from: from, to: progress.consumedKcal, builder: _kcalRow),
const SizedBox(height: AppSpacing.xs), const SizedBox(height: AppSpacing.xs),
Row( Text(
children: [ 'P ${_grams(progress.proteinG)} · '
MacroFigure( 'C ${_grams(progress.carbsG)} · '
kind: MacroKind.protein, 'F ${_grams(progress.fatG)}',
value: _grams(progress.proteinG), style: theme.textTheme.labelSmall,
),
const SizedBox(width: AppSpacing.md),
MacroFigure(
kind: MacroKind.carbs,
value: _grams(progress.carbsG),
),
const SizedBox(width: AppSpacing.md),
MacroFigure(kind: MacroKind.fat, value: _grams(progress.fatG)),
],
), ),
const SizedBox(height: AppSpacing.xs), const SizedBox(height: AppSpacing.xs),
CountUp( CountUp(
from: streakFrom.toDouble(), from: streakFrom.toDouble(),
to: progress.adherenceStreak.toDouble(), to: progress.adherenceStreak.toDouble(),
builder: (context, value) => Row( builder: (context, value) {
children: [ final days = value.round();
Icon( return Text(
Icons.local_fire_department, 'Adherence streak: $days ${_plural(days)}',
size: 16, style: theme.textTheme.labelSmall,
color: status.warning, );
semanticLabel: 'adherence streak', },
),
const SizedBox(width: 3),
Text('${value.round()}', style: theme.textTheme.labelMedium),
],
),
), ),
], ],
), ),
@ -180,49 +156,24 @@ class TodayProgressCard extends StatelessWidget {
final colors = theme.colorScheme; final colors = theme.colorScheme;
final remaining = progress.budgetKcal - consumed; final remaining = progress.budgetKcal - consumed;
final over = remaining < 0; final over = remaining < 0;
final tint = over ? colors.error : colors.onSurface; return Row(
// Bar fill = share of the budget used; it turns red AND the right-hand crossAxisAlignment: CrossAxisAlignment.baseline,
// glyph flips from a flag (room left) to a warning (over) past the budget. textBaseline: TextBaseline.alphabetic,
final used = progress.budgetKcal > 0
? (consumed / progress.budgetKcal).clamp(0.0, 1.0)
: 1.0;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Row(
children: [
Icon(
MacroKind.kcal.icon,
size: 18,
color: MacroKind.kcal.color,
semanticLabel: 'kcal',
),
const SizedBox(width: AppSpacing.xs),
Text( Text(
'${consumed.round()} / ${progress.budgetKcal}', '${consumed.round()} / ${progress.budgetKcal}',
style: theme.textTheme.titleMedium?.copyWith(color: tint), style: theme.textTheme.titleMedium?.copyWith(
color: over ? colors.error : colors.onSurface,
), ),
),
const SizedBox(width: AppSpacing.xs),
Text('kcal', style: theme.textTheme.labelSmall),
const Spacer(), const Spacer(),
Icon(
over ? Icons.warning_amber_rounded : Icons.flag_outlined,
size: 16,
color: over ? colors.error : colors.onSurfaceVariant,
semanticLabel: over ? 'over budget' : 'left',
),
const SizedBox(width: 3),
Text( Text(
'${remaining.abs().round()}', '${remaining.abs().round()} ${over ? 'over' : 'left'}',
style: theme.textTheme.labelMedium?.copyWith(color: tint), style: theme.textTheme.labelMedium?.copyWith(
color: over ? colors.error : colors.onSurfaceVariant,
), ),
],
),
const SizedBox(height: AppSpacing.xs),
LinearProgressIndicator(
value: used,
minHeight: 6,
borderRadius: BorderRadius.circular(3),
color: over ? colors.error : colors.primary,
backgroundColor: colors.surfaceContainerHighest,
), ),
], ],
); );

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go." description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none' publish_to: 'none'
version: 1.0.146+1 version: 1.0.138+1
environment: environment:
sdk: ^3.12.2 sdk: ^3.12.2

View File

@ -1,12 +1,10 @@
/// The "Fill all with catering" row: glyph per state, Cancel only when armed. /// The "Fill all with catering" row: label per state, Cancel only when armed.
library; library;
import 'package:diet_guard_app/widgets/fill_all_row.dart'; import 'package:diet_guard_app/widgets/fill_all_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'label_finders.dart';
Future<void> _pump( Future<void> _pump(
WidgetTester tester, { WidgetTester tester, {
bool canFetch = true, bool canFetch = true,
@ -33,30 +31,26 @@ void main() {
await _pump(t, canFetch: false, armed: 3); await _pump(t, canFetch: false, armed: 3);
expect(find.byType(OutlinedButton), findsNothing); expect(find.byType(OutlinedButton), findsNothing);
expect(byIconLabel(fillAllLabel), findsNothing); expect(find.text(fillAllLabel), findsNothing);
expect(byIconLabel('Cancel'), findsNothing); expect(find.text('Cancel'), findsNothing);
}); });
testWidgets('resting: the fill glyph and no Cancel', (t) async { testWidgets('resting: the fill label and no Cancel', (t) async {
await _pump(t); await _pump(t);
expect(byIconLabel(fillAllLabel), findsOneWidget); expect(find.text('🍱 Fill all with catering'), findsOneWidget);
expect(find.byIcon(Icons.playlist_add_check), findsOneWidget); expect(find.text('Cancel'), findsNothing);
expect(byIconLabel('Cancel'), findsNothing);
}); });
testWidgets('armed: double check with the count, and a Cancel button', ( testWidgets('armed: Confirm (N) and a Cancel button', (t) async {
t,
) async {
await _pump(t, armed: 3); await _pump(t, armed: 3);
expect(byIconLabel('Confirm'), findsOneWidget); expect(find.text('✓ Confirm (3)'), findsOneWidget);
expect(find.text('3'), findsOneWidget); expect(find.text(fillAllLabel), findsNothing);
expect(byIconLabel(fillAllLabel), findsNothing); expect(find.text('Cancel'), findsOneWidget);
expect(byIconLabel('Cancel'), findsOneWidget);
}); });
testWidgets('busy: spinner and both controls disabled', (t) async { testWidgets('busy: Working… and both controls disabled', (t) async {
var fills = 0; var fills = 0;
var cancels = 0; var cancels = 0;
await _pump( await _pump(
@ -67,15 +61,15 @@ void main() {
onCancel: () => cancels++, onCancel: () => cancels++,
); );
expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(find.text('Working…'), findsOneWidget);
expect(byIconLabel('Confirm'), findsNothing); expect(find.text('✓ Confirm (3)'), findsNothing);
expect( expect(
t.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed, t.widget<OutlinedButton>(find.byType(OutlinedButton)).onPressed,
isNull, isNull,
); );
expect(t.widget<IconButton>(find.byType(IconButton)).onPressed, isNull); expect(t.widget<TextButton>(find.byType(TextButton)).onPressed, isNull);
await t.tap(find.byType(OutlinedButton), warnIfMissed: false); await t.tap(find.byType(OutlinedButton), warnIfMissed: false);
await t.tap(find.byType(IconButton), warnIfMissed: false); await t.tap(find.byType(TextButton), warnIfMissed: false);
expect(fills + cancels, 0); expect(fills + cancels, 0);
}); });
@ -89,8 +83,8 @@ void main() {
onCancel: () => cancels++, onCancel: () => cancels++,
); );
await t.tap(byIconLabel('Confirm')); await t.tap(find.text('✓ Confirm (2)'));
await t.tap(byIconLabel('Cancel')); await t.tap(find.text('Cancel'));
expect([fills, cancels], [1, 1]); expect([fills, cancels], [1, 1]);
}); });

View File

@ -22,7 +22,6 @@ import 'package:diet_guard_app/widgets/day_status_calendar.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart'; import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'label_finders.dart';
/// Landscape and *short* — the supported floor. Phone-portrait sizes, which is /// Landscape and *short* — the supported floor. Phone-portrait sizes, which is
/// all the existing suite pinned, exercise neither constraint. /// all the existing suite pinned, exercise neither constraint.
@ -177,7 +176,7 @@ void main() {
// Delete used to be bound only to onLongPress, which has no keyboard // Delete used to be bound only to onLongPress, which has no keyboard
// equivalent whatsoever. // equivalent whatsoever.
expect( expect(
byIconLabel('Delete entry'), find.byTooltip('Delete entry'),
findsOneWidget, findsOneWidget,
reason: 'delete needs a tab-reachable control, not long-press only', reason: 'delete needs a tab-reachable control, not long-press only',
); );
@ -208,7 +207,7 @@ void main() {
// Delete stays id-only to avoid ambiguous time+desc matches, so the // Delete stays id-only to avoid ambiguous time+desc matches, so the
// control must be absent rather than present-and-failing. // control must be absent rather than present-and-failing.
expect(byIconLabel('Delete entry'), findsNothing); expect(find.byTooltip('Delete entry'), findsNothing);
}); });
}); });
} }

View File

@ -1,46 +0,0 @@
/// Finders for text-free controls: they match the spoken label that icons and
/// [Semantics] carry, so tests keep addressing widgets by name without any
/// visible text.
library;
import 'package:diet_guard_app/ui/cues.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// Finds an [Icon] with this `semanticLabel`.
Finder byIconLabel(String label) =>
find.byWidgetPredicate((w) => w is Icon && w.semanticLabel == label);
/// Finds a [Semantics] node with this label.
Finder bySemLabel(String label) => find.byWidgetPredicate(
(w) => w is Semantics && w.properties.label == label,
);
/// Finds the [TextField] captioned [label] (an [IconField] or a bare
/// [Semantics] wrapper).
Finder fieldByLabel(String label) =>
find.descendant(of: bySemLabel(label), matching: find.byType(TextField));
/// Finds the tappable control whose icon or semantics carries [label].
Finder controlByLabel(String label) => find
.ancestor(
of: byIconLabel(label),
matching: find.byWidgetPredicate(
(w) => w is IconButton || w is ButtonStyleButton || w is InkResponse,
),
)
.first;
/// Finds a [StatusCue] of [kind].
Finder cueOfKind(CueKind kind) =>
find.byWidgetPredicate((w) => w is StatusCue && w.kind == kind);
/// Finds a [StatusCue] whose spoken label is [label].
Finder cueLabelled(String label) =>
find.byWidgetPredicate((w) => w is StatusCue && w.semanticLabel == label);
/// Finds the chip ([FilterChip] or [ChoiceChip]) whose icon carries [label].
Finder chipByLabel(String label) => find.ancestor(
of: byIconLabel(label),
matching: find.byWidgetPredicate((w) => w is FilterChip || w is ChoiceChip),
);

View File

@ -2,11 +2,9 @@ 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_energy.dart';
import 'package:diet_guard_app/services/body_prefs.dart'; import 'package:diet_guard_app/services/body_prefs.dart';
import 'package:diet_guard_app/services/body_service.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/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import 'body_screen_support.dart'; import 'body_screen_support.dart';
void main() { void main() {
@ -24,12 +22,10 @@ void main() {
await seedPerson(store); await seedPerson(store);
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Daily calorie target'); 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<void> choose(String word, String option) async { Future<void> choose(String word, String option) async {
await tester.tap(bySemLabel(word).first); await tester.tap(find.text(word).first);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(bySemLabel(option).last); await tester.tap(find.text(option).last);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
@ -54,25 +50,24 @@ void main() {
); );
// A typed amount; junk is refused and the dialog stays open. // A typed amount; junk is refused and the dialog stays open.
final other = fieldByLabel('Other amount'); final other = find.widgetWithText(TextField, 'Other amount');
await tester.tap(find.text('1')); await tester.tap(find.text('1'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.enterText(other, ''); await tester.enterText(other, '');
await tester.tap(byIconLabel('OK')); await tester.tap(find.text('OK'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(byIconLabel('OK'), findsOneWidget); expect(find.text('OK'), findsOneWidget);
expect(cueOfKind(CueKind.error), findsOneWidget);
await tester.enterText(other, '2,5'); await tester.enterText(other, '2,5');
await tester.tap(byIconLabel('OK')); await tester.tap(find.text('OK'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(savedGoal(BodyService.instance).amount, 2.5); expect(savedGoal(BodyService.instance).amount, 2.5);
// Cancel changes nothing; neither does dismissing a sheet. // Cancel changes nothing; neither does dismissing a sheet.
await tester.tap(find.text('2.5')); await tester.tap(find.text('2.5'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(byIconLabel('Cancel')); await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(bySemLabel('gain').first); await tester.tap(find.text('gain'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tapAt(const Offset(5, 5)); await tester.tapAt(const Offset(5, 5));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@ -91,19 +86,16 @@ void main() {
await setGoal(body, const Goal('lose', 1, 'kg', 'week', 'measured:MET')); await setGoal(body, const Goal('lose', 1, 'kg', 'week', 'measured:MET'));
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
expect( expect(find.textContaining('no workouts published yet'), findsOneWidget);
cueLabelled('no workouts published yet (the PC publishes them).'), await tester.tap(find.text('Measured (MET)'));
findsOneWidget,
);
await tester.tap(bySemLabel('Measured (MET)').first);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(bySemLabel('Sedentary').last); await tester.tap(find.text('Sedentary').last);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(find.text('1')); await tester.tap(find.text('1'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.enterText(fieldByLabel('Other amount'), '3'); await tester.enterText(find.widgetWithText(TextField, 'Other amount'), '3');
await tester.tap(byIconLabel('OK')); await tester.tap(find.text('OK'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueLabelled('That is below the 1200 kcal floor.'), findsOneWidget); expect(find.textContaining('below the 1200 kcal floor'), findsOneWidget);
}); });
} }

View File

@ -1,11 +1,11 @@
import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/services/body_service.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/health_steps.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import '../services/health_steps_test.dart' show FakeStepsSource;
import 'body_screen_support.dart'; import 'body_screen_support.dart';
import '../services/health_steps_test.dart' show FakeStepsSource;
void main() { void main() {
final original = stepsSource; final original = stepsSource;
@ -36,14 +36,14 @@ void main() {
expect(fake.lastRead, isNull, reason: 'never reads before permission'); expect(fake.lastRead, isNull, reason: 'never reads before permission');
await openTile(tester, 'Activity'); await openTile(tester, 'Activity');
await tester.tap(byIconLabel('Connect Health Connect steps')); await tester.tap(find.text('Connect Health Connect steps'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(byIconLabel('Connect Health Connect steps'), findsOneWidget); expect(find.text('Connect Health Connect steps'), findsOneWidget);
fake.grantOnRequest = true; fake.grantOnRequest = true;
await tester.tap(byIconLabel('Connect Health Connect steps')); await tester.tap(find.text('Connect Health Connect steps'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(byIconLabel('Connect Health Connect steps'), findsNothing); expect(find.text('Connect Health Connect steps'), findsNothing);
expect( expect(
BodyService.instance.document.steps[localDateKey(yesterday)]!.n, BodyService.instance.document.steps[localDateKey(yesterday)]!.n,
6500, 6500,
@ -56,13 +56,13 @@ void main() {
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Activity'); await openTile(tester, 'Activity');
expect(fake.lastRead, isNotNull); expect(fake.lastRead, isNotNull);
expect(byIconLabel('Connect Health Connect steps'), findsNothing); expect(find.text('Connect Health Connect steps'), findsNothing);
}); });
testWidgets('a Health Connect error just hides nothing', (tester) async { testWidgets('a Health Connect error just hides nothing', (tester) async {
stepsSource = FakeStepsSource()..failWith = StateError('gone'); stepsSource = FakeStepsSource()..failWith = StateError('gone');
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Activity'); await openTile(tester, 'Activity');
expect(byIconLabel('Connect Health Connect steps'), findsOneWidget); expect(find.text('Connect Health Connect steps'), findsOneWidget);
}); });
} }

View File

@ -11,7 +11,6 @@ import 'package:diet_guard_app/widgets/body/body_tile_grid.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import '../services/body_test_support.dart'; import '../services/body_test_support.dart';
export '../services/body_test_support.dart'; export '../services/body_test_support.dart';
@ -90,11 +89,11 @@ Future<void> seedPerson(MemoryDocStore store, {Object? goal}) async {
double topOf(WidgetTester tester, Finder finder) => double topOf(WidgetTester tester, Finder finder) =>
tester.getTopLeft(finder.first).dy; tester.getTopLeft(finder.first).dy;
/// The overview tile spoken as [title]. /// The overview tile titled [title].
Finder tile(String title) => Finder tile(String title) =>
find.descendant(of: find.byType(BodyTileGrid), matching: bySemLabel(title)); find.descendant(of: find.byType(BodyTileGrid), matching: find.text(title));
/// Opens the sheet behind the tile spoken as [title]. /// Opens the sheet behind the tile titled [title].
Future<void> openTile(WidgetTester tester, String title) async { Future<void> openTile(WidgetTester tester, String title) async {
await tester.tap(tile(title)); await tester.tap(tile(title));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@ -110,9 +109,9 @@ Future<void> closeSheet(WidgetTester tester) async {
Finder inSheet(Finder finder) => Finder inSheet(Finder finder) =>
find.descendant(of: find.byType(BottomSheet), matching: finder); find.descendant(of: find.byType(BottomSheet), matching: finder);
/// Spoken names of the overview tiles, in display order. /// Titles of the overview tiles, in display order.
List<String> tileTitles(WidgetTester tester) => tester List<String> tileTitles(WidgetTester tester) => tester
.widget<BodyTileGrid>(find.byType(BodyTileGrid)) .widget<BodyTileGrid>(find.byType(BodyTileGrid))
.tiles .tiles
.map((t) => t.semanticLabel) .map((t) => t.title)
.toList(); .toList();

View File

@ -1,11 +1,9 @@
import 'package:diet_guard_app/models/local_time.dart'; import 'package:diet_guard_app/models/local_time.dart';
import 'package:diet_guard_app/screens/body_screen.dart'; import 'package:diet_guard_app/screens/body_screen.dart';
import 'package:diet_guard_app/services/body_service.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/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import 'body_screen_support.dart'; import 'body_screen_support.dart';
void main() { void main() {
@ -22,30 +20,18 @@ void main() {
) async { ) async {
await pumpBody(tester); await pumpBody(tester);
expect(tileTitles(tester).first, 'Profile'); expect(tileTitles(tester).first, 'Profile');
// Unknown age: the profile tile carries no number and no cake. expect(find.textContaining('Age unknown'), findsOneWidget);
expect(
find.descendant(of: tile('Profile'), matching: find.byIcon(Icons.cake)),
findsNothing,
);
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
// Both inputs missing: one warning glyph each (profile, weight). expect(find.textContaining('Set your profile and enter'), findsOneWidget);
expect(cueOfKind(CueKind.warn), findsNWidgets(2));
expect(
cueLabelled(bodyMissingNote(BodyService.instance)),
findsNWidgets(2),
);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Activity'); await openTile(tester, 'Activity');
expect( expect(find.textContaining('No activity data yet'), findsOneWidget);
cueLabelled('No activity data yet -- published by the PC.'),
findsOneWidget,
);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Weight'); await openTile(tester, 'Weight');
expect(byIconLabel('Need two readings for a graph.'), findsOneWidget); expect(find.text('Need two readings for a graph.'), findsOneWidget);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Body fat'); await openTile(tester, 'Body fat');
expect(byIconLabel('Need two readings for a graph.'), findsOneWidget); expect(find.text('Need two readings for a graph.'), findsOneWidget);
}); });
testWidgets('a weight without a profile asks for the profile', ( testWidgets('a weight without a profile asks for the profile', (
@ -54,12 +40,7 @@ void main() {
await BodyService.instance.setWeight('2026-09-20', 80); await BodyService.instance.setWeight('2026-09-20', 80);
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
expect( expect(find.textContaining('Set your profile (birth'), findsOneWidget);
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 { testWidgets('a profile without a weight asks for the weight', (tester) async {
@ -70,10 +51,7 @@ void main() {
); );
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
expect( expect(find.text('Enter your weight to see the numbers.'), findsOneWidget);
cueLabelled('Enter your weight to see the numbers.'),
findsOneWidget,
);
}); });
testWidgets('a full profile: goal first, profile then body fat last', ( testWidgets('a full profile: goal first, profile then body fat last', (
@ -90,52 +68,44 @@ void main() {
); );
expect(titles.last, 'Body fat'); expect(titles.last, 'Body fat');
// Headline numbers on the tiles themselves. // Headline numbers on the tiles themselves.
expect( expect(find.text('2209 kcal'), findsOneWidget);
find.descendant(
of: tile('Daily calorie target'),
matching: find.text('2209'),
),
findsOneWidget,
);
expect(find.text('80.0 kg'), findsOneWidget); expect(find.text('80.0 kg'), findsOneWidget);
expect(find.text('24.7'), findsOneWidget); expect(find.text('24.7'), findsOneWidget);
expect( expect(find.textContaining('Age 30'), findsOneWidget);
find.descendant(of: tile('Profile'), matching: find.text('30')),
findsOneWidget,
);
// 80 kg, 180 cm, 30 y, male, lose 0.5 kg/week on Moderate: // 80 kg, 180 cm, 30 y, male, lose 0.5 kg/week on Moderate:
// 1780 x 1.55 - 550 = 2209. // 1780 x 1.55 - 550 = 2209.
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
expect(inSheet(find.text('2209')), findsOneWidget); expect(find.text('2209'), findsOneWidget);
expect(inSheet(find.text('2759')), findsOneWidget); expect(
expect(inSheet(find.text('Mifflin-St Jeor')), findsOneWidget); find.textContaining('Maintenance 2759 kcal (Mifflin-St Jeor'),
findsOneWidget,
);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'BMI'); await openTile(tester, 'BMI');
expect(inSheet(find.text('24.7')), findsOneWidget); expect(inSheet(find.text('24.7')), findsOneWidget);
expect(find.text('59.9-80.7 kg'), findsOneWidget); expect(find.text('59.9-80.7 kg'), findsOneWidget);
expect(byIconLabel('normal'), findsOneWidget);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Ideal weight'); await openTile(tester, 'Ideal weight');
expect(byIconLabel('Average of all'), findsOneWidget); expect(find.text('Average of all'), findsOneWidget);
expect(find.textContaining('Broca'), findsNothing); expect(find.textContaining('Broca'), findsNothing);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Resting metabolism (BMR)'); await openTile(tester, 'Resting metabolism (BMR)');
expect(inSheet(find.text('1780')), findsOneWidget); expect(inSheet(find.text('1780 kcal')), findsOneWidget);
expect(byIconLabel('n/a -- log a body-fat %'), findsNWidgets(2)); expect(find.text('n/a -- log a body-fat %'), findsNWidgets(2));
await closeSheet(tester); await closeSheet(tester);
// 5000 steps over baseline x 0.747 m x 0.5 x 80 kg = 149.4 kcal, and // 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. // all the data is from yesterday, so the window is that one day.
await openTile(tester, 'Activity'); await openTile(tester, 'Activity');
expect(find.text('9000 ${yesterdayKey()}'), findsOneWidget);
expect(inSheet(find.text('149')), findsOneWidget);
expect( expect(
byIconLabel('Mean daily exercise, last 1 full days:'), find.textContaining('Steps outside workouts: 9000 on ${yesterdayKey()}'),
findsOneWidget, 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('Evening run'), findsOneWidget);
expect(find.textContaining('StrongLifts A'), findsOneWidget); expect(find.textContaining('StrongLifts A'), findsOneWidget);
expect(byIconLabel('Connect Health Connect steps'), findsNothing); expect(find.text('Connect Health Connect steps'), findsNothing);
}); });
testWidgets('a body fat switches the target to Katch-McArdle', ( testWidgets('a body fat switches the target to Katch-McArdle', (
@ -144,25 +114,24 @@ void main() {
await seedPerson(store); await seedPerson(store);
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Body fat'); await openTile(tester, 'Body fat');
final field = fieldByLabel('Body fat (%)'); final field = find.widgetWithText(TextField, 'Body fat (%)');
await tester.enterText(field, '99'); await tester.enterText(field, '99');
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueLabelled('Body fat must be 3-70 %.'), findsOneWidget); expect(find.text('Body fat must be 3-70 %.'), findsOneWidget);
expect(cueOfKind(CueKind.error), findsOneWidget);
await tester.enterText(field, '18,5'); await tester.enterText(field, '18,5');
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(BodyService.instance.latestBodyFat?.$2, 18.5); expect(BodyService.instance.latestBodyFat?.$2, 18.5);
await closeSheet(tester); await closeSheet(tester);
expect(find.text('18.5 %'), findsOneWidget); expect(find.text('18.5 %'), findsOneWidget);
await openTile(tester, 'Daily calorie target'); await openTile(tester, 'Daily calorie target');
expect(inSheet(find.text('Katch-McArdle')), findsOneWidget); expect(find.textContaining('(Katch-McArdle resting'), findsOneWidget);
expect(inSheet(find.text('2206')), findsOneWidget); expect(find.text('2206'), findsOneWidget);
await closeSheet(tester); await closeSheet(tester);
await openTile(tester, 'Resting metabolism (BMR)'); await openTile(tester, 'Resting metabolism (BMR)');
expect(inSheet(find.text('1778')), findsOneWidget); expect(inSheet(find.text('1778 kcal')), findsOneWidget);
}); });
testWidgets('saving and deleting a weight updates the numbers', ( testWidgets('saving and deleting a weight updates the numbers', (
@ -171,14 +140,14 @@ void main() {
await seedPerson(store); await seedPerson(store);
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Weight'); await openTile(tester, 'Weight');
final field = fieldByLabel('Weight (kg)'); final field = find.widgetWithText(TextField, 'Weight (kg)');
await tester.enterText(field, '5'); await tester.enterText(field, '5');
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueLabelled('Weight must be 20-400 kg.'), findsOneWidget); expect(find.text('Weight must be 20-400 kg.'), findsOneWidget);
await tester.enterText(field, '90,5'); await tester.enterText(field, '90,5');
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final today = localDateKey(DateTime.now()); final today = localDateKey(DateTime.now());
expect(BodyService.instance.latestWeight, (today, 90.5)); expect(BodyService.instance.latestWeight, (today, 90.5));
@ -186,32 +155,27 @@ void main() {
expect(find.text('27.9'), findsOneWidget); // 90.5 / 1.8^2 on the BMI tile expect(find.text('27.9'), findsOneWidget); // 90.5 / 1.8^2 on the BMI tile
await openTile(tester, 'Weight'); await openTile(tester, 'Weight');
await tester.tap(byIconLabel('Delete this day').first); await tester.tap(find.byTooltip('Delete this day').first);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(BodyService.instance.latestWeight?.$1, yesterdayKey()); 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 { testWidgets('the profile form validates height and saves', (tester) async {
await pumpBody(tester); await pumpBody(tester);
await openTile(tester, 'Profile'); await openTile(tester, 'Profile');
final field = fieldByLabel('Height (cm)'); final field = find.widgetWithText(TextField, 'Height (cm)');
await tester.enterText(field, '9'); await tester.enterText(field, '9');
await tester.tap(byIconLabel('Save profile')); await tester.tap(find.text('Save profile'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueLabelled('Height must be 50-260 cm.'), findsOneWidget); expect(find.text('Height must be 50-260 cm.'), findsOneWidget);
await tester.enterText(field, '172.5'); await tester.enterText(field, '172.5');
await tester.tap(byIconLabel('Female')); await tester.tap(find.text('Female'));
await tester.tap(byIconLabel('Save profile')); await tester.tap(find.text('Save profile'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(BodyService.instance.heightCm, 172.5); expect(BodyService.instance.heightCm, 172.5);
expect(BodyService.instance.sex, 'f'); expect(BodyService.instance.sex, 'f');
expect(cueLabelled('Saved.'), findsOneWidget); expect(find.text('Saved.'), findsOneWidget);
}); });
test('kcalByDay of an empty log is empty', () { test('kcalByDay of an empty log is empty', () {

View File

@ -8,10 +8,23 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
String _label(DateTime d) => const _monthNames = [
'${d.month.toString().padLeft(2, '0')} · ${d.year}'; 'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
String _label(DateTime d) => '${_monthNames[d.month - 1]} ${d.year}';
void main() { void main() {
late Directory tempDir; late Directory tempDir;
@ -20,7 +33,9 @@ void main() {
tempDir = await Directory.systemTemp.createTemp('diet_guard_calendar_'); tempDir = await Directory.systemTemp.createTemp('diet_guard_calendar_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir)); await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
}); });
tearDown(() async { tearDown(() async {
@ -55,7 +70,7 @@ void main() {
'button', (tester) async { 'button', (tester) async {
await pumpScreen(tester); await pumpScreen(tester);
expect(find.widgetWithText(TextField, '2200'), findsOneWidget); expect(find.widgetWithText(TextField, '2200'), findsOneWidget);
expect(controlByLabel('Edit'), findsOneWidget); expect(find.widgetWithText(FilledButton, 'Edit'), findsOneWidget);
final field = tester.widget<TextField>(find.byType(TextField)); final field = tester.widget<TextField>(find.byType(TextField));
expect(field.enabled, isFalse); expect(field.enabled, isFalse);
}); });
@ -64,10 +79,10 @@ void main() {
tester, tester,
) async { ) async {
await pumpScreen(tester); await pumpScreen(tester);
await tester.tap(controlByLabel('Edit')); await tester.tap(find.widgetWithText(FilledButton, 'Edit'));
await tester.pump(); await tester.pump();
expect(controlByLabel('Save'), findsOneWidget); expect(find.widgetWithText(FilledButton, 'Save'), findsOneWidget);
final field = tester.widget<TextField>(find.byType(TextField)); final field = tester.widget<TextField>(find.byType(TextField));
expect(field.enabled, isTrue); expect(field.enabled, isTrue);
}); });
@ -76,27 +91,27 @@ void main() {
tester, tester,
) async { ) async {
await pumpScreen(tester); await pumpScreen(tester);
await tester.tap(controlByLabel('Edit')); await tester.tap(find.widgetWithText(FilledButton, 'Edit'));
await tester.pump(); await tester.pump();
await tester.enterText(find.byType(TextField), ''); await tester.enterText(find.byType(TextField), '');
await tester.tap(controlByLabel('Save')); await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await tester.pump(); await tester.pump();
expect(cueLabelled('Enter a whole number of kcal.'), findsOneWidget); expect(find.text('Enter a whole number of kcal.'), findsOneWidget);
expect(controlByLabel('Save'), findsOneWidget); expect(find.widgetWithText(FilledButton, 'Save'), findsOneWidget);
}); });
testWidgets('a zero value is rejected and editing stays open', ( testWidgets('a zero value is rejected and editing stays open', (
tester, tester,
) async { ) async {
await pumpScreen(tester); await pumpScreen(tester);
await tester.tap(controlByLabel('Edit')); await tester.tap(find.widgetWithText(FilledButton, 'Edit'));
await tester.pump(); await tester.pump();
await tester.enterText(find.byType(TextField), '0'); await tester.enterText(find.byType(TextField), '0');
await tester.tap(controlByLabel('Save')); await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await tester.pump(); await tester.pump();
expect(cueLabelled('Budget must be a positive number.'), findsOneWidget); expect(find.text('Budget must be a positive number.'), findsOneWidget);
}); });
testWidgets('saving a valid value persists it and reverts to read-only', ( testWidgets('saving a valid value persists it and reverts to read-only', (
@ -108,17 +123,14 @@ void main() {
// frame pumps, mirroring settings_screen_test.dart's device-flow tests. // frame pumps, mirroring settings_screen_test.dart's device-flow tests.
await tester.runAsync(() async { await tester.runAsync(() async {
await pumpScreen(tester); await pumpScreen(tester);
await tester.tap(controlByLabel('Edit')); await tester.tap(find.widgetWithText(FilledButton, 'Edit'));
await tester.pump(); await tester.pump();
await tester.enterText(find.byType(TextField), '1800'); await tester.enterText(find.byType(TextField), '1800');
await tester.tap(controlByLabel('Save')); await tester.tap(find.widgetWithText(FilledButton, 'Save'));
await pumpUntil( await pumpUntil(tester, () => find.text('Saved.').evaluate().isNotEmpty);
tester,
() => cueLabelled('Saved.').evaluate().isNotEmpty,
);
expect(cueLabelled('Saved.'), findsOneWidget); expect(find.text('Saved.'), findsOneWidget);
expect(controlByLabel('Edit'), findsOneWidget); expect(find.widgetWithText(FilledButton, 'Edit'), findsOneWidget);
expect(AppSettingsService.dailyKcalGoal, 1800); expect(AppSettingsService.dailyKcalGoal, 1800);
final field = tester.widget<TextField>(find.byType(TextField)); final field = tester.widget<TextField>(find.byType(TextField));
expect(field.enabled, isFalse); expect(field.enabled, isFalse);
@ -127,8 +139,8 @@ void main() {
testWidgets('shows streak and year-to-date summary text', (tester) async { testWidgets('shows streak and year-to-date summary text', (tester) async {
await pumpScreen(tester); await pumpScreen(tester);
expect(byIconLabel('Logging streak'), findsOneWidget); expect(find.textContaining('Logging streak:'), findsOneWidget);
expect(byIconLabel('Days logged this year'), findsOneWidget); expect(find.textContaining('This year:'), findsOneWidget);
}); });
testWidgets('month navigation steps the displayed month back and forward', ( testWidgets('month navigation steps the displayed month back and forward', (

View File

@ -9,7 +9,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
const _entry = FoodEntry( const _entry = FoodEntry(
id: 'test-uuid', id: 'test-uuid',
@ -24,6 +23,7 @@ const _entry = FoodEntry(
); );
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -119,7 +119,7 @@ void main() {
'999', '999',
); );
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();
@ -141,7 +141,7 @@ void main() {
await tester.tap(find.text('pizza obok pracy')); await tester.tap(find.text('pizza obok pracy'));
await settle(tester); await settle(tester);
expect(find.byType(EditEntryScreen), findsOneWidget); expect(find.text('Edit meal'), findsOneWidget);
expect(find.text('pizza obok pracy'), findsOneWidget); expect(find.text('pizza obok pracy'), findsOneWidget);
// Macros are pre-filled. // Macros are pre-filled.
expect(find.text('1200'), findsOneWidget); expect(find.text('1200'), findsOneWidget);
@ -180,16 +180,15 @@ void main() {
await tester.tap(find.text('pizza obok pracy').last); await tester.tap(find.text('pizza obok pracy').last);
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
final saved = final saved = (await LogStorageService.instance.readLog())['2026-06-22']!
(await LogStorageService.instance.readLog())['2026-06-22']!.first; .first;
expect( expect(
saved.kcal, saved.kcal,
1200, 1200,
reason: reason: 'the banked portion must save as itself, not rescaled by '
'the banked portion must save as itself, not rescaled by '
'its own reference weight.', 'its own reference weight.',
); );
expect(saved.grams, 400); expect(saved.grams, 400);

View File

@ -9,7 +9,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
const _entry = FoodEntry( const _entry = FoodEntry(
id: 'test-uuid', id: 'test-uuid',
@ -24,6 +23,7 @@ const _entry = FoodEntry(
); );
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -72,8 +72,8 @@ void main() {
MaterialApp(home: EditEntryScreen(entry: _entry)), MaterialApp(home: EditEntryScreen(entry: _entry)),
); );
await settle(tester); await settle(tester);
expect(find.byType(EditEntryScreen), findsOneWidget); expect(find.text('Edit meal'), findsOneWidget);
expect(byIconLabel('Save'), findsOneWidget); expect(find.text('Save'), findsOneWidget);
}); });
}); });
testWidgets('shows error when description is cleared', (tester) async { testWidgets('shows error when description is cleared', (tester) async {
@ -92,10 +92,10 @@ void main() {
matching: find.byType(TextField), matching: find.byType(TextField),
); );
await tester.enterText(descField, ''); await tester.enterText(descField, '');
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
expect(cueLabelled('Description cannot be empty.'), findsOneWidget); expect(find.text('Description cannot be empty.'), findsOneWidget);
}); });
}); });
testWidgets('Save persists updated kcal to the log', (tester) async { testWidgets('Save persists updated kcal to the log', (tester) async {
@ -110,10 +110,13 @@ void main() {
// Change kcal. // Change kcal.
await tester.enterText( await tester.enterText(
find.ancestor(of: find.text('1200'), matching: find.byType(TextField)), find.ancestor(
of: find.text('1200'),
matching: find.byType(TextField),
),
'999', '999',
); );
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();
@ -143,7 +146,7 @@ void main() {
MaterialApp(home: EditEntryScreen(entry: legacy)), MaterialApp(home: EditEntryScreen(entry: legacy)),
); );
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();

View File

@ -19,13 +19,10 @@ import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_record_tile.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart'; import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import '../body_screen_support.dart'; import '../body_screen_support.dart';
import 'fit_support.dart'; import 'fit_support.dart';
@ -77,7 +74,7 @@ void main() {
await _pump(tester, const LogMealScreen()); await _pump(tester, const LogMealScreen());
await tester.enterText(find.byType(TextField).first, 'Oats'); await tester.enterText(find.byType(TextField).first, 'Oats');
await tester.runAsync(() async { await tester.runAsync(() async {
await tester.tap(controlByLabel('Log meal')); await tester.tap(find.byTooltip('Log meal'));
await Future<void>.delayed(const Duration(milliseconds: 500)); await Future<void>.delayed(const Duration(milliseconds: 500));
}); });
await tester.pump(const Duration(milliseconds: 300)); await tester.pump(const Duration(milliseconds: 300));
@ -116,7 +113,7 @@ void main() {
// A tile is hit-testable, and long-press/tap opens its detail sheet. // A tile is hit-testable, and long-press/tap opens its detail sheet.
await tester.tap(first); await tester.tap(first);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(RecordTile), findsOneWidget); expect(find.textContaining('P 1 g'), findsOneWidget);
await tester.tapAt(const Offset(200, 50)); // scrim closes the sheet await tester.tapAt(const Offset(200, 50)); // scrim closes the sheet
await tester.pumpAndSettle(); await tester.pumpAndSettle();
// Swiping to the next page reveals foods not on the first page. // Swiping to the next page reveals foods not on the first page.

View File

@ -1,22 +1,21 @@
import 'package:diet_guard_app/models/food_bank_record.dart'; import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart'; import 'package:diet_guard_app/screens/food_bank_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_add_entry_dialog.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'fb_test_support.dart'; import 'fb_test_support.dart';
void main() { void main() {
useTempFoodBankStores(); useTempFoodBankStores();
testWidgets('shows empty-bank message when no entries exist', (tester) async { testWidgets('shows empty-bank message when no entries exist', (
tester,
) async {
await tester.runAsync(() async { await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: FoodBankScreen())); await tester.pumpWidget(const MaterialApp(home: FoodBankScreen()));
await settle(tester); await settle(tester);
expect(byIconLabel('Food bank is empty.'), findsOneWidget); expect(find.textContaining('Food bank is empty'), findsOneWidget);
}); });
}); });
@ -51,12 +50,18 @@ void main() {
await tester.tap(find.byType(FloatingActionButton)); await tester.tap(find.byType(FloatingActionButton));
await settle(tester); await settle(tester);
expect(find.byType(AddEntryDialog), findsOneWidget); expect(find.text('Add to food bank'), findsOneWidget);
await tester.enterText(fieldByLabel('Name'), 'Test food'); await tester.enterText(
await tester.enterText(fieldByLabel('kcal'), '200'); find.widgetWithText(TextField, 'Name'),
'Test food',
);
await tester.enterText(
find.widgetWithText(TextField, 'Kcal'),
'200',
);
await tester.tap(byIconLabel('Save to bank')); await tester.tap(find.text('Save to bank'));
await settle(tester); await settle(tester);
// After saving, the screen reloads and shows the new entry. // After saving, the screen reloads and shows the new entry.
@ -72,10 +77,10 @@ void main() {
await tester.tap(find.byType(FloatingActionButton)); await tester.tap(find.byType(FloatingActionButton));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Cancel')); await tester.tap(find.text('Cancel'));
await settle(tester); await settle(tester);
expect(byIconLabel('Food bank is empty.'), findsOneWidget); expect(find.textContaining('Food bank is empty'), findsOneWidget);
}); });
}); });
@ -88,11 +93,11 @@ void main() {
await settle(tester); await settle(tester);
// Tap save without entering a name. // Tap save without entering a name.
await tester.tap(byIconLabel('Save to bank')); await tester.tap(find.text('Save to bank'));
await settle(tester); await settle(tester);
// Dialog stays open; no entry saved. // Dialog stays open; no entry saved.
expect(find.byType(AddEntryDialog), findsOneWidget); expect(find.text('Add to food bank'), findsOneWidget);
}); });
}); });
@ -151,17 +156,17 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FbFilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
// Type in the only TextField in the sheet (the name search field). // Type in the only TextField in the sheet (the name search field).
await tester.enterText(find.byType(TextField).first, 'Oat'); await tester.enterText(find.byType(TextField).first, 'Oat');
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
// Sheet is closed; only the matching entry is visible. // Sheet is closed; only the matching entry is visible.
expect(find.byType(FbFilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
expect(find.text('Oat'), findsOneWidget); expect(find.text('Oat'), findsOneWidget);
expect(find.text('Egg'), findsNothing); expect(find.text('Egg'), findsNothing);
}); });
@ -189,10 +194,10 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Clear all')); await tester.tap(find.text('Clear all'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.text('Walnut'), findsOneWidget); expect(find.text('Walnut'), findsOneWidget);

View File

@ -2,11 +2,9 @@ import 'package:diet_guard_app/models/food_bank_record.dart';
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/food_bank_screen.dart'; import 'package:diet_guard_app/screens/food_bank_screen.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/widgets/food_bank/fb_filter_sheet.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'fb_test_support.dart'; import 'fb_test_support.dart';
void main() { void main() {
@ -70,16 +68,21 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FbFilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
// Usage count is the default sort chip; pick the name chip instead. // With no sliders rendered, 'Sort by' and its dropdown are immediately
await tester.tap(chipByLabel('Name')); // visible — open the sort-field dropdown (shows 'Usage count' by default).
await tester.tap(find.text('Usage count'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); // Tap 'Name' in the dropdown overlay.
await tester.tap(find.text('Name').last);
await settle(tester); await settle(tester);
expect(find.byType(FbFilterSheet), findsNothing); await tester.tap(find.text('Apply'));
await settle(tester);
expect(find.text('Filter & Sort'), findsNothing);
expect(find.text('ZeroItem'), findsOneWidget); expect(find.text('ZeroItem'), findsOneWidget);
}); });
}); });
@ -137,10 +140,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.byType(FbFilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
}); });
}); });
@ -166,13 +169,13 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FbFilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
// Default sort is count-descending; the direction icon is arrow_downward. // Default sort is count-descending; the direction icon is arrow_downward.
await tester.tap(find.byIcon(Icons.arrow_downward)); await tester.tap(find.byIcon(Icons.arrow_downward));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.text('ZeroItem2'), findsOneWidget); expect(find.text('ZeroItem2'), findsOneWidget);

View File

@ -1,7 +1,6 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart'; import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart'; import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
@ -18,7 +17,6 @@ import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
/// Stub launcher that records the URL instead of opening it, so the device /// Stub launcher that records the URL instead of opening it, so the device
/// dialog's "Open GitHub & copy code" can be exercised without a real /// dialog's "Open GitHub & copy code" can be exercised without a real
@ -41,6 +39,8 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
} }
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -48,7 +48,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
}); });
@ -88,9 +90,13 @@ void main() {
} }
} }
/// Types [clientId] into the client-id field. /// Types [clientId] into the client-id field.
Future<void> enterClientId(WidgetTester tester, String clientId) async { Future<void> enterClientId(WidgetTester tester, String clientId) async {
await tester.enterText(fieldByLabel('OAuth App client id'), clientId); await tester.enterText(
find.widgetWithText(TextField, 'OAuth App client id'),
clientId,
);
} }
testWidgets('device flow happy path saves the token and syncs', ( testWidgets('device flow happy path saves the token and syncs', (
@ -130,7 +136,7 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, 'cid'); await enterClientId(tester, 'cid');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await pumpUntil( await pumpUntil(
tester, tester,
() => find.text('WXYZ-1234').evaluate().isNotEmpty, () => find.text('WXYZ-1234').evaluate().isNotEmpty,
@ -141,15 +147,15 @@ void main() {
// post-connect sync runs against the mock. // post-connect sync runs against the mock.
await pumpUntil( await pumpUntil(
tester, tester,
() => cueLabelled('Connected and synced.').evaluate().isNotEmpty, () => find.textContaining('Connected and synced').evaluate().isNotEmpty,
); );
expect(cueLabelled('Connected and synced.'), findsOneWidget); expect(find.textContaining('Connected and synced'), findsOneWidget);
}); });
}); });
testWidgets('device flow connects but surfaces a post-connect sync failure', ( testWidgets(
tester, 'device flow connects but surfaces a post-connect sync failure',
) async { (tester) async {
final mock = MockClient((req) async { final mock = MockClient((req) async {
if (req.url.path.contains('device/code')) { if (req.url.path.contains('device/code')) {
return http.Response( return http.Response(
@ -176,13 +182,14 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, 'cid'); await enterClientId(tester, 'cid');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await pumpUntil( await pumpUntil(
tester, tester,
() => cueOfKind(CueKind.error).evaluate().isNotEmpty, () => find.textContaining('sync failed').evaluate().isNotEmpty,
); );
expect(cueOfKind(CueKind.error), findsOneWidget); expect(find.textContaining('sync failed'), findsOneWidget);
});
}); });
},
);
} }

View File

@ -1,6 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart'; import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart'; import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
@ -17,7 +16,6 @@ import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
/// Stub launcher that records the URL instead of opening it, so the device /// Stub launcher that records the URL instead of opening it, so the device
/// dialog's "Open GitHub & copy code" can be exercised without a real /// dialog's "Open GitHub & copy code" can be exercised without a real
@ -40,6 +38,7 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
} }
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -47,7 +46,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
}); });
@ -87,9 +88,13 @@ void main() {
} }
} }
/// Types [clientId] into the client-id field. /// Types [clientId] into the client-id field.
Future<void> enterClientId(WidgetTester tester, String clientId) async { Future<void> enterClientId(WidgetTester tester, String clientId) async {
await tester.enterText(fieldByLabel('OAuth App client id'), clientId); await tester.enterText(
find.widgetWithText(TextField, 'OAuth App client id'),
clientId,
);
} }
testWidgets('Connect GitHub without a client id opens setup guidance', ( testWidgets('Connect GitHub without a client id opens setup guidance', (
@ -100,11 +105,11 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, ''); await enterClientId(tester, '');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await settle(tester); await settle(tester);
expect(find.byType(AlertDialog), findsOneWidget); expect(find.text('One-time GitHub setup needed'), findsOneWidget);
expect(fieldByLabel('Client ID'), findsOneWidget); expect(find.widgetWithText(TextField, 'Client ID'), findsOneWidget);
}); });
}); });
testWidgets('cancelling the client id setup dialog aborts the connect', ( testWidgets('cancelling the client id setup dialog aborts the connect', (
@ -115,12 +120,12 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, ''); await enterClientId(tester, '');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Cancel')); await tester.tap(find.text('Cancel'));
await settle(tester); await settle(tester);
expect(find.byType(AlertDialog), findsNothing); expect(find.text('One-time GitHub setup needed'), findsNothing);
}); });
}); });
testWidgets( testWidgets(
@ -134,16 +139,28 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, ''); await enterClientId(tester, '');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await settle(tester); await settle(tester);
await tester.enterText(fieldByLabel('Client ID'), 'cid'); await tester.enterText(
await tester.tap(byIconLabel('Continue')); find.widgetWithText(TextField, 'Client ID'),
'cid',
);
await tester.tap(find.text('Continue'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget);
expect(fieldByLabel('OAuth App client id'), findsOneWidget);
expect( expect(
(tester.widget(fieldByLabel('OAuth App client id')) as TextField) find.textContaining('Could not start device flow'),
findsOneWidget,
);
expect(
find.widgetWithText(TextField, 'OAuth App client id'),
findsOneWidget,
);
expect(
(tester.widget(
find.widgetWithText(TextField, 'OAuth App client id'),
)
as TextField)
.controller! .controller!
.text, .text,
'cid', 'cid',
@ -160,10 +177,13 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, 'cid'); await enterClientId(tester, 'cid');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget); expect(
find.textContaining('Could not start device flow'),
findsOneWidget,
);
}); });
}); });
} }

View File

@ -18,7 +18,6 @@ import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
/// Stub launcher that records the URL instead of opening it, so the device /// Stub launcher that records the URL instead of opening it, so the device
/// dialog's "Open GitHub & copy code" can be exercised without a real /// dialog's "Open GitHub & copy code" can be exercised without a real
@ -41,6 +40,8 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
} }
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -48,7 +49,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
}); });
@ -88,9 +91,13 @@ void main() {
} }
} }
/// Types [clientId] into the client-id field. /// Types [clientId] into the client-id field.
Future<void> enterClientId(WidgetTester tester, String clientId) async { Future<void> enterClientId(WidgetTester tester, String clientId) async {
await tester.enterText(fieldByLabel('OAuth App client id'), clientId); await tester.enterText(
find.widgetWithText(TextField, 'OAuth App client id'),
clientId,
);
} }
testWidgets('device dialog: failed poll shows the error and Open launches', ( testWidgets('device dialog: failed poll shows the error and Open launches', (
@ -137,7 +144,7 @@ void main() {
await settle(tester); await settle(tester);
await enterClientId(tester, 'cid'); await enterClientId(tester, 'cid');
await tester.tap(byIconLabel('Connect GitHub')); await tester.tap(find.text('Connect GitHub'));
await pumpUntil( await pumpUntil(
tester, tester,
() => find.text('WXYZ-1234').evaluate().isNotEmpty, () => find.text('WXYZ-1234').evaluate().isNotEmpty,

View File

@ -1,6 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart'; import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/services/app_settings_service.dart'; import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart'; import 'package:diet_guard_app/services/budget_history_service.dart';
@ -18,7 +17,6 @@ import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
/// Stub launcher that records the URL instead of opening it, so the device /// Stub launcher that records the URL instead of opening it, so the device
/// dialog's "Open GitHub & copy code" can be exercised without a real /// dialog's "Open GitHub & copy code" can be exercised without a real
@ -41,6 +39,7 @@ class _FakeUrlLauncher extends UrlLauncherPlatform
} }
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -48,7 +47,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
}); });
@ -88,9 +89,13 @@ void main() {
} }
} }
/// Types [clientId] into the client-id field. /// Types [clientId] into the client-id field.
Future<void> enterClientId(WidgetTester tester, String clientId) async { Future<void> enterClientId(WidgetTester tester, String clientId) async {
await tester.enterText(fieldByLabel('OAuth App client id'), clientId); await tester.enterText(
find.widgetWithText(TextField, 'OAuth App client id'),
clientId,
);
} }
testWidgets('shows the kuhyx/syncs defaults on a fresh install', ( testWidgets('shows the kuhyx/syncs defaults on a fresh install', (
@ -110,27 +115,31 @@ void main() {
await settle(tester); await settle(tester);
await tester.enterText( await tester.enterText(
fieldByLabel('Personal access token (fallback)'), find.widgetWithText(TextField, 'Personal access token (fallback)'),
'my-pat', 'my-pat',
); );
await tester.tap(controlByLabel('Save')); await tester.tap(find.widgetWithText(ElevatedButton, 'Save'));
await settle(tester); await settle(tester);
expect(cueLabelled('Saved.'), findsOneWidget); expect(find.text('Saved.'), findsOneWidget);
}); });
}); });
testWidgets('Test connection reports success', (tester) async { testWidgets('Test connection reports success', (tester) async {
final mock = MockClient((_) async => http.Response('{}', 200)); final mock = MockClient(
(_) async => http.Response('{}', 200),
);
await tester.runAsync(() async { await tester.runAsync(() async {
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)), MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Test GitHub connection')); await tester.tap(
find.widgetWithText(OutlinedButton, 'Test GitHub connection'),
);
await settle(tester); await settle(tester);
expect(cueLabelled('GitHub connection OK.'), findsOneWidget); expect(find.text('GitHub connection OK.'), findsOneWidget);
}); });
}); });
testWidgets('Test connection reports failure', (tester) async { testWidgets('Test connection reports failure', (tester) async {
@ -141,13 +150,17 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Test GitHub connection')); await tester.tap(
find.widgetWithText(OutlinedButton, 'Test GitHub connection'),
);
await settle(tester); await settle(tester);
expect(cueLabelled('GitHub connection failed.'), findsOneWidget); expect(find.text('GitHub connection failed.'), findsOneWidget);
}); });
}); });
testWidgets('Sync now runs a sync tick and reports success', (tester) async { testWidgets('Sync now runs a sync tick and reports success', (
tester,
) async {
final mock = MockClient((req) async { final mock = MockClient((req) async {
if (req.method == 'PUT') return http.Response('{}', 200); if (req.method == 'PUT') return http.Response('{}', 200);
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient // A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
@ -165,10 +178,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(find.widgetWithText(ElevatedButton, 'Sync now'));
await settle(tester); await settle(tester);
expect(cueLabelled('Synced.'), findsOneWidget); expect(find.text('Synced.'), findsOneWidget);
}); });
}); });
testWidgets('Sync now clears a stored failure so the banner lifts', ( testWidgets('Sync now clears a stored failure so the banner lifts', (
@ -195,10 +208,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(find.widgetWithText(ElevatedButton, 'Sync now'));
await settle(tester); await settle(tester);
expect(cueLabelled('Synced.'), findsOneWidget); expect(find.text('Synced.'), findsOneWidget);
final status = await SyncHealth.read(); final status = await SyncHealth.read();
expect(status.failureKind, isNull); expect(status.failureKind, isNull);
expect(status.isStalled, isFalse); expect(status.isStalled, isFalse);
@ -212,10 +225,12 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Test GitHub connection')); await tester.tap(
find.widgetWithText(OutlinedButton, 'Test GitHub connection'),
);
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget); expect(find.textContaining('GitHub connection failed:'), findsOneWidget);
}); });
}); });
testWidgets('Sync now reports a GitHub error', (tester) async { testWidgets('Sync now reports a GitHub error', (tester) async {
@ -226,10 +241,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Sync now')); await tester.tap(find.widgetWithText(ElevatedButton, 'Sync now'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget); expect(find.textContaining('Sync failed:'), findsOneWidget);
}); });
}); });
} }

View File

@ -1,55 +0,0 @@
import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'history_test_support.dart';
const _entry = FoodEntry(
id: 'keep-me',
time: '2026-06-22T12:00:00+02:00',
desc: 'lentil soup',
grams: 100,
kcal: 300,
proteinG: 15,
carbsG: 40,
fatG: 5,
source: 'manual',
);
void main() {
useTempHistoryStores();
testWidgets('delete is immediate and the icon-only undo restores it', (
tester,
) async {
await tester.runAsync(() async {
await LogStorageService.instance.writeLog({
'2026-06-22': [_entry],
});
await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
await settle(tester);
expect(find.text('lentil soup'), findsOneWidget);
await tester.tap(byIconLabel('Delete entry'));
// No confirmation dialog: the row vanishes and a snackbar offers undo.
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(AlertDialog), findsNothing);
expect(find.text('lentil soup'), findsNothing);
expect(bySemLabel('Entry deleted'), findsOneWidget);
await tester.tap(byIconLabel('Undo'));
await Future<void>.delayed(const Duration(milliseconds: 200));
await tester.pump(const Duration(milliseconds: 400));
expect(find.text('lentil soup'), findsOneWidget);
final stored = await LogStorageService.instance.allEntriesNewestFirst();
expect(stored.single.id, 'keep-me');
expect(stored.single.deleted, isFalse);
});
});
}

View File

@ -37,8 +37,7 @@ void main() {
await settle(tester); await settle(tester);
// The raw key is shown as the day header when formatting fails. // The raw key is shown as the day header when formatting fails.
// Header falls back to the raw key; the entry row prints its time too. expect(find.text('NOT-A-DATE'), findsOneWidget);
expect(find.text('NOT-A-DATE'), findsNWidgets(2));
}); });
}, },
); );

View File

@ -1,11 +1,9 @@
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart'; import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'history_test_support.dart'; import 'history_test_support.dart';
void main() { void main() {
@ -36,10 +34,10 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Clear all')); await tester.tap(find.text('Clear all'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.text('toast'), findsOneWidget); expect(find.text('toast'), findsOneWidget);
@ -74,16 +72,21 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
// The sort section is ~8px below the fold even with zero macros — scroll
// it into view before tapping the direction button.
await tester.drag(find.byType(ListView).last, const Offset(0, -120));
await settle(tester);
// Default sort is date-descending; direction icon is arrow_downward. // Default sort is date-descending; direction icon is arrow_downward.
await tester.tap(find.byIcon(Icons.arrow_downward)); await tester.tap(find.byIcon(Icons.arrow_downward));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
expect(find.textContaining('porridge'), findsOneWidget); expect(find.textContaining('porridge'), findsOneWidget);
}); });
}); });
@ -116,14 +119,22 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
// Pick the kcal sort chip (date is selected by default). // Scroll just enough to make the sort section visible.
await tester.tap(chipByLabel('Kcal')); await tester.drag(find.byType(ListView).last, const Offset(0, -120));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); // Open the sort dropdown (shows 'Date' by default).
await tester.tap(find.text('Date'));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsNothing); // Select 'Kcal' from the dropdown overlay.
await tester.tap(find.text('Kcal').last);
await settle(tester);
await tester.tap(find.text('Apply'));
await settle(tester);
expect(find.text('Filter & Sort'), findsNothing);
expect(find.textContaining('chicken'), findsOneWidget); expect(find.textContaining('chicken'), findsOneWidget);
}); });
}); });
@ -164,15 +175,15 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
await tester.tap(chipByLabel('manual')); await tester.tap(find.widgetWithText(FilterChip, 'manual'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
expect(find.textContaining('manual meal'), findsOneWidget); expect(find.textContaining('manual meal'), findsOneWidget);
expect(find.textContaining('bank meal'), findsNothing); expect(find.textContaining('bank meal'), findsNothing);
}); });

View File

@ -1,11 +1,9 @@
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart'; import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'history_test_support.dart'; import 'history_test_support.dart';
void main() { void main() {
@ -43,7 +41,7 @@ void main() {
await settle(tester); await settle(tester);
// Day header shows 800 kcal total (300 + 500) vs the 2200 goal. // Day header shows 800 kcal total (300 + 500) vs the 2200 goal.
expect(find.textContaining('800 / 2200'), findsOneWidget); expect(find.textContaining('800 / 2200 kcal'), findsOneWidget);
// Both entries appear as list tiles. // Both entries appear as list tiles.
expect(find.text('breakfast'), findsOneWidget); expect(find.text('breakfast'), findsOneWidget);
expect(find.text('lunch'), findsOneWidget); expect(find.text('lunch'), findsOneWidget);
@ -148,7 +146,7 @@ void main() {
await tester.tap(find.byIcon(Icons.filter_list)); await tester.tap(find.byIcon(Icons.filter_list));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsOneWidget); expect(find.text('Filter & Sort'), findsOneWidget);
}); });
}); });
@ -193,11 +191,11 @@ void main() {
await tester.enterText(find.byType(TextField).first, 'oat'); await tester.enterText(find.byType(TextField).first, 'oat');
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
// Sheet is closed; only the matching entry is visible. // Sheet is closed; only the matching entry is visible.
expect(find.byType(FilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
expect(find.text('oat porridge'), findsOneWidget); expect(find.text('oat porridge'), findsOneWidget);
expect(find.text('chicken breast'), findsNothing); expect(find.text('chicken breast'), findsNothing);
}); });

View File

@ -1,11 +1,9 @@
import 'package:diet_guard_app/models/food_entry.dart'; import 'package:diet_guard_app/models/food_entry.dart';
import 'package:diet_guard_app/screens/history_screen.dart'; import 'package:diet_guard_app/screens/history_screen.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/widgets/history/history_filter_sheet.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'history_test_support.dart'; import 'history_test_support.dart';
void main() { void main() {
@ -38,16 +36,16 @@ void main() {
// Tap 'manual' to set a source filter, then 'All' to reset it. // Tap 'manual' to set a source filter, then 'All' to reset it.
// Tapping 'All' when source is not null covers lines 798-800. // Tapping 'All' when source is not null covers lines 798-800.
await tester.tap(chipByLabel('manual')); await tester.tap(find.widgetWithText(FilterChip, 'manual'));
await settle(tester); await settle(tester);
await tester.tap(chipByLabel('All')); await tester.tap(find.widgetWithText(FilterChip, 'All'));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
expect(find.textContaining('all source entry'), findsOneWidget); expect(find.textContaining('all source entry'), findsOneWidget);
}); });
}); });
@ -99,7 +97,9 @@ void main() {
await settle(tester); await settle(tester);
// Protein slider. // Protein slider.
await tester.ensureVisible(find.byKey(const Key('protein-range-slider'))); await tester.ensureVisible(
find.byKey(const Key('protein-range-slider')),
);
await settle(tester); await settle(tester);
await tester.dragFrom( await tester.dragFrom(
tester.getRect(find.byKey(const Key('protein-range-slider'))).center, tester.getRect(find.byKey(const Key('protein-range-slider'))).center,
@ -125,10 +125,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Apply')); await tester.tap(find.text('Apply'));
await settle(tester); await settle(tester);
expect(find.byType(FilterSheet), findsNothing); expect(find.text('Filter & Sort'), findsNothing);
}); });
}); });
@ -160,7 +160,7 @@ void main() {
await settle(tester); await settle(tester);
// Open date range picker. // Open date range picker.
await tester.tap(controlByLabel('Date range')); await tester.tap(find.widgetWithText(OutlinedButton, 'Any date'));
await settle(tester); await settle(tester);
// The picker opens on the current month (no `currentDate` override // The picker opens on the current month (no `currentDate` override
@ -171,9 +171,9 @@ void main() {
// runs. // runs.
final now = DateTime.now(); final now = DateTime.now();
final expectedStart = DateTime(now.year, now.month); final expectedStart = DateTime(now.year, now.month);
await tester.tap(find.text('1').last); await tester.tap(find.text('1'));
await settle(tester); await settle(tester);
await tester.tap(find.text('2').last); await tester.tap(find.text('2'));
await settle(tester); await settle(tester);
await tester.tap(find.text('Save')); await tester.tap(find.text('Save'));
await settle(tester); await settle(tester);
@ -187,9 +187,9 @@ void main() {
); );
// "Clear date range" is now visible — tap it to exercise lines 639-642. // "Clear date range" is now visible — tap it to exercise lines 639-642.
await tester.tap(byIconLabel('Clear date range')); await tester.tap(find.text('Clear date range'));
await settle(tester); await settle(tester);
expect(byIconLabel('Clear date range'), findsNothing); expect(find.text('Any date'), findsOneWidget);
}); });
}, },
); );

View File

@ -6,7 +6,6 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../../label_finders.dart';
import 'history_test_support.dart'; import 'history_test_support.dart';
void main() { void main() {
@ -62,8 +61,8 @@ void main() {
// Same 2100 kcal on both days, judged against different budgets -- // Same 2100 kcal on both days, judged against different budgets --
// lowering the budget must not repaint the earlier day. // lowering the budget must not repaint the earlier day.
expect(find.text('2100 / 2200'), findsOneWidget); expect(find.text('2100 / 2200 kcal'), findsOneWidget);
expect(find.text('2100 / 2000'), findsOneWidget); expect(find.text('2100 / 2000 kcal'), findsOneWidget);
}); });
}); });
@ -72,7 +71,7 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: HistoryScreen())); await tester.pumpWidget(const MaterialApp(home: HistoryScreen()));
await settle(tester); await settle(tester);
expect(byIconLabel('Nothing logged yet.'), findsOneWidget); expect(find.text('Nothing logged yet.'), findsOneWidget);
}); });
}); });

View File

@ -22,7 +22,6 @@ import 'package:diet_guard_app/services/kuchnia_fill_flow.dart';
import 'package:diet_guard_app/services/kuchnia_import.dart'; import 'package:diet_guard_app/services/kuchnia_import.dart';
import 'package:diet_guard_app/services/kuchnia_queue.dart'; import 'package:diet_guard_app/services/kuchnia_queue.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/widgets/macro_input_row.dart'; import 'package:diet_guard_app/widgets/macro_input_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
@ -51,7 +50,6 @@ class _HostState extends State<_Host>
final MacroControllers macros = MacroControllers(); final MacroControllers macros = MacroControllers();
int publishes = 0; int publishes = 0;
String status = ''; String status = '';
CueKind statusKind = CueKind.info;
@override @override
int? selectedSlot; int? selectedSlot;
@ -76,11 +74,7 @@ class _HostState extends State<_Host>
} }
@override @override
void showFillStatus(String message, {CueKind kind = CueKind.info}) => void showFillStatus(String message) => setState(() => status = message);
setState(() {
status = message;
statusKind = kind;
});
/// Counted instead of run: the real one starts a network sync. /// Counted instead of run: the real one starts a network sync.
@override @override
@ -140,7 +134,6 @@ void main() {
}); });
expect(host.status, 'Logged 4 catering dishes.'); expect(host.status, 'Logged 4 catering dishes.');
expect(host.statusKind, CueKind.ok);
expect(await t.runAsync(() => loggedToday(storage)), hasLength(4)); expect(await t.runAsync(() => loggedToday(storage)), hasLength(4));
expect(host.publishes, 1, reason: 'one publish per batch, not per dish'); expect(host.publishes, 1, reason: 'one publish per batch, not per dish');
expect(KuchniaQueueService.remaining, 0); expect(KuchniaQueueService.remaining, 0);
@ -193,7 +186,6 @@ void main() {
await t.runAsync(host.onFillAll); await t.runAsync(host.onFillAll);
expect(host.status, startsWith('Fill all failed')); expect(host.status, startsWith('Fill all failed'));
expect(host.statusKind, CueKind.error);
expect(host.publishes, 1, reason: 'a partial batch must still sync'); expect(host.publishes, 1, reason: 'a partial batch must still sync');
expect(host.fillFlow.busy, isFalse); expect(host.fillFlow.busy, isFalse);
}); });

View File

@ -13,8 +13,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
void main() { void main() {
late Directory dir; late Directory dir;
final haptics = <String>[]; final haptics = <String>[];
@ -62,7 +60,7 @@ void main() {
await settle(tester); await settle(tester);
await tester.enterText(find.byType(TextField).at(0), 'toast'); await tester.enterText(find.byType(TextField).at(0), 'toast');
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log meal')); await tester.tap(find.byTooltip('Log meal'));
// One frame, no I/O wait: the haptic must not wait for the write. // One frame, no I/O wait: the haptic must not wait for the write.
await tester.pump(); await tester.pump();
expect(haptics, ['HapticFeedbackType.lightImpact']); expect(haptics, ['HapticFeedbackType.lightImpact']);
@ -82,24 +80,23 @@ void main() {
await settle(tester); await settle(tester);
await tester.enterText(find.byType(TextField).at(0), 'toast'); await tester.enterText(find.byType(TextField).at(0), 'toast');
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log meal')); await tester.tap(find.byTooltip('Log meal'));
await settle(tester); await settle(tester);
expect(haptics, ['HapticFeedbackType.lightImpact']); expect(haptics, ['HapticFeedbackType.lightImpact']);
expect(cues, 0); expect(cues, 0);
}); });
}); });
testWidgets('a rejected log (empty description) gives only the error tick', ( testWidgets('a rejected log (empty description) does not buzz', (
tester, tester,
) async { ) async {
await tester.runAsync(() async { await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log meal')); await tester.tap(find.byTooltip('Log meal'));
await settle(tester); await settle(tester);
expect(cueLabelled('Type what you ate first.'), findsOneWidget); expect(find.text('Type what you ate first.'), findsOneWidget);
// Only the error cue's own heavy tick: no success buzz. expect(haptics, isEmpty);
expect(haptics, ['HapticFeedbackType.heavyImpact']);
expect(cues, 0); expect(cues, 0);
}); });
}); });

View File

@ -12,8 +12,6 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
/// Covers logging a meal against a future date/slot through [LogMealScreen]'s /// Covers logging a meal against a future date/slot through [LogMealScreen]'s
/// "When" row -- its own file, split out the same way /// "When" row -- its own file, split out the same way
/// `log_meal_screen_nav_test.dart` and `log_meal_screen_sync_test.dart` are. /// `log_meal_screen_nav_test.dart` and `log_meal_screen_sync_test.dart` are.
@ -38,7 +36,7 @@ void main() {
await tempDir.delete(recursive: true); await tempDir.delete(recursive: true);
}); });
final logMealButton = controlByLabel('Log meal'); final logMealButton = find.byTooltip('Log meal');
// See log_meal_screen_test.dart's `settle` for why: fire-and-forget I/O // See log_meal_screen_test.dart's `settle` for why: fire-and-forget I/O
// that pumpAndSettle() alone does not wait for. // that pumpAndSettle() alone does not wait for.
@ -60,7 +58,7 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log for later')); await tester.tap(find.text('Log for later'));
await settle(tester); await settle(tester);
// The date picker's initialDate is already tomorrow, so confirming // The date picker's initialDate is already tomorrow, so confirming
// immediately picks it without touching a specific calendar cell. // immediately picks it without touching a specific calendar cell.
@ -91,8 +89,8 @@ void main() {
expect(future.time.startsWith(tomorrowKey), isTrue); expect(future.time.startsWith(tomorrowKey), isTrue);
// Back to logging for today. // Back to logging for today.
expect(find.text(tomorrowKey), findsNothing); expect(find.text('Today'), findsOneWidget);
expect(controlByLabel('Log for later'), findsOneWidget); expect(find.text('Log for later'), findsOneWidget);
}); });
}, },
); );
@ -104,7 +102,7 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log for later')); await tester.tap(find.text('Log for later'));
await settle(tester); await settle(tester);
await tester.tap(find.text('OK')); await tester.tap(find.text('OK'));
await settle(tester); await settle(tester);
@ -116,7 +114,7 @@ void main() {
await tester.tap(logMealButton); await tester.tap(logMealButton);
await settle(tester); await settle(tester);
expect(cueLabelled('Pick a slot for that date first.'), findsOneWidget); expect(find.text('Pick a slot for that date first.'), findsOneWidget);
final log = await LogStorageService.instance.readLog(); final log = await LogStorageService.instance.readLog();
expect(log.values.expand((e) => e), isEmpty); expect(log.values.expand((e) => e), isEmpty);
}); });
@ -129,17 +127,17 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Log for later')); await tester.tap(find.text('Log for later'));
await settle(tester); await settle(tester);
await tester.tap(find.text('OK')); await tester.tap(find.text('OK'));
await settle(tester); await settle(tester);
expect(find.text(localDateKey(tomorrow())), findsOneWidget); expect(find.text('Today'), findsNothing);
await tester.tap(controlByLabel('Back to today')); await tester.tap(find.byTooltip('Back to today'));
await settle(tester); await settle(tester);
expect(find.text(localDateKey(tomorrow())), findsNothing); expect(find.text('Today'), findsOneWidget);
expect(controlByLabel('Log for later'), findsOneWidget); expect(find.text('Log for later'), findsOneWidget);
}); });
}); });
} }

View File

@ -15,8 +15,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
@ -67,7 +65,7 @@ void main() {
await tempDir.delete(recursive: true); await tempDir.delete(recursive: true);
}); });
final logMealButton = controlByLabel('Log meal'); final logMealButton = find.byTooltip('Log meal');
// The screen's button handlers and description-field listener trigger // The screen's button handlers and description-field listener trigger
// real `dart:io` file I/O as fire-and-forget Futures that Flutter's frame // real `dart:io` file I/O as fire-and-forget Futures that Flutter's frame
@ -109,7 +107,7 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Body')); await tester.tap(find.byTooltip('Body'));
await settle(tester); await settle(tester);
expect(find.byType(BodyScreen), findsOneWidget); expect(find.byType(BodyScreen), findsOneWidget);

View File

@ -10,8 +10,6 @@ import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:http/testing.dart'; import 'package:http/testing.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@ -170,7 +168,7 @@ void main() {
await tester.enterText(find.byType(TextField).at(0), 'push-on-log'); await tester.enterText(find.byType(TextField).at(0), 'push-on-log');
await tester.pump(); await tester.pump();
await tester.tap(controlByLabel('Log meal')); await tester.tap(find.byTooltip('Log meal'));
// Wait for the push itself rather than a fixed 200 ms: under the // Wait for the push itself rather than a fixed 200 ms: under the
// CPU-capped pre-commit gate the real async hop can take longer, and // CPU-capped pre-commit gate the real async hop can take longer, and
// a wall-clock guess made this flaky there (passes 5/5 standalone). // a wall-clock guess made this flaky there (passes 5/5 standalone).

View File

@ -13,8 +13,6 @@ import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/widgets/today_progress_card.dart'; import 'package:diet_guard_app/widgets/today_progress_card.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
@ -52,7 +50,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
await MealScheduleService.initForTesting(FileDocumentStore(tempDir)); await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
}); });
@ -65,7 +65,7 @@ void main() {
await tempDir.delete(recursive: true); await tempDir.delete(recursive: true);
}); });
final logMealButton = controlByLabel('Log meal'); final logMealButton = find.byTooltip('Log meal');
// The screen's button handlers and description-field listener trigger // The screen's button handlers and description-field listener trigger
// real `dart:io` file I/O as fire-and-forget Futures that Flutter's frame // real `dart:io` file I/O as fire-and-forget Futures that Flutter's frame
@ -107,7 +107,9 @@ void main() {
expect(entries.single.kcal, 150); expect(entries.single.kcal, 150);
}); });
}); });
testWidgets('the progress card summarises today after a log', (tester) async { testWidgets('the progress card summarises today after a log', (
tester,
) async {
await tester.runAsync(() async { await tester.runAsync(() async {
await tester.pumpWidget(const MaterialApp(home: LogMealScreen())); await tester.pumpWidget(const MaterialApp(home: LogMealScreen()));
await settle(tester); await settle(tester);
@ -125,7 +127,7 @@ void main() {
expect(find.byType(TodayProgressCard), findsOneWidget); expect(find.byType(TodayProgressCard), findsOneWidget);
// Default budget is 2200 with the settings singleton uninitialised. // Default budget is 2200 with the settings singleton uninitialised.
expect(find.text('150 / 2200'), findsOneWidget); expect(find.text('150 / 2200'), findsOneWidget);
expect(find.text('2050'), findsOneWidget); expect(find.text('2050 left'), findsOneWidget);
}); });
}); });
testWidgets('typing a new description dismisses the progress card', ( testWidgets('typing a new description dismisses the progress card', (
@ -161,7 +163,7 @@ void main() {
await tester.tap(logMealButton); await tester.tap(logMealButton);
await settle(tester); await settle(tester);
expect(cueLabelled('Type what you ate first.'), findsOneWidget); expect(find.text('Type what you ate first.'), findsOneWidget);
expect(await LogStorageService.instance.todayEntries(), isEmpty); expect(await LogStorageService.instance.todayEntries(), isEmpty);
}); });
}); });
@ -195,8 +197,10 @@ void main() {
}); });
}, },
); );
testWidgets('selecting a food-bank suggestion stamps source food bank, but ' testWidgets(
'editing a macro afterward reverts it to manual', (tester) async { 'selecting a food-bank suggestion stamps source food bank, but '
'editing a macro afterward reverts it to manual',
(tester) async {
await tester.runAsync(() async { await tester.runAsync(() async {
const seed = FoodEntry( const seed = FoodEntry(
id: 'seed-1', id: 'seed-1',
@ -217,7 +221,7 @@ void main() {
await settle(tester); await settle(tester);
// The empty-query suggestion list shows the only banked food. // The empty-query suggestion list shows the only banked food.
await tester.tap(find.text('seeded food')); await tester.tap(find.text('seeded food · 250 kcal'));
await settle(tester); await settle(tester);
await tester.ensureVisible(logMealButton); await tester.ensureVisible(logMealButton);
await tester.tap(logMealButton); await tester.tap(logMealButton);
@ -228,7 +232,7 @@ void main() {
expect(firstEntry.source, 'food bank'); expect(firstEntry.source, 'food bank');
expect(firstEntry.kcal, 250); expect(firstEntry.kcal, 250);
await tester.tap(find.text('seeded food')); await tester.tap(find.text('seeded food · 250 kcal'));
await settle(tester); await settle(tester);
await tester.enterText(find.byType(TextField).at(2), '999'); await tester.enterText(find.byType(TextField).at(2), '999');
await settle(tester); await settle(tester);
@ -241,5 +245,6 @@ void main() {
expect(secondEntry.source, 'manual'); expect(secondEntry.source, 'manual');
expect(secondEntry.kcal, 999); expect(secondEntry.kcal, 999);
}); });
}); },
);
} }

View File

@ -6,9 +6,6 @@
/// likely to be typed, and it syncs from there to the phone), while the /// likely to be typed, and it syncs from there to the phone), while the
/// **fetch button** is Android-only, because the panel sends no CORS headers /// **fetch button** is Android-only, because the panel sends no CORS headers
/// and a browser cannot call it at all. /// and a browser cannot call it at all.
///
/// The section paints no text: controls are found by the spoken label their
/// icon carries, outcomes by the [StatusCue] kind they show.
library; library;
import 'dart:async'; import 'dart:async';
@ -16,12 +13,9 @@ import 'dart:async';
import 'package:diet_guard_app/screens/settings_kuchnia.dart'; import 'package:diet_guard_app/screens/settings_kuchnia.dart';
import 'package:diet_guard_app/services/document_store.dart'; import 'package:diet_guard_app/services/document_store.dart';
import 'package:diet_guard_app/services/kuchnia_credential_service.dart'; import 'package:diet_guard_app/services/kuchnia_credential_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
/// In-memory store, so these tests need no plugin channel. /// In-memory store, so these tests need no plugin channel.
class _MemoryStore implements DocumentStore { class _MemoryStore implements DocumentStore {
final Map<String, String> documents = {}; final Map<String, String> documents = {};
@ -35,10 +29,8 @@ class _MemoryStore implements DocumentStore {
} }
} }
Widget _host({ Widget _host({required bool canFetch, Future<String> Function()? onFetch}) =>
required bool canFetch, MaterialApp(
Future<FetchOutcome> Function()? onFetch,
}) => MaterialApp(
home: Scaffold( home: Scaffold(
body: SingleChildScrollView( body: SingleChildScrollView(
child: KuchniaSettingsSection(canFetch: canFetch, onFetch: onFetch), child: KuchniaSettingsSection(canFetch: canFetch, onFetch: onFetch),
@ -46,41 +38,34 @@ Widget _host({
), ),
); );
const _fetchLabel = "Fetch today's delivery";
/// The fetch button: the [IconButton] holding the delivery icon (or, while a
/// fetch runs, the spinner that replaces it).
Finder _fetchButton() => find.ancestor(
of: find.byWidgetPredicate(
(w) =>
w is CircularProgressIndicator ||
(w is Icon && w.semanticLabel == _fetchLabel),
),
matching: find.byType(IconButton),
);
void main() { void main() {
setUp(() => KuchniaCredentialService.resetForTesting(store: _MemoryStore())); setUp(() => KuchniaCredentialService.resetForTesting(store: _MemoryStore()));
tearDown(KuchniaCredentialService.resetForTesting); tearDown(KuchniaCredentialService.resetForTesting);
testWidgets('shows both credential fields on every platform', (tester) async { testWidgets('shows both credential fields on every platform', (tester) async {
await tester.pumpWidget(_host(canFetch: false)); await tester.pumpWidget(_host(canFetch: false));
expect(fieldByLabel('Panel e-mail'), findsOneWidget); expect(find.text('Panel e-mail'), findsOneWidget);
expect(fieldByLabel('Panel password'), findsOneWidget); expect(find.text('Panel password'), findsOneWidget);
}); });
testWidgets('the fetch button works only where it can', (tester) async { testWidgets('offers the fetch button only where it can work', (tester) async {
await tester.pumpWidget(_host(canFetch: true)); await tester.pumpWidget(_host(canFetch: true));
expect(tester.widget<IconButton>(_fetchButton()).onPressed, isNotNull); expect(find.text("Fetch today's delivery"), findsOneWidget);
await tester.pumpWidget(_host(canFetch: false)); await tester.pumpWidget(_host(canFetch: false));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text("Fetch today's delivery"), findsNothing);
});
testWidgets('explains the missing button rather than hiding it silently', (
tester,
) async {
await tester.pumpWidget(_host(canFetch: false));
expect( expect(
tester.widget<IconButton>(_fetchButton()).onPressed, find.textContaining('Android only'),
isNull, findsOneWidget,
reason: reason: 'a browser user needs to know why there is no fetch button, and '
'a browser user sees the button greyed out instead of vanishing; ' 'that entering the login here still helps their phone',
'entering the login here still helps their phone',
); );
}); });
@ -88,12 +73,12 @@ void main() {
await tester.pumpWidget(_host(canFetch: true)); await tester.pumpWidget(_host(canFetch: true));
await tester.enterText(find.byType(TextField).first, 'me@example.com'); await tester.enterText(find.byType(TextField).first, 'me@example.com');
await tester.enterText(find.byType(TextField).last, 'hunter2'); await tester.enterText(find.byType(TextField).last, 'hunter2');
await tester.tap(controlByLabel('Save login')); await tester.tap(find.text('Save login'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(KuchniaCredentialService.username, 'me@example.com'); expect(KuchniaCredentialService.username, 'me@example.com');
expect(KuchniaCredentialService.password, 'hunter2'); expect(KuchniaCredentialService.password, 'hunter2');
expect(cueOfKind(CueKind.ok), findsOneWidget); expect(find.textContaining('Saved'), findsOneWidget);
}); });
testWidgets('the password is obscured until revealed', (tester) async { testWidgets('the password is obscured until revealed', (tester) async {
@ -102,37 +87,27 @@ void main() {
tester.widget<TextField>(find.byType(TextField).last); tester.widget<TextField>(find.byType(TextField).last);
expect(passwordField().obscureText, isTrue); expect(passwordField().obscureText, isTrue);
await tester.tap(controlByLabel('Show password')); await tester.tap(find.byTooltip('Show password'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(passwordField().obscureText, isFalse); expect(passwordField().obscureText, isFalse);
}); });
testWidgets('a fetch shows its result as a cue and a count', (tester) async { testWidgets('a fetch shows its result', (tester) async {
await tester.pumpWidget( await tester.pumpWidget(
_host( _host(canFetch: true, onFetch: () async => '3 dishes added'),
canFetch: true,
onFetch: () async =>
const FetchOutcome(CueKind.ok, '3 dishes added', count: 3),
),
); );
await tester.tap(controlByLabel(_fetchLabel)); await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueOfKind(CueKind.ok), findsOneWidget); expect(find.text('3 dishes added'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
}); });
testWidgets('a failed fetch shows an error cue, not a crash', (tester) async { testWidgets('a failed fetch shows the reason, not a crash', (tester) async {
await tester.pumpWidget( await tester.pumpWidget(
_host( _host(canFetch: true, onFetch: () async => 'catering login rejected'),
canFetch: true,
onFetch: () async =>
const FetchOutcome(CueKind.error, 'catering login rejected'),
),
); );
await tester.tap(controlByLabel(_fetchLabel)); await tester.tap(find.text("Fetch today's delivery"));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(cueLabelled('catering login rejected'), findsOneWidget); expect(find.text('catering login rejected'), findsOneWidget);
expect(cueOfKind(CueKind.error), findsOneWidget);
}); });
testWidgets('the fetch button is disabled while a fetch is in flight', ( testWidgets('the fetch button is disabled while a fetch is in flight', (
@ -140,15 +115,16 @@ void main() {
) async { ) async {
// Otherwise an impatient double-tap pays a second login plus three // Otherwise an impatient double-tap pays a second login plus three
// requests against a third party. // requests against a third party.
final gate = Completer<FetchOutcome>(); final gate = Completer<String>();
await tester.pumpWidget(_host(canFetch: true, onFetch: () => gate.future)); await tester.pumpWidget(_host(canFetch: true, onFetch: () => gate.future));
await tester.tap(controlByLabel(_fetchLabel)); await tester.tap(find.text("Fetch today's delivery"));
await tester.pump(); await tester.pump();
expect(find.byType(CircularProgressIndicator), findsOneWidget); expect(find.text('Fetching…'), findsOneWidget);
expect(tester.widget<IconButton>(_fetchButton()).onPressed, isNull); final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
expect(button.onPressed, isNull);
gate.complete(const FetchOutcome(CueKind.ok, 'done')); gate.complete('done');
await tester.pumpAndSettle(); await tester.pumpAndSettle();
}); });
} }

View File

@ -8,16 +8,15 @@ import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/firebase_backend.dart'; import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler/permission_handler.dart'; import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
void main() { void main() {
late Directory tempDir; late Directory tempDir;
setUp(() async { setUp(() async {
@ -25,7 +24,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
}); });
@ -67,10 +68,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Disable battery optimization')); await tester.tap(find.text('Disable battery optimization'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.ok), findsOneWidget); expect(find.textContaining('exemption granted'), findsOneWidget);
}); });
}); });
testWidgets('battery exemption button reports a denied status', ( testWidgets('battery exemption button reports a denied status', (
@ -86,10 +87,10 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Disable battery optimization')); await tester.tap(find.text('Disable battery optimization'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.warn), findsOneWidget); expect(find.textContaining('not granted'), findsOneWidget);
}); });
}); });
testWidgets('battery exemption defaults to the real permission_handler ' testWidgets('battery exemption defaults to the real permission_handler '
@ -98,10 +99,13 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Disable battery optimization')); await tester.tap(find.text('Disable battery optimization'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget); expect(
find.textContaining('Could not request exemption'),
findsOneWidget,
);
}); });
}); });
testWidgets('battery exemption button surfaces a request failure', ( testWidgets('battery exemption button surfaces a request failure', (
@ -118,10 +122,13 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(controlByLabel('Disable battery optimization')); await tester.tap(find.text('Disable battery optimization'));
await settle(tester); await settle(tester);
expect(cueOfKind(CueKind.error), findsOneWidget); expect(
find.textContaining('Could not request exemption'),
findsOneWidget,
);
}); });
}); });
} }

View File

@ -16,7 +16,6 @@ import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import '../fake_secure_storage.dart'; import '../fake_secure_storage.dart';
import '../label_finders.dart';
void main() { void main() {
late Directory tempDir; late Directory tempDir;
@ -26,7 +25,9 @@ void main() {
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir)); LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir)); FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir)); AppSettingsService.resetForTesting(store: FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir)); BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
await MealScheduleService.initForTesting(FileDocumentStore(tempDir)); await MealScheduleService.initForTesting(FileDocumentStore(tempDir));
SharedPreferences.setMockInitialValues({}); SharedPreferences.setMockInitialValues({});
installFakeSecureStorage(); installFakeSecureStorage();
@ -75,10 +76,13 @@ void main() {
// The default schedule still derives the hours that used to be // The default schedule still derives the hours that used to be
// hardcoded, so an existing install sees no change. // hardcoded, so an existing install sees no change.
expect(find.text('08:00 · 12:00 · 16:00 · 20:00'), findsOneWidget); expect(
expect(bySemLabel('First meal'), findsOneWidget); find.text('08:00 · 12:00 · 16:00 · 20:00'),
expect(bySemLabel('Last meal'), findsOneWidget); findsOneWidget,
expect(bySemLabel('Meals per day'), findsOneWidget); );
expect(find.text('First meal'), findsOneWidget);
expect(find.text('Last meal'), findsOneWidget);
expect(find.text('Meals per day'), findsOneWidget);
}); });
}); });
testWidgets('an exact 07:23 first meal saves the schedule', (tester) async { testWidgets('an exact 07:23 first meal saves the schedule', (tester) async {
@ -86,7 +90,7 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Type or pick an exact time').first); await tester.tap(find.byTooltip('Type or pick an exact time').first);
await settle(tester); await settle(tester);
await tester.tap(find.byIcon(Icons.keyboard_outlined)); await tester.tap(find.byIcon(Icons.keyboard_outlined));
await settle(tester); await settle(tester);
@ -125,7 +129,10 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.enterText(fieldByLabel('Daily kcal goal'), '2100'); await tester.enterText(
find.widgetWithText(TextField, 'Daily kcal goal'),
'2100',
);
// Immediately after typing, the debounce has not fired yet. // Immediately after typing, the debounce has not fired yet.
expect(AppSettingsService.dailyKcalGoal, isNot(2100)); expect(AppSettingsService.dailyKcalGoal, isNot(2100));
@ -140,7 +147,10 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.enterText(fieldByLabel('Daily kcal goal'), '0'); await tester.enterText(
find.widgetWithText(TextField, 'Daily kcal goal'),
'0',
);
await Future<void>.delayed(const Duration(milliseconds: 700)); await Future<void>.delayed(const Duration(milliseconds: 700));
await tester.pump(); await tester.pump();
@ -154,7 +164,10 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.enterText(fieldByLabel('Daily kcal goal'), '1950'); await tester.enterText(
find.widgetWithText(TextField, 'Daily kcal goal'),
'1950',
);
// Leave before the 600ms debounce fires. dispose()'s flush fires the // Leave before the 600ms debounce fires. dispose()'s flush fires the
// persist unawaited (the framework cannot await dispose()), so the // persist unawaited (the framework cannot await dispose()), so the
// in-memory value updates synchronously but the disk write is still a // in-memory value updates synchronously but the disk write is still a
@ -182,14 +195,16 @@ void main() {
); );
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Sync settings')); await tester.tap(find.text('Sync settings'));
await settle(tester); await settle(tester);
expect(find.text('Firebase sync'), findsOneWidget); expect(find.text('Firebase sync'), findsOneWidget);
}); });
}); });
testWidgets('Sync settings wires storedAccount, not loadAccount, as the ' testWidgets(
'default accountLoader', (tester) async { 'Sync settings wires storedAccount, not loadAccount, as the '
'default accountLoader',
(tester) async {
// Verifies the read-back fix documented on SettingsScreen.accountLoader: // Verifies the read-back fix documented on SettingsScreen.accountLoader:
// on a device with a stored account and a live session, the shared // on a device with a stored account and a live session, the shared
// screen must show it as connected using the injected default, with no // screen must show it as connected using the injected default, with no
@ -208,13 +223,14 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Sync settings')); await tester.tap(find.text('Sync settings'));
await settle(tester); await settle(tester);
expect(find.text('sync@example.com'), findsOneWidget); expect(find.text('sync@example.com'), findsOneWidget);
expect(find.text('Disconnect'), findsOneWidget); expect(find.text('Disconnect'), findsOneWidget);
}); });
}); },
);
testWidgets( testWidgets(
'tapping Advanced sync (GitHub) opens the local GitHubMirrorScreen', 'tapping Advanced sync (GitHub) opens the local GitHubMirrorScreen',
(tester) async { (tester) async {
@ -222,10 +238,11 @@ void main() {
await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));
await settle(tester); await settle(tester);
await tester.tap(byIconLabel('Advanced sync (GitHub)')); await tester.tap(find.text('Advanced sync (GitHub)'));
await settle(tester); await settle(tester);
expect(byIconLabel('Connect GitHub'), findsOneWidget); expect(find.text('Advanced sync (GitHub)'), findsWidgets);
expect(find.text('Connect GitHub'), findsOneWidget);
}); });
}, },
); );

View File

@ -163,7 +163,8 @@ class _FakeBackend implements NotificationBackend {
Future<bool?> requestPermission() async => null; Future<bool?> requestPermission() async => null;
@override @override
Future<void> show(int slot, String title) async => shown.add(slot); Future<void> show(int slot, String title, String body) async =>
shown.add(slot);
@override @override
Future<void> cancel(int slot) async => cancelled.add(slot); Future<void> cancel(int slot) async => cancelled.add(slot);

View File

@ -1,110 +0,0 @@
/// Text-free status cues: kind -> icon/tint, haptics, snackbar undo.
library;
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
void main() {
final haptics = <String>[];
setUp(() {
haptics.clear();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method == 'HapticFeedback.vibrate') {
haptics.add(call.arguments as String);
}
return null;
});
});
Widget host(Widget child, {bool reduceMotion = false}) => MaterialApp(
theme: buildAppTheme(),
home: MediaQuery(
data: MediaQueryData(disableAnimations: reduceMotion),
child: Scaffold(body: child),
),
);
testWidgets('error cue: red error icon, heavy haptic, shakes', (t) async {
await t.pumpWidget(
host(const StatusCue(kind: CueKind.error, semanticLabel: 'bad input')),
);
final icon = t.widget<Icon>(find.byIcon(Icons.error));
expect(icon.color, buildAppTheme().colorScheme.error);
expect(haptics, ['HapticFeedbackType.heavyImpact']);
await t.pump(const Duration(milliseconds: 100));
final shifted = t.getTopLeft(find.byIcon(Icons.error)).dx;
await t.pumpAndSettle();
expect(t.getTopLeft(find.byIcon(Icons.error)).dx, isNot(shifted));
expect(cueLabelled('bad input'), findsOneWidget);
});
testWidgets('reduced motion skips the shake but keeps the haptic', (t) async {
await t.pumpWidget(
host(
const StatusCue(kind: CueKind.error, semanticLabel: 'bad input'),
reduceMotion: true,
),
);
final start = t.getTopLeft(find.byIcon(Icons.error));
await t.pump(const Duration(milliseconds: 100));
expect(t.getTopLeft(find.byIcon(Icons.error)), start);
expect(haptics, ['HapticFeedbackType.heavyImpact']);
});
testWidgets('ok cue taps lightly, info and warn stay silent', (t) async {
await t.pumpWidget(
host(const StatusCue(kind: CueKind.ok, semanticLabel: 'done')),
);
expect(haptics, ['HapticFeedbackType.lightImpact']);
haptics.clear();
for (final kind in [CueKind.info, CueKind.warn]) {
await t.pumpWidget(host(StatusCue(kind: kind, semanticLabel: 'x')));
expect(find.byIcon(kind.icon), findsOneWidget);
}
expect(haptics, isEmpty);
});
testWidgets('CueState.next bumps the sequence and rebuilds the cue', (
t,
) async {
final first = CueState.next(null, CueKind.info, 'a');
final second = CueState.next(first, CueKind.info, 'a');
expect(second.seq, first.seq + 1);
await t.pumpWidget(host(second.widget));
expect(cueLabelled('a'), findsOneWidget);
});
testWidgets('snackbar shows only a glyph and undo fires once', (t) async {
var undone = 0;
await t.pumpWidget(
host(
Builder(
builder: (context) => IconButton(
icon: const Icon(Icons.add),
onPressed: () => showCueSnack(
context,
kind: CueKind.warn,
semanticLabel: 'gone',
onUndo: () => undone++,
),
),
),
),
);
await t.tap(find.byIcon(Icons.add));
await t.pump();
await t.pump(const Duration(milliseconds: 500));
expect(find.byIcon(Icons.warning_amber_rounded), findsOneWidget);
expect(find.byType(Text), findsNothing);
await t.tap(controlByLabel('Undo'));
await t.pump();
expect(undone, 1);
});
}

View File

@ -1,26 +0,0 @@
import 'package:diet_guard_app/ui/source_icon.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test(
'every stored source has its own glyph, unknown ones a neutral ring',
() {
expect(sourceIcon('manual'), Icons.edit);
expect(sourceIcon('food bank'), Icons.restaurant_menu);
expect(sourceIcon('catering'), Icons.local_shipping);
expect(sourceIcon('legacy'), Icons.circle_outlined);
},
);
testWidgets('the mark paints no text and speaks the stored source', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: SourceMark('catering'))),
);
expect(find.byType(Text), findsNothing);
final icon = tester.widget<Icon>(find.byType(Icon));
expect(icon.semanticLabel, 'catering');
});
}

View File

@ -4,11 +4,8 @@ import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/main.dart'; import 'package:diet_guard_app/main.dart';
import 'package:diet_guard_app/services/foodbank_service.dart'; import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/screens/log_meal_screen.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'label_finders.dart';
void main() { void main() {
late Directory tempDir; late Directory tempDir;
@ -34,7 +31,7 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
}); });
expect(find.byType(LogMealScreen), findsOneWidget); expect(find.text('Diet Guard'), findsOneWidget);
expect(fieldByLabel('What did you eat?'), findsOneWidget); expect(find.text('What did you eat?'), findsOneWidget);
}); });
} }

View File

@ -2,7 +2,6 @@ import 'package:diet_guard_app/models/period_average.dart';
import 'package:diet_guard_app/widgets/average_summary_row.dart'; import 'package:diet_guard_app/widgets/average_summary_row.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import '../label_finders.dart';
PeriodAverage period({double? avgKcal, AverageBand? band}) => PeriodAverage( PeriodAverage period({double? avgKcal, AverageBand? band}) => PeriodAverage(
start: '2026-01-05', start: '2026-01-05',
@ -26,10 +25,13 @@ void main() {
month: period(avgKcal: 1900, band: AverageBand.under), month: period(avgKcal: 1900, band: AverageBand.under),
), ),
); );
expect(find.text('2100'), findsOneWidget); expect(
expect(find.text('1900'), findsOneWidget); find.text(
expect(byIconLabel('slightly over'), findsOneWidget); 'Avg/day (to yesterday): week 2100 kcal (slightly over) · '
expect(byIconLabel('under'), findsOneWidget); 'month 1900 kcal (under)',
),
findsOneWidget,
);
}); });
testWidgets('rounds the average to whole kcal', (tester) async { testWidgets('rounds the average to whole kcal', (tester) async {
@ -40,15 +42,16 @@ void main() {
month: period(avgKcal: 1900, band: AverageBand.under), month: period(avgKcal: 1900, band: AverageBand.under),
), ),
); );
expect(find.text('2101'), findsOneWidget); expect(find.textContaining('week 2101 kcal'), findsOneWidget);
}); });
testWidgets('an empty period shows the no-data glyph, never 0', ( testWidgets('an empty period reads "no data", never 0 kcal', (tester) async {
await pump(
tester, tester,
) async { AverageSummaryRow(week: period(), month: period()),
await pump(tester, AverageSummaryRow(week: period(), month: period())); );
expect(find.text('0'), findsNothing); expect(find.textContaining('0 kcal'), findsNothing);
expect(byIconLabel('no data'), findsNWidgets(2)); expect(find.textContaining('week no data'), findsOneWidget);
}); });
testWidgets('the placeholder empty period renders safely', (tester) async { testWidgets('the placeholder empty period renders safely', (tester) async {
@ -59,6 +62,6 @@ void main() {
month: PeriodAverage.empty, month: PeriodAverage.empty,
), ),
); );
expect(byIconLabel('no data'), findsNWidgets(2)); expect(find.textContaining('no data'), findsOneWidget);
}); });
} }

Some files were not shown because too many files have changed in this diff Show More