diff --git a/app/lib/screens/settings_meal_schedule.dart b/app/lib/screens/settings_meal_schedule.dart new file mode 100644 index 0000000..54c7ffd --- /dev/null +++ b/app/lib/screens/settings_meal_schedule.dart @@ -0,0 +1,147 @@ +// The meal-schedule editor: first meal, last meal, how many meals, and a +// live preview of the checkpoint times they derive. +// +// Split out of `settings_screen.dart` for the repo's 250-line cap. A `part` +// mixin for the same reason as `_SettingsKcalGoal`: it drives the screen's +// private state and calls `setState`. + +part of 'settings_screen.dart'; + +mixin _SettingsMealSchedule on State { + MealSchedule _schedule = kDefaultSchedule; + + void _loadSchedule() { + _schedule = MealScheduleService.current; + } + + /// The meal counts selectable for the current window. + /// + /// Capped at the number of whole hours the window holds, so the count + /// dropdown can never offer a value that would round two meals onto the + /// same hour. Invalid states are made unrepresentable here rather than + /// validated after the fact -- `MealSchedule.normalized` still clamps, but + /// that is the defence against corrupt synced data, not the input contract. + List get _selectableCounts { + final span = _schedule.last - _schedule.first; + final maxCount = span + 1 < kMaxMealCount ? span + 1 : kMaxMealCount; + return [for (var n = kMinMealCount; n <= maxCount; n++) n]; + } + + Future _applySchedule(MealSchedule next) async { + final normalized = next.normalized(); + setState(() => _schedule = normalized); + if (!MealScheduleService.isInitialized) return; + await MealScheduleService.instance.recordChange(normalized); + // The reminder ids are slot hours, so a schedule change orphans the ones + // it no longer contains. Re-running the check cancels them immediately + // rather than leaving a stale nag until the next background tick. + await checkAndNotify(pullWhenDue: false); + } + + /// Dropdowns rather than a time picker: `showTimePicker` returns minutes, + /// and slots are whole hours on both devices by design. + Widget _hourDropdown({ + required String label, + required int value, + required List hours, + required ValueChanged onChanged, + }) => ConstrainedBox( + constraints: const BoxConstraints(maxWidth: AppWidth.field), + child: InputDecorator( + decoration: InputDecoration(labelText: label), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: value, + isDense: true, + isExpanded: true, + items: [ + for (final hour in hours) + DropdownMenuItem(value: hour, child: Text(slotLabel(hour))), + ], + onChanged: (hour) => hour == null ? null : onChanged(hour), + ), + ), + ), + ); + + List _mealScheduleSection(BuildContext context) { + final theme = Theme.of(context); + final counts = _selectableCounts; + return [ + Text('Meal times', style: theme.textTheme.titleMedium), + const SizedBox(height: 4), + Text( + 'Checkpoints are spread evenly between your first and last meal.', + style: theme.textTheme.bodySmall, + ), + const SizedBox(height: 12), + _hourDropdown( + label: 'First meal', + value: _schedule.first, + // Leaves at least one hour of window, so `last` always has a value + // strictly after `first` to offer. + hours: [for (var h = kFirstHour; h < kLastHour; h++) h], + onChanged: (hour) => unawaited( + _applySchedule( + MealSchedule( + first: hour, + last: _schedule.last, + count: _schedule.count, + ), + ), + ), + ), + const SizedBox(height: 12), + _hourDropdown( + label: 'Last meal', + value: _schedule.last, + hours: [for (var h = _schedule.first + 1; h <= kLastHour; h++) h], + onChanged: (hour) => unawaited( + _applySchedule( + MealSchedule( + first: _schedule.first, + last: hour, + count: _schedule.count, + ), + ), + ), + ), + const SizedBox(height: 12), + ConstrainedBox( + constraints: const BoxConstraints(maxWidth: AppWidth.field), + child: InputDecorator( + decoration: const InputDecoration(labelText: 'Meals per day'), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: counts.contains(_schedule.count) + ? _schedule.count + : counts.last, + isDense: true, + isExpanded: true, + items: [ + for (final count in counts) + DropdownMenuItem(value: count, child: Text('$count')), + ], + onChanged: (count) => count == null + ? null + : unawaited( + _applySchedule( + MealSchedule( + first: _schedule.first, + last: _schedule.last, + count: count, + ), + ), + ), + ), + ), + ), + ), + const SizedBox(height: 12), + Text( + _schedule.slots().map(slotLabel).join(' · '), + style: theme.textTheme.bodyMedium, + ), + ]; + } +} diff --git a/app/lib/screens/settings_screen.dart b/app/lib/screens/settings_screen.dart index eddab4c..b2058f6 100644 --- a/app/lib/screens/settings_screen.dart +++ b/app/lib/screens/settings_screen.dart @@ -11,11 +11,15 @@ library; import 'dart:async'; import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/models/meal_schedule.dart'; +import 'package:diet_guard_app/models/slot.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/due_slot_check.dart'; import 'package:diet_guard_app/services/firebase_backend.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/meal_schedule_service.dart'; import 'package:diet_guard_app/ui/theme.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -25,6 +29,7 @@ import 'package:permission_handler/permission_handler.dart'; import 'package:sync_settings_ui/sync_settings_ui.dart'; part 'settings_kcal_goal.dart'; +part 'settings_meal_schedule.dart'; /// Screen for app-specific settings and links to sync configuration. class SettingsScreen extends StatefulWidget { @@ -91,13 +96,14 @@ class SettingsScreen extends StatefulWidget { } class _SettingsScreenState extends State - with _SettingsKcalGoal { + with _SettingsKcalGoal, _SettingsMealSchedule { final _kcalGoalController = TextEditingController(); @override void initState() { super.initState(); _kcalGoalController.text = AppSettingsService.dailyKcalGoal.toString(); + _loadSchedule(); } @override @@ -177,6 +183,10 @@ class _SettingsScreenState extends State ), const SizedBox(height: 24), const Divider(), + const SizedBox(height: 8), + ..._mealScheduleSection(context), + const SizedBox(height: 24), + const Divider(), ListTile( contentPadding: EdgeInsets.zero, title: const Text('Sync settings'), diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 063f6ea..d921946 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -2,7 +2,7 @@ name: diet_guard_app description: "Companion phone app for diet_guard: log meals on the go." publish_to: 'none' -version: 1.0.34+1 +version: 1.0.35+1 environment: sdk: ^3.12.2 diff --git a/app/test/screens/settings_screen_test.dart b/app/test/screens/settings_screen_test.dart index 593184f..18ba9cc 100644 --- a/app/test/screens/settings_screen_test.dart +++ b/app/test/screens/settings_screen_test.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:crdt_sync/crdt_sync.dart'; +import 'package:diet_guard_app/models/meal_schedule.dart'; import 'package:diet_guard_app/screens/settings_screen.dart'; import 'package:diet_guard_app/services/document_store_io.dart'; import 'package:diet_guard_app/services/app_settings_service.dart'; @@ -8,6 +9,7 @@ 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/foodbank_service.dart'; import 'package:diet_guard_app/services/log_storage_service.dart'; +import 'package:diet_guard_app/services/meal_schedule_service.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:permission_handler/permission_handler.dart'; @@ -16,7 +18,6 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../fake_secure_storage.dart'; void main() { - late Directory tempDir; setUp(() async { @@ -27,6 +28,7 @@ void main() { BudgetHistoryService.resetForTesting( store: FileDocumentStore(tempDir), ); + await MealScheduleService.initForTesting(FileDocumentStore(tempDir)); SharedPreferences.setMockInitialValues({}); installFakeSecureStorage(); }); @@ -36,6 +38,7 @@ void main() { FoodBankService.resetForTesting(); AppSettingsService.resetForTesting(); BudgetHistoryService.resetForTesting(); + MealScheduleService.resetForTesting(); await tempDir.delete(recursive: true); }); @@ -64,6 +67,40 @@ void main() { expect(find.widgetWithText(TextField, '1800'), findsOneWidget); }); }); + testWidgets('shows the derived meal times for the stored schedule', ( + tester, + ) async { + await tester.runAsync(() async { + await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); + await settle(tester); + + // The default schedule still derives the hours that used to be + // hardcoded, so an existing install sees no change. + expect( + find.text('08:00 · 12:00 · 16:00 · 20:00'), + findsOneWidget, + ); + expect(find.text('First meal'), findsOneWidget); + expect(find.text('Last meal'), findsOneWidget); + expect(find.text('Meals per day'), findsOneWidget); + }); + }); + testWidgets('reflects a five-meal schedule as the user\'s example', ( + tester, + ) async { + await tester.runAsync(() async { + await MealScheduleService.instance.recordChange( + const MealSchedule(first: 8, last: 20, count: 5), + ); + await tester.pumpWidget(const MaterialApp(home: SettingsScreen())); + await settle(tester); + + expect( + find.text('08:00 · 11:00 · 14:00 · 17:00 · 20:00'), + findsOneWidget, + ); + }); + }); testWidgets('typing a kcal goal debounces the save', (tester) async { await tester.runAsync(() async { await tester.pumpWidget(const MaterialApp(home: SettingsScreen()));