From a7410266a80bfc927d86aad6e3ad7332413949d2 Mon Sep 17 00:00:00 2001 From: andratwiro Date: Sun, 26 Jul 2026 16:35:50 +0200 Subject: [PATCH 01/29] Ask for confirmation before leaving a running workout Gym mode could be left with a single, easily accidental gesture. The iOS back swipe and the Android back gesture pop the route directly, and the close button called pop() unconditionally. Leaving mid-workout drops the session, the elapsed timer and the progress through the pages (logs that were already saved are kept). A PopScope now blocks the pop while a workout is in progress, that is from the moment the start page is left until the summary page is reached, and asks for confirmation instead. The close button uses maybePop() so that it goes through the same guard. Dismissing the dialog without answering keeps the workout. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01GQwZcRK8yTmBjCAppoeqXW --- .../routines/providers/gym_state.dart | 6 + lib/features/routines/screens/gym_mode.dart | 36 +++++- .../gym_mode/leave_workout_dialog.dart | 52 +++++++++ .../routines/widgets/gym_mode/navigation.dart | 4 +- lib/l10n/app_en.arb | 12 ++ .../routines/screens/gym_mode_test.dart | 110 ++++++++++++++++++ 6 files changed, 214 insertions(+), 6 deletions(-) create mode 100644 lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index ffb5f9b27..889abfa87 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -326,6 +326,12 @@ class GymModeState { return null; } + /// Whether the user is currently inside a running workout + /// + /// True from the moment the start page is left until the summary page is + /// reached, i.e. exactly while there is progress that leaving would discard. + bool get isWorkoutInProgress => isInitialized && currentPage > 0 && currentPage < totalPages - 1; + double get ratioCompleted { if (totalPages == 0) { return 0.0; diff --git a/lib/features/routines/screens/gym_mode.dart b/lib/features/routines/screens/gym_mode.dart index 057c3fc72..664194ed4 100644 --- a/lib/features/routines/screens/gym_mode.dart +++ b/lib/features/routines/screens/gym_mode.dart @@ -19,7 +19,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/gym_mode.dart'; +import 'package:wger/features/routines/widgets/gym_mode/leave_workout_dialog.dart'; class GymModeArguments { final int routineId; @@ -34,15 +36,39 @@ class GymModeScreen extends ConsumerWidget { static const routeName = '/gym-mode'; + /// Leaves gym mode, but only if the user confirms it + Future _confirmAndLeave(BuildContext context) async { + if (await confirmLeaveWorkout(context) && context.mounted) { + Navigator.of(context).pop(); + } + } + @override Widget build(BuildContext context, WidgetRef ref) { final args = ModalRoute.of(context)!.settings.arguments as GymModeArguments; + final workoutInProgress = ref.watch( + gymStateProvider.select((state) => state.isWorkoutInProgress), + ); - return Scaffold( - // backgroundColor: Theme.of(context).cardColor, - // primary: false, - body: SafeArea( - child: WidescreenWrapper(child: GymMode(args)), + return PopScope( + // While a workout is running, leaving is always an explicit choice: the + // iOS back swipe and the Android back gesture are easy to trigger by + // accident (e.g. when reaching for a podcast app mid-set), and popping + // the route drops the session, the elapsed timer and the progress + // through the workout. + canPop: !workoutInProgress, + onPopInvokedWithResult: (didPop, _) { + if (didPop) { + return; + } + _confirmAndLeave(context); + }, + child: Scaffold( + // backgroundColor: Theme.of(context).cardColor, + // primary: false, + body: SafeArea( + child: WidescreenWrapper(child: GymMode(args)), + ), ), ); } diff --git a/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart b/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart new file mode 100644 index 000000000..cee00d685 --- /dev/null +++ b/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart @@ -0,0 +1,52 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +/// Asks the user to confirm leaving gym mode with a workout in progress. +/// +/// Returns whether the workout should be left. Dismissing the dialog without +/// choosing (tapping outside, back gesture) keeps the workout, so that a second +/// accidental gesture can't leave it either. +Future confirmLeaveWorkout(BuildContext context) async { + final confirmed = await showDialog( + context: context, + builder: (dialogContext) { + final i18n = AppLocalizations.of(dialogContext); + return AlertDialog( + title: Text(i18n.leaveWorkoutTitle), + content: Text(i18n.leaveWorkoutConfirmation), + actions: [ + TextButton( + key: const ValueKey('keep-training-button'), + child: Text(MaterialLocalizations.of(dialogContext).cancelButtonLabel), + onPressed: () => Navigator.of(dialogContext).pop(false), + ), + TextButton( + key: const ValueKey('leave-workout-button'), + child: Text(i18n.leaveWorkout), + onPressed: () => Navigator.of(dialogContext).pop(true), + ), + ], + ); + }, + ); + + return confirmed ?? false; +} diff --git a/lib/features/routines/widgets/gym_mode/navigation.dart b/lib/features/routines/widgets/gym_mode/navigation.dart index 9025edd86..5e979b51f 100644 --- a/lib/features/routines/widgets/gym_mode/navigation.dart +++ b/lib/features/routines/widgets/gym_mode/navigation.dart @@ -42,8 +42,10 @@ class NavigationHeader extends StatelessWidget { children: [ IconButton( icon: const Icon(Icons.close), + // maybePop instead of pop so that the PopScope guarding gym mode + // gets to ask for confirmation while a workout is in progress onPressed: () { - Navigator.of(context).pop(); + Navigator.of(context).maybePop(); }, ), Expanded( diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c8026edc9..dd645e951 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1290,6 +1290,18 @@ "@endWorkout": { "description": "Use the imperative, label on button to finish the current workout in gym mode" }, + "leaveWorkoutTitle": "Leave the workout?", + "@leaveWorkoutTitle": { + "description": "Title of the dialog asking to confirm leaving gym mode while a workout is in progress" + }, + "leaveWorkoutConfirmation": "The workout is still in progress. Sets you already saved are kept.", + "@leaveWorkoutConfirmation": { + "description": "Body of the dialog asking to confirm leaving gym mode while a workout is in progress" + }, + "leaveWorkout": "Leave", + "@leaveWorkout": { + "description": "Use the imperative, label on the button that confirms leaving gym mode while a workout is in progress" + }, "themeMode": "Theme mode", "darkMode": "Always dark mode", "lightMode": "Always light mode", diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index 4835b65af..c8eaf40c4 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -492,4 +492,114 @@ void main() { }, semanticsEnabled: false, ); + + /// Opens gym mode and advances past the start page, so that a workout counts + /// as in progress + Future enterRunningWorkout(WidgetTester tester) async { + await tester.pumpWidget(renderGymMode()); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + + expect(find.byType(StartPage), findsOneWidget); + + await tester.tap(find.byIcon(Icons.chevron_right)); + await tester.pumpAndSettle(); + + expect(find.byType(ExerciseOverview), findsOneWidget); + } + + testWidgets( + 'the close button leaves the start page without asking', + (WidgetTester tester) async { + // Nothing has happened yet on the start page, so there is nothing to + // protect and closing stays a single tap. + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await tester.pumpWidget(renderGymMode()); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + + expect(find.byType(StartPage), findsOneWidget); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + + expect(find.text('Leave the workout?'), findsNothing); + expect(find.byType(GymModeScreen), findsNothing); + }); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'the close button asks for confirmation during a workout', + (WidgetTester tester) async { + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await enterRunningWorkout(tester); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + expect(find.text('Leave the workout?'), findsOneWidget); + + // Cancelling keeps the user on the very page they were on + await tester.tap(find.byKey(const ValueKey('keep-training-button'))); + await tester.pumpAndSettle(); + expect(find.text('Leave the workout?'), findsNothing); + expect(find.byType(ExerciseOverview), findsOneWidget); + + // Confirming leaves gym mode + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('leave-workout-button'))); + await tester.pumpAndSettle(); + expect(find.byType(GymModeScreen), findsNothing); + }); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'the system back gesture asks for confirmation during a workout', + (WidgetTester tester) async { + // This is the accident the guard is really about: the iOS back swipe and + // the Android back gesture both arrive here as a pop request. + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await enterRunningWorkout(tester); + + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + + expect(find.text('Leave the workout?'), findsOneWidget); + expect(find.byType(ExerciseOverview), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('keep-training-button'))); + await tester.pumpAndSettle(); + expect(find.byType(ExerciseOverview), findsOneWidget); + }); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'dismissing the confirmation keeps the workout', + (WidgetTester tester) async { + // A dialog dismissed without an answer (tap outside) must not be read as + // a confirmation, otherwise a stray tap leaves the workout after all. + await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await enterRunningWorkout(tester); + + await tester.tap(find.byIcon(Icons.close)); + await tester.pumpAndSettle(); + expect(find.text('Leave the workout?'), findsOneWidget); + + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + + expect(find.text('Leave the workout?'), findsNothing); + expect(find.byType(ExerciseOverview), findsOneWidget); + }); + }, + semanticsEnabled: false, + ); } From 7a1f74956915ff6842aec9ae7faa7ffcdbd9e6c6 Mon Sep 17 00:00:00 2001 From: andratwiro Date: Sun, 26 Jul 2026 16:42:59 +0200 Subject: [PATCH 02/29] Continue a workout the OS interrupted The gym mode state only lived in memory. Riverpod keeps it for as long as the app runs, so leaving gym mode and coming back already continued the workout, but a backgrounded app that the OS kills (e.g. after switching to a music app between two sets) lost the session, the elapsed time and which sets had been done. The progress is now also written to the preferences and read back when gym mode is opened. Only what can't be recalculated is stored, the pages themselves still come from the routine, which is why the finished log pages are referenced by page index instead of by their UUID (those are generated anew on every calculation). The stored progress is only used for the same day and iteration, only while the workout is plausibly still running (the existing 5 hour window), and only if the routine still has the page it stopped on. A workout that is still in memory wins over the stored one, and finishing a workout clears it. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01GQwZcRK8yTmBjCAppoeqXW --- .../routines/models/workout_progress.dart | 72 ++++++++++ .../routines/providers/gym_state.dart | 1 + .../providers/gym_state_notifier.dart | 116 ++++++++++++++++ .../routines/widgets/gym_mode/gym_mode.dart | 6 +- .../routines/providers/gym_state_test.dart | 128 ++++++++++++++++++ .../routines/screens/gym_mode_test.dart | 23 ++++ 6 files changed, 345 insertions(+), 1 deletion(-) create mode 100644 lib/features/routines/models/workout_progress.dart diff --git a/lib/features/routines/models/workout_progress.dart b/lib/features/routines/models/workout_progress.dart new file mode 100644 index 000000000..63c1a5611 --- /dev/null +++ b/lib/features/routines/models/workout_progress.dart @@ -0,0 +1,72 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +/// The progress through a running workout, as stored in the preferences +/// +/// Only the parts that can't be recalculated are kept. The pages themselves are +/// derived from the routine again on the next start, which is also why the +/// finished log pages are referenced by their page index: the UUIDs are +/// generated anew every time the pages are calculated. +class WorkoutProgress { + final int dayId; + final int iteration; + final int currentPage; + final DateTime workoutStart; + final DateTime validUntil; + + /// Absolute page indices of the log pages already marked as done + final List donePageIndices; + + const WorkoutProgress({ + required this.dayId, + required this.iteration, + required this.currentPage, + required this.workoutStart, + required this.validUntil, + required this.donePageIndices, + }); + + factory WorkoutProgress.fromJson(Map json) => WorkoutProgress( + dayId: json['dayId'] as int, + iteration: json['iteration'] as int, + currentPage: json['currentPage'] as int, + workoutStart: DateTime.parse(json['workoutStart'] as String), + validUntil: DateTime.parse(json['validUntil'] as String), + donePageIndices: (json['donePageIndices'] as List).cast(), + ); + + Map toJson() => { + 'dayId': dayId, + 'iteration': iteration, + 'currentPage': currentPage, + 'workoutStart': workoutStart.toIso8601String(), + 'validUntil': validUntil.toIso8601String(), + 'donePageIndices': donePageIndices, + }; + + @override + String toString() => + 'WorkoutProgress(' + 'dayId: $dayId, ' + 'iteration: $iteration, ' + 'currentPage: $currentPage, ' + 'workoutStart: $workoutStart, ' + 'validUntil: $validUntil, ' + 'donePageIndices: $donePageIndices' + ')'; +} diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 889abfa87..cf64459c5 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -34,6 +34,7 @@ const PREFS_COUNTDOWN_DURATION = 'countdownDurationSecondsPrefs'; const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; +const PREFS_WORKOUT_PROGRESS = 'workoutProgressPrefs'; /// In seconds const DEFAULT_COUNTDOWN_DURATION = 180; diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 5dc514e00..8ff828052 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:convert'; + import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; @@ -25,6 +27,7 @@ import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; +import 'package:wger/features/routines/models/workout_progress.dart'; import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; @@ -131,6 +134,115 @@ class GymStateNotifier extends _$GymStateNotifier { ); } + /// Absolute page indices of the log pages already marked as done + List get _donePageIndices => state.pages + .expand((page) => page.slotPages) + .where((slotPage) => slotPage.logDone) + .map((slotPage) => slotPage.pageIndex) + .toList(); + + /// Stores the progress through the running workout + /// + /// Riverpod keeps the state alive for as long as the app is running, but the + /// OS can kill a backgrounded app at any point, e.g. while the user switches + /// to a music app between two sets. Without this, that loses the session, the + /// elapsed time and which sets were already done. + Future _saveProgress() async { + // Before initData there is no dayId to store the progress under + if (!state.isInitialized) { + return; + } + + final progress = WorkoutProgress( + dayId: state.dayId, + iteration: state.iteration, + currentPage: state.currentPage, + workoutStart: state.workoutStart, + validUntil: state.validUntil, + donePageIndices: _donePageIndices, + ); + + await PreferenceHelper.asyncPref.setString( + PREFS_WORKOUT_PROGRESS, + json.encode(progress.toJson()), + ); + _logger.finer('Saved $progress'); + } + + Future _clearProgress() async { + await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_PROGRESS); + _logger.finer('Cleared stored workout progress'); + } + + /// Continues a workout that was interrupted by the app being killed + /// + /// Returns the page to continue on, or null when there is nothing to restore. + /// Call this after [initData] and [calculatePages], the restored "done" flags + /// are matched against the pages as they were just calculated. + Future restoreProgress() async { + final stored = await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS); + if (stored == null) { + return null; + } + + // A workout that is still in memory (the app was not killed, the user only + // left gym mode and came back) is more current than what was stored. + if (state.currentPage != 0) { + return null; + } + + final WorkoutProgress progress; + try { + progress = WorkoutProgress.fromJson(json.decode(stored) as Map); + } on Exception catch (e) { + _logger.warning('Discarding unreadable stored workout progress: $e'); + await _clearProgress(); + return null; + } + + // Only ever continue the same workout, only while it is plausibly still + // running, and only if the routine still has the page it stopped on (it + // might have been edited in the meantime). + if (progress.dayId != state.dayId || + progress.iteration != state.iteration || + progress.validUntil.isBefore(clock.now()) || + progress.currentPage >= state.totalPages) { + _logger.fine('Stored workout progress does not apply any more, discarding it'); + await _clearProgress(); + return null; + } + + state = state.copyWith( + currentPage: progress.currentPage, + workoutStart: progress.workoutStart, + validUntil: progress.validUntil, + pages: _pagesWithLogsDone(progress.donePageIndices), + ); + + _logger.fine('Restored workout progress on page ${progress.currentPage}'); + + return progress.currentPage; + } + + /// Copy of the current pages with the log pages in [donePageIndices] done + List _pagesWithLogsDone(List donePageIndices) { + return state.pages.map((page) { + if (page.type != PageType.set) { + return page; + } + + return page.copyWith( + slotPages: page.slotPages.map((slotPage) { + if (slotPage.type != SlotPageType.log) { + return slotPage; + } + + return slotPage.copyWith(logDone: donePageIndices.contains(slotPage.pageIndex)); + }).toList(), + ); + }).toList(); + } + /// Calculates the page entries void calculatePages() { var pageIndex = 0; @@ -303,6 +415,7 @@ class GymStateNotifier extends _$GymStateNotifier { void setCurrentPage(int page) { state = state.copyWith(currentPage: page); + _saveProgress(); // Ensure that there is a log entry for the current slot entry final slotEntryPage = state.getSlotEntryPageByIndex(); @@ -386,6 +499,7 @@ class GymStateNotifier extends _$GymStateNotifier { }).toList(); state = state.copyWith(pages: updatedPages); + _saveProgress(); _logger.fine('Set logDone=$isDone for slot page UUID $uuid'); } @@ -472,6 +586,7 @@ class GymStateNotifier extends _$GymStateNotifier { void startWorkout() { _logger.fine('Setting workout start time'); state = state.copyWith(workoutStart: clock.now()); + _saveProgress(); } void clear() { @@ -484,5 +599,6 @@ class GymStateNotifier extends _$GymStateNotifier { validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), ); + _clearProgress(); } } diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 7888972bb..42f6e97da 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -103,7 +103,11 @@ class _GymModeState extends ConsumerState { await gymViewModel.loadPrefs(); gymViewModel.calculatePages(); - return initialPage; + // A workout the OS interrupted (app killed while in the background) + // continues where it stopped, the pages have to be calculated by now + final restoredPage = await gymViewModel.restoreProgress(); + + return restoredPage ?? initialPage; } List _getContent(GymModeState state) { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index ea27b573d..4251e9009 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +import 'dart:convert'; + import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -384,6 +386,132 @@ void main() { }); }); + group('GymStateNotifier workout progress', () { + /// Simulates the app being killed and gym mode being opened again: a new + /// container means a new (empty) notifier, while the stored preferences + /// survive, exactly as on a real restart. + Future restartedNotifier({int dayId = 1, int iteration = 1}) async { + final restartedContainer = ProviderContainer.test(); + final restarted = restartedContainer.read(gymStateProvider.notifier); + restarted.initData(getTestRoutine(), dayId, iteration); + restarted.calculatePages(); + + return restarted; + } + + /// Runs a workout up to [currentPage], with one log page marked as done + Future runWorkout({int currentPage = 2}) async { + notifier.initData(getTestRoutine(), 1, 1); + notifier.calculatePages(); + notifier.markSlotPageAsDone(notifier.state.pages[1].slotPages[1].uuid, isDone: true); + notifier.setCurrentPage(currentPage); + await pumpEventQueue(); + } + + test('Continues an interrupted workout where it stopped', () async { + await runWorkout(); + + final restarted = await restartedNotifier(); + final restoredPage = await restarted.restoreProgress(); + + expect(restoredPage, 2); + expect(restarted.state.currentPage, 2); + expect( + restarted.state.pages[1].slotPages[1].logDone, + isTrue, + reason: 'the set that was already logged is still marked as done', + ); + }); + + test('Keeps the elapsed time of an interrupted workout', () async { + await withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () async { + await runWorkout(); + }); + + // Two minutes later the app is started again + await withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 32)), () async { + final restarted = await restartedNotifier(); + await restarted.restoreProgress(); + + expect(restarted.state.workoutStart, DateTime(2026, 7, 26, 18, 30)); + }); + }); + + test('Does not continue the workout of another day', () async { + await runWorkout(); + + // Rewrite the stored progress to belong to a different day of the + // routine, the workout that is opened now is not the one that stopped + final stored = + json.decode((await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS))!) + as Map; + stored['dayId'] = 2; + await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, json.encode(stored)); + + final restarted = await restartedNotifier(); + + expect(await restarted.restoreProgress(), isNull); + expect(restarted.state.currentPage, 0); + }); + + test('Does not continue a workout that is too old', () async { + await withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () async { + await runWorkout(); + }); + + // The next morning the workout is long over + await withClock(Clock.fixed(DateTime(2026, 7, 27, 9, 0)), () async { + final restarted = await restartedNotifier(); + + expect(await restarted.restoreProgress(), isNull); + expect(restarted.state.currentPage, 0); + }); + }); + + test('Does not continue on a page the routine no longer has', () async { + await runWorkout(); + + // The routine was edited in the meantime and is now shorter than the + // page the workout stopped on + final restarted = await restartedNotifier(); + restarted.state = restarted.state.copyWith(pages: restarted.state.pages.sublist(0, 1)); + + expect(await restarted.restoreProgress(), isNull); + }); + + test('Keeps the workout in memory over the stored one', () async { + await runWorkout(); + + // Same notifier, i.e. the app kept running and the user only left gym + // mode and came back. Nothing to restore, the state is already there. + expect(await notifier.restoreProgress(), isNull); + expect(notifier.state.currentPage, 2); + }); + + test('Forgets the workout once it is finished', () async { + await runWorkout(); + + notifier.clear(); + await pumpEventQueue(); + + final restarted = await restartedNotifier(); + expect(await restarted.restoreProgress(), isNull); + }); + + test('Ignores stored progress that can not be read', () async { + await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, 'not json'); + + final restarted = await restartedNotifier(); + + expect(await restarted.restoreProgress(), isNull); + expect( + await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS), + isNull, + reason: 'the unreadable value is cleared instead of failing again later', + ); + }); + }); + group('GymModeState.copyWith', () { test('Keeps the log scope when it is not passed', () { final state = notifier.state.copyWith(logScopeWeeks: 8); diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index c8eaf40c4..006bf6dde 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -493,9 +493,30 @@ void main() { semanticsEnabled: false, ); + /// Puts the preferences gym mode reads on open into a known state + /// + /// Installing a fresh in-memory store in setUp does not isolate the tests in + /// this file from one another, what one test writes is still visible in the + /// next. Both of these decide what is on screen after opening gym mode: a + /// workout left in the middle is continued where it stopped, and the exercise + /// pages setting decides which page follows the start page. + /// + /// This runs through [runAsync] because the notifier does not await its + /// writes, and a pending one uses real timers, which the fake clock of the + /// test binding never fires. + Future resetGymModePrefs(WidgetTester tester) async { + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 50)); + await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_PROGRESS); + await PreferenceHelper.asyncPref.setBool(PREFS_SHOW_EXERCISES, true); + }); + } + /// Opens gym mode and advances past the start page, so that a workout counts /// as in progress Future enterRunningWorkout(WidgetTester tester) async { + await resetGymModePrefs(tester); + await tester.pumpWidget(renderGymMode()); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); @@ -515,6 +536,8 @@ void main() { // Nothing has happened yet on the start page, so there is nothing to // protect and closing stays a single tap. await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { + await resetGymModePrefs(tester); + await tester.pumpWidget(renderGymMode()); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); From 72a983bd81ff8c1ed8d121448bc25e4219605fda Mon Sep 17 00:00:00 2001 From: Brian Hotopp Date: Tue, 28 Jul 2026 17:02:33 -0400 Subject: [PATCH 03/29] Show the upcoming set on the gym mode timer pages The timer pages only showed the countdown, wasting the whole rest period: to prepare for the next set (e.g. walk over and preload the plates) the user had to swipe forward to see what comes next, which also restarted the timer. The timers now show the upcoming set below the time: exercise name, set configuration (reps, weight, etc.) and set counter. This is always the next log page, which can be the next set of the same exercise (e.g. when progressing weights within an exercise) or the first set of the next exercise. After the last set of the day nothing is shown. --- .../routines/providers/gym_state.dart | 15 +++ .../routines/widgets/gym_mode/gym_mode.dart | 3 +- .../routines/widgets/gym_mode/timer.dart | 92 ++++++++++++++-- lib/l10n/app_en.arb | 4 + .../routines/providers/gym_state_test.dart | 28 +++++ .../routines/widgets/gym_mode/timer_test.dart | 104 ++++++++++++++++++ 6 files changed, 237 insertions(+), 9 deletions(-) create mode 100644 test/features/routines/widgets/gym_mode/timer_test.dart diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index ffb5f9b27..f43686b03 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -326,6 +326,21 @@ class GymModeState { return null; } + /// Returns the next log page after the slot page at [pageIndex], i.e. the + /// set that will be performed once the current rest timer ends. + /// + /// This deliberately returns the next *set*, which may belong to the same + /// exercise (e.g. when progressing weights within an exercise) or to the + /// next one. Returns null when the workout has no further sets. + SlotPageEntry? getNextLogPage(int pageIndex) { + for (final slotPage in pages.expand((p) => p.slotPages)) { + if (slotPage.pageIndex > pageIndex && slotPage.type == SlotPageType.log) { + return slotPage; + } + } + return null; + } + double get ratioCompleted { if (totalPages == 0) { return 0.0; diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index 7888972bb..dcc709068 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -132,8 +132,9 @@ class _GymModeState extends ConsumerState { ? TimerCountdownWidget( _controller, (rest ?? gymState.countdownDuration.inSeconds).toInt(), + slotPage.uuid, ) - : TimerWidget(_controller), + : TimerWidget(_controller, slotPage.uuid), ); } } diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index efe21e26f..e1b807606 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -21,6 +21,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -28,7 +29,12 @@ import 'package:wger/l10n/generated/app_localizations.dart'; class TimerWidget extends StatefulWidget { final PageController _controller; - const TimerWidget(this._controller); + /// Identifies which slot page this widget renders, so it shows its own + /// up-next information instead of whatever the globally-current page + /// happens to be. + final String slotUuid; + + const TimerWidget(this._controller, this.slotUuid); @override _TimerWidgetState createState() => _TimerWidgetState(); @@ -71,13 +77,18 @@ class _TimerWidgetState extends State { widget._controller, ), Expanded( - child: Center( - child: Text( - DateFormat('m:ss').format(displayTime), - style: Theme.of( - context, - ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), - ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + DateFormat('m:ss').format(displayTime), + style: Theme.of( + context, + ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), + ), + const SizedBox(height: 16), + UpNextWidget(widget.slotUuid), + ], ), ), NavigationFooter(widget._controller), @@ -90,9 +101,15 @@ class TimerCountdownWidget extends ConsumerStatefulWidget { final PageController _controller; final int _seconds; + /// Identifies which slot page this widget renders, so it shows its own + /// up-next information instead of whatever the globally-current page + /// happens to be. + final String slotUuid; + const TimerCountdownWidget( this._controller, this._seconds, + this.slotUuid, ); @override @@ -161,6 +178,7 @@ class _TimerCountdownWidgetState extends ConsumerState { ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), ), const SizedBox(height: 16), + UpNextWidget(widget.slotUuid), ], ), ), @@ -169,3 +187,61 @@ class _TimerCountdownWidgetState extends ConsumerState { ); } } + +/// Shows the set that will be performed once the rest timer on the slot page +/// identified by [slotUuid] ends. This can be the next set of the same +/// exercise (e.g. when progressing weights within an exercise) or the first +/// set of the next exercise. Renders nothing for the last rest of the day. +class UpNextWidget extends ConsumerWidget { + final String slotUuid; + + const UpNextWidget(this.slotUuid, {super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final theme = Theme.of(context); + final gymState = ref.watch(gymStateProvider); + + final currentSlotPage = gymState.getSlotPageByUUID(slotUuid); + final nextSlotPage = currentSlotPage == null + ? null + : gymState.getNextLogPage(currentSlotPage.pageIndex); + if (nextSlotPage == null) { + return const SizedBox.shrink(); + } + + final setConfigData = nextSlotPage.setConfigData!; + final exerciseName = setConfigData.exercise + .getTranslation(Localizations.localeOf(context).languageCode) + .name; + final nrOfLogPages = gymState + .getPageByIndex(nextSlotPage.pageIndex) + ?.slotPages + .where((e) => e.type == SlotPageType.log) + .length; + + return Column( + children: [ + Text( + AppLocalizations.of(context).upNext, + style: theme.textTheme.titleMedium, + ), + Text( + exerciseName, + textAlign: TextAlign.center, + style: theme.textTheme.headlineSmall, + ), + Text( + setConfigData.textReprWithType, + textAlign: TextAlign.center, + style: theme.textTheme.titleLarge?.copyWith(color: theme.colorScheme.primary), + ), + if (nrOfLogPages != null) + Text( + '${nextSlotPage.setIndex + 1} / $nrOfLogPages', + style: theme.textTheme.bodyLarge, + ), + ], + ); + } +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1aff62662..a3d76eaf9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -407,6 +407,10 @@ "@pause": { "description": "Noun, not an imperative! Label used for the pause when using the gym mode" }, + "upNext": "Up next", + "@upNext": { + "description": "Label shown on the rest timer pages in the gym mode above the information about the upcoming set" + }, "jumpTo": "Jump to", "@jumpTo": { "description": "Imperative. Label used in popup allowing the user to jump to a specific exercise while in the gym mode" diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index cb7894b3f..a0b95bf7d 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -625,4 +625,32 @@ void main() { expect(state.copyWith(clearLogScopeWeeks: true).logScopeWeeks, isNull); }); }); + + group('GymModeState.getNextLogPage', () { + // Page structure of the test routine (exercise + timer pages enabled): + // start(0) + // slot 1 (exercise 1): overview(1), log(2), timer(3), log(4), timer(5), log(6), timer(7) + // slot 2 (exercise 6): overview(8), log(9), timer(10), log(11), timer(12), log(13), timer(14) + // session(15), summary(16) + + test('Returns the next set of the same exercise for a rest between sets', () { + final next = notifier.state.getNextLogPage(3); + + expect(next!.type, SlotPageType.log); + expect(next.pageIndex, 4); + expect(next.setConfigData!.exerciseId, getTestExercises()[0].id); + }); + + test('Returns the first set of the next exercise after the final rest of an exercise', () { + final next = notifier.state.getNextLogPage(7); + + expect(next!.type, SlotPageType.log); + expect(next.pageIndex, 9); + expect(next.setConfigData!.exerciseId, getTestExercises()[5].id); + }); + + test('Returns null after the last set of the day', () { + expect(notifier.state.getNextLogPage(14), isNull); + }); + }); } diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart new file mode 100644 index 000000000..6e5cfef95 --- /dev/null +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -0,0 +1,104 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * wger Workout Manager is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/features/routines/providers/gym_state.dart'; +import 'package:wger/features/routines/providers/gym_state_notifier.dart'; +import 'package:wger/features/routines/widgets/gym_mode/timer.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; + +import '../../../../../test_data/routines.dart' as testdata; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('Timer up-next', () { + late ProviderContainer container; + + // Page structure of the test routine (exercise + timer pages enabled): + // start(0) + // slot 1 (bench press): overview(1), log(2), timer(3), log(4), timer(5), log(6), timer(7) + // slot 2 (side raises): overview(8), log(9), timer(10), log(11), timer(12), log(13), timer(14) + // session(15), summary(16) + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + container = ProviderContainer.test(); + final notifier = container.read(gymStateProvider.notifier); + final routine = testdata.getTestRoutine(); + notifier.initData(routine, routine.days.first.id!, 1); + }); + + Future pumpTimer(WidgetTester tester, int timerPageIndex) async { + final slotPage = container.read(gymStateProvider).getSlotEntryPageByIndex(timerPageIndex)!; + expect(slotPage.type, SlotPageType.timer); + + // No pumpAndSettle: the widgets keep a periodic UI timer alive, which + // would never settle. + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Builder( + builder: (context) { + final controller = PageController(); + return PageView( + controller: controller, + children: [TimerCountdownWidget(controller, 90, slotPage.uuid)], + ); + }, + ), + ), + ), + ), + ); + await tester.pump(); + } + + testWidgets('shows the next set of the same exercise for a rest between sets', (tester) async { + await pumpTimer(tester, 3); + + expect(find.text('Up next'), findsOneWidget); + expect(find.text('Bench press'), findsOneWidget); + expect(find.text('3x100kg'), findsOneWidget); + expect(find.text('2 / 3'), findsOneWidget); + }); + + testWidgets('shows the next exercise after the final rest of an exercise', (tester) async { + await pumpTimer(tester, 7); + + expect(find.text('Up next'), findsOneWidget); + expect(find.text('Side raises'), findsOneWidget); + expect(find.text('12x10kg'), findsOneWidget); + expect(find.text('1 / 3'), findsOneWidget); + }); + + testWidgets('shows nothing after the last set of the day', (tester) async { + await pumpTimer(tester, 14); + + expect(find.text('Up next'), findsNothing); + }); + }); +} From e226c53084c1b0058e189a36a9af27481cd5d222 Mon Sep 17 00:00:00 2001 From: Brian Hotopp Date: Tue, 28 Jul 2026 17:03:44 -0400 Subject: [PATCH 04/29] Allow correcting logged sets during the workout and persist rest timers Two related fixes for navigating back during gym mode: * Re-visiting an already logged page showed the set-config template again and saving inserted a second, duplicate log row. The saved log is now kept on the slot page and the form is seeded from it, so the previously entered values are shown and saving updates the existing row instead of duplicating it (e.g. adding a forgotten RiR). * The rest timers kept their start time in the widget, so leaving the page disposed it and restarted the countdown on return. The start time now lives in the gym state and both timers derive the elapsed or remaining time from it, so the countdown continues while the user e.g. goes back to correct a set. Revisiting an already expired countdown also no longer triggers the end-of-countdown alert again. --- .../routines/providers/gym_log_notifier.dart | 7 ++ .../routines/providers/gym_state.dart | 17 +++++ .../providers/gym_state_notifier.dart | 55 +++++++++++--- .../routines/widgets/gym_mode/log_page.dart | 16 +++- .../routines/widgets/gym_mode/timer.dart | 52 ++++++++++--- .../routines/providers/gym_state_test.dart | 76 +++++++++++++++++++ .../widgets/gym_mode/log_page_test.dart | 45 ++++++++++- .../routines/widgets/gym_mode/timer_test.dart | 27 +++++++ 8 files changed, 274 insertions(+), 21 deletions(-) diff --git a/lib/features/routines/providers/gym_log_notifier.dart b/lib/features/routines/providers/gym_log_notifier.dart index 5bbf5bd5f..92dc2f99f 100644 --- a/lib/features/routines/providers/gym_log_notifier.dart +++ b/lib/features/routines/providers/gym_log_notifier.dart @@ -51,6 +51,13 @@ class GymLogNotifier extends _$GymLogNotifier { state = out; } + /// Starts editing a log that was already persisted during the current + /// workout. Unlike [setLog], the id, session and date are kept so saving + /// updates the existing row instead of inserting a duplicate. + void editLog(Log log) { + state = log; + } + void setWeight(num weight) { state = state?.copyWith(weight: weight); } diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index f43686b03..f0d01e64b 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -21,6 +21,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/uuid.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; @@ -118,6 +119,16 @@ class SlotPageEntry { /// Whether the log page has been marked as done final bool logDone; + /// The log saved from this page during the current workout, if any. Kept + /// so revisiting the page pre-fills the form with the saved values and + /// saving updates the row instead of inserting a duplicate. + final Log? loggedEntry; + + /// When the timer of this page was started. Lives in the state (not the + /// timer widget) so the countdown continues when the user navigates away + /// and back. + final DateTime? timerStartedAt; + /// The associated SetConfigData final SetConfigData? setConfigData; @@ -127,6 +138,8 @@ class SlotPageEntry { required this.setIndex, this.setConfigData, this.logDone = false, + this.loggedEntry, + this.timerStartedAt, String? uuid, }) : assert( type != SlotPageType.log || setConfigData != null, @@ -142,6 +155,8 @@ class SlotPageEntry { int? pageIndex, SetConfigData? setConfigData, bool? logDone, + Log? loggedEntry, + DateTime? timerStartedAt, }) { return SlotPageEntry( uuid: uuid ?? this.uuid, @@ -150,6 +165,8 @@ class SlotPageEntry { pageIndex: pageIndex ?? this.pageIndex, setConfigData: setConfigData ?? this.setConfigData, logDone: logDone ?? this.logDone, + loggedEntry: loggedEntry ?? this.loggedEntry, + timerStartedAt: timerStartedAt ?? this.timerStartedAt, ); } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 83e4bd186..21e0e5445 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -314,6 +314,15 @@ class GymStateNotifier extends _$GymStateNotifier { return; } + // Re-visiting a page that was already logged in this workout: seed the + // form with the saved entry (keeping its id and session) so saving + // updates the row instead of inserting a duplicate. + final loggedEntry = slotEntryPage.loggedEntry; + if (loggedEntry != null) { + ref.read(gymLogProvider.notifier).editLog(loggedEntry); + return; + } + final log = Log.fromSetConfigData( slotEntryPage.setConfigData!, routineId: state.routine.id, @@ -365,15 +374,8 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } - void markSlotPageAsDone(String uuid, {required bool isDone}) { - final slotPage = state.getSlotPageByUUID(uuid); - if (slotPage == null) { - _logger.warning('No slot page found for UUID $uuid'); - return; - } - - final updatedSlotPage = slotPage.copyWith(logDone: isDone); - + /// Replaces the slot page with [uuid] by [updatedSlotPage] in the state. + void _updateSlotPage(String uuid, SlotPageEntry updatedSlotPage) { final updatedPages = state.pages.map((page) { if (page.type != PageType.set) { return page; @@ -390,6 +392,41 @@ class GymStateNotifier extends _$GymStateNotifier { }).toList(); state = state.copyWith(pages: updatedPages); + } + + /// Starts the timer of the slot page with [uuid], unless it is already + /// running. + /// + /// The start time lives in the gym state (not the timer widget) so the + /// countdown continues when the page is disposed and re-created while + /// navigating, e.g. when going back to correct a logged set during the + /// rest period. + void startTimerIfNeeded(String uuid) { + final slotPage = state.getSlotPageByUUID(uuid); + if (slotPage == null) { + _logger.warning('No slot page found for UUID $uuid'); + return; + } + if (slotPage.timerStartedAt != null) { + return; + } + + _updateSlotPage(uuid, slotPage.copyWith(timerStartedAt: clock.now())); + _logger.fine('Started timer for slot page UUID $uuid'); + } + + /// [log] is the entry saved from this page during the current workout. It + /// is kept on the slot page so revisiting the page pre-fills the form with + /// the saved values and saving updates the row instead of inserting a + /// duplicate. + void markSlotPageAsDone(String uuid, {required bool isDone, Log? log}) { + final slotPage = state.getSlotPageByUUID(uuid); + if (slotPage == null) { + _logger.warning('No slot page found for UUID $uuid'); + return; + } + + _updateSlotPage(uuid, slotPage.copyWith(logDone: isDone, loggedEntry: log)); _logger.fine('Set logDone=$isDone for slot page UUID $uuid'); } diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 6226bee1f..3ee625c30 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -393,12 +393,24 @@ class _LogFormWidgetState extends ConsumerState { // A failed write is intentionally left to propagate to the global // error handler; the success path below is then skipped. - await logProvider.addEntry(log); + // + // Re-saving a page that was already logged in this workout + // updates the existing row instead of inserting a duplicate. + // The id/session can be missing on the form log, e.g. after + // copying values from a past log, so restore them first. + final existingEntry = page.loggedEntry; + if (existingEntry == null) { + await logProvider.addEntry(log); + } else { + log.id = existingEntry.id; + log.sessionId = existingEntry.sessionId; + await logProvider.updateEntry(log); + } if (!context.mounted) { return; } - gymProvider.markSlotPageAsDone(page.uuid, isDone: true); + gymProvider.markSlotPageAsDone(page.uuid, isDone: true, log: log); showSnackbar( context, i18n.successfullySaved, diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index e1b807606..76f77750a 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -17,6 +17,8 @@ */ import 'dart:async'; +import 'package:clock/clock.dart'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -26,7 +28,7 @@ import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/navigation.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -class TimerWidget extends StatefulWidget { +class TimerWidget extends ConsumerStatefulWidget { final PageController _controller; /// Identifies which slot page this widget renders, so it shows its own @@ -40,15 +42,22 @@ class TimerWidget extends StatefulWidget { _TimerWidgetState createState() => _TimerWidgetState(); } -class _TimerWidgetState extends State { - late DateTime _startTime; +class _TimerWidgetState extends ConsumerState { final _maxSeconds = 600; late Timer _uiTimer; @override void initState() { super.initState(); - _startTime = DateTime.now(); + + // The start time lives in the gym state so the timer continues when the + // page is disposed and re-created while navigating. Deferred because a + // provider can't be modified during the widget life-cycle. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); + } + }); _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate @@ -66,7 +75,11 @@ class _TimerWidgetState extends State { @override Widget build(BuildContext context) { - final elapsed = DateTime.now().difference(_startTime).inSeconds; + final startTime = ref + .watch(gymStateProvider) + .getSlotPageByUUID(widget.slotUuid) + ?.timerStartedAt; + final elapsed = clock.now().difference(startTime ?? clock.now()).inSeconds; final displaySeconds = elapsed > _maxSeconds ? _maxSeconds : elapsed; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: displaySeconds)); @@ -117,15 +130,36 @@ class TimerCountdownWidget extends ConsumerStatefulWidget { } class _TimerCountdownWidgetState extends ConsumerState { - late DateTime _endTime; late Timer _uiTimer; bool _hasNotified = false; + /// The moment the countdown ends. The start time lives in the gym state so + /// the countdown continues when the page is disposed and re-created while + /// navigating; until the state is updated, fall back to starting now. + DateTime _endTime(GymModeState gymState) { + final startedAt = gymState.getSlotPageByUUID(widget.slotUuid)?.timerStartedAt; + return (startedAt ?? clock.now()).add(Duration(seconds: widget._seconds)); + } + @override void initState() { super.initState(); - _endTime = DateTime.now().add(Duration(seconds: widget._seconds)); + + // Deferred because a provider can't be modified during the widget + // life-cycle. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); + + // Don't notify when returning to a countdown that already expired while + // the user was on another page. + if (_endTime(ref.read(gymStateProvider)).isBefore(clock.now())) { + _hasNotified = true; + } + }); _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate @@ -143,10 +177,10 @@ class _TimerCountdownWidgetState extends ConsumerState { @override Widget build(BuildContext context) { - final remaining = _endTime.difference(DateTime.now()); + final gymState = ref.watch(gymStateProvider); + final remaining = _endTime(gymState).difference(clock.now()); final remainingSeconds = remaining.inSeconds <= 0 ? 0 : remaining.inSeconds; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds)); - final gymState = ref.watch(gymStateProvider); // When countdown finishes, notify ONCE, and respect settings if (remainingSeconds == 0 && !_hasNotified) { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index a0b95bf7d..5559ab652 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -30,9 +30,11 @@ import 'package:wger/features/account/providers/user_profile_repository.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; +import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; @@ -86,6 +88,80 @@ void main() { } } }); + + test('Stores the logged entry on the slot page', () { + // Arrange + final slotPage = notifier.state.pages[1].slotPages[1]; + expect(slotPage.type, SlotPageType.log); + final log = Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1'; + + // Act + notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + + // Assert + expect(notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry, same(log)); + }); + }); + + group('GymStateNotifier.setCurrentPage', () { + test('Seeds the gym log from the saved entry when re-visiting a logged page', () { + // Arrange + final slotPage = notifier.state.pages[1].slotPages[1]; + expect(slotPage.type, SlotPageType.log); + final log = Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1' + ..sessionId = 'session-1'; + notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + + // Act + notifier.setCurrentPage(slotPage.pageIndex); + + // Assert: the id and session are kept so saving updates the row + // instead of inserting a duplicate + final gymLog = container.read(gymLogProvider); + expect(gymLog, same(log)); + expect(gymLog!.id, 'log-1'); + expect(gymLog.sessionId, 'session-1'); + }); + + test('Seeds a fresh template for a page without a saved entry', () { + // Act + notifier.setCurrentPage(2); + + // Assert + expect(container.read(gymLogProvider)!.id, isNull); + }); + }); + + group('GymStateNotifier.startTimerIfNeeded', () { + test('Sets the start time only once', () { + // Arrange + final timerPage = notifier.state.pages[1].slotPages[2]; + expect(timerPage.type, SlotPageType.timer); + + // Act + withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { + notifier.startTimerIfNeeded(timerPage.uuid); + }); + + // Assert + expect( + notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + DateTime(2024, 5, 2, 12), + ); + + // Act: starting again does not restart the timer + withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 5)), () { + notifier.startTimerIfNeeded(timerPage.uuid); + }); + + // Assert + expect( + notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + DateTime(2024, 5, 2, 12), + ); + }); }); group('GymStateNotifier.recalculateIndices', () { diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index d941ab314..6169e5aa9 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -32,6 +32,7 @@ import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; +import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/workout_logs_repository.dart'; @@ -72,7 +73,11 @@ void main() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); testExercises = getTestExercises(); mockWorkoutLogRepo = MockWorkoutLogRepository(); - when(mockWorkoutLogRepo.addLocalDrift(any)).thenAnswer((_) async {}); + // Mimic the real insert: the freshly minted id is written back to the log + when(mockWorkoutLogRepo.addLocalDrift(any)).thenAnswer((invocation) async { + (invocation.positionalArguments[0] as Log).id = 'new-log-id'; + }); + when(mockWorkoutLogRepo.updateLocalDrift(any)).thenAnswer((_) async {}); // Past logs on the page come from this stream (per exercise); reuse the // test routine's logs so the previous-entries assertions keep working. when( @@ -244,6 +249,44 @@ void main() { expect(saved.iteration, gymState.iteration); }); + testWidgets('re-visiting a logged page restores the saved values and saving updates the row', ( + tester, + ) async { + seedLogPage(testdata.getTestRoutine()); + await pumpLogPage(tester); + + // Enter and save non-default values + final fields = find.byType(TextFormField); + await tester.enterText(fields.at(0), '12'); // reps + await tester.enterText(fields.at(1), '34'); // weight + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + verify(mockWorkoutLogRepo.addLocalDrift(captureAny)).called(1); + + // Navigate away (page 3 is the timer) and back (page 2 is the log page) + final gymNotifier = container.read(gymStateProvider.notifier); + gymNotifier.setCurrentPage(3); + gymNotifier.setCurrentPage(2); + await tester.pumpAndSettle(); + + // The form is seeded from the saved entry, keeping its id + expect(container.read(gymLogProvider)!.id, 'new-log-id'); + final repField = tester.widget(find.byType(EditableText).at(0)); + expect(repField.controller.text, '12'); + + // Saving again updates the existing row instead of inserting a duplicate + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + + final updated = + verify(mockWorkoutLogRepo.updateLocalDrift(captureAny)).captured.single as Log; + expect(updated.id, 'new-log-id'); + expect(updated.repetitions, 12); + expect(updated.weight, 34); + verifyNever(mockWorkoutLogRepo.addLocalDrift(any)); + }); + testWidgets('reps quick buttons increment and decrement the value', (tester) async { final routine = testdata.getTestRoutine(); routine.dayDataGym[0].slots[0].setConfigs[0].repetitions = 0; diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 6e5cfef95..863a74975 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -100,5 +101,31 @@ void main() { expect(find.text('Up next'), findsNothing); }); + + testWidgets('countdown continues when the page is disposed and re-created', (tester) async { + final t0 = DateTime(2024, 5, 2, 12); + + await withClock(Clock.fixed(t0), () async { + await pumpTimer(tester, 3); + expect(find.text('1:30'), findsOneWidget); + }); + + // 30s later the countdown kept running (re-pumping forces a rebuild, + // in the app the periodic UI timer does this every second) + await withClock(Clock.fixed(t0.add(const Duration(seconds: 30))), () async { + await pumpTimer(tester, 3); + expect(find.text('1:00'), findsOneWidget); + }); + + // Leaving the page disposes the widget ... + await withClock(Clock.fixed(t0.add(const Duration(seconds: 45))), () async { + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + + // ... and coming back must not restart the countdown + await pumpTimer(tester, 3); + expect(find.text('0:45'), findsOneWidget); + }); + }); }); } From 01e22be8052974aad58a302a7983cc20e00be74d Mon Sep 17 00:00:00 2001 From: Brian Hotopp Date: Tue, 28 Jul 2026 17:41:24 -0400 Subject: [PATCH 05/29] Add optional sticky set values to the gym mode When dialing in the weight over the first sets of an exercise, the log form of every following set is pre-filled with the planned values again, so any adjustment has to be re-entered for every set. When the new "sticky set values" setting is enabled, the values (weight, repetitions, RiR, units) logged for a set are remembered and the next set of the same exercise is pre-filled with them instead of the planned ones. This intentionally only copies the values: the id, session, slot entry and targets stay those of a fresh template, so saving still creates a new log row for the correct slot. The setting is disabled by default and can be toggled in the gym mode options; it is persisted like the other gym mode settings. The remembered values are cleared when the workout ends. --- .../routines/providers/gym_state.dart | 17 ++++ .../providers/gym_state_notifier.dart | 40 +++++++++ .../routines/widgets/gym_mode/log_page.dart | 1 + .../routines/widgets/gym_mode/start_page.dart | 7 ++ lib/l10n/app_en.arb | 8 ++ .../routines/providers/gym_state_test.dart | 87 +++++++++++++++++++ .../widgets/gym_mode/log_page_test.dart | 29 +++++++ .../widgets/gym_mode/start_page_test.dart | 8 ++ 8 files changed, 197 insertions(+) diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index ffb5f9b27..1f4b905eb 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -21,6 +21,7 @@ import 'package:flutter/material.dart'; import 'package:wger/core/uuid.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; @@ -34,6 +35,7 @@ const PREFS_COUNTDOWN_DURATION = 'countdownDurationSecondsPrefs'; const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; +const PREFS_STICKY_SET_VALUES = 'stickySetValuesPrefs'; /// In seconds const DEFAULT_COUNTDOWN_DURATION = 180; @@ -186,6 +188,15 @@ class GymModeState { final bool showDistinctLogs; final bool showWorkoutDuration; + /// Whether the log form of a set is pre-filled with the values last + /// logged for the same exercise during this workout, instead of the + /// planned ones. Disabled by default. + final bool stickySetValues; + + /// The values last logged per exercise during this workout, used to + /// pre-fill the log form when [stickySetValues] is enabled. + final Map lastLoggedValues; + // Routine data late final int dayId; late final int iteration; @@ -204,6 +215,8 @@ class GymModeState { this.logScopeWeeks, this.showDistinctLogs = true, this.showWorkoutDuration = true, + this.stickySetValues = false, + this.lastLoggedValues = const {}, int? dayId, int? iteration, Routine? routine, @@ -248,6 +261,8 @@ class GymModeState { bool clearLogScopeWeeks = false, bool? showDistinctLogs, bool? showWorkoutDuration, + bool? stickySetValues, + Map? lastLoggedValues, }) { return GymModeState( isInitialized: isInitialized ?? this.isInitialized, @@ -270,6 +285,8 @@ class GymModeState { logScopeWeeks: clearLogScopeWeeks ? null : (logScopeWeeks ?? this.logScopeWeeks), showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, + stickySetValues: stickySetValues ?? this.stickySetValues, + lastLoggedValues: lastLoggedValues ?? this.lastLoggedValues, ); } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 83e4bd186..d1032ac4b 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -91,6 +91,11 @@ class GymStateNotifier extends _$GymStateNotifier { state = state.copyWith(showWorkoutDuration: showWorkoutDuration); } + final stickySetValues = await prefs.getBool(PREFS_STICKY_SET_VALUES); + if (stickySetValues != null && stickySetValues != state.stickySetValues) { + state = state.copyWith(stickySetValues: stickySetValues); + } + _logger.finer( 'Loaded saved preferences: ' 'showExercise=$showExercise ' @@ -121,6 +126,7 @@ class GymStateNotifier extends _$GymStateNotifier { } await prefs.setBool(PREFS_SHOW_DISTINCT_LOGS, state.showDistinctLogs); await prefs.setBool(PREFS_SHOW_WORKOUT_DURATION, state.showWorkoutDuration); + await prefs.setBool(PREFS_STICKY_SET_VALUES, state.stickySetValues); _logger.finer( 'Saved preferences: ' @@ -319,6 +325,25 @@ class GymStateNotifier extends _$GymStateNotifier { routineId: state.routine.id, iteration: state.iteration, ); + + // Pre-fill with the values last logged for this exercise during this + // workout (e.g. when dialing in the weight over the first sets), if + // enabled. This intentionally only copies the values: the id, session, + // slot entry and targets stay those of a fresh template. + final lastValues = state.stickySetValues + ? state.lastLoggedValues[slotEntryPage.setConfigData!.exerciseId] + : null; + if (lastValues != null) { + log + ..repetitions = lastValues.repetitions + ..repetitionsUnitId = lastValues.repetitionsUnitId + ..repetitionsUnitObj = lastValues.repetitionsUnitObj + ..weight = lastValues.weight + ..weightUnitId = lastValues.weightUnitId + ..weightUnitObj = lastValues.weightUnitObj + ..rir = lastValues.rir; + } + ref.read(gymLogProvider.notifier).setLog(log); } @@ -365,6 +390,20 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } + void setStickySetValues(bool value) { + state = state.copyWith(stickySetValues: value); + _savePrefs(); + } + + /// Remembers the values logged for the log's exercise so that the next + /// set of the exercise can be pre-filled with them, see + /// [GymModeState.stickySetValues]. + void recordLoggedValues(Log log) { + final updated = Map.of(state.lastLoggedValues); + updated[log.exerciseId] = log; + state = state.copyWith(lastLoggedValues: updated); + } + void markSlotPageAsDone(String uuid, {required bool isDone}) { final slotPage = state.getSlotPageByUUID(uuid); if (slotPage == null) { @@ -493,6 +532,7 @@ class GymStateNotifier extends _$GymStateNotifier { isInitialized: false, pages: [], currentPage: 0, + lastLoggedValues: const {}, validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 6226bee1f..b968d562d 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -399,6 +399,7 @@ class _LogFormWidgetState extends ConsumerState { } gymProvider.markSlotPageAsDone(page.uuid, isDone: true); + gymProvider.recordLoggedValues(log); showSnackbar( context, i18n.successfullySaved, diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 471a113cc..5766f011b 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -196,6 +196,13 @@ class _GymModeOptionsState extends ConsumerState { value: gymState.showDistinctLogs, onChanged: (value) => gymNotifier.setShowDistinctLogs(value), ), + SwitchListTile( + key: const ValueKey('gym-mode-sticky-set-values'), + title: Text(i18n.gymModeStickySetValues), + subtitle: Text(i18n.gymModeStickySetValuesHelp), + value: gymState.stickySetValues, + onChanged: (value) => gymNotifier.setStickySetValues(value), + ), ], ), ), diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1aff62662..18fc05b9a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -407,6 +407,14 @@ "@pause": { "description": "Noun, not an imperative! Label used for the pause when using the gym mode" }, + "gymModeStickySetValues": "Sticky set values", + "@gymModeStickySetValues": { + "description": "Label for a gym mode setting: when enabled, the next set of an exercise is pre-filled with the values last logged instead of the planned ones" + }, + "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values (weight, repetitions, RiR) you last logged for it during this workout", + "@gymModeStickySetValuesHelp": { + "description": "Help text for the sticky set values setting in the gym mode" + }, "jumpTo": "Jump to", "@jumpTo": { "description": "Imperative. Label used in popup allowing the user to jump to a specific exercise while in the gym mode" diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index cb7894b3f..a841578d4 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -30,9 +30,11 @@ import 'package:wger/features/account/providers/user_profile_repository.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; +import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; +import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; @@ -508,6 +510,91 @@ void main() { }); }); + group('GymStateNotifier sticky set values', () { + // Page structure of the test routine (exercise + timer pages enabled): + // start(0) + // slot 1 (exercise 1): overview(1), log(2), timer(3), log(4), timer(5), log(6), timer(7) + // slot 2 (exercise 6): overview(8), log(9), ... + + Log buildLoggedValues() { + final slotPage = notifier.state.pages[1].slotPages[1]; + return Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..repetitions = 7 + ..weight = 42.5 + ..rir = 1; + } + + test('Sets the flag and persists it', () async { + // Act + notifier.setStickySetValues(true); + await pumpEventQueue(); + + // Assert + expect(notifier.state.stickySetValues, true); + expect(await PreferenceHelper.asyncPref.getBool(PREFS_STICKY_SET_VALUES), true); + }); + + test( + 'Pre-fills the next set of the exercise with the last logged values when enabled', + () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + notifier.recordLoggedValues(buildLoggedValues()); + + // Act: navigate to the second set of the same exercise + notifier.setCurrentPage(4); + + // Assert + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 7); + expect(gymLog.weight, 42.5); + expect(gymLog.rir, 1); + expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); + }, + ); + + test('Pre-fills with the planned values when disabled', () { + // Arrange + notifier.recordLoggedValues(buildLoggedValues()); + + // Act + notifier.setCurrentPage(4); + + // Assert: the values of the set configuration + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 3); + expect(gymLog.weight, 100); + }); + + test('Does not carry values over to a different exercise', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + notifier.recordLoggedValues(buildLoggedValues()); + + // Act: navigate to the first set of the second exercise + notifier.setCurrentPage(9); + + // Assert: the values of that exercise's set configuration + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 12); + expect(gymLog.weight, 10); + }); + + test('Clearing the state forgets the logged values', () { + // Arrange + notifier.recordLoggedValues(buildLoggedValues()); + expect(notifier.state.lastLoggedValues, isNotEmpty); + + // Act + notifier.clear(); + + // Assert + expect(notifier.state.lastLoggedValues, isEmpty); + }); + }); + group('GymStateNotifier.startWorkout', () { test('Resets the workout start time to now', () { // Arrange diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index d941ab314..041945ff8 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -32,6 +32,7 @@ import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; +import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/workout_logs_repository.dart'; @@ -244,6 +245,34 @@ void main() { expect(saved.iteration, gymState.iteration); }); + testWidgets('carries the logged values over to the next set when sticky values are enabled', ( + tester, + ) async { + seedLogPage(testdata.getTestRoutine()); + container.read(gymStateProvider.notifier).setStickySetValues(true); + await pumpLogPage(tester); + + // Log a set with non-default values + final fields = find.byType(TextFormField); + await tester.enterText(fields.at(0), '12'); // reps + await tester.enterText(fields.at(1), '34'); // weight + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + + // Navigate to the next set of the same exercise + container.read(gymStateProvider.notifier).setCurrentPage(4); + await tester.pumpAndSettle(); + + // The form is pre-filled with the values just logged, not the planned ones + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 12); + expect(gymLog.weight, 34); + expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); + final repField = tester.widget(find.byType(EditableText).at(0)); + expect(repField.controller.text, '12'); + }); + testWidgets('reps quick buttons increment and decrement the value', (tester) async { final routine = testdata.getTestRoutine(); routine.dayDataGym[0].slots[0].setConfigs[0].repetitions = 0; diff --git a/test/features/routines/widgets/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index dcc9105fe..30ee77a8a 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -113,11 +113,19 @@ void main() { await tester.tap(durationSwitch); await tester.pump(); + // Toggle sticky set values + final stickySwitch = find.byKey(const ValueKey('gym-mode-sticky-set-values')); + expect(stickySwitch, findsOneWidget); + await tester.ensureVisible(stickySwitch); + await tester.tap(stickySwitch); + await tester.pump(); + final notifier = container.read(gymStateProvider.notifier); expect(notifier.state.showExercisePages, isFalse); expect(notifier.state.showTimerPages, isFalse); expect(notifier.state.alertOnCountdownEnd, isTrue); expect(notifier.state.showWorkoutDuration, isFalse); + expect(notifier.state.stickySetValues, isTrue); }); testWidgets('Dropdown, text field and refresh button update notifier state', (tester) async { From a1a30316bef42e737864bb1483325b043f051d04 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 20:53:40 +0100 Subject: [PATCH 06/29] Don't persist checkout credentials in CI workflows --- .github/workflows/analyze.yml | 2 ++ .github/workflows/build-android.yml | 2 ++ .github/workflows/build-apple.yml | 3 +++ .github/workflows/build-linux.yml | 1 + .github/workflows/build-web.yml | 1 + .github/workflows/build-windows.yml | 1 + .github/workflows/ci.yml | 2 ++ .github/workflows/codeql-analysis.yml | 2 ++ .github/workflows/make-release.yml | 1 + .github/workflows/screenshots.yml | 4 ++++ 10 files changed, 19 insertions(+) diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml index ca737991a..ee9c1934f 100644 --- a/.github/workflows/analyze.yml +++ b/.github/workflows/analyze.yml @@ -34,6 +34,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - name: Common flutter setup uses: ./.github/actions/flutter-common diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index eec4f6757..cfa13eccf 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -28,6 +28,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Common flutter setup @@ -58,6 +59,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Common setup diff --git a/.github/workflows/build-apple.yml b/.github/workflows/build-apple.yml index 1d23800bc..c98b52759 100644 --- a/.github/workflows/build-apple.yml +++ b/.github/workflows/build-apple.yml @@ -23,6 +23,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Xcode setup @@ -51,6 +52,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Xcode setup @@ -79,6 +81,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Xcode setup diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index b3a7f5a56..9932502d2 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -46,6 +46,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Read Flutter SDK version diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 740dfa1eb..01887fb04 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -24,6 +24,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Common flutter setup diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index 1f3bc7365..f88588860 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -26,6 +26,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false ref: ${{ inputs.ref }} - name: Common flutter setup diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6daf9661b..35d2f06f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,6 +36,8 @@ jobs: TZ: Europe/Berlin steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - name: Common flutter setup uses: ./.github/actions/flutter-common diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 46ca42e11..b3a3fad73 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -26,6 +26,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v7 + with: + persist-credentials: false # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/make-release.yml b/.github/workflows/make-release.yml index 513a95c35..4d9c3dd9d 100644 --- a/.github/workflows/make-release.yml +++ b/.github/workflows/make-release.yml @@ -75,6 +75,7 @@ jobs: - name: Checkout application uses: actions/checkout@v7 with: + persist-credentials: false lfs: true ref: ${{ github.event.inputs.version }} diff --git a/.github/workflows/screenshots.yml b/.github/workflows/screenshots.yml index 98083c6bc..987a2508a 100644 --- a/.github/workflows/screenshots.yml +++ b/.github/workflows/screenshots.yml @@ -34,6 +34,8 @@ jobs: folder: iPad 13 steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - name: Common flutter setup uses: ./.github/actions/flutter-common @@ -93,6 +95,8 @@ jobs: folder: tenInchScreenshots steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - name: Common flutter setup uses: ./.github/actions/flutter-common From 80375a3e740ac3016e957d9262d2eb0f87458355 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 20:59:16 +0100 Subject: [PATCH 07/29] Forget sticky set values when a new workout starts --- .../providers/gym_state_notifier.dart | 18 +++----- .../routines/providers/gym_state_test.dart | 42 +++++++++++++++++++ 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index d1032ac4b..bcc0c0e20 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -298,6 +298,8 @@ class GymStateNotifier extends _$GymStateNotifier { currentPage: initialPage, // A fresh workout also restarts the elapsed timer workoutStart: shouldReset ? clock.now() : null, + // An abandoned workout never reaches clear(), so forget its values here + lastLoggedValues: shouldReset ? const {} : null, ); // Calculate the pages. @@ -325,26 +327,16 @@ class GymStateNotifier extends _$GymStateNotifier { routineId: state.routine.id, iteration: state.iteration, ); + final logNotifier = ref.read(gymLogProvider.notifier)..setLog(log); // Pre-fill with the values last logged for this exercise during this - // workout (e.g. when dialing in the weight over the first sets), if - // enabled. This intentionally only copies the values: the id, session, - // slot entry and targets stay those of a fresh template. + // workout (e.g. when dialing in the weight over the first sets), if enabled final lastValues = state.stickySetValues ? state.lastLoggedValues[slotEntryPage.setConfigData!.exerciseId] : null; if (lastValues != null) { - log - ..repetitions = lastValues.repetitions - ..repetitionsUnitId = lastValues.repetitionsUnitId - ..repetitionsUnitObj = lastValues.repetitionsUnitObj - ..weight = lastValues.weight - ..weightUnitId = lastValues.weightUnitId - ..weightUnitObj = lastValues.weightUnitObj - ..rir = lastValues.rir; + logNotifier.copyValuesFrom(lastValues); } - - ref.read(gymLogProvider.notifier).setLog(log); } void setShowExercisePages(bool value) { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index a1ab5613b..1fbfbfccb 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -582,6 +582,48 @@ void main() { expect(gymLog.weight, 10); }); + test('A new workout forgets the values of an abandoned one', () async { + // Arrange: the summary page (and clear()) is never reached + notifier.setStickySetValues(true); + await pumpEventQueue(); + notifier.state = notifier.state.copyWith( + isInitialized: true, + dayId: 1, + validUntil: DateTime(2024, 5, 1, 10, 0), + ); + notifier.recordLoggedValues(buildLoggedValues()); + + // Act + withClock( + Clock.fixed(DateTime(2024, 5, 2, 18, 0)), + () => notifier.initData(getTestRoutine(), 1, 1), + ); + notifier.setCurrentPage(2); + + // Assert: the values of the set configuration + expect(notifier.state.lastLoggedValues, isEmpty); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 3); + expect(gymLog.weight, 100); + }); + + test('Resuming the same workout keeps the logged values', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + notifier.state = notifier.state.copyWith(isInitialized: true, dayId: 1); + notifier.recordLoggedValues(buildLoggedValues()); + + // Act + notifier.initData(getTestRoutine(), 1, 1); + notifier.setCurrentPage(4); + + // Assert + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 7); + expect(gymLog.weight, 42.5); + }); + test('Clearing the state forgets the logged values', () { // Arrange notifier.recordLoggedValues(buildLoggedValues()); From 43cf37efcfc64ce4f2726a07f8609294d5072459 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:11:53 +0100 Subject: [PATCH 08/29] Shorten help string and translate --- lib/l10n/app_de.arb | 4 +++- lib/l10n/app_en.arb | 2 +- lib/l10n/app_es.arb | 4 +++- lib/l10n/app_fr.arb | 4 +++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 865a77e64..4ba982886 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1177,5 +1177,7 @@ "calculationHelpExercises": "Zwischen {min} und {max} Übungen, {count} ausgewählt.", "calculationHelpMaxReps": "{min} bis {max}. Sätze darüber werden ignoriert.", "calculationHelpWindowDays": "{min} bis {max}. Wie weit zurück ein bester Satz zählt.", - "useDynamicColor": "Dynamische Farben verwenden" + "useDynamicColor": "Dynamische Farben verwenden", + "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", + "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du in diesem Training zuletzt dafür eingetragen hast" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 93db460ad..edd2feefc 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -411,7 +411,7 @@ "@gymModeStickySetValues": { "description": "Label for a gym mode setting: when enabled, the next set of an exercise is pre-filled with the values last logged instead of the planned ones" }, - "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values (weight, repetitions, RiR) you last logged for it during this workout", + "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values you last logged for it during this workout", "@gymModeStickySetValuesHelp": { "description": "Help text for the sticky set values setting in the gym mode" }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index eeb9974c7..412a6a8b1 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1194,5 +1194,7 @@ "calculationHelpExercises": "Entre {min} y {max} ejercicios, {count} seleccionados.", "calculationHelpMaxReps": "De {min} a {max}. Las series por encima se ignoran.", "calculationHelpWindowDays": "De {min} a {max}. Hasta dónde cuenta la mejor serie.", - "useDynamicColor": "Usar color dinámico" + "useDynamicColor": "Usar color dinámico", + "gymModeStickySetValues": "Mantener los valores de la última serie", + "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez durante este entrenamiento" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 11f0a9372..855f85b39 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1186,5 +1186,7 @@ "calculationHelpExercises": "Entre {min} et {max} exercices, {count} sélectionnés.", "calculationHelpMaxReps": "De {min} à {max}. Les séries au-dessus sont ignorées.", "calculationHelpWindowDays": "De {min} à {max}. Jusqu’où remonte la meilleure série.", - "useDynamicColor": "Utiliser les couleurs dynamiques" + "useDynamicColor": "Utiliser les couleurs dynamiques", + "gymModeStickySetValues": "Reprendre les valeurs de la dernière série", + "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées pendant cet entraînement" } From 6fdc85738156d3c3fdfe4dce72741b3c447a068d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:32:54 +0100 Subject: [PATCH 09/29] Don't alert again when returning to an expired rest countdown --- .../routines/widgets/gym_mode/timer.dart | 15 ++++---- .../routines/widgets/gym_mode/timer_test.dart | 35 +++++++++++++++++++ 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index ac2e50736..438b590b2 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -145,18 +145,15 @@ class _TimerCountdownWidgetState extends ConsumerState { void initState() { super.initState(); + // Don't notify when returning to a countdown that already expired while + // the user was on another page. Set before the first build, which notifies. + _hasNotified = _endTime(ref.read(gymStateProvider)).isBefore(clock.now()); + // Deferred because a provider can't be modified during the widget // life-cycle. WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); - - // Don't notify when returning to a countdown that already expired while - // the user was on another page. - if (_endTime(ref.read(gymStateProvider)).isBefore(clock.now())) { - _hasNotified = true; + if (mounted) { + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); } }); diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 863a74975..60c7e4013 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -18,6 +18,7 @@ import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; @@ -127,5 +128,39 @@ void main() { expect(find.text('0:45'), findsOneWidget); }); }); + + testWidgets('alerts once, but not again when returning to an expired countdown', ( + tester, + ) async { + final haptics = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + call, + ) async { + if (call.method == 'HapticFeedback.vibrate') { + haptics.add(call); + } + return null; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final t0 = DateTime(2024, 5, 2, 12); + + await withClock(Clock.fixed(t0), () => pumpTimer(tester, 3)); + + // The 90s countdown runs out while the page is shown + await withClock(Clock.fixed(t0.add(const Duration(seconds: 95))), () => pumpTimer(tester, 3)); + expect(haptics, hasLength(1)); + + // Leaving and coming back re-creates the widget + await withClock(Clock.fixed(t0.add(const Duration(seconds: 120))), () async { + await tester.pumpWidget(const SizedBox()); + await pumpTimer(tester, 3); + }); + expect(haptics, hasLength(1)); + }); }); } From 58cd06bb4cfa7e2fdcb65ea4dcc8656c8b258a2d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:36:21 +0100 Subject: [PATCH 10/29] Restart the rest timer when its set is saved for the first time --- .../providers/gym_state_notifier.dart | 8 +++++ .../routines/providers/gym_state_test.dart | 34 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index d1b1a76d7..18aa0cc7f 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -450,6 +450,8 @@ class GymStateNotifier extends _$GymStateNotifier { /// is kept on the slot page so revisiting the page pre-fills the form with /// the saved values and saving updates the row instead of inserting a /// duplicate. + /// + /// The first save also (re)starts the rest timer that follows the set. void markSlotPageAsDone(String uuid, {required bool isDone, Log? log}) { final slotPage = state.getSlotPageByUUID(uuid); if (slotPage == null) { @@ -459,6 +461,12 @@ class GymStateNotifier extends _$GymStateNotifier { _updateSlotPage(uuid, slotPage.copyWith(logDone: isDone, loggedEntry: log)); _logger.fine('Set logDone=$isDone for slot page UUID $uuid'); + + // Scrolling past the timer (e.g. "jump to") already started it + final timerPage = state.getSlotEntryPageByIndex(slotPage.pageIndex + 1); + if (slotPage.loggedEntry == null && timerPage?.type == SlotPageType.timer) { + _updateSlotPage(timerPage!.uuid, timerPage.copyWith(timerStartedAt: clock.now())); + } } void replaceExercises( diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 412d907db..6ac4ad5c8 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -162,6 +162,40 @@ void main() { DateTime(2024, 5, 2, 12), ); }); + + test('Saving a set restarts the following timer, editing it does not', () { + // Arrange: the timer was started by scrolling past it + final logPage = notifier.state.pages[1].slotPages[1]; + final timerPage = notifier.state.pages[1].slotPages[2]; + expect(logPage.type, SlotPageType.log); + expect(timerPage.type, SlotPageType.timer); + withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { + notifier.startTimerIfNeeded(timerPage.uuid); + }); + final log = Log.fromSetConfigData(logPage.setConfigData!, routineId: 1, iteration: 1); + + // Act: the set is saved + withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 10)), () { + notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: log); + }); + + // Assert + expect( + notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + DateTime(2024, 5, 2, 12, 10), + ); + + // Act: correcting the saved set keeps the running timer + withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 11)), () { + notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: log); + }); + + // Assert + expect( + notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + DateTime(2024, 5, 2, 12, 10), + ); + }); }); group('GymStateNotifier.recalculateIndices', () { From d4808234273e43fae17f8cc0029d134e1f37cd9f Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:41:42 +0100 Subject: [PATCH 11/29] Edit a copy when correcting a logged set in gym mode --- .../routines/providers/gym_log_notifier.dart | 5 +-- .../providers/gym_state_notifier.dart | 3 +- .../routines/providers/gym_state_test.dart | 5 +-- .../widgets/gym_mode/log_page_test.dart | 36 +++++++++++++++++++ 4 files changed, 44 insertions(+), 5 deletions(-) diff --git a/lib/features/routines/providers/gym_log_notifier.dart b/lib/features/routines/providers/gym_log_notifier.dart index b89788aeb..06b04e5d5 100644 --- a/lib/features/routines/providers/gym_log_notifier.dart +++ b/lib/features/routines/providers/gym_log_notifier.dart @@ -58,9 +58,10 @@ class GymLogNotifier extends _$GymLogNotifier { /// Starts editing a log that was already persisted during the current /// workout. Unlike [setLog], the id, session and date are kept so saving - /// updates the existing row instead of inserting a duplicate. + /// updates the existing row instead of inserting a duplicate. [log] itself + /// is not modified by the edits. void editLog(Log log) { - state = log; + state = log.copyWith(); } void setWeight(num weight) { diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 18aa0cc7f..5ba4fa9d3 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -459,7 +459,8 @@ class GymStateNotifier extends _$GymStateNotifier { return; } - _updateSlotPage(uuid, slotPage.copyWith(logDone: isDone, loggedEntry: log)); + // A copy, so later edits in the form don't change the saved entry + _updateSlotPage(uuid, slotPage.copyWith(logDone: isDone, loggedEntry: log?.copyWith())); _logger.fine('Set logDone=$isDone for slot page UUID $uuid'); // Scrolling past the timer (e.g. "jump to") already started it diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 6ac4ad5c8..6a1a8107c 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -100,7 +100,9 @@ void main() { notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); // Assert - expect(notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry, same(log)); + final loggedEntry = notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry!; + expect(loggedEntry.id, 'log-1'); + expect(loggedEntry, isNot(same(log))); }); }); @@ -120,7 +122,6 @@ void main() { // Assert: the id and session are kept so saving updates the row // instead of inserting a duplicate final gymLog = container.read(gymLogProvider); - expect(gymLog, same(log)); expect(gymLog!.id, 'log-1'); expect(gymLog.sessionId, 'session-1'); }); diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index 577c4c681..b0bf88fea 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -326,6 +326,42 @@ void main() { verifyNever(mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); + testWidgets('an unsaved edit on a logged page does not change the saved entry', ( + tester, + ) async { + seedLogPage(testdata.getTestRoutine()); + await pumpLogPage(tester); + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + final gymNotifier = container.read(gymStateProvider.notifier); + final logPageUuid = container.read(gymStateProvider).getSlotEntryPageByIndex(2)!.uuid; + final savedRir = container + .read(gymStateProvider) + .getSlotPageByUUID(logPageUuid)! + .loggedEntry! + .rir; + expect(savedRir, isNot(3)); + + // Go back to the logged set and change the RiR without saving + gymNotifier.setCurrentPage(3); + gymNotifier.setCurrentPage(2); + await tester.pumpAndSettle(); + tester.widget(find.byType(Slider)).onChanged!(3); + await tester.pump(); + + // Leave and come back + gymNotifier.setCurrentPage(3); + gymNotifier.setCurrentPage(2); + await tester.pumpAndSettle(); + + final loggedEntry = container + .read(gymStateProvider) + .getSlotPageByUUID(logPageUuid)! + .loggedEntry!; + expect(loggedEntry.rir, savedRir); + expect(container.read(gymLogProvider)!.rir, savedRir); + }); + testWidgets('reps quick buttons increment and decrement the value', (tester) async { final routine = testdata.getTestRoutine(); routine.dayDataGym[0].slots[0].setConfigs[0].repetitions = 0; From deed86606a6f9d0fd4c750e51441f4d22ffaf861 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:44:27 +0100 Subject: [PATCH 12/29] Drop the id and session restore when re-saving a logged set The form's log always carries both now: editLog copies them and copyValuesFrom keeps them. --- lib/features/routines/widgets/gym_mode/log_page.dart | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 3dce01f22..5686ee0a4 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -389,14 +389,9 @@ class _LogFormWidgetState extends ConsumerState { // // Re-saving a page that was already logged in this workout // updates the existing row instead of inserting a duplicate. - // The id/session can be missing on the form log, e.g. after - // copying values from a past log, so restore them first. - final existingEntry = page.loggedEntry; - if (existingEntry == null) { + if (page.loggedEntry == null) { await logProvider.addEntry(log, dayId: gymState.dayId); } else { - log.id = existingEntry.id; - log.sessionId = existingEntry.sessionId; await logProvider.updateEntry(log); } if (!context.mounted) { From 8165b286e957670e0ddc8963c16ccb3b4a5dd6fc Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:49:00 +0100 Subject: [PATCH 13/29] Keep the sticky set values when correcting an earlier set --- .../routines/widgets/gym_mode/log_page.dart | 7 +- .../widgets/gym_mode/log_page_test.dart | 64 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 5686ee0a4..272cce4f2 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -399,7 +399,12 @@ class _LogFormWidgetState extends ConsumerState { } gymProvider.markSlotPageAsDone(page.uuid, isDone: true, log: log); - gymProvider.recordLoggedValues(log); + + // Correcting an earlier set must not replace a later set's values + final lastLogged = gymState.lastLoggedValues[log.exerciseId]; + if (page.loggedEntry == null || lastLogged?.id == log.id) { + gymProvider.recordLoggedValues(log); + } showSnackbar( context, i18n.successfullySaved, diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index b0bf88fea..983f38df0 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -288,6 +288,70 @@ void main() { expect(repField.controller.text, '12'); }); + group('sticky values when correcting a logged set', () { + Future logSet(WidgetTester tester, int page, {String? reps, String? weight}) async { + container.read(gymStateProvider.notifier).setCurrentPage(page); + await tester.pumpWidget(const SizedBox()); + await pumpLogPage(tester); + final fields = find.byType(TextFormField); + if (reps != null) { + await tester.enterText(fields.at(0), reps); + } + if (weight != null) { + await tester.enterText(fields.at(1), weight); + } + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + } + + setUp(() { + // Distinct ids, so the saved sets can be told apart + var count = 0; + when( + mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), + ).thenAnswer((invocation) async { + (invocation.positionalArguments[0] as Log).id = 'log-${++count}'; + }); + }); + + testWidgets('correcting an earlier set keeps the values of a later one', (tester) async { + seedLogPage(testdata.getTestRoutine()); + container.read(gymStateProvider.notifier).setStickySetValues(true); + + // Sets 1 and 2 of the same exercise (pages 2 and 4) + await logSet(tester, 2, reps: '12', weight: '34'); + await logSet(tester, 4, reps: '14', weight: '40'); + + // Correct set 1 + await logSet(tester, 2, reps: '13'); + verify(mockWorkoutLogRepo.updateLocalDrift(any)).called(1); + + // Set 3 is pre-filled with the values of set 2 + container.read(gymStateProvider.notifier).setCurrentPage(6); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 14); + expect(gymLog.weight, 40); + }); + + testWidgets('correcting the latest set updates the values', (tester) async { + seedLogPage(testdata.getTestRoutine()); + container.read(gymStateProvider.notifier).setStickySetValues(true); + + await logSet(tester, 2, reps: '12', weight: '34'); + + // Correct the weight of the same set + await logSet(tester, 2, weight: '36'); + verify(mockWorkoutLogRepo.updateLocalDrift(any)).called(1); + + // Set 2 is pre-filled with the corrected values + container.read(gymStateProvider.notifier).setCurrentPage(4); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 12); + expect(gymLog.weight, 36); + }); + }); + testWidgets('re-visiting a logged page restores the saved values and saving updates the row', ( tester, ) async { From 33c577272a268916b5f76bd33ff6a69b915a97cd Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 21:55:38 +0100 Subject: [PATCH 14/29] Cleanups --- lib/l10n/app_de.arb | 3 ++- lib/l10n/app_es.arb | 3 ++- lib/l10n/app_fr.arb | 3 ++- test/features/routines/widgets/gym_mode/timer_test.dart | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 4ba982886..5148a8e7b 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1179,5 +1179,6 @@ "calculationHelpWindowDays": "{min} bis {max}. Wie weit zurück ein bester Satz zählt.", "useDynamicColor": "Dynamische Farben verwenden", "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", - "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du in diesem Training zuletzt dafür eingetragen hast" + "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du in diesem Training zuletzt dafür eingetragen hast", + "upNext": "Als Nächstes" } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 412a6a8b1..1b6ee3eac 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1196,5 +1196,6 @@ "calculationHelpWindowDays": "De {min} a {max}. Hasta dónde cuenta la mejor serie.", "useDynamicColor": "Usar color dinámico", "gymModeStickySetValues": "Mantener los valores de la última serie", - "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez durante este entrenamiento" + "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez durante este entrenamiento", + "upNext": "A continuación" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 855f85b39..d15127b8a 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1188,5 +1188,6 @@ "calculationHelpWindowDays": "De {min} à {max}. Jusqu’où remonte la meilleure série.", "useDynamicColor": "Utiliser les couleurs dynamiques", "gymModeStickySetValues": "Reprendre les valeurs de la dernière série", - "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées pendant cet entraînement" + "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées pendant cet entraînement", + "upNext": "À suivre" } diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 60c7e4013..08b2661e2 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -17,10 +17,10 @@ */ import 'package:clock/clock.dart'; -import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; From 6814711fe6c49ffde4c61bac031420e287bfd6c7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Sun, 25 Oct 2026 22:12:31 +0100 Subject: [PATCH 15/29] Make it more obvious when an edit takes place We now show whether the user will add a new entry or edit the last one --- .../routines/providers/gym_log_notifier.dart | 5 + .../providers/gym_state_notifier.dart | 26 ++-- .../routines/widgets/gym_mode/log_page.dart | 121 ++++++++++-------- .../routines/providers/gym_state_test.dart | 40 +++++- .../widgets/gym_mode/log_page_test.dart | 48 +++++++ 5 files changed, 177 insertions(+), 63 deletions(-) diff --git a/lib/features/routines/providers/gym_log_notifier.dart b/lib/features/routines/providers/gym_log_notifier.dart index 06b04e5d5..04c1b4a60 100644 --- a/lib/features/routines/providers/gym_log_notifier.dart +++ b/lib/features/routines/providers/gym_log_notifier.dart @@ -35,6 +35,11 @@ class GymLogNotifier extends _$GymLogNotifier { return null; } + /// [Log.==] ignores the id, so a fresh entry would be "equal" to a saved one + /// with the same values and the form wouldn't switch over + @override + bool updateShouldNotify(Log? previous, Log? next) => !identical(previous, next); + void setLog(Log log) { // Clear the id so Drift mints a fresh UUID on insert, and the sessionId so // the entry lands in today's session. diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 5ba4fa9d3..286816974 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -316,21 +316,27 @@ class GymStateNotifier extends _$GymStateNotifier { void setCurrentPage(int page) { state = state.copyWith(currentPage: page); - // Ensure that there is a log entry for the current slot entry - final slotEntryPage = state.getSlotEntryPageByIndex(); - if (slotEntryPage == null || slotEntryPage.setConfigData == null) { - return; - } - // Re-visiting a page that was already logged in this workout: seed the // form with the saved entry (keeping its id and session) so saving // updates the row instead of inserting a duplicate. - final loggedEntry = slotEntryPage.loggedEntry; + final loggedEntry = state.getSlotEntryPageByIndex()?.loggedEntry; if (loggedEntry != null) { ref.read(gymLogProvider.notifier).editLog(loggedEntry); return; } + startNewEntry(); + } + + /// Seeds the log form of the current page with a fresh entry, also to log + /// another set on a page that was already logged. + void startNewEntry() { + // Ensure that there is a log entry for the current slot entry + final slotEntryPage = state.getSlotEntryPageByIndex(); + if (slotEntryPage == null || slotEntryPage.setConfigData == null) { + return; + } + final log = Log.fromSetConfigData( slotEntryPage.setConfigData!, routineId: state.routine.id, @@ -451,7 +457,8 @@ class GymStateNotifier extends _$GymStateNotifier { /// the saved values and saving updates the row instead of inserting a /// duplicate. /// - /// The first save also (re)starts the rest timer that follows the set. + /// Saving a new entry, unlike correcting one, also (re)starts the rest timer + /// that follows the set. void markSlotPageAsDone(String uuid, {required bool isDone, Log? log}) { final slotPage = state.getSlotPageByUUID(uuid); if (slotPage == null) { @@ -465,7 +472,8 @@ class GymStateNotifier extends _$GymStateNotifier { // Scrolling past the timer (e.g. "jump to") already started it final timerPage = state.getSlotEntryPageByIndex(slotPage.pageIndex + 1); - if (slotPage.loggedEntry == null && timerPage?.type == SlotPageType.timer) { + final isNewEntry = slotPage.loggedEntry?.id != log?.id; + if (isNewEntry && timerPage?.type == SlotPageType.timer) { _updateSlotPage(timerPage!.uuid, timerPage.copyWith(timerStartedAt: clock.now())); } } diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 272cce4f2..45509c798 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -303,13 +303,16 @@ class _LogFormWidgetState extends ConsumerState { return const SizedBox.shrink(); } + // A log with an id was already saved, saving it again updates the row + final isNewEntry = log.id == null; + return Form( key: _form, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( - i18n.newEntry, + isNewEntry ? i18n.newEntry : i18n.edit, style: Theme.of(context).textTheme.titleLarge, textAlign: TextAlign.center, ), @@ -361,62 +364,76 @@ class _LogFormWidgetState extends ConsumerState { log.rir = value == '' ? null : num.parse(value); }, ), - FilledButton( - key: const ValueKey('save-log-button'), - onPressed: () async { - final isValid = _form.currentState!.validate(); - if (!isValid) { - return; - } - _form.currentState!.save(); + // Side by side to save the height, wrapped only if they don't fit + Wrap( + alignment: WrapAlignment.center, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + children: [ + if (!isNewEntry) + TextButton.icon( + key: const ValueKey('add-set-button'), + onPressed: () => ref.read(gymStateProvider.notifier).startNewEntry(), + label: Text(i18n.addSet), + ), + FilledButton( + key: const ValueKey('save-log-button'), + onPressed: () async { + final isValid = _form.currentState!.validate(); + if (!isValid) { + return; + } + _form.currentState!.save(); - final error = validateWorkoutLogCrossField( - repetitions: log.repetitions, - weight: log.weight, - i18n: i18n, - ); - if (error != null) { - showSnackbar(context, error); - return; - } + final error = validateWorkoutLogCrossField( + repetitions: log.repetitions, + weight: log.weight, + i18n: i18n, + ); + if (error != null) { + showSnackbar(context, error); + return; + } - final gymState = ref.read(gymStateProvider); - final gymProvider = ref.read(gymStateProvider.notifier); - final page = gymState.getSlotEntryPageByIndex()!; + final gymState = ref.read(gymStateProvider); + final gymProvider = ref.read(gymStateProvider.notifier); + final page = gymState.getSlotEntryPageByIndex()!; - // A failed write is intentionally left to propagate to the global - // error handler; the success path below is then skipped. - // - // Re-saving a page that was already logged in this workout - // updates the existing row instead of inserting a duplicate. - if (page.loggedEntry == null) { - await logProvider.addEntry(log, dayId: gymState.dayId); - } else { - await logProvider.updateEntry(log); - } - if (!context.mounted) { - return; - } + // A failed write is intentionally left to propagate to the global + // error handler; the success path below is then skipped. + // + // Re-saving a page that was already logged in this workout + // updates the existing row instead of inserting a duplicate. + if (isNewEntry) { + await logProvider.addEntry(log, dayId: gymState.dayId); + } else { + await logProvider.updateEntry(log); + } + if (!context.mounted) { + return; + } - gymProvider.markSlotPageAsDone(page.uuid, isDone: true, log: log); + gymProvider.markSlotPageAsDone(page.uuid, isDone: true, log: log); - // Correcting an earlier set must not replace a later set's values - final lastLogged = gymState.lastLoggedValues[log.exerciseId]; - if (page.loggedEntry == null || lastLogged?.id == log.id) { - gymProvider.recordLoggedValues(log); - } - showSnackbar( - context, - i18n.successfullySaved, - center: true, - duration: const Duration(seconds: 2), - ); - widget.controller.nextPage( - duration: DEFAULT_ANIMATION_DURATION, - curve: DEFAULT_ANIMATION_CURVE, - ); - }, - child: Text(i18n.save), + // Correcting an earlier set must not replace a later set's values + final lastLogged = gymState.lastLoggedValues[log.exerciseId]; + if (isNewEntry || lastLogged?.id == log.id) { + gymProvider.recordLoggedValues(log); + } + showSnackbar( + context, + i18n.successfullySaved, + center: true, + duration: const Duration(seconds: 2), + ); + widget.controller.nextPage( + duration: DEFAULT_ANIMATION_DURATION, + curve: DEFAULT_ANIMATION_CURVE, + ); + }, + child: Text(i18n.save), + ), + ], ), ], ), diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 6a1a8107c..70cde3aa6 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -135,6 +135,28 @@ void main() { }); }); + group('GymStateNotifier.startNewEntry', () { + test('Seeds a fresh entry on a page that was already logged', () { + // Arrange + final slotPage = notifier.state.pages[1].slotPages[1]; + final log = Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1' + ..repetitions = 99; + notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + notifier.setCurrentPage(slotPage.pageIndex); + expect(container.read(gymLogProvider)!.id, 'log-1'); + + // Act + notifier.startNewEntry(); + + // Assert: the planned values, without an id so saving inserts a row + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.id, isNull); + expect(gymLog.repetitions, slotPage.setConfigData!.repetitions); + expect(notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry!.id, 'log-1'); + }); + }); + group('GymStateNotifier.startTimerIfNeeded', () { test('Sets the start time only once', () { // Arrange @@ -164,7 +186,7 @@ void main() { ); }); - test('Saving a set restarts the following timer, editing it does not', () { + test('Saving a new set restarts the following timer, correcting it does not', () { // Arrange: the timer was started by scrolling past it final logPage = notifier.state.pages[1].slotPages[1]; final timerPage = notifier.state.pages[1].slotPages[2]; @@ -173,7 +195,9 @@ void main() { withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { notifier.startTimerIfNeeded(timerPage.uuid); }); - final log = Log.fromSetConfigData(logPage.setConfigData!, routineId: 1, iteration: 1); + // The id is minted by the insert + final log = Log.fromSetConfigData(logPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1'; // Act: the set is saved withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 10)), () { @@ -196,6 +220,18 @@ void main() { notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, DateTime(2024, 5, 2, 12, 10), ); + + // Act: another set is logged on the same page ("add set") + final extraLog = log.copyWith(id: 'log-2'); + withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 15)), () { + notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: extraLog); + }); + + // Assert + expect( + notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + DateTime(2024, 5, 2, 12, 15), + ); }); }); diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index 983f38df0..925821d2e 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -390,6 +390,54 @@ void main() { verifyNever(mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); + testWidgets('a logged page is shown for editing and "add set" logs another row', ( + tester, + ) async { + var count = 0; + when( + mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), + ).thenAnswer((invocation) async { + (invocation.positionalArguments[0] as Log).id = 'log-${++count}'; + }); + seedLogPage(testdata.getTestRoutine()); + await pumpLogPage(tester); + expect(find.text('New entry'), findsOneWidget); + expect(find.byKey(const ValueKey('add-set-button')), findsNothing); + + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + + // Going back shows the saved set for editing + final gymNotifier = container.read(gymStateProvider.notifier); + gymNotifier.setCurrentPage(3); + gymNotifier.setCurrentPage(2); + await tester.pumpAndSettle(); + expect(find.text('Edit'), findsOneWidget); + expect(find.text('New entry'), findsNothing); + + // "Add set" switches to a fresh entry + await tester.tap(find.byKey(const ValueKey('add-set-button'))); + await tester.pumpAndSettle(); + expect(find.text('New entry'), findsOneWidget); + expect(find.byKey(const ValueKey('add-set-button')), findsNothing); + + await tester.enterText(find.byType(TextFormField).at(0), '10'); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('save-log-button'))); + await tester.pumpAndSettle(); + + // A second row, the first one is left alone + final added = verify( + mockWorkoutLogRepo.addLocalDrift(captureAny, dayId: anyNamed('dayId')), + ).captured; + expect(added, hasLength(2)); + expect((added[1] as Log).id, 'log-2'); + expect((added[1] as Log).repetitions, 10); + verifyNever(mockWorkoutLogRepo.updateLocalDrift(any)); + final page = container.read(gymStateProvider).getSlotEntryPageByIndex(2)!; + expect(page.loggedEntry!.id, 'log-2'); + }); + testWidgets('an unsaved edit on a logged page does not change the saved entry', ( tester, ) async { From f6168422f74866105f5cbf80645fe49b40bc66e7 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 20:51:55 +0100 Subject: [PATCH 16/29] Revert "Ask for confirmation before leaving a running workout" This reverts commit a7410266a80bfc927d86aad6e3ad7332413949d2. # Conflicts: # lib/features/routines/providers/gym_state.dart # test/features/routines/screens/gym_mode_test.dart --- .../routines/providers/gym_state.dart | 6 - lib/features/routines/screens/gym_mode.dart | 36 +---- .../gym_mode/leave_workout_dialog.dart | 52 ------- .../routines/widgets/gym_mode/navigation.dart | 4 +- lib/l10n/app_en.arb | 12 -- .../routines/screens/gym_mode_test.dart | 133 ------------------ 6 files changed, 6 insertions(+), 237 deletions(-) delete mode 100644 lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index aeb747f54..710c72bf4 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -360,12 +360,6 @@ class GymModeState { return null; } - /// Whether the user is currently inside a running workout - /// - /// True from the moment the start page is left until the summary page is - /// reached, i.e. exactly while there is progress that leaving would discard. - bool get isWorkoutInProgress => isInitialized && currentPage > 0 && currentPage < totalPages - 1; - /// Returns the next log page after the slot page at [pageIndex], i.e. the /// set that will be performed once the current rest timer ends. /// diff --git a/lib/features/routines/screens/gym_mode.dart b/lib/features/routines/screens/gym_mode.dart index 023f96477..2a0bab18e 100644 --- a/lib/features/routines/screens/gym_mode.dart +++ b/lib/features/routines/screens/gym_mode.dart @@ -19,9 +19,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; -import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/widgets/gym_mode/gym_mode.dart'; -import 'package:wger/features/routines/widgets/gym_mode/leave_workout_dialog.dart'; class GymModeArguments { final int routineId; @@ -36,39 +34,15 @@ class GymModeScreen extends ConsumerWidget { static const routeName = '/gym-mode'; - /// Leaves gym mode, but only if the user confirms it - Future _confirmAndLeave(BuildContext context) async { - if (await confirmLeaveWorkout(context) && context.mounted) { - Navigator.of(context).pop(); - } - } - @override Widget build(BuildContext context, WidgetRef ref) { final args = ModalRoute.of(context)!.settings.arguments as GymModeArguments; - final workoutInProgress = ref.watch( - gymStateProvider.select((state) => state.isWorkoutInProgress), - ); - return PopScope( - // While a workout is running, leaving is always an explicit choice: the - // iOS back swipe and the Android back gesture are easy to trigger by - // accident (e.g. when reaching for a podcast app mid-set), and popping - // the route drops the session, the elapsed timer and the progress - // through the workout. - canPop: !workoutInProgress, - onPopInvokedWithResult: (didPop, _) { - if (didPop) { - return; - } - _confirmAndLeave(context); - }, - child: Scaffold( - // backgroundColor: Theme.of(context).cardColor, - // primary: false, - body: SafeArea( - child: WidescreenWrapper(child: GymMode(args)), - ), + return Scaffold( + // backgroundColor: Theme.of(context).cardColor, + // primary: false, + body: SafeArea( + child: WidescreenWrapper(child: GymMode(args)), ), ); } diff --git a/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart b/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart deleted file mode 100644 index cee00d685..000000000 --- a/lib/features/routines/widgets/gym_mode/leave_workout_dialog.dart +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2026 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import 'package:flutter/material.dart'; -import 'package:wger/l10n/generated/app_localizations.dart'; - -/// Asks the user to confirm leaving gym mode with a workout in progress. -/// -/// Returns whether the workout should be left. Dismissing the dialog without -/// choosing (tapping outside, back gesture) keeps the workout, so that a second -/// accidental gesture can't leave it either. -Future confirmLeaveWorkout(BuildContext context) async { - final confirmed = await showDialog( - context: context, - builder: (dialogContext) { - final i18n = AppLocalizations.of(dialogContext); - return AlertDialog( - title: Text(i18n.leaveWorkoutTitle), - content: Text(i18n.leaveWorkoutConfirmation), - actions: [ - TextButton( - key: const ValueKey('keep-training-button'), - child: Text(MaterialLocalizations.of(dialogContext).cancelButtonLabel), - onPressed: () => Navigator.of(dialogContext).pop(false), - ), - TextButton( - key: const ValueKey('leave-workout-button'), - child: Text(i18n.leaveWorkout), - onPressed: () => Navigator.of(dialogContext).pop(true), - ), - ], - ); - }, - ); - - return confirmed ?? false; -} diff --git a/lib/features/routines/widgets/gym_mode/navigation.dart b/lib/features/routines/widgets/gym_mode/navigation.dart index 8c906da3f..bdde77212 100644 --- a/lib/features/routines/widgets/gym_mode/navigation.dart +++ b/lib/features/routines/widgets/gym_mode/navigation.dart @@ -41,10 +41,8 @@ class NavigationHeader extends StatelessWidget { children: [ IconButton( icon: const Icon(Icons.close), - // maybePop instead of pop so that the PopScope guarding gym mode - // gets to ask for confirmation while a workout is in progress onPressed: () { - Navigator.of(context).maybePop(); + Navigator.of(context).pop(); }, ), Expanded( diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index afebaff41..7f1d75eca 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1593,18 +1593,6 @@ "@endWorkout": { "description": "Use the imperative, label on button to finish the current workout in gym mode" }, - "leaveWorkoutTitle": "Leave the workout?", - "@leaveWorkoutTitle": { - "description": "Title of the dialog asking to confirm leaving gym mode while a workout is in progress" - }, - "leaveWorkoutConfirmation": "The workout is still in progress. Sets you already saved are kept.", - "@leaveWorkoutConfirmation": { - "description": "Body of the dialog asking to confirm leaving gym mode while a workout is in progress" - }, - "leaveWorkout": "Leave", - "@leaveWorkout": { - "description": "Use the imperative, label on the button that confirms leaving gym mode while a workout is in progress" - }, "themeMode": "Theme mode", "darkMode": "Always dark mode", "lightMode": "Always light mode", diff --git a/test/features/routines/screens/gym_mode_test.dart b/test/features/routines/screens/gym_mode_test.dart index a45852bdf..bc7ae4bbf 100644 --- a/test/features/routines/screens/gym_mode_test.dart +++ b/test/features/routines/screens/gym_mode_test.dart @@ -561,139 +561,6 @@ void main() { }, semanticsEnabled: false, ); - - /// Puts the preferences gym mode reads on open into a known state - /// - /// Installing a fresh in-memory store in setUp does not isolate the tests in - /// this file from one another, what one test writes is still visible in the - /// next. Both of these decide what is on screen after opening gym mode: a - /// workout left in the middle is continued where it stopped, and the exercise - /// pages setting decides which page follows the start page. - /// - /// This runs through [runAsync] because the notifier does not await its - /// writes, and a pending one uses real timers, which the fake clock of the - /// test binding never fires. - Future resetGymModePrefs(WidgetTester tester) async { - await tester.runAsync(() async { - await Future.delayed(const Duration(milliseconds: 50)); - await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_PROGRESS); - await PreferenceHelper.asyncPref.setBool(PREFS_SHOW_EXERCISES, true); - }); - } - - /// Opens gym mode and advances past the start page, so that a workout counts - /// as in progress - Future enterRunningWorkout(WidgetTester tester) async { - await resetGymModePrefs(tester); - - await tester.pumpWidget(renderGymMode()); - await tester.pumpAndSettle(); - await tester.tap(find.byType(TextButton)); - await tester.pumpAndSettle(); - - expect(find.byType(StartPage), findsOneWidget); - - await tester.tap(find.byIcon(Icons.chevron_right)); - await tester.pumpAndSettle(); - - expect(find.byType(ExerciseOverview), findsOneWidget); - } - - testWidgets( - 'the close button leaves the start page without asking', - (WidgetTester tester) async { - // Nothing has happened yet on the start page, so there is nothing to - // protect and closing stays a single tap. - await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { - await resetGymModePrefs(tester); - - await tester.pumpWidget(renderGymMode()); - await tester.pumpAndSettle(); - await tester.tap(find.byType(TextButton)); - await tester.pumpAndSettle(); - - expect(find.byType(StartPage), findsOneWidget); - - await tester.tap(find.byIcon(Icons.close)); - await tester.pumpAndSettle(); - - expect(find.text('Leave the workout?'), findsNothing); - expect(find.byType(GymModeScreen), findsNothing); - }); - }, - semanticsEnabled: false, - ); - - testWidgets( - 'the close button asks for confirmation during a workout', - (WidgetTester tester) async { - await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { - await enterRunningWorkout(tester); - - await tester.tap(find.byIcon(Icons.close)); - await tester.pumpAndSettle(); - expect(find.text('Leave the workout?'), findsOneWidget); - - // Cancelling keeps the user on the very page they were on - await tester.tap(find.byKey(const ValueKey('keep-training-button'))); - await tester.pumpAndSettle(); - expect(find.text('Leave the workout?'), findsNothing); - expect(find.byType(ExerciseOverview), findsOneWidget); - - // Confirming leaves gym mode - await tester.tap(find.byIcon(Icons.close)); - await tester.pumpAndSettle(); - await tester.tap(find.byKey(const ValueKey('leave-workout-button'))); - await tester.pumpAndSettle(); - expect(find.byType(GymModeScreen), findsNothing); - }); - }, - semanticsEnabled: false, - ); - - testWidgets( - 'the system back gesture asks for confirmation during a workout', - (WidgetTester tester) async { - // This is the accident the guard is really about: the iOS back swipe and - // the Android back gesture both arrive here as a pop request. - await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { - await enterRunningWorkout(tester); - - await tester.binding.handlePopRoute(); - await tester.pumpAndSettle(); - - expect(find.text('Leave the workout?'), findsOneWidget); - expect(find.byType(ExerciseOverview), findsOneWidget); - - await tester.tap(find.byKey(const ValueKey('keep-training-button'))); - await tester.pumpAndSettle(); - expect(find.byType(ExerciseOverview), findsOneWidget); - }); - }, - semanticsEnabled: false, - ); - - testWidgets( - 'dismissing the confirmation keeps the workout', - (WidgetTester tester) async { - // A dialog dismissed without an answer (tap outside) must not be read as - // a confirmation, otherwise a stray tap leaves the workout after all. - await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { - await enterRunningWorkout(tester); - - await tester.tap(find.byIcon(Icons.close)); - await tester.pumpAndSettle(); - expect(find.text('Leave the workout?'), findsOneWidget); - - await tester.tapAt(const Offset(10, 10)); - await tester.pumpAndSettle(); - - expect(find.text('Leave the workout?'), findsNothing); - expect(find.byType(ExerciseOverview), findsOneWidget); - }); - }, - semanticsEnabled: false, - ); } /// A gym state as an interrupted-but-still-valid session leaves it behind: From 0c5dc0186f3658a3093442fa3534a6fe90c0b670 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 20:58:39 +0100 Subject: [PATCH 17/29] Bind the preferences helper to the current platform store A test installing a fresh in-memory store in setUp still read and wrote the store of the first test, so prefs leaked from one test into the next. --- lib/core/shared_preferences.dart | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/core/shared_preferences.dart b/lib/core/shared_preferences.dart index 588e6b46a..13d811fd2 100644 --- a/lib/core/shared_preferences.dart +++ b/lib/core/shared_preferences.dart @@ -11,13 +11,13 @@ import 'package:wger/features/nutrition/models/ingredient_filters.dart'; /// and handles migration from the legacy SharedPreferences to /// SharedPreferencesAsync. class PreferenceHelper { - SharedPreferencesAsync _asyncPref = SharedPreferencesAsync(); - PreferenceHelper._instantiate(); static final PreferenceHelper _instance = PreferenceHelper._instantiate(); - static SharedPreferencesAsync get asyncPref => _instance._asyncPref; + /// Always bound to the current platform store, so a store swapped in by a + /// test isn't shadowed by one an earlier test left behind. + static SharedPreferencesAsync get asyncPref => SharedPreferencesAsync(); static PreferenceHelper get instance => _instance; @@ -35,7 +35,6 @@ class PreferenceHelper { sharedPreferencesAsyncOptions: sharedPreferencesOptions, migrationCompletedKey: 'migrationCompleted', ); - _asyncPref = SharedPreferencesAsync(); } //ingredients filters From e71ec000364994bd42732f3663ac90354b468067 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 21:01:04 +0100 Subject: [PATCH 18/29] Restart the resume window with every new workout --- lib/features/routines/providers/gym_state_notifier.dart | 3 ++- test/features/routines/providers/gym_state_test.dart | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 1d433c8b6..ed06f9931 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -408,8 +408,9 @@ class GymStateNotifier extends _$GymStateNotifier { routine: routine, iteration: iteration, currentPage: initialPage, - // A fresh workout also restarts the elapsed timer + // A fresh workout also restarts the elapsed timer and the resume window workoutStart: shouldReset ? clock.now() : null, + validUntil: shouldReset ? clock.now().add(DEFAULT_DURATION) : null, // An abandoned workout never reaches clear(), so forget its values here lastLoggedValues: shouldReset ? const {} : null, ); diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index baa2d8dac..4aa8b55c6 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -885,6 +885,15 @@ void main() { ); expect(page, 0); + + // The new workout gets its own window, so it can be resumed in turn + notifier.state = notifier.state.copyWith(currentPage: 3); + final resumedPage = withClock( + Clock.fixed(DateTime(2024, 5, 2, 19, 0)), + () => notifier.initData(getTestRoutine(), 1, 1), + ); + + expect(resumedPage, 3); }); }); From 1a69a3b471fa7042916b5e6cc277ae5bebf01ede Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 21:12:02 +0100 Subject: [PATCH 19/29] Keep the progress when reopening gym mode --- .../providers/gym_state_notifier.dart | 40 +++++---- .../routines/widgets/gym_mode/gym_mode.dart | 17 +--- .../routines/providers/gym_state_test.dart | 88 +++++++++---------- 3 files changed, 70 insertions(+), 75 deletions(-) diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index ed06f9931..2f00d6cc6 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -184,20 +184,29 @@ class GymStateNotifier extends _$GymStateNotifier { _logger.finer('Cleared stored workout progress'); } - /// Continues a workout that was interrupted by the app being killed + /// Opens gym mode for a day and returns the page to start on /// - /// Returns the page to continue on, or null when there is nothing to restore. - /// Call this after [initData] and [calculatePages], the restored "done" flags - /// are matched against the pages as they were just calculated. - Future restoreProgress() async { - final stored = await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS); - if (stored == null) { - return null; + /// Continues the workout still in memory as it is, otherwise starts a new one + /// that picks up the progress stored before the app was killed, if any. + Future open(Routine routine, int dayId, int iteration) async { + final resume = _canResume(dayId); + final initialPage = initData(routine, dayId, iteration); + await loadPrefs(); + + if (resume && state.pages.isNotEmpty) { + return initialPage; } - // A workout that is still in memory (the app was not killed, the user only - // left gym mode and came back) is more current than what was stored. - if (state.currentPage != 0) { + calculatePages(); + return await _restoreProgress() ?? initialPage; + } + + /// Applies the stored progress to the freshly calculated pages + /// + /// Returns the page to continue on, or null when there is nothing to restore. + Future _restoreProgress() async { + final stored = await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS); + if (stored == null) { return null; } @@ -389,13 +398,14 @@ class GymStateNotifier extends _$GymStateNotifier { return out.join('\n'); } + /// Whether the workout in memory is the one for [dayId] and still valid + bool _canResume(int dayId) => + state.isInitialized && dayId == state.dayId && !state.validUntil.isBefore(clock.now()); + int initData(Routine routine, int dayId, int iteration) { - final validUntil = state.validUntil; final currentPage = state.currentPage; - final shouldReset = - (!state.isInitialized || state.isInitialized && dayId != state.dayId) || - validUntil.isBefore(clock.now()); + final shouldReset = !_canResume(dayId); if (shouldReset) { _logger.fine('Day ID mismatch or expired validUntil date. Resetting to page 0.'); } diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index c98b96c62..d0a9a0678 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -98,20 +98,9 @@ class _GymModeState extends ConsumerState { fallbackLog: 'Server unreachable, starting from the local routine', ); - final gymViewModel = ref.read(gymStateProvider.notifier); - final initialPage = gymViewModel.initData( - routine, - widget._args.dayId, - widget._args.iteration, - ); - await gymViewModel.loadPrefs(); - gymViewModel.calculatePages(); - - // A workout the OS interrupted (app killed while in the background) - // continues where it stopped, the pages have to be calculated by now - final restoredPage = await gymViewModel.restoreProgress(); - - return restoredPage ?? initialPage; + return ref + .read(gymStateProvider.notifier) + .open(routine, widget._args.dayId, widget._args.iteration); } List _getContent(GymModeState state) { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 4aa8b55c6..99acc4444 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -898,34 +898,50 @@ void main() { }); group('GymStateNotifier workout progress', () { - /// Simulates the app being killed and gym mode being opened again: a new - /// container means a new (empty) notifier, while the stored preferences - /// survive, exactly as on a real restart. - Future restartedNotifier({int dayId = 1, int iteration = 1}) async { - final restartedContainer = ProviderContainer.test(); - final restarted = restartedContainer.read(gymStateProvider.notifier); - restarted.initData(getTestRoutine(), dayId, iteration); - restarted.calculatePages(); + /// Simulates the app being killed: a new container means a new (empty) + /// notifier, while the stored preferences survive, as on a real restart. + GymStateNotifier restartedNotifier() => + ProviderContainer.test().read(gymStateProvider.notifier); - return restarted; - } + Future openDay1(GymStateNotifier gymNotifier) => gymNotifier.open(getTestRoutine(), 1, 1); /// Runs a workout up to [currentPage], with one log page marked as done Future runWorkout({int currentPage = 2}) async { - notifier.initData(getTestRoutine(), 1, 1); - notifier.calculatePages(); + await openDay1(notifier); notifier.markSlotPageAsDone(notifier.state.pages[1].slotPages[1].uuid, isDone: true); notifier.setCurrentPage(currentPage); await pumpEventQueue(); } + /// Changes one field of the stored progress + Future editStoredProgress(String key, Object value) async { + final stored = + json.decode((await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS))!) + as Map; + stored[key] = value; + await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, json.encode(stored)); + } + + test('Continues the workout in memory with its progress', () async { + await runWorkout(); + final doneUuid = notifier.state.pages[1].slotPages[1].uuid; + + // The app kept running, the user only left gym mode and came back + expect(await openDay1(notifier), 2); + expect(notifier.state.pages[1].slotPages[1].uuid, doneUuid); + expect( + notifier.state.pages[1].slotPages[1].logDone, + isTrue, + reason: 'the set that was already logged is still marked as done', + ); + }); + test('Continues an interrupted workout where it stopped', () async { await runWorkout(); - final restarted = await restartedNotifier(); - final restoredPage = await restarted.restoreProgress(); + final restarted = restartedNotifier(); - expect(restoredPage, 2); + expect(await openDay1(restarted), 2); expect(restarted.state.currentPage, 2); expect( restarted.state.pages[1].slotPages[1].logDone, @@ -941,8 +957,8 @@ void main() { // Two minutes later the app is started again await withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 32)), () async { - final restarted = await restartedNotifier(); - await restarted.restoreProgress(); + final restarted = restartedNotifier(); + await openDay1(restarted); expect(restarted.state.workoutStart, DateTime(2026, 7, 26, 18, 30)); }); @@ -950,18 +966,11 @@ void main() { test('Does not continue the workout of another day', () async { await runWorkout(); + await editStoredProgress('dayId', 2); - // Rewrite the stored progress to belong to a different day of the - // routine, the workout that is opened now is not the one that stopped - final stored = - json.decode((await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS))!) - as Map; - stored['dayId'] = 2; - await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, json.encode(stored)); + final restarted = restartedNotifier(); - final restarted = await restartedNotifier(); - - expect(await restarted.restoreProgress(), isNull); + expect(await openDay1(restarted), 0); expect(restarted.state.currentPage, 0); }); @@ -972,9 +981,9 @@ void main() { // The next morning the workout is long over await withClock(Clock.fixed(DateTime(2026, 7, 27, 9, 0)), () async { - final restarted = await restartedNotifier(); + final restarted = restartedNotifier(); - expect(await restarted.restoreProgress(), isNull); + expect(await openDay1(restarted), 0); expect(restarted.state.currentPage, 0); }); }); @@ -984,19 +993,9 @@ void main() { // The routine was edited in the meantime and is now shorter than the // page the workout stopped on - final restarted = await restartedNotifier(); - restarted.state = restarted.state.copyWith(pages: restarted.state.pages.sublist(0, 1)); + await editStoredProgress('currentPage', 999); - expect(await restarted.restoreProgress(), isNull); - }); - - test('Keeps the workout in memory over the stored one', () async { - await runWorkout(); - - // Same notifier, i.e. the app kept running and the user only left gym - // mode and came back. Nothing to restore, the state is already there. - expect(await notifier.restoreProgress(), isNull); - expect(notifier.state.currentPage, 2); + expect(await openDay1(restartedNotifier()), 0); }); test('Forgets the workout once it is finished', () async { @@ -1005,16 +1004,13 @@ void main() { notifier.clear(); await pumpEventQueue(); - final restarted = await restartedNotifier(); - expect(await restarted.restoreProgress(), isNull); + expect(await openDay1(restartedNotifier()), 0); }); test('Ignores stored progress that can not be read', () async { await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, 'not json'); - final restarted = await restartedNotifier(); - - expect(await restarted.restoreProgress(), isNull); + expect(await openDay1(restartedNotifier()), 0); expect( await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS), isNull, From 49616f795ab99d682c72e64e5c89024be02c0431 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 21:44:15 +0100 Subject: [PATCH 20/29] Keep the gym mode progress apart from the pages --- .../routines/models/page_progress.dart | 39 ++++ .../models/page_progress.freezed.dart | 207 ++++++++++++++++++ .../routines/models/workout_progress.dart | 6 +- .../routines/providers/gym_state.dart | 77 +++---- .../providers/gym_state_notifier.dart | 134 ++++++------ .../providers/gym_state_notifier.g.dart | 2 +- .../widgets/gym_mode/exercise_overview.dart | 8 +- .../routines/widgets/gym_mode/gym_mode.dart | 8 +- .../routines/widgets/gym_mode/log_page.dart | 14 +- .../routines/widgets/gym_mode/timer.dart | 31 ++- .../widgets/gym_mode/workout_menu.dart | 60 ++--- .../routines/providers/gym_state_test.dart | 183 ++++++++++++---- .../widgets/gym_mode/log_page_test.dart | 23 +- .../routines/widgets/gym_mode/timer_test.dart | 2 +- .../widgets/gym_mode/workout_menu_test.dart | 4 +- 15 files changed, 564 insertions(+), 234 deletions(-) create mode 100644 lib/features/routines/models/page_progress.dart create mode 100644 lib/features/routines/models/page_progress.freezed.dart diff --git a/lib/features/routines/models/page_progress.dart b/lib/features/routines/models/page_progress.dart new file mode 100644 index 000000000..a67eb3bfd --- /dev/null +++ b/lib/features/routines/models/page_progress.dart @@ -0,0 +1,39 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:wger/features/routines/models/log.dart'; + +part 'page_progress.freezed.dart'; + +/// What happened on one gym mode page during the running workout +@freezed +class PageProgress with _$PageProgress { + /// Whether the set of a log page has been logged + final bool done; + + /// The log saved from a log page, so revisiting the page pre-fills the form + /// and saving updates the row instead of inserting a duplicate + final Log? loggedEntry; + + /// When the rest of a timer page started, so the countdown keeps running + /// while the page is not shown + final DateTime? timerStartedAt; + + const PageProgress({this.done = false, this.loggedEntry, this.timerStartedAt}); +} diff --git a/lib/features/routines/models/page_progress.freezed.dart b/lib/features/routines/models/page_progress.freezed.dart new file mode 100644 index 000000000..d36507462 --- /dev/null +++ b/lib/features/routines/models/page_progress.freezed.dart @@ -0,0 +1,207 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'page_progress.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$PageProgress { + + +/// Create a copy of PageProgress +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$PageProgressCopyWith get copyWith => _$PageProgressCopyWithImpl(this as PageProgress, _$identity); + + + +@override +bool operator ==(Object other) { + final _this = this as PageProgress; + return identical(this, other) || (other.runtimeType == runtimeType&&other is PageProgress&&(identical(other.done, _this.done) || other.done == _this.done)&&(identical(other.loggedEntry, _this.loggedEntry) || other.loggedEntry == _this.loggedEntry)&&(identical(other.timerStartedAt, _this.timerStartedAt) || other.timerStartedAt == _this.timerStartedAt)); +} + + +@override +int get hashCode { + final _this = this as PageProgress; + return Object.hash(runtimeType,_this.done,_this.loggedEntry,_this.timerStartedAt); +} + +@override +String toString() { + final _this = this as PageProgress; + return 'PageProgress(done: ${_this.done}, loggedEntry: ${_this.loggedEntry}, timerStartedAt: ${_this.timerStartedAt})'; +} + + +} + +/// @nodoc +abstract mixin class $PageProgressCopyWith<$Res> { + factory $PageProgressCopyWith(PageProgress value, $Res Function(PageProgress) _then) = _$PageProgressCopyWithImpl; +@useResult +$Res call({ + bool done, Log? loggedEntry, DateTime? timerStartedAt +}); + + + + +} +/// @nodoc +class _$PageProgressCopyWithImpl<$Res> + implements $PageProgressCopyWith<$Res> { + _$PageProgressCopyWithImpl(this._self, this._then); + + final PageProgress _self; + final $Res Function(PageProgress) _then; + +/// Create a copy of PageProgress +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? done = null,Object? loggedEntry = freezed,Object? timerStartedAt = freezed,}) { + return _then(PageProgress( +done: null == done ? _self.done : done // ignore: cast_nullable_to_non_nullable +as bool,loggedEntry: freezed == loggedEntry ? _self.loggedEntry : loggedEntry // ignore: cast_nullable_to_non_nullable +as Log?,timerStartedAt: freezed == timerStartedAt ? _self.timerStartedAt : timerStartedAt // ignore: cast_nullable_to_non_nullable +as DateTime?, + )); +} + +} + + +/// Adds pattern-matching-related methods to [PageProgress]. +extension PageProgressPatterns on PageProgress { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(){ +final _that = this; +switch (_that) { +case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(){ +final _that = this; +switch (_that) { +case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({required TResult orElse(),}) {final _that = this; +switch (_that) { +case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when() {final _that = this; +switch (_that) { +case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull() {final _that = this; +switch (_that) { +case _: + return null; + +} +} + +} + +// dart format on diff --git a/lib/features/routines/models/workout_progress.dart b/lib/features/routines/models/workout_progress.dart index 63c1a5611..002463ff8 100644 --- a/lib/features/routines/models/workout_progress.dart +++ b/lib/features/routines/models/workout_progress.dart @@ -18,10 +18,8 @@ /// The progress through a running workout, as stored in the preferences /// -/// Only the parts that can't be recalculated are kept. The pages themselves are -/// derived from the routine again on the next start, which is also why the -/// finished log pages are referenced by their page index: the UUIDs are -/// generated anew every time the pages are calculated. +/// Only the parts that can't be recalculated are kept, the pages themselves +/// are derived from the routine again on the next start. class WorkoutProgress { final int dayId; final int iteration; diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 710c72bf4..16e82c06f 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -18,10 +18,10 @@ import 'package:clock/clock.dart'; import 'package:material_ui/material_ui.dart'; -import 'package:wger/core/uuid.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; @@ -57,7 +57,8 @@ enum SlotPageType { } class PageEntry { - final String uuid; + /// Identifies the page across recalculations, derived from the routine + final String key; final PageType type; @@ -69,22 +70,21 @@ class PageEntry { PageEntry({ required this.type, required this.pageIndex, + required this.key, this.slotPages = const [], - String? uuid, - }) : uuid = uuid ?? uuidV4(), - assert( + }) : assert( slotPages.isEmpty || type == PageType.set, 'SlotEntries can only be set for set pages', ); PageEntry copyWith({ - String? uuid, + String? key, PageType? type, int? pageIndex, List? slotPages, }) { return PageEntry( - uuid: uuid ?? this.uuid, + key: key ?? this.key, type: type ?? this.type, pageIndex: pageIndex ?? this.pageIndex, slotPages: slotPages ?? this.slotPages, @@ -99,16 +99,13 @@ class PageEntry { return exerciseSet.toList(); } - // Whether all sub-pages (e.g. log pages) are marked as done. - bool get allLogsDone => - slotPages.where((entry) => entry.type == SlotPageType.log).every((entry) => entry.logDone); - @override - String toString() => 'PageEntry(type: $type, pageIndex: $pageIndex)'; + String toString() => 'PageEntry(key: $key, type: $type, pageIndex: $pageIndex)'; } class SlotPageEntry { - final String uuid; + /// Identifies the page across recalculations, derived from the routine + final String key; final SlotPageType type; @@ -118,19 +115,6 @@ class SlotPageEntry { /// Absolute page index final int pageIndex; - /// Whether the log page has been marked as done - final bool logDone; - - /// The log saved from this page during the current workout, if any. Kept - /// so revisiting the page pre-fills the form with the saved values and - /// saving updates the row instead of inserting a duplicate. - final Log? loggedEntry; - - /// When the timer of this page was started. Lives in the state (not the - /// timer widget) so the countdown continues when the user navigates away - /// and back. - final DateTime? timerStartedAt; - /// The associated SetConfigData final SetConfigData? setConfigData; @@ -138,48 +122,37 @@ class SlotPageEntry { required this.type, required this.pageIndex, required this.setIndex, + required this.key, this.setConfigData, - this.logDone = false, - this.loggedEntry, - this.timerStartedAt, - String? uuid, }) : assert( type != SlotPageType.log || setConfigData != null, 'You need to set setConfigData for SlotPageType.log', - ), - uuid = uuid ?? uuidV4(); + ); SlotPageEntry copyWith({ - String? uuid, + String? key, SlotPageType? type, int? exerciseId, int? setIndex, int? pageIndex, SetConfigData? setConfigData, - bool? logDone, - Log? loggedEntry, - DateTime? timerStartedAt, }) { return SlotPageEntry( - uuid: uuid ?? this.uuid, + key: key ?? this.key, type: type ?? this.type, setIndex: setIndex ?? this.setIndex, pageIndex: pageIndex ?? this.pageIndex, setConfigData: setConfigData ?? this.setConfigData, - logDone: logDone ?? this.logDone, - loggedEntry: loggedEntry ?? this.loggedEntry, - timerStartedAt: timerStartedAt ?? this.timerStartedAt, ); } @override String toString() => 'SlotPageEntry(' - 'uuid: $uuid, ' + 'key: $key, ' 'type: $type, ' 'setIndex: $setIndex, ' - 'pageIndex: $pageIndex, ' - 'logDone: $logDone' + 'pageIndex: $pageIndex' ')'; } @@ -214,6 +187,10 @@ class GymModeState { /// pre-fill the log form when [stickySetValues] is enabled. final Map lastLoggedValues; + /// What happened on the pages so far, by page key. Kept apart from the pages + /// so that recalculating them doesn't lose it. + final Map progress; + // Routine data late final int dayId; late final int iteration; @@ -234,6 +211,7 @@ class GymModeState { this.showWorkoutDuration = true, this.stickySetValues = false, this.lastLoggedValues = const {}, + this.progress = const {}, int? dayId, int? iteration, Routine? routine, @@ -280,6 +258,7 @@ class GymModeState { bool? showWorkoutDuration, bool? stickySetValues, Map? lastLoggedValues, + Map? progress, }) { return GymModeState( isInitialized: isInitialized ?? this.isInitialized, @@ -304,9 +283,17 @@ class GymModeState { showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, stickySetValues: stickySetValues ?? this.stickySetValues, lastLoggedValues: lastLoggedValues ?? this.lastLoggedValues, + progress: progress ?? this.progress, ); } + PageProgress progressOf(String key) => progress[key] ?? const PageProgress(); + + /// Whether every set of [page] has been logged + bool allLogsDone(PageEntry page) => page.slotPages + .where((entry) => entry.type == SlotPageType.log) + .every((entry) => progressOf(entry.key).done); + /// The start of the workout as a [TimeOfDay], e.g. for the session form TimeOfDay get startTime => TimeOfDay.fromDateTime(workoutStart); @@ -351,9 +338,9 @@ class GymModeState { return null; } - SlotPageEntry? getSlotPageByUUID(String uuid) { + SlotPageEntry? getSlotPageByKey(String key) { for (final slotPage in pages.expand((p) => p.slotPages)) { - if (slotPage.uuid == uuid) { + if (slotPage.key == key) { return slotPage; } } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 2f00d6cc6..da6216c13 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -27,6 +27,7 @@ import 'package:wger/core/shared_preferences.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/weight_unit.dart'; @@ -147,7 +148,7 @@ class GymStateNotifier extends _$GymStateNotifier { /// Absolute page indices of the log pages already marked as done List get _donePageIndices => state.pages .expand((page) => page.slotPages) - .where((slotPage) => slotPage.logDone) + .where((slotPage) => state.progressOf(slotPage.key).done) .map((slotPage) => slotPage.pageIndex) .toList(); @@ -235,7 +236,12 @@ class GymStateNotifier extends _$GymStateNotifier { currentPage: progress.currentPage, workoutStart: progress.workoutStart, validUntil: progress.validUntil, - pages: _pagesWithLogsDone(progress.donePageIndices), + progress: { + for (final slotPage in state.pages.expand((page) => page.slotPages)) + if (slotPage.type == SlotPageType.log && + progress.donePageIndices.contains(slotPage.pageIndex)) + slotPage.key: const PageProgress(done: true), + }, ); _logger.fine('Restored workout progress on page ${progress.currentPage}'); @@ -243,40 +249,31 @@ class GymStateNotifier extends _$GymStateNotifier { return progress.currentPage; } - /// Copy of the current pages with the log pages in [donePageIndices] done - List _pagesWithLogsDone(List donePageIndices) { - return state.pages.map((page) { - if (page.type != PageType.set) { - return page; - } - - return page.copyWith( - slotPages: page.slotPages.map((slotPage) { - if (slotPage.type != SlotPageType.log) { - return slotPage; - } - - return slotPage.copyWith(logDone: donePageIndices.contains(slotPage.pageIndex)); - }).toList(), - ); - }).toList(); - } - /// Calculates the page entries void calculatePages() { var pageIndex = 0; final List pages = [ // Start page - PageEntry(type: PageType.start, pageIndex: pageIndex), + PageEntry(type: PageType.start, pageIndex: pageIndex, key: 'start'), ]; + // Pages are keyed by a slot entry (a database row) and the number of its + // set. Counted over the whole day, so an entry in two slots can't collide. + final setsPerEntry = {}; + String nextSet(int slotEntryId) => '$slotEntryId:${(setsPerEntry[slotEntryId] ?? 0) + 1}'; + pageIndex++; - for (final slotData in state.dayDataGym.slots) { + for (final (slotIndex, slotData) in state.dayDataGym.slots.indexed) { final slotPageIndex = pageIndex; final slotEntries = []; int setIndex = 0; + final firstConfig = slotData.setConfigs.firstOrNull; + final slotKey = firstConfig == null + ? 'slot:empty$slotIndex' + : 'slot:${nextSet(firstConfig.slotEntryId)}'; + // exercise overview page if (state.showExercisePages) { // Add one overview page per exercise in the slot (e.g. for supersets) @@ -292,6 +289,7 @@ class GymStateNotifier extends _$GymStateNotifier { type: SlotPageType.exerciseOverview, setIndex: setIndex, pageIndex: pageIndex, + key: 'overview:${nextSet(setConfig.slotEntryId)}', setConfigData: setConfig, ), ); @@ -300,12 +298,16 @@ class GymStateNotifier extends _$GymStateNotifier { } for (final config in slotData.setConfigs) { + final setKey = nextSet(config.slotEntryId); + setsPerEntry.update(config.slotEntryId, (nr) => nr + 1, ifAbsent: () => 1); + // Log page slotEntries.add( SlotPageEntry( type: SlotPageType.log, setIndex: setIndex, pageIndex: pageIndex, + key: 'log:$setKey', setConfigData: config, ), ); @@ -319,6 +321,7 @@ class GymStateNotifier extends _$GymStateNotifier { type: SlotPageType.timer, setIndex: setIndex, pageIndex: pageIndex, + key: 'timer:$setKey', setConfigData: config, ), ); @@ -330,14 +333,17 @@ class GymStateNotifier extends _$GymStateNotifier { PageEntry( type: PageType.set, pageIndex: slotPageIndex, + key: slotKey, slotPages: slotEntries, ), ); } // Session and summary page - pages.add(PageEntry(type: PageType.session, pageIndex: pageIndex)); - pages.add(PageEntry(type: PageType.workoutSummary, pageIndex: pageIndex + 1)); + pages.add(PageEntry(type: PageType.session, pageIndex: pageIndex, key: 'session')); + pages.add( + PageEntry(type: PageType.workoutSummary, pageIndex: pageIndex + 1, key: 'summary'), + ); state = state.copyWith(pages: pages); // print(readPageStructure()); @@ -423,6 +429,7 @@ class GymStateNotifier extends _$GymStateNotifier { validUntil: shouldReset ? clock.now().add(DEFAULT_DURATION) : null, // An abandoned workout never reaches clear(), so forget its values here lastLoggedValues: shouldReset ? const {} : null, + progress: shouldReset ? const {} : null, ); // Calculate the pages. @@ -443,7 +450,8 @@ class GymStateNotifier extends _$GymStateNotifier { // Re-visiting a page that was already logged in this workout: seed the // form with the saved entry (keeping its id and session) so saving // updates the row instead of inserting a duplicate. - final loggedEntry = state.getSlotEntryPageByIndex()?.loggedEntry; + final slotPage = state.getSlotEntryPageByIndex(); + final loggedEntry = slotPage == null ? null : state.progressOf(slotPage.key).loggedEntry; if (loggedEntry != null) { ref.read(gymLogProvider.notifier).editLog(loggedEntry); return; @@ -535,45 +543,30 @@ class GymStateNotifier extends _$GymStateNotifier { state = state.copyWith(lastLoggedValues: updated); } - /// Replaces the slot page with [uuid] by [updatedSlotPage] in the state. - void _updateSlotPage(String uuid, SlotPageEntry updatedSlotPage) { - final updatedPages = state.pages.map((page) { - if (page.type != PageType.set) { - return page; - } - - final updatedSlotPages = page.slotPages.map((sp) { - if (sp.uuid == uuid) { - return updatedSlotPage; - } - return sp; - }).toList(); - - return page.copyWith(slotPages: updatedSlotPages); - }).toList(); - - state = state.copyWith(pages: updatedPages); + /// Applies [update] to the progress of the page with [key] + void _updateProgress(String key, PageProgress Function(PageProgress) update) { + state = state.copyWith(progress: {...state.progress, key: update(state.progressOf(key))}); } - /// Starts the timer of the slot page with [uuid], unless it is already + /// Starts the timer of the slot page with [key], unless it is already /// running. /// /// The start time lives in the gym state (not the timer widget) so the /// countdown continues when the page is disposed and re-created while /// navigating, e.g. when going back to correct a logged set during the /// rest period. - void startTimerIfNeeded(String uuid) { - final slotPage = state.getSlotPageByUUID(uuid); + void startTimerIfNeeded(String key) { + final slotPage = state.getSlotPageByKey(key); if (slotPage == null) { - _logger.warning('No slot page found for UUID $uuid'); + _logger.warning('No slot page found for key $key'); return; } - if (slotPage.timerStartedAt != null) { + if (state.progressOf(key).timerStartedAt != null) { return; } - _updateSlotPage(uuid, slotPage.copyWith(timerStartedAt: clock.now())); - _logger.fine('Started timer for slot page UUID $uuid'); + _updateProgress(key, (p) => p.copyWith(timerStartedAt: clock.now())); + _logger.fine('Started timer for slot page $key'); } /// [log] is the entry saved from this page during the current workout. It @@ -583,28 +576,33 @@ class GymStateNotifier extends _$GymStateNotifier { /// /// Saving a new entry, unlike correcting one, also (re)starts the rest timer /// that follows the set. - void markSlotPageAsDone(String uuid, {required bool isDone, Log? log}) { - final slotPage = state.getSlotPageByUUID(uuid); + void markSlotPageAsDone(String key, {required bool isDone, Log? log}) { + final slotPage = state.getSlotPageByKey(key); if (slotPage == null) { - _logger.warning('No slot page found for UUID $uuid'); + _logger.warning('No slot page found for key $key'); return; } + final previousEntry = state.progressOf(key).loggedEntry; + // A copy, so later edits in the form don't change the saved entry - _updateSlotPage(uuid, slotPage.copyWith(logDone: isDone, loggedEntry: log?.copyWith())); + _updateProgress( + key, + (p) => p.copyWith(done: isDone, loggedEntry: log?.copyWith() ?? p.loggedEntry), + ); _saveProgress(); - _logger.fine('Set logDone=$isDone for slot page UUID $uuid'); + _logger.fine('Set done=$isDone for slot page $key'); // Scrolling past the timer (e.g. "jump to") already started it final timerPage = state.getSlotEntryPageByIndex(slotPage.pageIndex + 1); - final isNewEntry = slotPage.loggedEntry?.id != log?.id; + final isNewEntry = previousEntry?.id != log?.id; if (isNewEntry && timerPage?.type == SlotPageType.timer) { - _updateSlotPage(timerPage!.uuid, timerPage.copyWith(timerStartedAt: clock.now())); + _updateProgress(timerPage!.key, (p) => p.copyWith(timerStartedAt: clock.now())); } } void replaceExercises( - String pageEntryUUID, { + String pageEntryKey, { required int originalExerciseId, required Exercise newExercise, }) { @@ -613,7 +611,7 @@ class GymStateNotifier extends _$GymStateNotifier { return page; } - if (page.uuid != pageEntryUUID) { + if (page.key != pageEntryKey) { return page; } @@ -642,7 +640,7 @@ class GymStateNotifier extends _$GymStateNotifier { } void addExerciseAfterPage( - String pageEntryUUID, { + String pageEntryKey, { required Exercise newExercise, }) { // Ad-hoc set configs bypass routine hydration, so resolve the profile @@ -653,11 +651,14 @@ class GymStateNotifier extends _$GymStateNotifier { final defaultWeightUnitId = profile?.defaultWeightUnitId ?? WEIGHT_UNIT_KG; final defaultWeightUnit = weightUnits.firstWhereOrNull((u) => u.id == defaultWeightUnitId); + // Not part of the routine, so numbered in the order they were added + final addedKey = 'added:${state.pages.where((p) => p.key.startsWith('added:')).length + 1}'; + final List pages = []; for (final page in state.pages) { pages.add(page); - if (page.uuid == pageEntryUUID) { + if (page.key == pageEntryKey) { final setConfigData = page.slotPages.first.setConfigData!; final List newSlotPages = []; @@ -667,6 +668,7 @@ class GymStateNotifier extends _$GymStateNotifier { type: SlotPageType.log, pageIndex: 1, setIndex: 0, + key: '$addedKey:log:$i', setConfigData: SetConfigData( textRepr: '-/-', exerciseId: newExercise.id, @@ -678,7 +680,12 @@ class GymStateNotifier extends _$GymStateNotifier { ); } - final newPage = PageEntry(type: PageType.set, pageIndex: 1, slotPages: newSlotPages); + final newPage = PageEntry( + type: PageType.set, + pageIndex: 1, + key: addedKey, + slotPages: newSlotPages, + ); pages.add(newPage); } @@ -705,6 +712,7 @@ class GymStateNotifier extends _$GymStateNotifier { pages: [], currentPage: 0, lastLoggedValues: const {}, + progress: const {}, validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 691ca7d7f..dbc5009fa 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'be5943c4201793dc053ef44a4a243226e6d38526'; +String _$gymStateNotifierHash() => r'da56aac7af47067aad83c59123d06162583f018b'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/lib/features/routines/widgets/gym_mode/exercise_overview.dart b/lib/features/routines/widgets/gym_mode/exercise_overview.dart index 1d041bed3..5ab829700 100644 --- a/lib/features/routines/widgets/gym_mode/exercise_overview.dart +++ b/lib/features/routines/widgets/gym_mode/exercise_overview.dart @@ -28,17 +28,17 @@ class ExerciseOverview extends ConsumerWidget { /// Identifies which slot page this widget renders, so it shows its own /// content instead of whatever the globally-current page happens to be. - final String slotUuid; + final String slotKey; - ExerciseOverview(this._controller, this.slotUuid); + ExerciseOverview(this._controller, this.slotKey); @override Widget build(BuildContext context, WidgetRef ref) { - final page = ref.watch(gymStateProvider).getSlotPageByUUID(slotUuid); + final page = ref.watch(gymStateProvider).getSlotPageByKey(slotKey); if (page == null) { _logger.info( - 'getSlotPageByUUID for $slotUuid returned null, showing empty container.', + 'getSlotPageByKey for $slotKey returned null, showing empty container.', ); return Container(); } diff --git a/lib/features/routines/widgets/gym_mode/gym_mode.dart b/lib/features/routines/widgets/gym_mode/gym_mode.dart index d0a9a0678..653474649 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -114,11 +114,11 @@ class _GymModeState extends ConsumerState { for (final page in state.pages) { for (final slotPage in page.slotPages) { if (slotPage.type == SlotPageType.exerciseOverview) { - out.add(ExerciseOverview(_controller, slotPage.uuid)); + out.add(ExerciseOverview(_controller, slotPage.key)); } if (slotPage.type == SlotPageType.log) { - out.add(LogPage(_controller, slotPage.uuid)); + out.add(LogPage(_controller, slotPage.key)); } // Timer. Use rest time from config data if available, otherwise use user settings @@ -129,9 +129,9 @@ class _GymModeState extends ConsumerState { ? TimerCountdownWidget( _controller, (rest ?? gymState.countdownDuration.inSeconds).toInt(), - slotPage.uuid, + slotPage.key, ) - : TimerWidget(_controller, slotPage.uuid), + : TimerWidget(_controller, slotPage.key), ); } } diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index 45509c798..f7d70ea8a 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -48,9 +48,9 @@ class LogPage extends ConsumerWidget { /// Identifies which slot page this widget renders, so it shows its own /// content instead of whatever the globally-current page happens to be. - final String slotUuid; + final String slotKey; - LogPage(this._controller, this.slotUuid); + LogPage(this._controller, this.slotKey); @override Widget build(BuildContext context, WidgetRef ref) { @@ -58,9 +58,9 @@ class LogPage extends ConsumerWidget { final gymState = ref.watch(gymStateProvider); final languageCode = Localizations.localeOf(context).languageCode; - final slotEntryPage = gymState.getSlotPageByUUID(slotUuid); + final slotEntryPage = gymState.getSlotPageByKey(slotKey); if (slotEntryPage == null) { - _logger.info('getSlotPageByUUID for $slotUuid returned null, showing empty container.'); + _logger.info('getSlotPageByKey for $slotKey returned null, showing empty container.'); return Container(); } @@ -85,7 +85,7 @@ class LogPage extends ConsumerWidget { ); // Mark done sets - final decorationStyle = slotEntryPage.logDone + final decorationStyle = gymState.progressOf(slotEntryPage.key).done ? TextDecoration.lineThrough : TextDecoration.none; @@ -154,7 +154,7 @@ class LogPage extends ConsumerWidget { child: LogFormWidget( controller: _controller, configData: setConfigData, - key: ValueKey('log-form-${slotEntryPage.uuid}'), + key: ValueKey('log-form-${slotEntryPage.key}'), ), ), ), @@ -413,7 +413,7 @@ class _LogFormWidgetState extends ConsumerState { return; } - gymProvider.markSlotPageAsDone(page.uuid, isDone: true, log: log); + gymProvider.markSlotPageAsDone(page.key, isDone: true, log: log); // Correcting an earlier set must not replace a later set's values final lastLogged = gymState.lastLoggedValues[log.exerciseId]; diff --git a/lib/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index 438b590b2..f647a3332 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -33,9 +33,9 @@ class TimerWidget extends ConsumerStatefulWidget { /// Identifies which slot page this widget renders, so it shows its own /// up-next information instead of whatever the globally-current page /// happens to be. - final String slotUuid; + final String slotKey; - const TimerWidget(this._controller, this.slotUuid); + const TimerWidget(this._controller, this.slotKey); @override _TimerWidgetState createState() => _TimerWidgetState(); @@ -54,7 +54,7 @@ class _TimerWidgetState extends ConsumerState { // provider can't be modified during the widget life-cycle. WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { - ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotKey); } }); @@ -74,10 +74,7 @@ class _TimerWidgetState extends ConsumerState { @override Widget build(BuildContext context) { - final startTime = ref - .watch(gymStateProvider) - .getSlotPageByUUID(widget.slotUuid) - ?.timerStartedAt; + final startTime = ref.watch(gymStateProvider).progressOf(widget.slotKey).timerStartedAt; final elapsed = clock.now().difference(startTime ?? clock.now()).inSeconds; final displaySeconds = elapsed > _maxSeconds ? _maxSeconds : elapsed; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: displaySeconds)); @@ -99,7 +96,7 @@ class _TimerWidgetState extends ConsumerState { ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), ), const SizedBox(height: 16), - UpNextWidget(widget.slotUuid), + UpNextWidget(widget.slotKey), ], ), ), @@ -116,12 +113,12 @@ class TimerCountdownWidget extends ConsumerStatefulWidget { /// Identifies which slot page this widget renders, so it shows its own /// up-next information instead of whatever the globally-current page /// happens to be. - final String slotUuid; + final String slotKey; const TimerCountdownWidget( this._controller, this._seconds, - this.slotUuid, + this.slotKey, ); @override @@ -137,7 +134,7 @@ class _TimerCountdownWidgetState extends ConsumerState { /// the countdown continues when the page is disposed and re-created while /// navigating; until the state is updated, fall back to starting now. DateTime _endTime(GymModeState gymState) { - final startedAt = gymState.getSlotPageByUUID(widget.slotUuid)?.timerStartedAt; + final startedAt = gymState.progressOf(widget.slotKey).timerStartedAt; return (startedAt ?? clock.now()).add(Duration(seconds: widget._seconds)); } @@ -153,7 +150,7 @@ class _TimerCountdownWidgetState extends ConsumerState { // life-cycle. WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { - ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotUuid); + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotKey); } }); @@ -208,7 +205,7 @@ class _TimerCountdownWidgetState extends ConsumerState { ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), ), const SizedBox(height: 16), - UpNextWidget(widget.slotUuid), + UpNextWidget(widget.slotKey), ], ), ), @@ -219,20 +216,20 @@ class _TimerCountdownWidgetState extends ConsumerState { } /// Shows the set that will be performed once the rest timer on the slot page -/// identified by [slotUuid] ends. This can be the next set of the same +/// identified by [slotKey] ends. This can be the next set of the same /// exercise (e.g. when progressing weights within an exercise) or the first /// set of the next exercise. Renders nothing for the last rest of the day. class UpNextWidget extends ConsumerWidget { - final String slotUuid; + final String slotKey; - const UpNextWidget(this.slotUuid, {super.key}); + const UpNextWidget(this.slotKey, {super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final gymState = ref.watch(gymStateProvider); - final currentSlotPage = gymState.getSlotPageByUUID(slotUuid); + final currentSlotPage = gymState.getSlotPageByKey(slotKey); final nextSlotPage = currentSlotPage == null ? null : gymState.getNextLogPage(currentSlotPage.pageIndex); diff --git a/lib/features/routines/widgets/gym_mode/workout_menu.dart b/lib/features/routines/widgets/gym_mode/workout_menu.dart index 0d64f36e7..0d3448f55 100644 --- a/lib/features/routines/widgets/gym_mode/workout_menu.dart +++ b/lib/features/routines/widgets/gym_mode/workout_menu.dart @@ -72,7 +72,7 @@ class NavigationTab extends ConsumerWidget { children: [ ...state.pages.where((pageEntry) => pageEntry.type == PageType.set).map((page) { return ListTile( - leading: page.allLogsDone ? const Icon(Icons.check) : null, + leading: state.allLogsDone(page) ? const Icon(Icons.check) : null, title: Text( page.exercises .map( @@ -83,7 +83,9 @@ class NavigationTab extends ConsumerWidget { .toList() .join('\n'), style: TextStyle( - decoration: page.allLogsDone ? TextDecoration.lineThrough : TextDecoration.none, + decoration: state.allLogsDone(page) + ? TextDecoration.lineThrough + : TextDecoration.none, ), ), trailing: const Icon(Icons.chevron_right), @@ -131,7 +133,7 @@ class _ProgressionTabState extends ConsumerState { children: [ ...state.pages.where((page) => page.type == PageType.set).map((page) { if (page.exercises.isEmpty) { - widget._logger.warning('Page ${page.uuid} has no exercises, skipping'); + widget._logger.warning('Page ${page.key} has no exercises, skipping'); return Container(); } @@ -170,12 +172,12 @@ class _ProgressionTabState extends ConsumerState { } // Sets that are done are marked with a strikethrough - final decoration = slotPage.logDone + final decoration = state.progressOf(slotPage.key).done ? TextDecoration.lineThrough : TextDecoration.none; // Sets that are done have a lighter color - final color = slotPage.logDone + final color = state.progressOf(slotPage.key).done ? theme.colorScheme.onSurface.withValues(alpha: 0.6) : null; @@ -185,7 +187,7 @@ class _ProgressionTabState extends ConsumerState { : null; IconData icon = Icons.circle_outlined; - if (slotPage.logDone) { + if (state.progressOf(slotPage.key).done) { icon = Icons.check_circle_rounded; } else if (state.currentPage == slotPage.pageIndex) { icon = Icons.play_circle_fill; @@ -213,45 +215,45 @@ class _ProgressionTabState extends ConsumerState { //mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - onPressed: page.allLogsDone + onPressed: state.allLogsDone(page) ? null : () { - if (showSwapWidgetToPage == page.uuid) { + if (showSwapWidgetToPage == page.key) { setState(() { showSwapWidgetToPage = null; }); } else { setState(() { - showSwapWidgetToPage = page.uuid; + showSwapWidgetToPage = page.key; showAddExerciseWidgetToPage = null; }); } }, icon: Icon( - key: ValueKey('swap-icon-${page.uuid}'), - showSwapWidgetToPage == page.uuid + key: ValueKey('swap-icon-${page.key}'), + showSwapWidgetToPage == page.key ? Icons.change_circle : Icons.change_circle_outlined, ), ), IconButton( - onPressed: page.allLogsDone + onPressed: state.allLogsDone(page) ? null : () { - if (showAddExerciseWidgetToPage == page.uuid) { + if (showAddExerciseWidgetToPage == page.key) { setState(() { showAddExerciseWidgetToPage = null; }); } else { setState(() { - showAddExerciseWidgetToPage = page.uuid; + showAddExerciseWidgetToPage = page.key; showSwapWidgetToPage = null; }); } }, icon: Icon( - key: ValueKey('add-icon-${page.uuid}'), - showAddExerciseWidgetToPage == page.uuid ? Icons.add_circle : Icons.add, + key: ValueKey('add-icon-${page.key}'), + showAddExerciseWidgetToPage == page.key ? Icons.add_circle : Icons.add, ), ), Expanded(child: Container()), @@ -268,18 +270,18 @@ class _ProgressionTabState extends ConsumerState { ), ], ), - if (showSwapWidgetToPage == page.uuid) + if (showSwapWidgetToPage == page.key) ExerciseSwapWidget( - page.uuid, + page.key, onDone: () { setState(() { showSwapWidgetToPage = null; }); }, ), - if (showAddExerciseWidgetToPage == page.uuid) + if (showAddExerciseWidgetToPage == page.key) ExerciseAddWidget( - page.uuid, + page.key, onDone: () { setState(() { showAddExerciseWidgetToPage = null; @@ -309,16 +311,16 @@ class _ProgressionTabState extends ConsumerState { class ExerciseSwapWidget extends ConsumerWidget { final _logger = Logger('ExerciseSwapWidget'); - final String pageUUID; + final String pageKey; final VoidCallback? onDone; - ExerciseSwapWidget(this.pageUUID, {this.onDone, super.key}); + ExerciseSwapWidget(this.pageKey, {this.onDone, super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final state = ref.watch(gymStateProvider); final gymProvider = ref.read(gymStateProvider.notifier); - final page = state.pages.firstWhere((p) => p.uuid == pageUUID); + final page = state.pages.firstWhere((p) => p.key == pageKey); return Padding( padding: const EdgeInsets.symmetric(vertical: 10), @@ -339,7 +341,7 @@ class ExerciseSwapWidget extends ConsumerWidget { ExerciseAutocompleter( onExerciseSelected: (exercise) { gymProvider.replaceExercises( - page.uuid, + page.key, originalExerciseId: e.id, newExercise: exercise, ); @@ -362,16 +364,16 @@ class ExerciseSwapWidget extends ConsumerWidget { class ExerciseAddWidget extends ConsumerWidget { final _logger = Logger('ExerciseAddWidget'); - final String pageUUID; + final String pageKey; final VoidCallback? onDone; - ExerciseAddWidget(this.pageUUID, {this.onDone, super.key}); + ExerciseAddWidget(this.pageKey, {this.onDone, super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final state = ref.watch(gymStateProvider); final gymProvider = ref.read(gymStateProvider.notifier); - final page = state.pages.firstWhere((p) => p.uuid == pageUUID); + final page = state.pages.firstWhere((p) => p.key == pageKey); return Padding( padding: const EdgeInsets.symmetric(vertical: 10), @@ -383,11 +385,11 @@ class ExerciseAddWidget extends ConsumerWidget { ExerciseAutocompleter( onExerciseSelected: (exercise) { gymProvider.addExerciseAfterPage( - page.uuid, + page.key, newExercise: exercise, ); onDone?.call(); - _logger.fine('Added exercise ${exercise.id} after page $pageUUID'); + _logger.fine('Added exercise ${exercise.id} after page $pageKey'); }, ), const Icon(Icons.arrow_downward), diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 99acc4444..b8526a106 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -33,6 +33,7 @@ import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/slot_data.dart'; @@ -71,21 +72,23 @@ void main() { final slotPage = notifier.state.pages[1].slotPages[1]; expect(slotPage.type, SlotPageType.log); expect( - notifier.state.pages.every((p) => p.slotPages.every((s) => !s.logDone)), + notifier.state.pages.every( + (p) => p.slotPages.every((s) => !notifier.state.progressOf(s.key).done), + ), true, reason: 'All slot pages are initially not done', ); // Act - notifier.markSlotPageAsDone(slotPage.uuid, isDone: true); + notifier.markSlotPageAsDone(slotPage.key, isDone: true); // Assert for (final page in notifier.state.pages.where((p) => p.type == PageType.set)) { for (final slot in page.slotPages.where((s) => s.type == SlotPageType.log)) { - if (slot.uuid == slotPage.uuid) { - expect(slot.logDone, true); + if (slot.key == slotPage.key) { + expect(notifier.state.progressOf(slot.key).done, true); } else { - expect(slot.logDone, false); + expect(notifier.state.progressOf(slot.key).done, false); } } } @@ -99,10 +102,10 @@ void main() { ..id = 'log-1'; // Act - notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + notifier.markSlotPageAsDone(slotPage.key, isDone: true, log: log); // Assert - final loggedEntry = notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry!; + final loggedEntry = notifier.state.progressOf(slotPage.key).loggedEntry!; expect(loggedEntry.id, 'log-1'); expect(loggedEntry, isNot(same(log))); }); @@ -116,7 +119,7 @@ void main() { final log = Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) ..id = 'log-1' ..sessionId = 'session-1'; - notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + notifier.markSlotPageAsDone(slotPage.key, isDone: true, log: log); // Act notifier.setCurrentPage(slotPage.pageIndex); @@ -144,7 +147,7 @@ void main() { final log = Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) ..id = 'log-1' ..repetitions = 99; - notifier.markSlotPageAsDone(slotPage.uuid, isDone: true, log: log); + notifier.markSlotPageAsDone(slotPage.key, isDone: true, log: log); notifier.setCurrentPage(slotPage.pageIndex); expect(container.read(gymLogProvider)!.id, 'log-1'); @@ -155,7 +158,7 @@ void main() { final gymLog = container.read(gymLogProvider)!; expect(gymLog.id, isNull); expect(gymLog.repetitions, slotPage.setConfigData!.repetitions); - expect(notifier.state.getSlotPageByUUID(slotPage.uuid)!.loggedEntry!.id, 'log-1'); + expect(notifier.state.progressOf(slotPage.key).loggedEntry!.id, 'log-1'); }); }); @@ -167,23 +170,23 @@ void main() { // Act withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { - notifier.startTimerIfNeeded(timerPage.uuid); + notifier.startTimerIfNeeded(timerPage.key); }); // Assert expect( - notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + notifier.state.progressOf(timerPage.key).timerStartedAt, DateTime(2024, 5, 2, 12), ); // Act: starting again does not restart the timer withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 5)), () { - notifier.startTimerIfNeeded(timerPage.uuid); + notifier.startTimerIfNeeded(timerPage.key); }); // Assert expect( - notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + notifier.state.progressOf(timerPage.key).timerStartedAt, DateTime(2024, 5, 2, 12), ); }); @@ -195,7 +198,7 @@ void main() { expect(logPage.type, SlotPageType.log); expect(timerPage.type, SlotPageType.timer); withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { - notifier.startTimerIfNeeded(timerPage.uuid); + notifier.startTimerIfNeeded(timerPage.key); }); // The id is minted by the insert final log = Log.fromSetConfigData(logPage.setConfigData!, routineId: 1, iteration: 1) @@ -203,35 +206,35 @@ void main() { // Act: the set is saved withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 10)), () { - notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: log); + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); }); // Assert expect( - notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + notifier.state.progressOf(timerPage.key).timerStartedAt, DateTime(2024, 5, 2, 12, 10), ); // Act: correcting the saved set keeps the running timer withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 11)), () { - notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: log); + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); }); // Assert expect( - notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + notifier.state.progressOf(timerPage.key).timerStartedAt, DateTime(2024, 5, 2, 12, 10), ); // Act: another set is logged on the same page ("add set") final extraLog = log.copyWith(id: 'log-2'); withClock(Clock.fixed(DateTime(2024, 5, 2, 12, 15)), () { - notifier.markSlotPageAsDone(logPage.uuid, isDone: true, log: extraLog); + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: extraLog); }); // Assert expect( - notifier.state.getSlotPageByUUID(timerPage.uuid)!.timerStartedAt, + notifier.state.progressOf(timerPage.key).timerStartedAt, DateTime(2024, 5, 2, 12, 15), ); }); @@ -245,36 +248,36 @@ void main() { PageEntry( type: PageType.set, pageIndex: 1111, - uuid: 'new-page-1', + key: 'new-page-1', ), PageEntry( type: PageType.set, pageIndex: 9, - uuid: 'new-page-2', + key: 'new-page-2', ), ...notifier.state.pages.sublist(2), PageEntry( type: PageType.set, pageIndex: 0, - uuid: 'new-page-3', + key: 'new-page-3', slotPages: [ SlotPageEntry( type: SlotPageType.timer, pageIndex: 10, setIndex: 9, - uuid: 'new-slot-1', + key: 'new-slot-1', ), SlotPageEntry( type: SlotPageType.timer, pageIndex: 10, setIndex: 6, - uuid: 'new-slot-2', + key: 'new-slot-2', ), SlotPageEntry( type: SlotPageType.timer, pageIndex: 100, setIndex: 100, - uuid: 'new-slot-3', + key: 'new-slot-3', ), ], ), @@ -300,17 +303,17 @@ void main() { expect(pages[7].pageIndex, 17); // Preserve the order of new pages - expect(pages[7].uuid, 'new-page-3'); + expect(pages[7].key, 'new-page-3'); // Slot pages have correct indices, the original order is preserved final slotPages = pages[7].slotPages; - expect(slotPages[0].uuid, 'new-slot-1'); + expect(slotPages[0].key, 'new-slot-1'); expect(slotPages[0].pageIndex, 17); expect(slotPages[0].setIndex, 0); - expect(slotPages[1].uuid, 'new-slot-2'); + expect(slotPages[1].key, 'new-slot-2'); expect(slotPages[1].pageIndex, 18); expect(slotPages[1].setIndex, 1); - expect(slotPages[2].uuid, 'new-slot-3'); + expect(slotPages[2].key, 'new-slot-3'); expect(slotPages[2].pageIndex, 19); expect(slotPages[2].setIndex, 2); }); @@ -329,7 +332,7 @@ void main() { ); // Act - notifier.replaceExercises(page.uuid, originalExerciseId: 1, newExercise: testSquats); + notifier.replaceExercises(page.key, originalExerciseId: 1, newExercise: testSquats); // Assert: every slot page of that page carries the new exercise, and the // routine itself was rebuilt too (the log draft reads from it) @@ -384,17 +387,27 @@ void main() { imperialNotifier.calculatePages(); final setPage = imperialNotifier.state.pages.firstWhere((p) => p.type == PageType.set); - imperialNotifier.addExerciseAfterPage(setPage.uuid, newExercise: testSquats); + imperialNotifier.addExerciseAfterPage(setPage.key, newExercise: testSquats); - // recalculateIndices copies the page objects, so look the page up by uuid. + // recalculateIndices copies the page objects, so look the page up by key. final pages = imperialNotifier.state.pages; - final newPage = pages[pages.indexWhere((p) => p.uuid == setPage.uuid) + 1]; + final newPage = pages[pages.indexWhere((p) => p.key == setPage.key) + 1]; expect(newPage.slotPages, isNotEmpty); for (final slotPage in newPage.slotPages) { // testWeightUnit2 has id 2 == WEIGHT_UNIT_LB. expect(slotPage.setConfigData!.weightUnit, testWeightUnit2); expect(slotPage.setConfigData!.weightUnitId, isNull); } + + // The ad-hoc sets borrow the slot entry of the page they follow, so + // their keys must not be derived from it + expect(newPage.key, 'added:1'); + expect(newPage.slotPages.map((p) => p.key), [ + 'added:1:log:1', + 'added:1:log:2', + 'added:1:log:3', + 'added:1:log:4', + ]); }); }); @@ -505,9 +518,82 @@ void main() { ); expect(slotPages.where((p) => p.type == SlotPageType.log), hasLength(1)); }); + + test('numbers the sets of each exercise on its own', () { + final exercises = getTestExercises(); + notifier.state = notifier.state.copyWith( + showExercisePages: false, + showTimerPages: true, + dayId: 1, + iteration: 1, + routine: supersetRoutine( + [1, 2], + setConfigs: [ + configFor(1, exercises[0]), + configFor(2, exercises[1]), + configFor(1, exercises[0]), + configFor(2, exercises[1]), + ], + ), + ); + + notifier.calculatePages(); + + expect(notifier.state.pages[1].slotPages.map((p) => p.key), [ + 'log:1:1', + 'timer:1:1', + 'log:2:1', + 'timer:2:1', + 'log:1:2', + 'timer:1:2', + 'log:2:2', + 'timer:2:2', + ]); + }); }); group('GymStateNotifier.calculatePages', () { + test('Keeps the progress when the layout changes mid-workout', () { + final logPage = notifier.state.pages[1].slotPages[1]; + final timerPage = notifier.state.pages[1].slotPages[2]; + final log = Log(id: 'log-1', exerciseId: 1, date: DateTime(2026, 7, 26)); + withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () { + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); + }); + + notifier.state = notifier.state.copyWith(showExercisePages: false); + notifier.calculatePages(); + + expect(notifier.state.pages[1].slotPages.first.key, logPage.key); + final progress = notifier.state.progressOf(logPage.key); + expect(progress.done, isTrue); + expect(progress.loggedEntry!.id, 'log-1'); + expect( + notifier.state.progressOf(timerPage.key).timerStartedAt, + DateTime(2026, 7, 26, 18, 30), + ); + }); + + test('Keeps the keys of the set pages when the layout changes', () { + List logKeys() => [ + for (final slotPage in notifier.state.pages.expand((p) => p.slotPages)) + if (slotPage.type == SlotPageType.log) slotPage.key, + ]; + + notifier.state = notifier.state.copyWith(showExercisePages: true, showTimerPages: true); + notifier.calculatePages(); + final allKeys = [ + for (final page in notifier.state.pages) ...[page.key, ...page.slotPages.map((p) => p.key)], + ]; + final keysWithAllPages = logKeys(); + + notifier.state = notifier.state.copyWith(showExercisePages: false, showTimerPages: false); + notifier.calculatePages(); + + expect(logKeys(), keysWithAllPages); + expect(allKeys.toSet(), hasLength(allKeys.length), reason: 'every page has its own key'); + }); + test( 'Correctly generates pages - exercise and timer', () { @@ -801,9 +887,12 @@ void main() { }); group('GymStateNotifier.clear', () { - test('Resets the workout start time', () { + test('Resets the workout start time and the progress', () { // Arrange - notifier.state = notifier.state.copyWith(workoutStart: DateTime(2024, 5, 1, 10, 0)); + notifier.state = notifier.state.copyWith( + workoutStart: DateTime(2024, 5, 1, 10, 0), + progress: {'log:1:1': const PageProgress(done: true)}, + ); // Act withClock(Clock.fixed(DateTime(2024, 5, 2, 9, 15)), () { @@ -812,6 +901,7 @@ void main() { // Assert expect(notifier.state.workoutStart, DateTime(2024, 5, 2, 9, 15)); + expect(notifier.state.progress, isEmpty); }); }); @@ -863,10 +953,12 @@ void main() { isInitialized: true, dayId: 1, currentPage: 4, + progress: {'log:1:1': const PageProgress(done: true)}, ); expect(notifier.initData(getTestRoutine(), 2, 1), 0); expect(notifier.state.dayId, 2); + expect(notifier.state.progress, isEmpty, reason: 'the new workout starts without progress'); }); test('An expired validUntil resets even on the same day', () { @@ -908,7 +1000,7 @@ void main() { /// Runs a workout up to [currentPage], with one log page marked as done Future runWorkout({int currentPage = 2}) async { await openDay1(notifier); - notifier.markSlotPageAsDone(notifier.state.pages[1].slotPages[1].uuid, isDone: true); + notifier.markSlotPageAsDone(notifier.state.pages[1].slotPages[1].key, isDone: true); notifier.setCurrentPage(currentPage); await pumpEventQueue(); } @@ -924,16 +1016,23 @@ void main() { test('Continues the workout in memory with its progress', () async { await runWorkout(); - final doneUuid = notifier.state.pages[1].slotPages[1].uuid; + final timerKey = notifier.state.pages[1].slotPages[2].key; + withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () { + notifier.startTimerIfNeeded(timerKey); + }); // The app kept running, the user only left gym mode and came back expect(await openDay1(notifier), 2); - expect(notifier.state.pages[1].slotPages[1].uuid, doneUuid); expect( - notifier.state.pages[1].slotPages[1].logDone, + notifier.state.progressOf(notifier.state.pages[1].slotPages[1].key).done, isTrue, reason: 'the set that was already logged is still marked as done', ); + expect( + notifier.state.progressOf(timerKey).timerStartedAt, + DateTime(2026, 7, 26, 18, 30), + reason: 'the rest timer is not part of the stored progress, only of the one in memory', + ); }); test('Continues an interrupted workout where it stopped', () async { @@ -944,7 +1043,7 @@ void main() { expect(await openDay1(restarted), 2); expect(restarted.state.currentPage, 2); expect( - restarted.state.pages[1].slotPages[1].logDone, + restarted.state.progressOf(restarted.state.pages[1].slotPages[1].key).done, isTrue, reason: 'the set that was already logged is still marked as done', ); diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index 925821d2e..eaa41adc6 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -109,9 +109,9 @@ void main() { } Future pumpLogPage(WidgetTester tester) async { - // The widget resolves its own slot now, so hand it the uuid of the slot + // The widget resolves its own slot now, so hand it the key of the slot // the gym state was seeded on (via setCurrentPage above). - final slotUuid = container.read(gymStateProvider).getSlotEntryPageByIndex()!.uuid; + final slotKey = container.read(gymStateProvider).getSlotEntryPageByIndex()!.key; await tester.pumpWidget( UncontrolledProviderScope( container: container, @@ -126,7 +126,7 @@ void main() { final controller = PageController(); return PageView( controller: controller, - children: [LogPage(controller, slotUuid)], + children: [LogPage(controller, slotKey)], ); }, ), @@ -434,8 +434,8 @@ void main() { expect((added[1] as Log).id, 'log-2'); expect((added[1] as Log).repetitions, 10); verifyNever(mockWorkoutLogRepo.updateLocalDrift(any)); - final page = container.read(gymStateProvider).getSlotEntryPageByIndex(2)!; - expect(page.loggedEntry!.id, 'log-2'); + final state = container.read(gymStateProvider); + expect(state.progressOf(state.getSlotEntryPageByIndex(2)!.key).loggedEntry!.id, 'log-2'); }); testWidgets('an unsaved edit on a logged page does not change the saved entry', ( @@ -446,12 +446,8 @@ void main() { await tester.tap(find.byKey(const ValueKey('save-log-button'))); await tester.pumpAndSettle(); final gymNotifier = container.read(gymStateProvider.notifier); - final logPageUuid = container.read(gymStateProvider).getSlotEntryPageByIndex(2)!.uuid; - final savedRir = container - .read(gymStateProvider) - .getSlotPageByUUID(logPageUuid)! - .loggedEntry! - .rir; + final logPageKey = container.read(gymStateProvider).getSlotEntryPageByIndex(2)!.key; + final savedRir = container.read(gymStateProvider).progressOf(logPageKey).loggedEntry!.rir; expect(savedRir, isNot(3)); // Go back to the logged set and change the RiR without saving @@ -466,10 +462,7 @@ void main() { gymNotifier.setCurrentPage(2); await tester.pumpAndSettle(); - final loggedEntry = container - .read(gymStateProvider) - .getSlotPageByUUID(logPageUuid)! - .loggedEntry!; + final loggedEntry = container.read(gymStateProvider).progressOf(logPageKey).loggedEntry!; expect(loggedEntry.rir, savedRir); expect(container.read(gymLogProvider)!.rir, savedRir); }); diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 08b2661e2..2b5223957 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -68,7 +68,7 @@ void main() { final controller = PageController(); return PageView( controller: controller, - children: [TimerCountdownWidget(controller, 90, slotPage.uuid)], + children: [TimerCountdownWidget(controller, 90, slotPage.key)], ); }, ), diff --git a/test/features/routines/widgets/gym_mode/workout_menu_test.dart b/test/features/routines/widgets/gym_mode/workout_menu_test.dart index ca3874278..3f63896da 100644 --- a/test/features/routines/widgets/gym_mode/workout_menu_test.dart +++ b/test/features/routines/widgets/gym_mode/workout_menu_test.dart @@ -87,7 +87,7 @@ void main() { expect(find.byType(ExerciseSwapWidget), findsNothing); - await tester.tap(find.byKey(Key('swap-icon-${notifier.state.pages[1].uuid}'))); + await tester.tap(find.byKey(Key('swap-icon-${notifier.state.pages[1].key}'))); await tester.pumpAndSettle(); expect(find.byType(ExerciseSwapWidget), findsOne); }); @@ -97,7 +97,7 @@ void main() { expect(find.byType(ExerciseAddWidget), findsNothing); - await tester.tap(find.byKey(Key('add-icon-${notifier.state.pages[1].uuid}'))); + await tester.tap(find.byKey(Key('add-icon-${notifier.state.pages[1].key}'))); await tester.pumpAndSettle(); expect(find.byType(ExerciseAddWidget), findsOne); }); From d7781845fd9f1f517551bbf2d1eec296d1469abc Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 22:25:27 +0100 Subject: [PATCH 21/29] Keep exercises added in gym mode across recalculations --- .../routines/models/added_exercise.dart | 44 ++++ .../models/added_exercise.freezed.dart | 208 ++++++++++++++++++ lib/features/routines/models/routine.dart | 8 + .../routines/providers/gym_state.dart | 7 + .../providers/gym_state_notifier.dart | 175 ++++++--------- .../providers/gym_state_notifier.g.dart | 2 +- .../routines/providers/gym_state_test.dart | 151 ++++++------- 7 files changed, 402 insertions(+), 193 deletions(-) create mode 100644 lib/features/routines/models/added_exercise.dart create mode 100644 lib/features/routines/models/added_exercise.freezed.dart diff --git a/lib/features/routines/models/added_exercise.dart b/lib/features/routines/models/added_exercise.dart new file mode 100644 index 000000000..759ade653 --- /dev/null +++ b/lib/features/routines/models/added_exercise.dart @@ -0,0 +1,44 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:wger/features/exercises/models/exercise.dart'; +import 'package:wger/features/routines/models/weight_unit.dart'; + +part 'added_exercise.freezed.dart'; + +/// An exercise added in gym mode that is not part of the routine +@freezed +class AddedExercise with _$AddedExercise { + /// Key of the page the exercise follows + final String afterPageKey; + + final Exercise exercise; + + /// Borrowed from the page it follows, the logs need one + final int slotEntryId; + + final WeightUnit? weightUnit; + + const AddedExercise({ + required this.afterPageKey, + required this.exercise, + required this.slotEntryId, + this.weightUnit, + }); +} diff --git a/lib/features/routines/models/added_exercise.freezed.dart b/lib/features/routines/models/added_exercise.freezed.dart new file mode 100644 index 000000000..b2941aa1e --- /dev/null +++ b/lib/features/routines/models/added_exercise.freezed.dart @@ -0,0 +1,208 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'added_exercise.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AddedExercise { + + +/// Create a copy of AddedExercise +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AddedExerciseCopyWith get copyWith => _$AddedExerciseCopyWithImpl(this as AddedExercise, _$identity); + + + +@override +bool operator ==(Object other) { + final _this = this as AddedExercise; + return identical(this, other) || (other.runtimeType == runtimeType&&other is AddedExercise&&(identical(other.afterPageKey, _this.afterPageKey) || other.afterPageKey == _this.afterPageKey)&&(identical(other.exercise, _this.exercise) || other.exercise == _this.exercise)&&(identical(other.slotEntryId, _this.slotEntryId) || other.slotEntryId == _this.slotEntryId)&&(identical(other.weightUnit, _this.weightUnit) || other.weightUnit == _this.weightUnit)); +} + + +@override +int get hashCode { + final _this = this as AddedExercise; + return Object.hash(runtimeType,_this.afterPageKey,_this.exercise,_this.slotEntryId,_this.weightUnit); +} + +@override +String toString() { + final _this = this as AddedExercise; + return 'AddedExercise(afterPageKey: ${_this.afterPageKey}, exercise: ${_this.exercise}, slotEntryId: ${_this.slotEntryId}, weightUnit: ${_this.weightUnit})'; +} + + +} + +/// @nodoc +abstract mixin class $AddedExerciseCopyWith<$Res> { + factory $AddedExerciseCopyWith(AddedExercise value, $Res Function(AddedExercise) _then) = _$AddedExerciseCopyWithImpl; +@useResult +$Res call({ + String afterPageKey, Exercise exercise, int slotEntryId, WeightUnit? weightUnit +}); + + + + +} +/// @nodoc +class _$AddedExerciseCopyWithImpl<$Res> + implements $AddedExerciseCopyWith<$Res> { + _$AddedExerciseCopyWithImpl(this._self, this._then); + + final AddedExercise _self; + final $Res Function(AddedExercise) _then; + +/// Create a copy of AddedExercise +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? afterPageKey = null,Object? exercise = null,Object? slotEntryId = null,Object? weightUnit = freezed,}) { + return _then(AddedExercise( +afterPageKey: null == afterPageKey ? _self.afterPageKey : afterPageKey // ignore: cast_nullable_to_non_nullable +as String,exercise: null == exercise ? _self.exercise : exercise // ignore: cast_nullable_to_non_nullable +as Exercise,slotEntryId: null == slotEntryId ? _self.slotEntryId : slotEntryId // ignore: cast_nullable_to_non_nullable +as int,weightUnit: freezed == weightUnit ? _self.weightUnit : weightUnit // ignore: cast_nullable_to_non_nullable +as WeightUnit?, + )); +} + +} + + +/// Adds pattern-matching-related methods to [AddedExercise]. +extension AddedExercisePatterns on AddedExercise { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap({required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(){ +final _that = this; +switch (_that) { +case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(){ +final _that = this; +switch (_that) { +case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen({required TResult orElse(),}) {final _that = this; +switch (_that) { +case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when() {final _that = this; +switch (_that) { +case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull() {final _that = this; +switch (_that) { +case _: + return null; + +} +} + +} + +// dart format on diff --git a/lib/features/routines/models/routine.dart b/lib/features/routines/models/routine.dart index eeb5edb5b..458c8526a 100644 --- a/lib/features/routines/models/routine.dart +++ b/lib/features/routines/models/routine.dart @@ -296,6 +296,10 @@ class Routine { for (final day in updatedRoutine.dayData) { for (final slot in day.slots) { + slot.exerciseIds = [ + for (final id in slot.exerciseIds) + if (id == oldExerciseId) newExercise.id else id, + ]; for (final config in slot.setConfigs) { if (config.exerciseId == oldExerciseId) { config.exerciseId = newExercise.id; @@ -307,6 +311,10 @@ class Routine { for (final day in updatedRoutine.dayDataGym) { for (final slot in day.slots) { + slot.exerciseIds = [ + for (final id in slot.exerciseIds) + if (id == oldExerciseId) newExercise.id else id, + ]; for (final config in slot.setConfigs) { if (config.exerciseId == oldExerciseId) { config.exerciseId = newExercise.id; diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 16e82c06f..bb13847a5 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -19,6 +19,7 @@ import 'package:clock/clock.dart'; import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; +import 'package:wger/features/routines/models/added_exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/page_progress.dart'; @@ -191,6 +192,9 @@ class GymModeState { /// so that recalculating them doesn't lose it. final Map progress; + /// Exercises added during the workout, in the order they were added + final List addedExercises; + // Routine data late final int dayId; late final int iteration; @@ -212,6 +216,7 @@ class GymModeState { this.stickySetValues = false, this.lastLoggedValues = const {}, this.progress = const {}, + this.addedExercises = const [], int? dayId, int? iteration, Routine? routine, @@ -259,6 +264,7 @@ class GymModeState { bool? stickySetValues, Map? lastLoggedValues, Map? progress, + List? addedExercises, }) { return GymModeState( isInitialized: isInitialized ?? this.isInitialized, @@ -284,6 +290,7 @@ class GymModeState { stickySetValues: stickySetValues ?? this.stickySetValues, lastLoggedValues: lastLoggedValues ?? this.lastLoggedValues, progress: progress ?? this.progress, + addedExercises: addedExercises ?? this.addedExercises, ); } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index da6216c13..431fa36d5 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -26,6 +26,7 @@ import 'package:wger/core/consts.dart'; import 'package:wger/core/shared_preferences.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; import 'package:wger/features/exercises/models/exercise.dart'; +import 'package:wger/features/routines/models/added_exercise.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; @@ -263,6 +264,42 @@ class GymStateNotifier extends _$GymStateNotifier { final setsPerEntry = {}; String nextSet(int slotEntryId) => '$slotEntryId:${(setsPerEntry[slotEntryId] ?? 0) + 1}'; + // Exercises added during the workout follow the page they were added after + void addAddedPages(String afterKey) { + for (final (i, added) in state.addedExercises.indexed) { + if (added.afterPageKey != afterKey) { + continue; + } + + final addedKey = 'added:${i + 1}'; + final slotPageIndex = pageIndex; + pages.add( + PageEntry( + type: PageType.set, + pageIndex: slotPageIndex, + key: addedKey, + slotPages: [ + for (var nr = 1; nr <= 4; nr++) + SlotPageEntry( + type: SlotPageType.log, + setIndex: nr - 1, + pageIndex: pageIndex++, + key: '$addedKey:log:$nr', + setConfigData: SetConfigData( + textRepr: '-/-', + exerciseId: added.exercise.id, + exercise: added.exercise, + slotEntryId: added.slotEntryId, + weightUnit: added.weightUnit, + ), + ), + ], + ), + ); + addAddedPages(addedKey); + } + } + pageIndex++; for (final (slotIndex, slotData) in state.dayDataGym.slots.indexed) { final slotPageIndex = pageIndex; @@ -337,6 +374,7 @@ class GymStateNotifier extends _$GymStateNotifier { slotPages: slotEntries, ), ); + addAddedPages(slotKey); } // Session and summary page @@ -350,44 +388,6 @@ class GymStateNotifier extends _$GymStateNotifier { _logger.finer('Initialized ${state.pages.length} pages'); } - // Recalculates the indices of all pages - void recalculateIndices() { - var pageIndex = 0; - final updatedPages = []; - - for (final page in state.pages) { - final slotPageIndex = pageIndex; - var setIndex = 0; - final updatedSlotPages = []; - - for (final slotPage in page.slotPages) { - updatedSlotPages.add( - slotPage.copyWith( - pageIndex: pageIndex, - setIndex: setIndex, - ), - ); - setIndex++; - pageIndex++; - } - - if (page.type != PageType.set) { - pageIndex++; - } - - updatedPages.add( - page.copyWith( - pageIndex: slotPageIndex, - slotPages: updatedSlotPages, - ), - ); - } - - state = state.copyWith(pages: updatedPages); - // _logger.fine(readPageStructure()); - _logger.fine('Recalculated page indices'); - } - /// Reads the current page structure for debugging purposes String readPageStructure() { final List out = []; @@ -430,6 +430,7 @@ class GymStateNotifier extends _$GymStateNotifier { // An abandoned workout never reaches clear(), so forget its values here lastLoggedValues: shouldReset ? const {} : null, progress: shouldReset ? const {} : null, + addedExercises: shouldReset ? const [] : null, ); // Calculate the pages. @@ -601,41 +602,23 @@ class GymStateNotifier extends _$GymStateNotifier { } } + /// Replaces the exercise everywhere in the workout, also where it was added void replaceExercises( String pageEntryKey, { required int originalExerciseId, required Exercise newExercise, }) { - final updatedPages = state.pages.map((page) { - if (page.type != PageType.set) { - return page; - } - - if (page.key != pageEntryKey) { - return page; - } - - final updatedSlotPages = page.slotPages.map((slotPage) { - if (slotPage.setConfigData != null && - slotPage.setConfigData!.exercise.id == originalExerciseId) { - final updatedSetConfigData = slotPage.setConfigData!.copyWith( - exerciseId: newExercise.id, - exercise: newExercise, - ); - return slotPage.copyWith(setConfigData: updatedSetConfigData); - } - return slotPage; - }).toList(); - - return page.copyWith(slotPages: updatedSlotPages); - }).toList(); - - // replace and update new immutable routine instance - final updatedRoutine = state.routine.replaceExercise(originalExerciseId, newExercise); state = state.copyWith( - pages: updatedPages, - routine: updatedRoutine, + routine: state.routine.replaceExercise(originalExerciseId, newExercise), + addedExercises: [ + for (final added in state.addedExercises) + if (added.exercise.id == originalExerciseId) + added.copyWith(exercise: newExercise) + else + added, + ], ); + calculatePages(); _logger.fine('Replaced exercise $originalExerciseId with ${newExercise.id}'); } @@ -643,6 +626,12 @@ class GymStateNotifier extends _$GymStateNotifier { String pageEntryKey, { required Exercise newExercise, }) { + final page = state.pages.firstWhereOrNull((p) => p.key == pageEntryKey); + if (page == null) { + _logger.warning('No page found for key $pageEntryKey'); + return; + } + // Ad-hoc set configs bypass routine hydration, so resolve the profile // default weight unit (kg/lb) here; the log draft picks it up from the // unit object. @@ -651,51 +640,18 @@ class GymStateNotifier extends _$GymStateNotifier { final defaultWeightUnitId = profile?.defaultWeightUnitId ?? WEIGHT_UNIT_KG; final defaultWeightUnit = weightUnits.firstWhereOrNull((u) => u.id == defaultWeightUnitId); - // Not part of the routine, so numbered in the order they were added - final addedKey = 'added:${state.pages.where((p) => p.key.startsWith('added:')).length + 1}'; - - final List pages = []; - for (final page in state.pages) { - pages.add(page); - - if (page.key == pageEntryKey) { - final setConfigData = page.slotPages.first.setConfigData!; - - final List newSlotPages = []; - for (var i = 1; i <= 4; i++) { - newSlotPages.add( - SlotPageEntry( - type: SlotPageType.log, - pageIndex: 1, - setIndex: 0, - key: '$addedKey:log:$i', - setConfigData: SetConfigData( - textRepr: '-/-', - exerciseId: newExercise.id, - exercise: newExercise, - slotEntryId: setConfigData.slotEntryId, - weightUnit: defaultWeightUnit, - ), - ), - ); - } - - final newPage = PageEntry( - type: PageType.set, - pageIndex: 1, - key: addedKey, - slotPages: newSlotPages, - ); - - pages.add(newPage); - } - } - state = state.copyWith( - pages: pages, + addedExercises: [ + ...state.addedExercises, + AddedExercise( + afterPageKey: pageEntryKey, + exercise: newExercise, + slotEntryId: page.slotPages.first.setConfigData!.slotEntryId, + weightUnit: defaultWeightUnit, + ), + ], ); - - recalculateIndices(); + calculatePages(); } /// Resets the workout start time to now, e.g. when the user taps "start" @@ -713,6 +669,7 @@ class GymStateNotifier extends _$GymStateNotifier { currentPage: 0, lastLoggedValues: const {}, progress: const {}, + addedExercises: const [], validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index dbc5009fa..3b42d7dcd 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'da56aac7af47067aad83c59123d06162583f018b'; +String _$gymStateNotifierHash() => r'4008686bd5f5402fbdc8e54f9a312bd4e98b908f'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index b8526a106..2c671bb8f 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -30,6 +30,7 @@ import 'package:wger/features/account/models/user_profile.dart'; import 'package:wger/features/account/providers/user_profile_notifier.dart'; import 'package:wger/features/account/providers/user_profile_repository.dart'; import 'package:wger/features/exercises/models/exercise.dart'; +import 'package:wger/features/routines/models/added_exercise.dart'; import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; import 'package:wger/features/routines/models/log.dart'; @@ -240,90 +241,12 @@ void main() { }); }); - group('GymStateNotifier.recalculateIndices', () { - test('Correctly recalculates indices if new pages are added', () { - // Arrange - final newPages = [ - ...notifier.state.pages.sublist(0, 2), - PageEntry( - type: PageType.set, - pageIndex: 1111, - key: 'new-page-1', - ), - PageEntry( - type: PageType.set, - pageIndex: 9, - key: 'new-page-2', - ), - ...notifier.state.pages.sublist(2), - PageEntry( - type: PageType.set, - pageIndex: 0, - key: 'new-page-3', - slotPages: [ - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 10, - setIndex: 9, - key: 'new-slot-1', - ), - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 10, - setIndex: 6, - key: 'new-slot-2', - ), - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 100, - setIndex: 100, - key: 'new-slot-3', - ), - ], - ), - ]; - notifier.state = notifier.state.copyWith(pages: newPages); - - // Act - notifier.recalculateIndices(); - - // Assert - final pages = notifier.state.pages; - expect(pages[0].pageIndex, 0); - expect(pages[1].pageIndex, 1); - - // These three have the same pageIndex because the new ones don't have any slot - // pages (this should not happen in practice) - expect(pages[2].pageIndex, 8); - expect(pages[3].pageIndex, 8); - expect(pages[4].pageIndex, 8); - - expect(pages[5].pageIndex, 15); - expect(pages[6].pageIndex, 16); - expect(pages[7].pageIndex, 17); - - // Preserve the order of new pages - expect(pages[7].key, 'new-page-3'); - - // Slot pages have correct indices, the original order is preserved - final slotPages = pages[7].slotPages; - expect(slotPages[0].key, 'new-slot-1'); - expect(slotPages[0].pageIndex, 17); - expect(slotPages[0].setIndex, 0); - expect(slotPages[1].key, 'new-slot-2'); - expect(slotPages[1].pageIndex, 18); - expect(slotPages[1].setIndex, 1); - expect(slotPages[2].key, 'new-slot-3'); - expect(slotPages[2].pageIndex, 19); - expect(slotPages[2].setIndex, 2); - }); - }); - group('GymStateNotifier.replaceExercises', () { test('Correctly swaps an exercise', () { // Arrange final page = notifier.state.pages[1]; final slotPage = page.slotPages[1]; + final slotPageKeys = page.slotPages.map((s) => s.key).toList(); expect(slotPage.type, SlotPageType.log); expect( notifier.state.pages.every((p) => p.exercises.every((e) => e.id != testSquats.id)), @@ -337,6 +260,11 @@ void main() { // Assert: every slot page of that page carries the new exercise, and the // routine itself was rebuilt too (the log draft reads from it) final updated = notifier.state.pages[1]; + expect( + updated.slotPages.map((s) => s.key), + slotPageKeys, + reason: 'the layout is the same, including the overview of the exercise', + ); expect( updated.slotPages .where((s) => s.setConfigData != null) @@ -356,9 +284,8 @@ void main() { }); group('GymStateNotifier.addExerciseAfterPage', () { - test('Stamps the profile default weight unit on the ad-hoc set configs', () async { - // Ad-hoc exercises bypass routine hydration, so the notifier itself - // resolves the profile default: lb (id 2) for an imperial user. + /// A notifier for an imperial user, with the pages calculated + Future imperialGymNotifier() async { final profileRepo = MockUserProfileRepository(); when( profileRepo.watchDrift(), @@ -385,11 +312,18 @@ void main() { routine: getTestRoutine(), ); imperialNotifier.calculatePages(); + return imperialNotifier; + } + + test('Stamps the profile default weight unit on the ad-hoc set configs', () async { + // Ad-hoc exercises bypass routine hydration, so the notifier itself + // resolves the profile default: lb (id 2) for an imperial user. + final imperialNotifier = await imperialGymNotifier(); final setPage = imperialNotifier.state.pages.firstWhere((p) => p.type == PageType.set); imperialNotifier.addExerciseAfterPage(setPage.key, newExercise: testSquats); - // recalculateIndices copies the page objects, so look the page up by key. + // The pages are recalculated, so look the page up by key final pages = imperialNotifier.state.pages; final newPage = pages[pages.indexWhere((p) => p.key == setPage.key) + 1]; expect(newPage.slotPages, isNotEmpty); @@ -409,6 +343,49 @@ void main() { 'added:1:log:4', ]); }); + + test('Keeps the added exercises when the pages are recalculated', () async { + final gymNotifier = await imperialGymNotifier(); + final slotKey = gymNotifier.state.pages[1].key; + gymNotifier.addExerciseAfterPage(slotKey, newExercise: testSquats); + gymNotifier.addExerciseAfterPage('added:1', newExercise: testCurls); + gymNotifier.markSlotPageAsDone('added:1:log:1', isDone: true); + + gymNotifier.state = gymNotifier.state.copyWith(showExercisePages: false); + gymNotifier.calculatePages(); + + final pages = gymNotifier.state.pages; + expect(pages.map((p) => p.key).toList().sublist(1, 4), [slotKey, 'added:1', 'added:2']); + expect(pages[2].exercises.single.id, testSquats.id); + expect(pages[3].exercises.single.id, testCurls.id); + expect( + pages[2].slotPages.map((p) => p.setIndex), + [0, 1, 2, 3], + reason: 'the sets of the exercise are numbered on their own', + ); + expect(pages[2].slotPages.first.setConfigData!.weightUnit, testWeightUnit2); + expect(gymNotifier.state.progressOf('added:1:log:1').done, isTrue); + expect( + pages.expand((p) => p.slotPages).map((p) => p.pageIndex), + List.generate(pages.expand((p) => p.slotPages).length, (i) => i + 1), + reason: 'the page indices stay consecutive', + ); + }); + + test('Keeps a replaced added exercise when the pages are recalculated', () async { + final gymNotifier = await imperialGymNotifier(); + gymNotifier.addExerciseAfterPage(gymNotifier.state.pages[1].key, newExercise: testSquats); + + gymNotifier.replaceExercises( + 'added:1', + originalExerciseId: testSquats.id, + newExercise: testCurls, + ); + gymNotifier.calculatePages(); + + final added = gymNotifier.state.pages.firstWhere((p) => p.key == 'added:1'); + expect(added.exercises.single.id, testCurls.id); + }); }); group('GymStateNotifier.calculatePages, supersets', () { @@ -892,6 +869,9 @@ void main() { notifier.state = notifier.state.copyWith( workoutStart: DateTime(2024, 5, 1, 10, 0), progress: {'log:1:1': const PageProgress(done: true)}, + addedExercises: [ + AddedExercise(afterPageKey: 'slot:1:1', exercise: testSquats, slotEntryId: 1), + ], ); // Act @@ -902,6 +882,7 @@ void main() { // Assert expect(notifier.state.workoutStart, DateTime(2024, 5, 2, 9, 15)); expect(notifier.state.progress, isEmpty); + expect(notifier.state.addedExercises, isEmpty); }); }); @@ -954,11 +935,15 @@ void main() { dayId: 1, currentPage: 4, progress: {'log:1:1': const PageProgress(done: true)}, + addedExercises: [ + AddedExercise(afterPageKey: 'slot:1:1', exercise: testSquats, slotEntryId: 1), + ], ); expect(notifier.initData(getTestRoutine(), 2, 1), 0); expect(notifier.state.dayId, 2); expect(notifier.state.progress, isEmpty, reason: 'the new workout starts without progress'); + expect(notifier.state.addedExercises, isEmpty); }); test('An expired validUntil resets even on the same day', () { From 4522f018ad3b215e4124bec398feded173a146fb Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 22:34:35 +0100 Subject: [PATCH 22/29] Store the gym mode progress by page key --- .../routines/models/workout_progress.dart | 79 +-- .../models/workout_progress.freezed.dart | 570 ++++++++++++++++++ .../routines/models/workout_progress.g.dart | 46 ++ .../routines/providers/gym_state.dart | 25 + .../providers/gym_state_notifier.dart | 82 ++- .../providers/gym_state_notifier.g.dart | 2 +- .../providers/workout_logs_repository.dart | 62 +- .../routines/providers/gym_state_test.dart | 101 +++- .../providers/gym_state_test.mocks.dart | 87 +++ .../workout_logs_notifier_test.mocks.dart | 9 + .../workout_logs_repository_test.dart | 17 + .../routines/screens/gym_mode_test.mocks.dart | 9 + .../routine_logs_screen_test.mocks.dart | 9 + 13 files changed, 983 insertions(+), 115 deletions(-) create mode 100644 lib/features/routines/models/workout_progress.freezed.dart create mode 100644 lib/features/routines/models/workout_progress.g.dart create mode 100644 test/features/routines/providers/gym_state_test.mocks.dart diff --git a/lib/features/routines/models/workout_progress.dart b/lib/features/routines/models/workout_progress.dart index 002463ff8..76ffa86d5 100644 --- a/lib/features/routines/models/workout_progress.dart +++ b/lib/features/routines/models/workout_progress.dart @@ -16,55 +16,38 @@ * along with this program. If not, see . */ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'workout_progress.freezed.dart'; +part 'workout_progress.g.dart'; + /// The progress through a running workout, as stored in the preferences /// -/// Only the parts that can't be recalculated are kept, the pages themselves -/// are derived from the routine again on the next start. -class WorkoutProgress { - final int dayId; - final int iteration; - final int currentPage; - final DateTime workoutStart; - final DateTime validUntil; +/// Only the parts that can't be recalculated are kept. The pages are derived +/// from the routine again and matched by their keys. +@freezed +sealed class WorkoutProgress with _$WorkoutProgress { + const factory WorkoutProgress({ + required int dayId, + required int iteration, + required String currentPageKey, + required DateTime workoutStart, + required DateTime validUntil, + @Default({}) Map pages, + }) = _WorkoutProgress; - /// Absolute page indices of the log pages already marked as done - final List donePageIndices; - - const WorkoutProgress({ - required this.dayId, - required this.iteration, - required this.currentPage, - required this.workoutStart, - required this.validUntil, - required this.donePageIndices, - }); - - factory WorkoutProgress.fromJson(Map json) => WorkoutProgress( - dayId: json['dayId'] as int, - iteration: json['iteration'] as int, - currentPage: json['currentPage'] as int, - workoutStart: DateTime.parse(json['workoutStart'] as String), - validUntil: DateTime.parse(json['validUntil'] as String), - donePageIndices: (json['donePageIndices'] as List).cast(), - ); - - Map toJson() => { - 'dayId': dayId, - 'iteration': iteration, - 'currentPage': currentPage, - 'workoutStart': workoutStart.toIso8601String(), - 'validUntil': validUntil.toIso8601String(), - 'donePageIndices': donePageIndices, - }; - - @override - String toString() => - 'WorkoutProgress(' - 'dayId: $dayId, ' - 'iteration: $iteration, ' - 'currentPage: $currentPage, ' - 'workoutStart: $workoutStart, ' - 'validUntil: $validUntil, ' - 'donePageIndices: $donePageIndices' - ')'; + factory WorkoutProgress.fromJson(Map json) => _$WorkoutProgressFromJson(json); +} + +/// The stored part of a page's progress, the logged entry only by its ID +@freezed +sealed class StoredPageProgress with _$StoredPageProgress { + const factory StoredPageProgress({ + @Default(false) bool done, + String? logId, + DateTime? timerStartedAt, + }) = _StoredPageProgress; + + factory StoredPageProgress.fromJson(Map json) => + _$StoredPageProgressFromJson(json); } diff --git a/lib/features/routines/models/workout_progress.freezed.dart b/lib/features/routines/models/workout_progress.freezed.dart new file mode 100644 index 000000000..7ce451f97 --- /dev/null +++ b/lib/features/routines/models/workout_progress.freezed.dart @@ -0,0 +1,570 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'workout_progress.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// dart format off +T _$identity(T value) => value; + +/// @nodoc +mixin _$WorkoutProgress { + + int get dayId; int get iteration; String get currentPageKey; DateTime get workoutStart; DateTime get validUntil; Map get pages; +/// Create a copy of WorkoutProgress +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$WorkoutProgressCopyWith get copyWith => _$WorkoutProgressCopyWithImpl(this as WorkoutProgress, _$identity); + + /// Serializes this WorkoutProgress to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + final _this = this as WorkoutProgress; + return identical(this, other) || (other.runtimeType == runtimeType&&other is WorkoutProgress&&(identical(other.dayId, _this.dayId) || other.dayId == _this.dayId)&&(identical(other.iteration, _this.iteration) || other.iteration == _this.iteration)&&(identical(other.currentPageKey, _this.currentPageKey) || other.currentPageKey == _this.currentPageKey)&&(identical(other.workoutStart, _this.workoutStart) || other.workoutStart == _this.workoutStart)&&(identical(other.validUntil, _this.validUntil) || other.validUntil == _this.validUntil)&&const DeepCollectionEquality().equals(other.pages, _this.pages)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode { + final _this = this as WorkoutProgress; + return Object.hash(runtimeType,_this.dayId,_this.iteration,_this.currentPageKey,_this.workoutStart,_this.validUntil,const DeepCollectionEquality().hash(_this.pages)); +} + +@override +String toString() { + final _this = this as WorkoutProgress; + return 'WorkoutProgress(dayId: ${_this.dayId}, iteration: ${_this.iteration}, currentPageKey: ${_this.currentPageKey}, workoutStart: ${_this.workoutStart}, validUntil: ${_this.validUntil}, pages: ${_this.pages})'; +} + + +} + +/// @nodoc +abstract mixin class $WorkoutProgressCopyWith<$Res> { + factory $WorkoutProgressCopyWith(WorkoutProgress value, $Res Function(WorkoutProgress) _then) = _$WorkoutProgressCopyWithImpl; +@useResult +$Res call({ + int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map pages +}); + + + + +} +/// @nodoc +class _$WorkoutProgressCopyWithImpl<$Res> + implements $WorkoutProgressCopyWith<$Res> { + _$WorkoutProgressCopyWithImpl(this._self, this._then); + + final WorkoutProgress _self; + final $Res Function(WorkoutProgress) _then; + +/// Create a copy of WorkoutProgress +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? dayId = null,Object? iteration = null,Object? currentPageKey = null,Object? workoutStart = null,Object? validUntil = null,Object? pages = null,}) { + return _then(WorkoutProgress( +dayId: null == dayId ? _self.dayId : dayId // ignore: cast_nullable_to_non_nullable +as int,iteration: null == iteration ? _self.iteration : iteration // ignore: cast_nullable_to_non_nullable +as int,currentPageKey: null == currentPageKey ? _self.currentPageKey : currentPageKey // ignore: cast_nullable_to_non_nullable +as String,workoutStart: null == workoutStart ? _self.workoutStart : workoutStart // ignore: cast_nullable_to_non_nullable +as DateTime,validUntil: null == validUntil ? _self.validUntil : validUntil // ignore: cast_nullable_to_non_nullable +as DateTime,pages: null == pages ? _self.pages : pages // ignore: cast_nullable_to_non_nullable +as Map, + )); +} + +} + + +/// Adds pattern-matching-related methods to [WorkoutProgress]. +extension WorkoutProgressPatterns on WorkoutProgress { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _WorkoutProgress value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _WorkoutProgress() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _WorkoutProgress value) $default,){ +final _that = this; +switch (_that) { +case _WorkoutProgress(): +return $default(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _WorkoutProgress value)? $default,){ +final _that = this; +switch (_that) { +case _WorkoutProgress() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map pages)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _WorkoutProgress() when $default != null: +return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map pages) $default,) {final _that = this; +switch (_that) { +case _WorkoutProgress(): +return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map pages)? $default,) {final _that = this; +switch (_that) { +case _WorkoutProgress() when $default != null: +return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _WorkoutProgress implements WorkoutProgress { + const _WorkoutProgress({required this.dayId, required this.iteration, required this.currentPageKey, required this.workoutStart, required this.validUntil, Map pages = const {}}): _pages = pages; + factory _WorkoutProgress.fromJson(Map json) => _$WorkoutProgressFromJson(json); + +@override final int dayId; +@override final int iteration; +@override final String currentPageKey; +@override final DateTime workoutStart; +@override final DateTime validUntil; + final Map _pages; +@override@JsonKey() Map get pages { + if (_pages is EqualUnmodifiableMapView) return _pages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_pages); +} + + +/// Create a copy of WorkoutProgress +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$WorkoutProgressCopyWith<_WorkoutProgress> get copyWith => __$WorkoutProgressCopyWithImpl<_WorkoutProgress>(this, _$identity); + +@override +Map toJson() { + return _$WorkoutProgressToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _WorkoutProgress&&(identical(other.dayId, dayId) || other.dayId == dayId)&&(identical(other.iteration, iteration) || other.iteration == iteration)&&(identical(other.currentPageKey, currentPageKey) || other.currentPageKey == currentPageKey)&&(identical(other.workoutStart, workoutStart) || other.workoutStart == workoutStart)&&(identical(other.validUntil, validUntil) || other.validUntil == validUntil)&&const DeepCollectionEquality().equals(other.pages, _pages)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode { + return Object.hash(runtimeType,dayId,iteration,currentPageKey,workoutStart,validUntil,const DeepCollectionEquality().hash(_pages)); +} + +@override +String toString() { + return 'WorkoutProgress(dayId: $dayId, iteration: $iteration, currentPageKey: $currentPageKey, workoutStart: $workoutStart, validUntil: $validUntil, pages: $pages)'; +} + + +} + +/// @nodoc +abstract mixin class _$WorkoutProgressCopyWith<$Res> implements $WorkoutProgressCopyWith<$Res> { + factory _$WorkoutProgressCopyWith(_WorkoutProgress value, $Res Function(_WorkoutProgress) _then) = __$WorkoutProgressCopyWithImpl; +@override @useResult +$Res call({ + int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map pages +}); + + + + +} +/// @nodoc +class __$WorkoutProgressCopyWithImpl<$Res> + implements _$WorkoutProgressCopyWith<$Res> { + __$WorkoutProgressCopyWithImpl(this._self, this._then); + + final _WorkoutProgress _self; + final $Res Function(_WorkoutProgress) _then; + +/// Create a copy of WorkoutProgress +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? dayId = null,Object? iteration = null,Object? currentPageKey = null,Object? workoutStart = null,Object? validUntil = null,Object? pages = null,}) { + return _then(_WorkoutProgress( +dayId: null == dayId ? _self.dayId : dayId // ignore: cast_nullable_to_non_nullable +as int,iteration: null == iteration ? _self.iteration : iteration // ignore: cast_nullable_to_non_nullable +as int,currentPageKey: null == currentPageKey ? _self.currentPageKey : currentPageKey // ignore: cast_nullable_to_non_nullable +as String,workoutStart: null == workoutStart ? _self.workoutStart : workoutStart // ignore: cast_nullable_to_non_nullable +as DateTime,validUntil: null == validUntil ? _self.validUntil : validUntil // ignore: cast_nullable_to_non_nullable +as DateTime,pages: null == pages ? _self._pages : pages // ignore: cast_nullable_to_non_nullable +as Map, + )); +} + + +} + + +/// @nodoc +mixin _$StoredPageProgress { + + bool get done; String? get logId; DateTime? get timerStartedAt; +/// Create a copy of StoredPageProgress +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$StoredPageProgressCopyWith get copyWith => _$StoredPageProgressCopyWithImpl(this as StoredPageProgress, _$identity); + + /// Serializes this StoredPageProgress to a JSON map. + Map toJson(); + + +@override +bool operator ==(Object other) { + final _this = this as StoredPageProgress; + return identical(this, other) || (other.runtimeType == runtimeType&&other is StoredPageProgress&&(identical(other.done, _this.done) || other.done == _this.done)&&(identical(other.logId, _this.logId) || other.logId == _this.logId)&&(identical(other.timerStartedAt, _this.timerStartedAt) || other.timerStartedAt == _this.timerStartedAt)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode { + final _this = this as StoredPageProgress; + return Object.hash(runtimeType,_this.done,_this.logId,_this.timerStartedAt); +} + +@override +String toString() { + final _this = this as StoredPageProgress; + return 'StoredPageProgress(done: ${_this.done}, logId: ${_this.logId}, timerStartedAt: ${_this.timerStartedAt})'; +} + + +} + +/// @nodoc +abstract mixin class $StoredPageProgressCopyWith<$Res> { + factory $StoredPageProgressCopyWith(StoredPageProgress value, $Res Function(StoredPageProgress) _then) = _$StoredPageProgressCopyWithImpl; +@useResult +$Res call({ + bool done, String? logId, DateTime? timerStartedAt +}); + + + + +} +/// @nodoc +class _$StoredPageProgressCopyWithImpl<$Res> + implements $StoredPageProgressCopyWith<$Res> { + _$StoredPageProgressCopyWithImpl(this._self, this._then); + + final StoredPageProgress _self; + final $Res Function(StoredPageProgress) _then; + +/// Create a copy of StoredPageProgress +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? done = null,Object? logId = freezed,Object? timerStartedAt = freezed,}) { + return _then(StoredPageProgress( +done: null == done ? _self.done : done // ignore: cast_nullable_to_non_nullable +as bool,logId: freezed == logId ? _self.logId : logId // ignore: cast_nullable_to_non_nullable +as String?,timerStartedAt: freezed == timerStartedAt ? _self.timerStartedAt : timerStartedAt // ignore: cast_nullable_to_non_nullable +as DateTime?, + )); +} + +} + + +/// Adds pattern-matching-related methods to [StoredPageProgress]. +extension StoredPageProgressPatterns on StoredPageProgress { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _StoredPageProgress value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _StoredPageProgress() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _StoredPageProgress value) $default,){ +final _that = this; +switch (_that) { +case _StoredPageProgress(): +return $default(_that);} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _StoredPageProgress value)? $default,){ +final _that = this; +switch (_that) { +case _StoredPageProgress() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( bool done, String? logId, DateTime? timerStartedAt)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _StoredPageProgress() when $default != null: +return $default(_that.done,_that.logId,_that.timerStartedAt);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( bool done, String? logId, DateTime? timerStartedAt) $default,) {final _that = this; +switch (_that) { +case _StoredPageProgress(): +return $default(_that.done,_that.logId,_that.timerStartedAt);} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( bool done, String? logId, DateTime? timerStartedAt)? $default,) {final _that = this; +switch (_that) { +case _StoredPageProgress() when $default != null: +return $default(_that.done,_that.logId,_that.timerStartedAt);case _: + return null; + +} +} + +} + +/// @nodoc +@JsonSerializable() + +class _StoredPageProgress implements StoredPageProgress { + const _StoredPageProgress({this.done = false, this.logId, this.timerStartedAt}); + factory _StoredPageProgress.fromJson(Map json) => _$StoredPageProgressFromJson(json); + +@override@JsonKey() final bool done; +@override final String? logId; +@override final DateTime? timerStartedAt; + +/// Create a copy of StoredPageProgress +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$StoredPageProgressCopyWith<_StoredPageProgress> get copyWith => __$StoredPageProgressCopyWithImpl<_StoredPageProgress>(this, _$identity); + +@override +Map toJson() { + return _$StoredPageProgressToJson(this, ); +} + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _StoredPageProgress&&(identical(other.done, done) || other.done == done)&&(identical(other.logId, logId) || other.logId == logId)&&(identical(other.timerStartedAt, timerStartedAt) || other.timerStartedAt == timerStartedAt)); +} + +@JsonKey(includeFromJson: false, includeToJson: false) +@override +int get hashCode { + return Object.hash(runtimeType,done,logId,timerStartedAt); +} + +@override +String toString() { + return 'StoredPageProgress(done: $done, logId: $logId, timerStartedAt: $timerStartedAt)'; +} + + +} + +/// @nodoc +abstract mixin class _$StoredPageProgressCopyWith<$Res> implements $StoredPageProgressCopyWith<$Res> { + factory _$StoredPageProgressCopyWith(_StoredPageProgress value, $Res Function(_StoredPageProgress) _then) = __$StoredPageProgressCopyWithImpl; +@override @useResult +$Res call({ + bool done, String? logId, DateTime? timerStartedAt +}); + + + + +} +/// @nodoc +class __$StoredPageProgressCopyWithImpl<$Res> + implements _$StoredPageProgressCopyWith<$Res> { + __$StoredPageProgressCopyWithImpl(this._self, this._then); + + final _StoredPageProgress _self; + final $Res Function(_StoredPageProgress) _then; + +/// Create a copy of StoredPageProgress +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? done = null,Object? logId = freezed,Object? timerStartedAt = freezed,}) { + return _then(_StoredPageProgress( +done: null == done ? _self.done : done // ignore: cast_nullable_to_non_nullable +as bool,logId: freezed == logId ? _self.logId : logId // ignore: cast_nullable_to_non_nullable +as String?,timerStartedAt: freezed == timerStartedAt ? _self.timerStartedAt : timerStartedAt // ignore: cast_nullable_to_non_nullable +as DateTime?, + )); +} + + +} + +// dart format on diff --git a/lib/features/routines/models/workout_progress.g.dart b/lib/features/routines/models/workout_progress.g.dart new file mode 100644 index 000000000..c2a323229 --- /dev/null +++ b/lib/features/routines/models/workout_progress.g.dart @@ -0,0 +1,46 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'workout_progress.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_WorkoutProgress _$WorkoutProgressFromJson(Map json) => _WorkoutProgress( + dayId: (json['dayId'] as num).toInt(), + iteration: (json['iteration'] as num).toInt(), + currentPageKey: json['currentPageKey'] as String, + workoutStart: DateTime.parse(json['workoutStart'] as String), + validUntil: DateTime.parse(json['validUntil'] as String), + pages: + (json['pages'] as Map?)?.map( + (k, e) => MapEntry( + k, + StoredPageProgress.fromJson(e as Map), + ), + ) ?? + const {}, +); + +Map _$WorkoutProgressToJson(_WorkoutProgress instance) => { + 'dayId': instance.dayId, + 'iteration': instance.iteration, + 'currentPageKey': instance.currentPageKey, + 'workoutStart': instance.workoutStart.toIso8601String(), + 'validUntil': instance.validUntil.toIso8601String(), + 'pages': instance.pages, +}; + +_StoredPageProgress _$StoredPageProgressFromJson(Map json) => _StoredPageProgress( + done: json['done'] as bool? ?? false, + logId: json['logId'] as String?, + timerStartedAt: json['timerStartedAt'] == null + ? null + : DateTime.parse(json['timerStartedAt'] as String), +); + +Map _$StoredPageProgressToJson(_StoredPageProgress instance) => { + 'done': instance.done, + 'logId': instance.logId, + 'timerStartedAt': instance.timerStartedAt?.toIso8601String(), +}; diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index bb13847a5..51bf588c6 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -345,6 +345,31 @@ class GymModeState { return null; } + /// Key of the page shown at [pageIndex] + String? keyOfPage(int pageIndex) { + for (final page in pages) { + if (page.type != PageType.set && page.pageIndex == pageIndex) { + return page.key; + } + for (final slotPage in page.slotPages) { + if (slotPage.pageIndex == pageIndex) { + return slotPage.key; + } + } + } + return null; + } + + /// Index of the page with [key], the reverse of [keyOfPage] + int? pageIndexOf(String key) { + for (final page in pages) { + if (page.type != PageType.set && page.key == key) { + return page.pageIndex; + } + } + return getSlotPageByKey(key)?.pageIndex; + } + SlotPageEntry? getSlotPageByKey(String key) { for (final slotPage in pages.expand((p) => p.slotPages)) { if (slotPage.key == key) { diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 431fa36d5..ba7363af8 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -36,6 +36,7 @@ import 'package:wger/features/routines/models/workout_progress.dart'; import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_repository.dart'; part 'gym_state_notifier.g.dart'; @@ -146,19 +147,11 @@ class GymStateNotifier extends _$GymStateNotifier { ); } - /// Absolute page indices of the log pages already marked as done - List get _donePageIndices => state.pages - .expand((page) => page.slotPages) - .where((slotPage) => state.progressOf(slotPage.key).done) - .map((slotPage) => slotPage.pageIndex) - .toList(); - /// Stores the progress through the running workout /// /// Riverpod keeps the state alive for as long as the app is running, but the /// OS can kill a backgrounded app at any point, e.g. while the user switches - /// to a music app between two sets. Without this, that loses the session, the - /// elapsed time and which sets were already done. + /// to a music app between two sets. Future _saveProgress() async { // Before initData there is no dayId to store the progress under if (!state.isInitialized) { @@ -168,10 +161,17 @@ class GymStateNotifier extends _$GymStateNotifier { final progress = WorkoutProgress( dayId: state.dayId, iteration: state.iteration, - currentPage: state.currentPage, + currentPageKey: state.keyOfPage(state.currentPage) ?? 'start', workoutStart: state.workoutStart, validUntil: state.validUntil, - donePageIndices: _donePageIndices, + pages: { + for (final MapEntry(:key, :value) in state.progress.entries) + key: StoredPageProgress( + done: value.done, + logId: value.loggedEntry?.id, + timerStartedAt: value.timerStartedAt, + ), + }, ); await PreferenceHelper.asyncPref.setString( @@ -212,42 +212,60 @@ class GymStateNotifier extends _$GymStateNotifier { return null; } - final WorkoutProgress progress; + final WorkoutProgress saved; try { - progress = WorkoutProgress.fromJson(json.decode(stored) as Map); - } on Exception catch (e) { + saved = WorkoutProgress.fromJson(json.decode(stored) as Map); + } catch (e) { _logger.warning('Discarding unreadable stored workout progress: $e'); await _clearProgress(); return null; } - // Only ever continue the same workout, only while it is plausibly still - // running, and only if the routine still has the page it stopped on (it - // might have been edited in the meantime). - if (progress.dayId != state.dayId || - progress.iteration != state.iteration || - progress.validUntil.isBefore(clock.now()) || - progress.currentPage >= state.totalPages) { + // Only ever continue the same workout, and only while it is plausibly + // still running + if (saved.dayId != state.dayId || + saved.iteration != state.iteration || + saved.validUntil.isBefore(clock.now())) { _logger.fine('Stored workout progress does not apply any more, discarding it'); await _clearProgress(); return null; } + final logIds = saved.pages.values.map((p) => p.logId).nonNulls.toList(); + final logs = { + if (logIds.isNotEmpty) + for (final log in await ref.read(workoutLogRepositoryProvider).getLogsByIds(logIds)) + log.id: log, + }; + + // Pages the routine no longer has (it was edited, or they were added + // during the workout) are left out + final slotPages = state.pages.expand((page) => page.slotPages); + final progress = { + for (final slotPage in slotPages) + if (saved.pages[slotPage.key] case final stored?) + slotPage.key: PageProgress( + done: stored.done, + loggedEntry: logs[stored.logId], + timerStartedAt: stored.timerStartedAt, + ), + }; + state = state.copyWith( - currentPage: progress.currentPage, - workoutStart: progress.workoutStart, - validUntil: progress.validUntil, - progress: { - for (final slotPage in state.pages.expand((page) => page.slotPages)) - if (slotPage.type == SlotPageType.log && - progress.donePageIndices.contains(slotPage.pageIndex)) - slotPage.key: const PageProgress(done: true), + currentPage: state.pageIndexOf(saved.currentPageKey) ?? 0, + workoutStart: saved.workoutStart, + validUntil: saved.validUntil, + progress: progress, + // In page order, so the last set of an exercise wins + lastLoggedValues: { + for (final log in slotPages.map((p) => progress[p.key]?.loggedEntry).nonNulls) + log.exerciseId: log, }, ); - _logger.fine('Restored workout progress on page ${progress.currentPage}'); + _logger.fine('Restored workout progress on page ${state.currentPage}'); - return progress.currentPage; + return state.currentPage; } /// Calculates the page entries @@ -547,6 +565,7 @@ class GymStateNotifier extends _$GymStateNotifier { /// Applies [update] to the progress of the page with [key] void _updateProgress(String key, PageProgress Function(PageProgress) update) { state = state.copyWith(progress: {...state.progress, key: update(state.progressOf(key))}); + _saveProgress(); } /// Starts the timer of the slot page with [key], unless it is already @@ -591,7 +610,6 @@ class GymStateNotifier extends _$GymStateNotifier { key, (p) => p.copyWith(done: isDone, loggedEntry: log?.copyWith() ?? p.loggedEntry), ); - _saveProgress(); _logger.fine('Set done=$isDone for slot page $key'); // Scrolling past the timer (e.g. "jump to") already started it diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 3b42d7dcd..8ffd11a9c 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'4008686bd5f5402fbdc8e54f9a312bd4e98b908f'; +String _$gymStateNotifierHash() => r'1f0009a2972509e3a444896208f3865835ba77a7'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/lib/features/routines/providers/workout_logs_repository.dart b/lib/features/routines/providers/workout_logs_repository.dart index 318ab65bb..4346cc226 100644 --- a/lib/features/routines/providers/workout_logs_repository.dart +++ b/lib/features/routines/providers/workout_logs_repository.dart @@ -34,8 +34,8 @@ final workoutLogRepositoryProvider = Provider((ref) { }); /// Local access to the `workout_log` table: writes (add/update/delete) plus a -/// per-exercise read stream. Reading logs grouped under their parent session -/// happens through `WorkoutSessionRepository.watchAllDrift`. +/// per-exercise read stream and a lookup by ID. Reading logs grouped under +/// their parent session happens through `WorkoutSessionRepository.watchAllDrift`. class WorkoutLogRepository { final _logger = Logger('WorkoutLogRepository'); final DriftPowersyncDatabase _db; @@ -58,16 +58,7 @@ class WorkoutLogRepository { 'routine ${routineId ?? 'any'}, since ${since ?? 'always'}', ); - final query = _db.select(_db.workoutLogTable).join([ - leftOuterJoin( - _db.routineRepetitionUnitTable, - _db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId), - ), - leftOuterJoin( - _db.routineWeightUnitTable, - _db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId), - ), - ]); + final query = _selectWithUnits(); var whereCondition = _db.workoutLogTable.exerciseId.equals(exerciseId); if (routineId != null) { @@ -81,20 +72,39 @@ class WorkoutLogRepository { OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc), ]); - return query.watch().map((rows) { - return rows.map((row) { - final log = row.readTable(_db.workoutLogTable); - final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable); - if (repetitionUnit != null) { - log.repetitionUnit = repetitionUnit; - } - final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable); - if (weightUnit != null) { - log.weightUnit = weightUnit; - } - return log; - }).toList(); - }); + return query.watch().map((rows) => rows.map(_readWithUnits).toList()); + } + + /// The logs with one of the [ids] that exist locally, with their units + Future> getLogsByIds(List ids) async { + final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids)); + return (await query.get()).map(_readWithUnits).toList(); + } + + JoinedSelectStatement _selectWithUnits() { + return _db.select(_db.workoutLogTable).join([ + leftOuterJoin( + _db.routineRepetitionUnitTable, + _db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId), + ), + leftOuterJoin( + _db.routineWeightUnitTable, + _db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId), + ), + ]); + } + + Log _readWithUnits(TypedResult row) { + final log = row.readTable(_db.workoutLogTable); + final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable); + if (repetitionUnit != null) { + log.repetitionUnit = repetitionUnit; + } + final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable); + if (weightUnit != null) { + log.weightUnit = weightUnit; + } + return log; } Future deleteLocalDrift(String id) async { diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 2c671bb8f..af1218290 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -22,6 +22,7 @@ import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; @@ -42,11 +43,14 @@ import 'package:wger/features/routines/providers/gym_log_notifier.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; import 'package:wger/features/routines/providers/routines_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_repository.dart'; import '../../../../test_data/exercises.dart'; import '../../../../test_data/routines.dart'; import '../helpers/routine_form_test_overrides.dart'; +import 'gym_state_test.mocks.dart'; +@GenerateMocks([WorkoutLogRepository]) void main() { late GymStateNotifier notifier; late ProviderContainer container; @@ -976,9 +980,20 @@ void main() { group('GymStateNotifier workout progress', () { /// Simulates the app being killed: a new container means a new (empty) - /// notifier, while the stored preferences survive, as on a real restart. - GymStateNotifier restartedNotifier() => - ProviderContainer.test().read(gymStateProvider.notifier); + /// notifier, while the stored preferences and [logs] survive, as on a real + /// restart. + GymStateNotifier restartedNotifier({List logs = const []}) { + final logRepo = MockWorkoutLogRepository(); + when(logRepo.getLogsByIds(any)).thenAnswer( + (invocation) async => [ + for (final log in logs) + if ((invocation.positionalArguments.first as List).contains(log.id)) log, + ], + ); + return ProviderContainer.test( + overrides: [workoutLogRepositoryProvider.overrideWithValue(logRepo)], + ).read(gymStateProvider.notifier); + } Future openDay1(GymStateNotifier gymNotifier) => gymNotifier.open(getTestRoutine(), 1, 1); @@ -1016,7 +1031,7 @@ void main() { expect( notifier.state.progressOf(timerKey).timerStartedAt, DateTime(2026, 7, 26, 18, 30), - reason: 'the rest timer is not part of the stored progress, only of the one in memory', + reason: 'the rest timer keeps running', ); }); @@ -1072,14 +1087,84 @@ void main() { }); }); - test('Does not continue on a page the routine no longer has', () async { + test('Restores the logged entries and the rest timers', () async { + final logPage = notifier.state.pages[1].slotPages[1]; + final timerKey = notifier.state.pages[1].slotPages[2].key; + final log = Log(id: 'log-1', exerciseId: 1, weight: 80, date: DateTime(2026, 7, 26)); + await openDay1(notifier); + withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () { + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); + }); + notifier.setCurrentPage(3); + await pumpEventQueue(); + + final restarted = restartedNotifier(logs: [log]); + + expect(await openDay1(restarted), 3); + expect(restarted.state.progressOf(logPage.key).loggedEntry!.id, 'log-1'); + expect( + restarted.state.progressOf(timerKey).timerStartedAt, + DateTime(2026, 7, 26, 18, 30), + reason: 'the rest that started with the logged set keeps running', + ); + expect( + restarted.state.lastLoggedValues[1]!.weight, + 80, + reason: 'the sticky values come from the restored logs', + ); + }); + + test('Stores a rest timer as soon as it starts', () async { + await runWorkout(); + final timerKey = notifier.state.pages[1].slotPages[2].key; + + // Killed during the rest, before moving on to another page + withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () { + notifier.startTimerIfNeeded(timerKey); + }); + await pumpEventQueue(); + + final restarted = restartedNotifier(); + await openDay1(restarted); + + expect(restarted.state.progressOf(timerKey).timerStartedAt, DateTime(2026, 7, 26, 18, 30)); + }); + + test('Leaves out the pages the routine no longer has', () async { await runWorkout(); - // The routine was edited in the meantime and is now shorter than the - // page the workout stopped on - await editStoredProgress('currentPage', 999); + // The routine was edited in the meantime, the page the workout stopped + // on and one of the done sets are gone + await editStoredProgress('currentPageKey', 'log:999:1'); + final stored = + json.decode((await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS))!) + as Map; + await editStoredProgress('pages', { + ...stored['pages'] as Map, + 'log:999:2': {'done': true}, + }); + + final restarted = restartedNotifier(); + + expect(await openDay1(restarted), 0); + expect(restarted.state.progress.keys, ['log:1:1']); + }); + + test('Ignores progress stored in an older format', () async { + await PreferenceHelper.asyncPref.setString( + PREFS_WORKOUT_PROGRESS, + json.encode({ + 'dayId': 1, + 'iteration': 1, + 'currentPage': 2, + 'workoutStart': DateTime.now().toIso8601String(), + 'validUntil': DateTime.now().add(const Duration(hours: 1)).toIso8601String(), + 'donePageIndices': [2], + }), + ); expect(await openDay1(restartedNotifier()), 0); + expect(await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS), isNull); }); test('Forgets the workout once it is finished', () async { diff --git a/test/features/routines/providers/gym_state_test.mocks.dart b/test/features/routines/providers/gym_state_test.mocks.dart new file mode 100644 index 000000000..9ffda94cb --- /dev/null +++ b/test/features/routines/providers/gym_state_test.mocks.dart @@ -0,0 +1,87 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/routines/providers/gym_state_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes + +import 'dart:async' as _i3; + +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/features/routines/models/log.dart' as _i4; +import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i2; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: experimental_member_use +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +/// A class which mocks [WorkoutLogRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository { + MockWorkoutLogRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchLogsByExerciseDrift({ + int? routineId, + required int? exerciseId, + DateTime? since, + }) => + (super.noSuchMethod( + Invocation.method(#watchLogsByExerciseDrift, [], { + #routineId: routineId, + #exerciseId: exerciseId, + #since: since, + }), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i4.Log>[]), + ) + as _i3.Future>); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future updateLocalDrift(_i4.Log? log) => + (super.noSuchMethod( + Invocation.method(#updateLocalDrift, [log]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addLocalDrift(_i4.Log? log, {int? dayId}) => + (super.noSuchMethod( + Invocation.method(#addLocalDrift, [log], {#dayId: dayId}), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +} diff --git a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart index 9714b0872..614da26dc 100644 --- a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart +++ b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; @@ -49,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i4.Log>[]), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/features/routines/providers/workout_logs_repository_test.dart b/test/features/routines/providers/workout_logs_repository_test.dart index 0e3bd4945..3c8b43d78 100644 --- a/test/features/routines/providers/workout_logs_repository_test.dart +++ b/test/features/routines/providers/workout_logs_repository_test.dart @@ -464,4 +464,21 @@ void main() { await sub.cancel(); }); }); + + group('getLogsByIds', () { + test('returns the logs with the given ids, with their units', () async { + await seedUnits(); + final logs = [ + for (final weight in [10, 20, 30]) makeLog(weight: weight, sessionId: 's'), + ]; + for (final log in logs) { + await repo.addLocalDrift(log); + } + + final found = await repo.getLogsByIds([logs[0].id!, logs[2].id!, 'does-not-exist']); + + expect(found.map((l) => l.weight), unorderedEquals([10, 30])); + expect(found.map((l) => l.weightUnitObj?.name), everyElement('kg')); + }); + }); } diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index bd57a091e..95fc3f0ab 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i10; import 'package:mockito/mockito.dart' as _i1; @@ -552,6 +553,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i27.WorkoutLogReposi ) as _i10.Stream>); + @override + _i10.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i10.Future>.value(<_i28.Log>[]), + ) + as _i10.Future>); + @override _i10.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/features/routines/screens/routine_logs_screen_test.mocks.dart b/test/features/routines/screens/routine_logs_screen_test.mocks.dart index 035a259ff..c2ab95ffc 100644 --- a/test/features/routines/screens/routine_logs_screen_test.mocks.dart +++ b/test/features/routines/screens/routine_logs_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:mockito/mockito.dart' as _i1; @@ -155,6 +156,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit ) as _i5.Stream>); + @override + _i5.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i5.Future>.value(<_i10.Log>[]), + ) + as _i5.Future>); + @override _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( From 999ac4b5464bd51f8fc81b252ac05065d986b88d Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 22:39:19 +0100 Subject: [PATCH 23/29] Drop the stored workout progress with the local data --- lib/core/network/powersync_session.dart | 5 +++-- lib/core/shared_preferences.dart | 4 ++++ lib/features/routines/providers/gym_state.dart | 1 - test/core/network/auth_notifier_login_test.dart | 2 ++ 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/core/network/powersync_session.dart b/lib/core/network/powersync_session.dart index 7f6258be5..cd2b0b180 100644 --- a/lib/core/network/powersync_session.dart +++ b/lib/core/network/powersync_session.dart @@ -88,10 +88,11 @@ class PowerSyncSession { } // The account-scoped preferences leave with the data: the next account - // must not inherit the health-sync opt-in and watermarks, nor a timezone - // marker that would let the sync overwrite its chosen zone + // must not inherit the health-sync opt-in and watermarks, a timezone marker + // that would let the sync overwrite its chosen zone, or a running workout await PreferenceHelper.instance.clearHealthSyncPreferences(); await PreferenceHelper.asyncPref.remove(reportedTimezonePrefKey); + await PreferenceHelper.asyncPref.remove(PREFS_WORKOUT_PROGRESS); } } diff --git a/lib/core/shared_preferences.dart b/lib/core/shared_preferences.dart index 13d811fd2..2a4550b90 100644 --- a/lib/core/shared_preferences.dart +++ b/lib/core/shared_preferences.dart @@ -7,6 +7,10 @@ import 'package:wger/features/exercises/models/exercise_filters.dart'; import 'package:wger/features/nutrition/models/ingredient.dart'; import 'package:wger/features/nutrition/models/ingredient_filters.dart'; +/// The progress of a running gym mode workout. Belongs to the account, so it +/// leaves with the local data. +const PREFS_WORKOUT_PROGRESS = 'workoutProgressPrefs'; + /// A helper class that manages preferences using SharedPreferencesAsync /// and handles migration from the legacy SharedPreferences to /// SharedPreferencesAsync. diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 51bf588c6..869aaa5e1 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -37,7 +37,6 @@ const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; const PREFS_STICKY_SET_VALUES = 'stickySetValuesPrefs'; -const PREFS_WORKOUT_PROGRESS = 'workoutProgressPrefs'; /// In seconds const DEFAULT_COUNTDOWN_DURATION = 180; diff --git a/test/core/network/auth_notifier_login_test.dart b/test/core/network/auth_notifier_login_test.dart index 676b0e025..afa8ea6a1 100644 --- a/test/core/network/auth_notifier_login_test.dart +++ b/test/core/network/auth_notifier_login_test.dart @@ -404,6 +404,7 @@ void main() { await PreferenceHelper.asyncPref.setString(PREFS_DB_OWNER_USER_ID, '5'); await PreferenceHelper.instance.setHealthSyncEnabled(true); await PreferenceHelper.asyncPref.setString(reportedTimezonePrefKey, 'Pacific/Auckland'); + await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, '{"dayId": 1}'); stubLoginSuccess(makeJwt({'sub': '7', 'exp': 1900000000})); final container = makeContainer(); @@ -412,6 +413,7 @@ void main() { expect(await PreferenceHelper.instance.getHealthSyncEnabled(), isFalse); expect(await PreferenceHelper.asyncPref.getString(reportedTimezonePrefKey), isNull); + expect(await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS), isNull); }); test('same user logging back in keeps the local DB', () async { From d7498bc18f39c4edadabb0935dfd068e40cd8d65 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 22:48:24 +0100 Subject: [PATCH 24/29] Regenerate code after the json_serializable and mockito bumps --- lib/features/gallery/models/image.g.dart | 2 +- lib/features/routines/models/routine.g.dart | 2 +- .../providers/gym_log_notifier.g.dart | 2 +- .../providers/gym_state_notifier.g.dart | 2 +- .../media_url_prefix_notifier_test.mocks.dart | 1 + .../auth_credentials_storage_test.mocks.dart | 1 + .../network/auth_http_client_test.mocks.dart | 1 + .../auth_notifier_login_test.mocks.dart | 1 + .../auth_notifier_powersync_test.mocks.dart | 1 + .../network/base_provider_test.mocks.dart | 1 + test/core/recovery_screens_test.mocks.dart | 1 + test/core/validators_test.mocks.dart | 45 +++++++++++++++++++ .../account_notifier_test.mocks.dart | 1 + .../account_repository_test.mocks.dart | 1 + .../user_profile_notifier_test.mocks.dart | 1 + .../account/widgets/forms_test.mocks.dart | 1 + .../account/widgets/settings_test.mocks.dart | 1 + .../auth/screens/auth_screen_test.mocks.dart | 1 + .../mfa_challenge_screen_test.mocks.dart | 1 + .../add_exercise_notifier_test.mocks.dart | 1 + .../add_exercise_repository_test.mocks.dart | 1 + .../exercise_filters_notifier_test.mocks.dart | 1 + .../exercise_repository_test.mocks.dart | 1 + .../exercises_notifier_test.mocks.dart | 1 + .../add_exercise_screen_test.mocks.dart | 1 + .../exercises_detail_widget_test.mocks.dart | 1 + .../gallery_notifier_test.mocks.dart | 1 + .../gallery_repository_test.mocks.dart | 1 + .../screens/gallery_screen_test.mocks.dart | 1 + .../gallery/widgets/forms_test.mocks.dart | 1 + .../gallery/widgets/overview_test.mocks.dart | 1 + .../health_repository_test.mocks.dart | 1 + .../body_weight_provider_test.mocks.dart | 1 + .../measurement_notifier_test.mocks.dart | 1 + ...surement_categories_screen_test.mocks.dart | 1 + ...ement_category_sort_screen_test.mocks.dart | 1 + ...measurement_entries_screen_test.mocks.dart | 1 + .../screens/weight_screen_test.mocks.dart | 1 + .../widgets/calculation_mark_test.mocks.dart | 1 + .../calculation_params_test.mocks.dart | 1 + .../widgets/categories_test.mocks.dart | 1 + .../widgets/entries_test.mocks.dart | 1 + .../widgets/forms/category_test.mocks.dart | 1 + .../widgets/forms/entry_test.mocks.dart | 1 + .../widgets/forms/group_entry_test.mocks.dart | 1 + .../widgets/measurement_fab_test.mocks.dart | 1 + .../widgets/measurement_tile_test.mocks.dart | 1 + .../widgets/metric_picker_test.mocks.dart | 1 + .../widgets/weight_form_test.mocks.dart | 1 + .../ingredient_notifier_test.mocks.dart | 1 + .../ingredient_repository_test.mocks.dart | 1 + .../nutrition_notifier_test.mocks.dart | 1 + .../nutritional_plan_screen_test.mocks.dart | 1 + .../nutritional_plans_screen_test.mocks.dart | 1 + .../ingredient_typeahead_test.mocks.dart | 1 + .../nutritional_meal_form_test.mocks.dart | 1 + ...nutritional_meal_item_form_test.mocks.dart | 1 + .../nutritional_plan_form_test.mocks.dart | 1 + .../widgets/plan_weight_chart_test.mocks.dart | 1 + .../routine_form_test_overrides.mocks.dart | 1 + .../providers/plate_weights_test.mocks.dart | 1 + .../routines_notifier_test.mocks.dart | 1 + .../routines_repository_test.mocks.dart | 1 + .../workout_logs_notifier_test.mocks.dart | 1 + .../routines/screens/gym_mode_test.mocks.dart | 1 + .../routine_list_screen_test.mocks.dart | 1 + .../routine_logs_screen_test.mocks.dart | 1 + .../widgets/forms/day_form_test.mocks.dart | 1 + .../forms/routine_form_test.mocks.dart | 1 + .../forms/session_form_test.mocks.dart | 1 + .../forms/slot_entry_form_test.mocks.dart | 1 + .../widgets/forms/slot_test.mocks.dart | 1 + .../widgets/gym_mode/log_page_test.mocks.dart | 1 + .../gym_mode/session_page_test.mocks.dart | 1 + .../widgets/routine_edit_test.mocks.dart | 1 + .../trophy_repository_test.mocks.dart | 1 + test/powersync/api_client_test.mocks.dart | 1 + test/powersync/connector_test.mocks.dart | 1 + .../screenshots_01_dashboard.mocks.dart | 21 +++++++++ .../screenshots_02_workout.mocks.dart | 1 + .../screenshots_04_measurements.mocks.dart | 1 + ...screenshots_05_nutritional_plan.mocks.dart | 1 + 82 files changed, 146 insertions(+), 4 deletions(-) diff --git a/lib/features/gallery/models/image.g.dart b/lib/features/gallery/models/image.g.dart index 1746385d9..55114cbdb 100644 --- a/lib/features/gallery/models/image.g.dart +++ b/lib/features/gallery/models/image.g.dart @@ -10,7 +10,7 @@ GalleryImage _$GalleryImageFromJson(Map json) { $checkKeys(json, requiredKeys: const ['id', 'date']); return GalleryImage( id: (json['id'] as num?)?.toInt(), - date: utcIso8601ToLocalDate(json['date'] as String), + date: json['date'] == null ? null : utcIso8601ToLocalDate(json['date'] as String), imagePath: json['image'] as String?, description: json['description'] as String? ?? '', ); diff --git a/lib/features/routines/models/routine.g.dart b/lib/features/routines/models/routine.g.dart index 4beef3c50..86ffc93c3 100644 --- a/lib/features/routines/models/routine.g.dart +++ b/lib/features/routines/models/routine.g.dart @@ -21,7 +21,7 @@ Routine _$RoutineFromJson(Map json) { ); return Routine( id: (json['id'] as num?)?.toInt(), - created: utcIso8601ToLocalDate(json['created'] as String), + created: json['created'] == null ? null : utcIso8601ToLocalDate(json['created'] as String), name: json['name'] as String, start: json['start'] == null ? null : DateTime.parse(json['start'] as String), end: json['end'] == null ? null : DateTime.parse(json['end'] as String), diff --git a/lib/features/routines/providers/gym_log_notifier.g.dart b/lib/features/routines/providers/gym_log_notifier.g.dart index 0b99b311d..bbb2f8767 100644 --- a/lib/features/routines/providers/gym_log_notifier.g.dart +++ b/lib/features/routines/providers/gym_log_notifier.g.dart @@ -40,7 +40,7 @@ final class GymLogNotifierProvider extends $NotifierProvider r'f19f65118fc2746149178debd2f5fcb1cdfcab3c'; +String _$gymLogNotifierHash() => r'd50243d3e4a87c02812e15b3c5bb207a8ef2d1b6'; abstract class _$GymLogNotifier extends $Notifier { Log? build(); diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 691ca7d7f..9e8adfb2f 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'be5943c4201793dc053ef44a4a243226e6d38526'; +String _$gymStateNotifierHash() => r'6edef80da81e457a1d2b600dc205194d34adb407'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/test/core/media_url_prefix_notifier_test.mocks.dart b/test/core/media_url_prefix_notifier_test.mocks.dart index 2b8a924d3..c9d566eaa 100644 --- a/test/core/media_url_prefix_notifier_test.mocks.dart +++ b/test/core/media_url_prefix_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:http/http.dart' as _i2; diff --git a/test/core/network/auth_credentials_storage_test.mocks.dart b/test/core/network/auth_credentials_storage_test.mocks.dart index 1e0646949..48e9fc57f 100644 --- a/test/core/network/auth_credentials_storage_test.mocks.dart +++ b/test/core/network/auth_credentials_storage_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/core/network/auth_http_client_test.mocks.dart b/test/core/network/auth_http_client_test.mocks.dart index 70638b4d6..c7c520663 100644 --- a/test/core/network/auth_http_client_test.mocks.dart +++ b/test/core/network/auth_http_client_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/core/network/auth_notifier_login_test.mocks.dart b/test/core/network/auth_notifier_login_test.mocks.dart index f96a457ba..5a9b46dcf 100644 --- a/test/core/network/auth_notifier_login_test.mocks.dart +++ b/test/core/network/auth_notifier_login_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'dart:convert' as _i5; import 'dart:typed_data' as _i7; diff --git a/test/core/network/auth_notifier_powersync_test.mocks.dart b/test/core/network/auth_notifier_powersync_test.mocks.dart index 2ee94da66..ee143ccaf 100644 --- a/test/core/network/auth_notifier_powersync_test.mocks.dart +++ b/test/core/network/auth_notifier_powersync_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/core/network/base_provider_test.mocks.dart b/test/core/network/base_provider_test.mocks.dart index 8907696e3..6cf38afda 100644 --- a/test/core/network/base_provider_test.mocks.dart +++ b/test/core/network/base_provider_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/core/recovery_screens_test.mocks.dart b/test/core/recovery_screens_test.mocks.dart index acbbaf708..136dda357 100644 --- a/test/core/recovery_screens_test.mocks.dart +++ b/test/core/recovery_screens_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index d81e0e6dd..2b86b41fe 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i3; import 'package:wger/l10n/generated/app_localizations.dart' as _i2; @@ -1548,6 +1549,39 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get upNext => + (super.noSuchMethod( + Invocation.getter(#upNext), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#upNext), + ), + ) + as String); + + @override + String get gymModeStickySetValues => + (super.noSuchMethod( + Invocation.getter(#gymModeStickySetValues), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeStickySetValues), + ), + ) + as String); + + @override + String get gymModeStickySetValuesHelp => + (super.noSuchMethod( + Invocation.getter(#gymModeStickySetValuesHelp), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#gymModeStickySetValuesHelp), + ), + ) + as String); + @override String get jumpTo => (super.noSuchMethod( @@ -3687,6 +3721,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get authorHelpText => + (super.noSuchMethod( + Invocation.getter(#authorHelpText), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#authorHelpText), + ), + ) + as String); + @override String get imageDetailsAuthorLink => (super.noSuchMethod( diff --git a/test/features/account/providers/account_notifier_test.mocks.dart b/test/features/account/providers/account_notifier_test.mocks.dart index f6cbee1b3..f18fadbfb 100644 --- a/test/features/account/providers/account_notifier_test.mocks.dart +++ b/test/features/account/providers/account_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/account/providers/account_repository_test.mocks.dart b/test/features/account/providers/account_repository_test.mocks.dart index a3f8eeb1f..9e68d43d2 100644 --- a/test/features/account/providers/account_repository_test.mocks.dart +++ b/test/features/account/providers/account_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/features/account/providers/user_profile_notifier_test.mocks.dart b/test/features/account/providers/user_profile_notifier_test.mocks.dart index 7cc0e06d1..55ed4730d 100644 --- a/test/features/account/providers/user_profile_notifier_test.mocks.dart +++ b/test/features/account/providers/user_profile_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/account/widgets/forms_test.mocks.dart b/test/features/account/widgets/forms_test.mocks.dart index f176c81d6..6a099aa4c 100644 --- a/test/features/account/widgets/forms_test.mocks.dart +++ b/test/features/account/widgets/forms_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/account/widgets/settings_test.mocks.dart b/test/features/account/widgets/settings_test.mocks.dart index ed63072bf..280237914 100644 --- a/test/features/account/widgets/settings_test.mocks.dart +++ b/test/features/account/widgets/settings_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/auth/screens/auth_screen_test.mocks.dart b/test/features/auth/screens/auth_screen_test.mocks.dart index 3f7dc258b..638a8f276 100644 --- a/test/features/auth/screens/auth_screen_test.mocks.dart +++ b/test/features/auth/screens/auth_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/features/auth/screens/mfa_challenge_screen_test.mocks.dart b/test/features/auth/screens/mfa_challenge_screen_test.mocks.dart index 658221c37..2b5d7189d 100644 --- a/test/features/auth/screens/mfa_challenge_screen_test.mocks.dart +++ b/test/features/auth/screens/mfa_challenge_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/features/exercises/providers/add_exercise_notifier_test.mocks.dart b/test/features/exercises/providers/add_exercise_notifier_test.mocks.dart index 8822b6cc4..eb040c9f9 100644 --- a/test/features/exercises/providers/add_exercise_notifier_test.mocks.dart +++ b/test/features/exercises/providers/add_exercise_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/exercises/providers/add_exercise_repository_test.mocks.dart b/test/features/exercises/providers/add_exercise_repository_test.mocks.dart index 2fb5cf6a7..0b495f1a0 100644 --- a/test/features/exercises/providers/add_exercise_repository_test.mocks.dart +++ b/test/features/exercises/providers/add_exercise_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/features/exercises/providers/exercise_filters_notifier_test.mocks.dart b/test/features/exercises/providers/exercise_filters_notifier_test.mocks.dart index c3509ff43..b8d5fb491 100644 --- a/test/features/exercises/providers/exercise_filters_notifier_test.mocks.dart +++ b/test/features/exercises/providers/exercise_filters_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/exercises/providers/exercise_repository_test.mocks.dart b/test/features/exercises/providers/exercise_repository_test.mocks.dart index 33e2d3686..75f77bd35 100644 --- a/test/features/exercises/providers/exercise_repository_test.mocks.dart +++ b/test/features/exercises/providers/exercise_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/features/exercises/providers/exercises_notifier_test.mocks.dart b/test/features/exercises/providers/exercises_notifier_test.mocks.dart index e10304eea..6026d4804 100644 --- a/test/features/exercises/providers/exercises_notifier_test.mocks.dart +++ b/test/features/exercises/providers/exercises_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/exercises/screens/add_exercise_screen_test.mocks.dart b/test/features/exercises/screens/add_exercise_screen_test.mocks.dart index bcd4499e1..8cf7d4cbf 100644 --- a/test/features/exercises/screens/add_exercise_screen_test.mocks.dart +++ b/test/features/exercises/screens/add_exercise_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/exercises/widgets/exercises_detail_widget_test.mocks.dart b/test/features/exercises/widgets/exercises_detail_widget_test.mocks.dart index f73b561e3..46afc69df 100644 --- a/test/features/exercises/widgets/exercises_detail_widget_test.mocks.dart +++ b/test/features/exercises/widgets/exercises_detail_widget_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/gallery/providers/gallery_notifier_test.mocks.dart b/test/features/gallery/providers/gallery_notifier_test.mocks.dart index 9929651ba..e5e35b70b 100644 --- a/test/features/gallery/providers/gallery_notifier_test.mocks.dart +++ b/test/features/gallery/providers/gallery_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:image_picker/image_picker.dart' as _i5; diff --git a/test/features/gallery/providers/gallery_repository_test.mocks.dart b/test/features/gallery/providers/gallery_repository_test.mocks.dart index 594009242..c481cc59d 100644 --- a/test/features/gallery/providers/gallery_repository_test.mocks.dart +++ b/test/features/gallery/providers/gallery_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/features/gallery/screens/gallery_screen_test.mocks.dart b/test/features/gallery/screens/gallery_screen_test.mocks.dart index 3847d332a..772d5d7ba 100644 --- a/test/features/gallery/screens/gallery_screen_test.mocks.dart +++ b/test/features/gallery/screens/gallery_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:image_picker/image_picker.dart' as _i5; diff --git a/test/features/gallery/widgets/forms_test.mocks.dart b/test/features/gallery/widgets/forms_test.mocks.dart index 3fb68c25a..27f4978cc 100644 --- a/test/features/gallery/widgets/forms_test.mocks.dart +++ b/test/features/gallery/widgets/forms_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:image_picker/image_picker.dart' as _i5; diff --git a/test/features/gallery/widgets/overview_test.mocks.dart b/test/features/gallery/widgets/overview_test.mocks.dart index 525618162..0feb3b23e 100644 --- a/test/features/gallery/widgets/overview_test.mocks.dart +++ b/test/features/gallery/widgets/overview_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:image_picker/image_picker.dart' as _i5; diff --git a/test/features/health/providers/health_repository_test.mocks.dart b/test/features/health/providers/health_repository_test.mocks.dart index ba3f40ae5..74afde0eb 100644 --- a/test/features/health/providers/health_repository_test.mocks.dart +++ b/test/features/health/providers/health_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:health_bridge/health.dart' as _i2; diff --git a/test/features/measurements/providers/body_weight_provider_test.mocks.dart b/test/features/measurements/providers/body_weight_provider_test.mocks.dart index 0f0a8f6c5..5cf2c0219 100644 --- a/test/features/measurements/providers/body_weight_provider_test.mocks.dart +++ b/test/features/measurements/providers/body_weight_provider_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/providers/measurement_notifier_test.mocks.dart b/test/features/measurements/providers/measurement_notifier_test.mocks.dart index 865d07b2f..76d4db4e8 100644 --- a/test/features/measurements/providers/measurement_notifier_test.mocks.dart +++ b/test/features/measurements/providers/measurement_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart index 75b12d435..e2b848d7b 100644 --- a/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_categories_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart b/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart index ef9871131..392179bd8 100644 --- a/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_category_sort_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart index 8273f2ac8..83a781f8d 100644 --- a/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart +++ b/test/features/measurements/screens/measurement_entries_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/screens/weight_screen_test.mocks.dart b/test/features/measurements/screens/weight_screen_test.mocks.dart index 0524b8d8b..0b5a89db4 100644 --- a/test/features/measurements/screens/weight_screen_test.mocks.dart +++ b/test/features/measurements/screens/weight_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/calculation_mark_test.mocks.dart b/test/features/measurements/widgets/calculation_mark_test.mocks.dart index 79142d505..f25c77d02 100644 --- a/test/features/measurements/widgets/calculation_mark_test.mocks.dart +++ b/test/features/measurements/widgets/calculation_mark_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/calculation_params_test.mocks.dart b/test/features/measurements/widgets/calculation_params_test.mocks.dart index 5cc809076..75e880907 100644 --- a/test/features/measurements/widgets/calculation_params_test.mocks.dart +++ b/test/features/measurements/widgets/calculation_params_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/categories_test.mocks.dart b/test/features/measurements/widgets/categories_test.mocks.dart index 7b34abf07..395c793a7 100644 --- a/test/features/measurements/widgets/categories_test.mocks.dart +++ b/test/features/measurements/widgets/categories_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/entries_test.mocks.dart b/test/features/measurements/widgets/entries_test.mocks.dart index 4e07e7aed..22bea736e 100644 --- a/test/features/measurements/widgets/entries_test.mocks.dart +++ b/test/features/measurements/widgets/entries_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/forms/category_test.mocks.dart b/test/features/measurements/widgets/forms/category_test.mocks.dart index 60eae2f89..0f85dc4cd 100644 --- a/test/features/measurements/widgets/forms/category_test.mocks.dart +++ b/test/features/measurements/widgets/forms/category_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/forms/entry_test.mocks.dart b/test/features/measurements/widgets/forms/entry_test.mocks.dart index 697b76f90..41f0e3f6b 100644 --- a/test/features/measurements/widgets/forms/entry_test.mocks.dart +++ b/test/features/measurements/widgets/forms/entry_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/forms/group_entry_test.mocks.dart b/test/features/measurements/widgets/forms/group_entry_test.mocks.dart index 80547b03b..ccef757e0 100644 --- a/test/features/measurements/widgets/forms/group_entry_test.mocks.dart +++ b/test/features/measurements/widgets/forms/group_entry_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/measurement_fab_test.mocks.dart b/test/features/measurements/widgets/measurement_fab_test.mocks.dart index 008f63ee2..273101514 100644 --- a/test/features/measurements/widgets/measurement_fab_test.mocks.dart +++ b/test/features/measurements/widgets/measurement_fab_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/measurement_tile_test.mocks.dart b/test/features/measurements/widgets/measurement_tile_test.mocks.dart index 5d3f94fc1..53d599c46 100644 --- a/test/features/measurements/widgets/measurement_tile_test.mocks.dart +++ b/test/features/measurements/widgets/measurement_tile_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/metric_picker_test.mocks.dart b/test/features/measurements/widgets/metric_picker_test.mocks.dart index ce204fef8..b3322f065 100644 --- a/test/features/measurements/widgets/metric_picker_test.mocks.dart +++ b/test/features/measurements/widgets/metric_picker_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/measurements/widgets/weight_form_test.mocks.dart b/test/features/measurements/widgets/weight_form_test.mocks.dart index 9c9634d73..eb6a7b0d7 100644 --- a/test/features/measurements/widgets/weight_form_test.mocks.dart +++ b/test/features/measurements/widgets/weight_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/providers/ingredient_notifier_test.mocks.dart b/test/features/nutrition/providers/ingredient_notifier_test.mocks.dart index dfd0143c0..c6a3c4e84 100644 --- a/test/features/nutrition/providers/ingredient_notifier_test.mocks.dart +++ b/test/features/nutrition/providers/ingredient_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/providers/ingredient_repository_test.mocks.dart b/test/features/nutrition/providers/ingredient_repository_test.mocks.dart index 41a6d3836..3aebf6a1a 100644 --- a/test/features/nutrition/providers/ingredient_repository_test.mocks.dart +++ b/test/features/nutrition/providers/ingredient_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/features/nutrition/providers/nutrition_notifier_test.mocks.dart b/test/features/nutrition/providers/nutrition_notifier_test.mocks.dart index 3176aeaef..98a2ecf98 100644 --- a/test/features/nutrition/providers/nutrition_notifier_test.mocks.dart +++ b/test/features/nutrition/providers/nutrition_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/screens/nutritional_plan_screen_test.mocks.dart b/test/features/nutrition/screens/nutritional_plan_screen_test.mocks.dart index 2ca857a25..30254f28f 100644 --- a/test/features/nutrition/screens/nutritional_plan_screen_test.mocks.dart +++ b/test/features/nutrition/screens/nutritional_plan_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'dart:convert' as _i13; import 'dart:typed_data' as _i15; diff --git a/test/features/nutrition/screens/nutritional_plans_screen_test.mocks.dart b/test/features/nutrition/screens/nutritional_plans_screen_test.mocks.dart index 69a945d91..b3b1d807e 100644 --- a/test/features/nutrition/screens/nutritional_plans_screen_test.mocks.dart +++ b/test/features/nutrition/screens/nutritional_plans_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'dart:convert' as _i13; import 'dart:typed_data' as _i15; diff --git a/test/features/nutrition/widgets/ingredient_typeahead_test.mocks.dart b/test/features/nutrition/widgets/ingredient_typeahead_test.mocks.dart index be77b0d4c..2137cda5c 100644 --- a/test/features/nutrition/widgets/ingredient_typeahead_test.mocks.dart +++ b/test/features/nutrition/widgets/ingredient_typeahead_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/widgets/nutritional_meal_form_test.mocks.dart b/test/features/nutrition/widgets/nutritional_meal_form_test.mocks.dart index 68906ed1e..cffb83de6 100644 --- a/test/features/nutrition/widgets/nutritional_meal_form_test.mocks.dart +++ b/test/features/nutrition/widgets/nutritional_meal_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/widgets/nutritional_meal_item_form_test.mocks.dart b/test/features/nutrition/widgets/nutritional_meal_item_form_test.mocks.dart index b09c289e6..a3d172dd4 100644 --- a/test/features/nutrition/widgets/nutritional_meal_item_form_test.mocks.dart +++ b/test/features/nutrition/widgets/nutritional_meal_item_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/features/nutrition/widgets/nutritional_plan_form_test.mocks.dart b/test/features/nutrition/widgets/nutritional_plan_form_test.mocks.dart index a41a4e7d7..a2a0bd589 100644 --- a/test/features/nutrition/widgets/nutritional_plan_form_test.mocks.dart +++ b/test/features/nutrition/widgets/nutritional_plan_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/nutrition/widgets/plan_weight_chart_test.mocks.dart b/test/features/nutrition/widgets/plan_weight_chart_test.mocks.dart index 513b43ebd..7d334197a 100644 --- a/test/features/nutrition/widgets/plan_weight_chart_test.mocks.dart +++ b/test/features/nutrition/widgets/plan_weight_chart_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/helpers/routine_form_test_overrides.mocks.dart b/test/features/routines/helpers/routine_form_test_overrides.mocks.dart index 926cb4930..b8d4b1d3a 100644 --- a/test/features/routines/helpers/routine_form_test_overrides.mocks.dart +++ b/test/features/routines/helpers/routine_form_test_overrides.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/providers/plate_weights_test.mocks.dart b/test/features/routines/providers/plate_weights_test.mocks.dart index ff81daa22..02ad308bb 100644 --- a/test/features/routines/providers/plate_weights_test.mocks.dart +++ b/test/features/routines/providers/plate_weights_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/providers/routines_notifier_test.mocks.dart b/test/features/routines/providers/routines_notifier_test.mocks.dart index b79498965..5d483eeee 100644 --- a/test/features/routines/providers/routines_notifier_test.mocks.dart +++ b/test/features/routines/providers/routines_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/providers/routines_repository_test.mocks.dart b/test/features/routines/providers/routines_repository_test.mocks.dart index 4bbcf4e3a..f2143ebb8 100644 --- a/test/features/routines/providers/routines_repository_test.mocks.dart +++ b/test/features/routines/providers/routines_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i7; import 'package:drift/backends.dart' as _i5; diff --git a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart index 9714b0872..bb10c76e4 100644 --- a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart +++ b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index bd57a091e..c76d91f0d 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i10; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/screens/routine_list_screen_test.mocks.dart b/test/features/routines/screens/routine_list_screen_test.mocks.dart index 245091a09..3a9025161 100644 --- a/test/features/routines/screens/routine_list_screen_test.mocks.dart +++ b/test/features/routines/screens/routine_list_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/screens/routine_logs_screen_test.mocks.dart b/test/features/routines/screens/routine_logs_screen_test.mocks.dart index 035a259ff..85050f1cc 100644 --- a/test/features/routines/screens/routine_logs_screen_test.mocks.dart +++ b/test/features/routines/screens/routine_logs_screen_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/forms/day_form_test.mocks.dart b/test/features/routines/widgets/forms/day_form_test.mocks.dart index 9c66902a3..76d02fd29 100644 --- a/test/features/routines/widgets/forms/day_form_test.mocks.dart +++ b/test/features/routines/widgets/forms/day_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/forms/routine_form_test.mocks.dart b/test/features/routines/widgets/forms/routine_form_test.mocks.dart index ed2d71550..d5acddf4a 100644 --- a/test/features/routines/widgets/forms/routine_form_test.mocks.dart +++ b/test/features/routines/widgets/forms/routine_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i9; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/forms/session_form_test.mocks.dart b/test/features/routines/widgets/forms/session_form_test.mocks.dart index cdeb52d55..9b8f5051d 100644 --- a/test/features/routines/widgets/forms/session_form_test.mocks.dart +++ b/test/features/routines/widgets/forms/session_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/forms/slot_entry_form_test.mocks.dart b/test/features/routines/widgets/forms/slot_entry_form_test.mocks.dart index c316dfbaf..0a21ff398 100644 --- a/test/features/routines/widgets/forms/slot_entry_form_test.mocks.dart +++ b/test/features/routines/widgets/forms/slot_entry_form_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/forms/slot_test.mocks.dart b/test/features/routines/widgets/forms/slot_test.mocks.dart index 1cc6ae65a..9b70f8df7 100644 --- a/test/features/routines/widgets/forms/slot_test.mocks.dart +++ b/test/features/routines/widgets/forms/slot_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart index 353d5c80f..3853e98bc 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/gym_mode/session_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/session_page_test.mocks.dart index 3a6b9c085..eea43ee18 100644 --- a/test/features/routines/widgets/gym_mode/session_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/session_page_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i4; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/routines/widgets/routine_edit_test.mocks.dart b/test/features/routines/widgets/routine_edit_test.mocks.dart index aa9a0af27..8b46c481e 100644 --- a/test/features/routines/widgets/routine_edit_test.mocks.dart +++ b/test/features/routines/widgets/routine_edit_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/features/trophies/providers/trophy_repository_test.mocks.dart b/test/features/trophies/providers/trophy_repository_test.mocks.dart index c32a0da46..74ddcd9aa 100644 --- a/test/features/trophies/providers/trophy_repository_test.mocks.dart +++ b/test/features/trophies/providers/trophy_repository_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/powersync/api_client_test.mocks.dart b/test/powersync/api_client_test.mocks.dart index b8b5477a7..7acda923e 100644 --- a/test/powersync/api_client_test.mocks.dart +++ b/test/powersync/api_client_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'dart:convert' as _i4; import 'dart:typed_data' as _i6; diff --git a/test/powersync/connector_test.mocks.dart b/test/powersync/connector_test.mocks.dart index f02041f88..54ed3b9d6 100644 --- a/test/powersync/connector_test.mocks.dart +++ b/test/powersync/connector_test.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i5; import 'package:http/http.dart' as _i2; diff --git a/test/screenshots/screenshots_01_dashboard.mocks.dart b/test/screenshots/screenshots_01_dashboard.mocks.dart index 240a529ea..54b5672fb 100644 --- a/test/screenshots/screenshots_01_dashboard.mocks.dart +++ b/test/screenshots/screenshots_01_dashboard.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i11; import 'package:health_bridge/health.dart' as _i44; @@ -1126,6 +1127,14 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository { ) as String); + @override + bool get hasPlatformTotals => + (super.noSuchMethod( + Invocation.getter(#hasPlatformTotals), + returnValue: false, + ) + as bool); + @override _i11.Future<_i43.HealthPlatformAvailability> availability() => (super.noSuchMethod( @@ -1173,6 +1182,18 @@ class MockHealthRepository extends _i1.Mock implements _i43.HealthRepository { ) as _i11.Future); + @override + _i11.Future platformTotal( + _i44.HealthDataType? type, + DateTime? start, + DateTime? end, + ) => + (super.noSuchMethod( + Invocation.method(#platformTotal, [type, start, end]), + returnValue: _i11.Future.value(), + ) + as _i11.Future); + @override _i11.Future read({ required List<_i44.HealthDataType>? types, diff --git a/test/screenshots/screenshots_02_workout.mocks.dart b/test/screenshots/screenshots_02_workout.mocks.dart index 75cbef624..697c180be 100644 --- a/test/screenshots/screenshots_02_workout.mocks.dart +++ b/test/screenshots/screenshots_02_workout.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i8; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/screenshots/screenshots_04_measurements.mocks.dart b/test/screenshots/screenshots_04_measurements.mocks.dart index 7d81ff71f..42b600d29 100644 --- a/test/screenshots/screenshots_04_measurements.mocks.dart +++ b/test/screenshots/screenshots_04_measurements.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; diff --git a/test/screenshots/screenshots_05_nutritional_plan.mocks.dart b/test/screenshots/screenshots_05_nutritional_plan.mocks.dart index 570d1d92d..6dee10acf 100644 --- a/test/screenshots/screenshots_05_nutritional_plan.mocks.dart +++ b/test/screenshots/screenshots_05_nutritional_plan.mocks.dart @@ -3,6 +3,7 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes + import 'dart:async' as _i3; import 'package:mockito/mockito.dart' as _i1; From 64ecba31bb2594d384d35e892f30c24287aaf2b8 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Mon, 26 Oct 2026 22:58:29 +0100 Subject: [PATCH 25/29] Copy the changed objects when replacing an exercise in gym mode replaceExercise only copied the lists, but changed the contained set configs, slots and logs in place. These are shared with the cached routine, so swapping an exercise in gym mode also changed the routine screens and the session logs until the next reload. --- lib/features/routines/models/routine.dart | 90 ++++++++++--------- .../routines/models/routine_test.dart | 25 ++++++ 2 files changed, 71 insertions(+), 44 deletions(-) diff --git a/lib/features/routines/models/routine.dart b/lib/features/routines/models/routine.dart index 458c8526a..8407c84ec 100644 --- a/lib/features/routines/models/routine.dart +++ b/lib/features/routines/models/routine.dart @@ -26,6 +26,7 @@ import 'package:wger/features/routines/models/day.dart'; import 'package:wger/features/routines/models/day_data.dart'; import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/session.dart'; +import 'package:wger/features/routines/models/slot_data.dart'; part 'routine.g.dart'; @@ -278,51 +279,52 @@ class Routine { return groupedLogs; } + /// Returns a copy with [oldExerciseId] replaced by [newExercise] in the days + /// and session logs, this routine is left untouched Routine replaceExercise(int oldExerciseId, Exercise newExercise) { - final updatedRoutine = copyWith( - sessions: List.from(sessions), - dayData: List.from(dayData), - dayDataGym: List.from(dayDataGym), + List replaceInDays(List days) => [ + for (final day in days) + DayData( + iteration: day.iteration, + date: day.date, + label: day.label, + day: day.day, + slots: [ + for (final slot in day.slots) + SlotData( + comment: slot.comment, + isSuperset: slot.isSuperset, + exerciseIds: [ + for (final id in slot.exerciseIds) + if (id == oldExerciseId) newExercise.id else id, + ], + setConfigs: [ + for (final config in slot.setConfigs) + if (config.exerciseId == oldExerciseId) + config.copyWith(exerciseId: newExercise.id, exercise: newExercise) + else + config, + ], + ), + ], + ), + ]; + + return copyWith( + sessions: [ + for (final session in sessions) + session.copyWith( + logs: [ + for (final log in session.logs) + if (log.exerciseId == oldExerciseId) + log.copyWith()..exercise = newExercise + else + log, + ], + ), + ], + dayData: replaceInDays(dayData), + dayDataGym: replaceInDays(dayDataGym), ); - - for (final session in updatedRoutine.sessions) { - for (final log in session.logs) { - if (log.exerciseId == oldExerciseId) { - log.exerciseId = newExercise.id; - log.exercise = newExercise; - } - } - } - - for (final day in updatedRoutine.dayData) { - for (final slot in day.slots) { - slot.exerciseIds = [ - for (final id in slot.exerciseIds) - if (id == oldExerciseId) newExercise.id else id, - ]; - for (final config in slot.setConfigs) { - if (config.exerciseId == oldExerciseId) { - config.exerciseId = newExercise.id; - config.exercise = newExercise; - } - } - } - } - - for (final day in updatedRoutine.dayDataGym) { - for (final slot in day.slots) { - slot.exerciseIds = [ - for (final id in slot.exerciseIds) - if (id == oldExerciseId) newExercise.id else id, - ]; - for (final config in slot.setConfigs) { - if (config.exerciseId == oldExerciseId) { - config.exerciseId = newExercise.id; - config.exercise = newExercise; - } - } - } - } - return updatedRoutine; } } diff --git a/test/features/routines/models/routine_test.dart b/test/features/routines/models/routine_test.dart index f39a1d30b..8aae84e78 100644 --- a/test/features/routines/models/routine_test.dart +++ b/test/features/routines/models/routine_test.dart @@ -18,6 +18,7 @@ import 'package:flutter_test/flutter_test.dart'; +import '../../../../test_data/exercises.dart'; import '../../../../test_data/routines.dart'; void main() { @@ -80,5 +81,29 @@ void main() { expect(result[10], [routine.logs[0]]); expect(result[12], [routine.logs[1]]); }); + + test('replaceExercise returns a copy and leaves the original untouched', () { + final routine = getTestRoutine(); + + final replaced = routine.replaceExercise(1, testSquats); + + final gymSlot = replaced.dayDataGym[0].slots[0]; + expect(gymSlot.exerciseIds, [testSquats.id]); + expect(gymSlot.setConfigs.map((c) => c.exerciseId), everyElement(testSquats.id)); + expect(gymSlot.setConfigs.map((c) => c.exercise.id), everyElement(testSquats.id)); + expect(replaced.dayData[0].slots[0].exerciseIds, [testSquats.id]); + expect(replaced.dayData[0].slots[0].setConfigs.single.exerciseId, testSquats.id); + expect(replaced.logs.map((l) => l.exerciseId), [testSquats.id, testSquats.id, 2]); + expect(replaced.logs.first.exerciseObj.id, testSquats.id); + + final originalGymSlot = routine.dayDataGym[0].slots[0]; + expect(originalGymSlot.exerciseIds, [1]); + expect(originalGymSlot.setConfigs.map((c) => c.exerciseId), everyElement(1)); + expect(originalGymSlot.setConfigs.map((c) => c.exercise.id), everyElement(1)); + expect(routine.dayData[0].slots[0].exerciseIds, [1]); + expect(routine.dayData[0].slots[0].setConfigs.single.exerciseId, 1); + expect(routine.logs.map((l) => l.exerciseId), [1, 1, 2]); + expect(routine.logs.first.exerciseObj.id, 1); + }); }); } From 70d6929a5c5f0c65af980a87c8dd4eaffc37500c Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 27 Oct 2026 21:27:20 +0100 Subject: [PATCH 26/29] Count the chart range cutoffs in calendar days --- lib/features/measurements/charts/range.dart | 17 ++++--- lib/features/measurements/charts/spark.dart | 3 +- .../measurements/charts/range_test.dart | 24 +++++++-- .../widgets/measurement_tile_test.dart | 51 ++++++++++--------- 4 files changed, 58 insertions(+), 37 deletions(-) diff --git a/lib/features/measurements/charts/range.dart b/lib/features/measurements/charts/range.dart index 28e61d012..9e993257b 100644 --- a/lib/features/measurements/charts/range.dart +++ b/lib/features/measurements/charts/range.dart @@ -16,7 +16,9 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; +import 'package:wger/features/measurements/charts/calendar.dart'; import 'package:wger/features/measurements/models/measurement_category.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -44,8 +46,7 @@ enum ChartRange { if (days == null) { return null; } - final from = DateTime.now().subtract(Duration(days: days)); - return DateTime(from.year, from.month, from.day); + return shiftDays(dayOf(clock.now()), -days); } /// Days read beyond [cutoff], so the moving average of the first days in @@ -58,21 +59,21 @@ enum ChartRange { /// /// Reaches [_averageLeadDays] beyond [cutoff], and is rounded down to /// midnight like [countCutoff], for the same reason. - DateTime? get readCutoff => _atMidnight(Duration(days: _averageLeadDays)); + DateTime? get readCutoff => _atMidnight(_averageLeadDays); /// Oldest entry to count, null for the full history: the range itself, with /// no lead, for the queries that summarise exactly what is on screen. - DateTime? get countCutoff => _atMidnight(Duration.zero); + DateTime? get countCutoff => _atMidnight(0); - /// [cutoff] minus [lead], rounded down to midnight. + /// [cutoff] moved back [leadDays] calendar days, at midnight. /// /// The rounding is deliberate: these identify a provider and have to stay /// the same across rebuilds, which a bound derived from the current instant /// would not. - DateTime? _atMidnight(Duration lead) { - final from = cutoff?.subtract(lead); + DateTime? _atMidnight(int leadDays) { + final from = cutoff; - return from == null ? null : DateTime(from.year, from.month, from.day); + return from == null ? null : shiftDays(from, -leadDays); } /// Label for the selector, counted rather than one string per range, so a diff --git a/lib/features/measurements/charts/spark.dart b/lib/features/measurements/charts/spark.dart index 4eb3abed0..3b5ddbd85 100644 --- a/lib/features/measurements/charts/spark.dart +++ b/lib/features/measurements/charts/spark.dart @@ -23,6 +23,7 @@ library; import 'dart:math'; +import 'package:clock/clock.dart'; import 'package:collection/collection.dart'; import 'package:wger/features/measurements/charts/calendar.dart'; import 'package:wger/features/measurements/charts/series.dart'; @@ -93,7 +94,7 @@ class SparkWindow { /// the heatmap follows it within its own, tighter legibility bounds. The /// delta window gets one slot beyond its weeks for the running week. SparkWindow sparkWindowFor(SparkKind kind, {required DateTime? cutoff, DateTime? today}) { - final now = dayOf(today ?? DateTime.now()); + final now = dayOf(today ?? clock.now()); final days = cutoff == null ? null : daysBetween(dayOf(cutoff), now) + 1; int weeksOf(int? days) => days == null ? sparkMaxWeeks : min(sparkMaxWeeks, (days / 7).ceil()); diff --git a/test/features/measurements/charts/range_test.dart b/test/features/measurements/charts/range_test.dart index 1ad1c6454..78bc5f35a 100644 --- a/test/features/measurements/charts/range_test.dart +++ b/test/features/measurements/charts/range_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:wger/features/measurements/charts/range.dart'; @@ -31,12 +32,25 @@ void main() { }); test('the week covers today plus the six days before it', () { - // Seven calendar days in all: the count cutoff sits at midnight six - // days back, so a weekday axis gets one letter per day - final count = ChartRange.lastWeek.countCutoff!; - final now = DateTime.now(); + // Seven calendar days, so a weekday axis gets one letter per day. Next to + // the European DST switches, where counting elapsed hours lands a day off + final weekStarts = { + DateTime(2026, 10, 26, 23, 30): DateTime(2026, 10, 20), + DateTime(2026, 3, 30, 0, 30): DateTime(2026, 3, 24), + }; - expect(DateTime(now.year, now.month, now.day - 6), count); + for (final MapEntry(key: now, value: start) in weekStarts.entries) { + withClock(Clock.fixed(now), () { + expect(ChartRange.lastWeek.countCutoff, start, reason: 'at $now'); + }); + } + }); + + test('the read cutoff counts its lead in calendar days', () { + // The 30-day lead from 4 April reaches back across the European spring DST switch + withClock(Clock.fixed(DateTime(2026, 4, 10, 12)), () { + expect(ChartRange.lastWeek.readCutoff, DateTime(2026, 3, 5)); + }); }); test('the cutoff sits at the same midnight as the count cutoff', () { diff --git a/test/features/measurements/widgets/measurement_tile_test.dart b/test/features/measurements/widgets/measurement_tile_test.dart index 93ab54c6f..9d60352ee 100644 --- a/test/features/measurements/widgets/measurement_tile_test.dart +++ b/test/features/measurements/widgets/measurement_tile_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'package:clock/clock.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -40,7 +41,7 @@ import 'measurement_tile_test.mocks.dart'; /// The calendar day [daysAgo] days back, at midnight like a day bucket. DateTime _day(int daysAgo) { - final now = DateTime.now(); + final now = clock.now(); return DateTime(now.year, now.month, now.day - daysAgo); } @@ -236,31 +237,35 @@ void main() { }); testWidgets('the range filter decides between daily and weekly slots', (tester) async { - final steps = MeasurementCategory( - id: 'steps', - name: 'Steps', - metricType: MetricType.steps, - ); - final entries = { - 'steps': [_entry('steps', 8000, _day(1)), _entry('steps', 6000, _day(2))], - }; + // Late evening the day after the European autumn DST switch, where counting the + // week in elapsed hours drops a day + await withClock(Clock.fixed(DateTime(2026, 10, 26, 23, 30)), () async { + final steps = MeasurementCategory( + id: 'steps', + name: 'Steps', + metricType: MetricType.steps, + ); + final entries = { + 'steps': [_entry('steps', 8000, _day(1)), _entry('steps', 6000, _day(2))], + }; - // A week is seven daily slots and a month one per day; three months - // come as calendar weeks - await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastWeek)); - await tester.pumpAndSettle(); - var chart = tester.widget(find.byType(SparkBarChart)); - expect(chart.data.slotCount, 7); + // A week is seven daily slots and a month one per day; three months + // come as calendar weeks + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastWeek)); + await tester.pumpAndSettle(); + var chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 7); - await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastMonth)); - await tester.pumpAndSettle(); - chart = tester.widget(find.byType(SparkBarChart)); - expect(chart.data.slotCount, 31); + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastMonth)); + await tester.pumpAndSettle(); + chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 31); - await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.last3Months)); - await tester.pumpAndSettle(); - chart = tester.widget(find.byType(SparkBarChart)); - expect(chart.data.slotCount, 13); + await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.last3Months)); + await tester.pumpAndSettle(); + chart = tester.widget(find.byType(SparkBarChart)); + expect(chart.data.slotCount, 13); + }); }); testWidgets('blood pressure tile: the reading quoted high over low', (tester) async { From ce66da762b5f78c0204a65a6b6649ed296ea8566 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Tue, 27 Oct 2026 21:35:21 +0100 Subject: [PATCH 27/29] Restore the workout progress even if its logs can't be read --- .../providers/gym_state_notifier.dart | 24 ++++++++---- .../routines/providers/gym_state_test.dart | 39 ++++++++++++++++--- 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index ba7363af8..0228b2b24 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -231,12 +231,20 @@ class GymStateNotifier extends _$GymStateNotifier { return null; } + // Without the logs the done sets and timers still come back, a correction + // then inserts a new row instead of updating the old one final logIds = saved.pages.values.map((p) => p.logId).nonNulls.toList(); - final logs = { - if (logIds.isNotEmpty) - for (final log in await ref.read(workoutLogRepositoryProvider).getLogsByIds(logIds)) - log.id: log, - }; + var logs = {}; + if (logIds.isNotEmpty) { + try { + logs = { + for (final log in await ref.read(workoutLogRepositoryProvider).getLogsByIds(logIds)) + log.id: log, + }; + } catch (e) { + _logger.warning('Could not read the logs of the stored workout progress: $e'); + } + } // Pages the routine no longer has (it was edited, or they were added // during the workout) are left out @@ -590,9 +598,9 @@ class GymStateNotifier extends _$GymStateNotifier { } /// [log] is the entry saved from this page during the current workout. It - /// is kept on the slot page so revisiting the page pre-fills the form with - /// the saved values and saving updates the row instead of inserting a - /// duplicate. + /// is kept in the page's progress so revisiting the page pre-fills the form + /// with the saved values and saving updates the row instead of inserting a + /// duplicate. Without [log], an entry saved before is kept. /// /// Saving a new entry, unlike correcting one, also (re)starts the rest timer /// that follows the set. diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index af1218290..8a4dd8817 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -99,7 +99,7 @@ void main() { } }); - test('Stores the logged entry on the slot page', () { + test('Stores the logged entry in the page progress', () { // Arrange final slotPage = notifier.state.pages[1].slotPages[1]; expect(slotPage.type, SlotPageType.log); @@ -113,6 +113,11 @@ void main() { final loggedEntry = notifier.state.progressOf(slotPage.key).loggedEntry!; expect(loggedEntry.id, 'log-1'); expect(loggedEntry, isNot(same(log))); + + // Undoing the flag without a log, e.g. after a failed write, keeps the entry + notifier.markSlotPageAsDone(slotPage.key, isDone: false); + expect(notifier.state.progressOf(slotPage.key).done, isFalse); + expect(notifier.state.progressOf(slotPage.key).loggedEntry!.id, 'log-1'); }); }); @@ -982,14 +987,17 @@ void main() { /// Simulates the app being killed: a new container means a new (empty) /// notifier, while the stored preferences and [logs] survive, as on a real /// restart. - GymStateNotifier restartedNotifier({List logs = const []}) { + GymStateNotifier restartedNotifier({List logs = const [], Object? lookupError}) { final logRepo = MockWorkoutLogRepository(); - when(logRepo.getLogsByIds(any)).thenAnswer( - (invocation) async => [ + when(logRepo.getLogsByIds(any)).thenAnswer((invocation) async { + if (lookupError != null) { + throw lookupError; + } + return [ for (final log in logs) if ((invocation.positionalArguments.first as List).contains(log.id)) log, - ], - ); + ]; + }); return ProviderContainer.test( overrides: [workoutLogRepositoryProvider.overrideWithValue(logRepo)], ).read(gymStateProvider.notifier); @@ -1114,6 +1122,25 @@ void main() { ); }); + test('Restores the rest of the progress when the logs can not be read', () async { + final logPage = notifier.state.pages[1].slotPages[1]; + final timerKey = notifier.state.pages[1].slotPages[2].key; + final log = Log(id: 'log-1', exerciseId: 1, date: DateTime(2026, 7, 26)); + await openDay1(notifier); + withClock(Clock.fixed(DateTime(2026, 7, 26, 18, 30)), () { + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); + }); + notifier.setCurrentPage(3); + await pumpEventQueue(); + + final restarted = restartedNotifier(lookupError: StateError('database closed')); + + expect(await openDay1(restarted), 3); + expect(restarted.state.progressOf(logPage.key).done, isTrue); + expect(restarted.state.progressOf(logPage.key).loggedEntry, isNull); + expect(restarted.state.progressOf(timerKey).timerStartedAt, DateTime(2026, 7, 26, 18, 30)); + }); + test('Stores a rest timer as soon as it starts', () async { await runWorkout(); final timerKey = notifier.state.pages[1].slotPages[2].key; From bf82e4c3437138f0eb6cef1fdb0886007b8d8056 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 29 Oct 2026 19:46:53 +0100 Subject: [PATCH 28/29] Update comments --- lib/features/routines/models/workout_progress.dart | 6 ++---- .../routines/providers/gym_state_notifier.dart | 13 ++++--------- .../routines/providers/gym_state_notifier.g.dart | 2 +- 3 files changed, 7 insertions(+), 14 deletions(-) diff --git a/lib/features/routines/models/workout_progress.dart b/lib/features/routines/models/workout_progress.dart index 76ffa86d5..174cf4442 100644 --- a/lib/features/routines/models/workout_progress.dart +++ b/lib/features/routines/models/workout_progress.dart @@ -21,10 +21,8 @@ import 'package:freezed_annotation/freezed_annotation.dart'; part 'workout_progress.freezed.dart'; part 'workout_progress.g.dart'; -/// The progress through a running workout, as stored in the preferences -/// -/// Only the parts that can't be recalculated are kept. The pages are derived -/// from the routine again and matched by their keys. +/// The progress through a running workout, as stored in the preferences. The +/// pages themselves are derived from the routine again and matched by key. @freezed sealed class WorkoutProgress with _$WorkoutProgress { const factory WorkoutProgress({ diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 0228b2b24..7b9dff9e2 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -147,11 +147,8 @@ class GymStateNotifier extends _$GymStateNotifier { ); } - /// Stores the progress through the running workout - /// - /// Riverpod keeps the state alive for as long as the app is running, but the - /// OS can kill a backgrounded app at any point, e.g. while the user switches - /// to a music app between two sets. + /// Stores the progress through the running workout, since the OS can kill a + /// backgrounded app at any point, e.g. between two sets Future _saveProgress() async { // Before initData there is no dayId to store the progress under if (!state.isInitialized) { @@ -186,10 +183,8 @@ class GymStateNotifier extends _$GymStateNotifier { _logger.finer('Cleared stored workout progress'); } - /// Opens gym mode for a day and returns the page to start on - /// - /// Continues the workout still in memory as it is, otherwise starts a new one - /// that picks up the progress stored before the app was killed, if any. + /// Opens gym mode for a day and returns the page to start on. Continues the + /// workout in memory, otherwise starts one that picks up any stored progress. Future open(Routine routine, int dayId, int iteration) async { final resume = _canResume(dayId); final initialPage = initData(routine, dayId, iteration); diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 8ffd11a9c..bf7e610e1 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'1f0009a2972509e3a444896208f3865835ba77a7'; +String _$gymStateNotifierHash() => r'd677a108bd0fa3ae52320cfbf6855ae25bdbc6fe'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); From f6ee298a12444521e2011a890bdb34e916a22292 Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 29 Oct 2026 20:03:02 +0100 Subject: [PATCH 29/29] Read the sticky set values from the logs in the database --- .../routines/providers/gym_state.dart | 12 +- .../providers/gym_state_notifier.dart | 38 ++--- .../providers/gym_state_notifier.g.dart | 2 +- .../providers/workout_logs_repository.dart | 11 ++ .../routines/widgets/gym_mode/log_page.dart | 6 - lib/l10n/app_de.arb | 2 +- lib/l10n/app_en.arb | 2 +- lib/l10n/app_es.arb | 2 +- lib/l10n/app_fr.arb | 2 +- .../routines/providers/gym_state_test.dart | 152 ++++++++---------- .../providers/gym_state_test.mocks.dart | 8 + .../workout_logs_notifier_test.mocks.dart | 8 + .../workout_logs_repository_test.dart | 34 ++++ .../routines/screens/gym_mode_test.mocks.dart | 8 + .../routine_logs_screen_test.mocks.dart | 8 + .../widgets/gym_mode/log_page_test.dart | 30 +++- .../widgets/gym_mode/log_page_test.mocks.dart | 16 ++ 17 files changed, 205 insertions(+), 136 deletions(-) diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 869aaa5e1..ef5b5c9ac 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -21,7 +21,6 @@ import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/added_exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; -import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; @@ -179,14 +178,10 @@ class GymModeState { final bool showWorkoutDuration; /// Whether the log form of a set is pre-filled with the values last - /// logged for the same exercise during this workout, instead of the - /// planned ones. Disabled by default. + /// logged for the same exercise, in this or an earlier workout, instead + /// of the planned ones. Disabled by default. final bool stickySetValues; - /// The values last logged per exercise during this workout, used to - /// pre-fill the log form when [stickySetValues] is enabled. - final Map lastLoggedValues; - /// What happened on the pages so far, by page key. Kept apart from the pages /// so that recalculating them doesn't lose it. final Map progress; @@ -213,7 +208,6 @@ class GymModeState { this.showDistinctLogs = true, this.showWorkoutDuration = true, this.stickySetValues = false, - this.lastLoggedValues = const {}, this.progress = const {}, this.addedExercises = const [], int? dayId, @@ -261,7 +255,6 @@ class GymModeState { bool? showDistinctLogs, bool? showWorkoutDuration, bool? stickySetValues, - Map? lastLoggedValues, Map? progress, List? addedExercises, }) { @@ -287,7 +280,6 @@ class GymModeState { showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, stickySetValues: stickySetValues ?? this.stickySetValues, - lastLoggedValues: lastLoggedValues ?? this.lastLoggedValues, progress: progress ?? this.progress, addedExercises: addedExercises ?? this.addedExercises, ); diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 7b9dff9e2..29d6a71a2 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -259,11 +259,6 @@ class GymStateNotifier extends _$GymStateNotifier { workoutStart: saved.workoutStart, validUntil: saved.validUntil, progress: progress, - // In page order, so the last set of an exercise wins - lastLoggedValues: { - for (final log in slotPages.map((p) => progress[p.key]?.loggedEntry).nonNulls) - log.exerciseId: log, - }, ); _logger.fine('Restored workout progress on page ${state.currentPage}'); @@ -448,8 +443,6 @@ class GymStateNotifier extends _$GymStateNotifier { // A fresh workout also restarts the elapsed timer and the resume window workoutStart: shouldReset ? clock.now() : null, validUntil: shouldReset ? clock.now().add(DEFAULT_DURATION) : null, - // An abandoned workout never reaches clear(), so forget its values here - lastLoggedValues: shouldReset ? const {} : null, progress: shouldReset ? const {} : null, addedExercises: shouldReset ? const [] : null, ); @@ -484,7 +477,7 @@ class GymStateNotifier extends _$GymStateNotifier { /// Seeds the log form of the current page with a fresh entry, also to log /// another set on a page that was already logged. - void startNewEntry() { + Future startNewEntry() async { // Ensure that there is a log entry for the current slot entry final slotEntryPage = state.getSlotEntryPageByIndex(); if (slotEntryPage == null || slotEntryPage.setConfigData == null) { @@ -497,13 +490,20 @@ class GymStateNotifier extends _$GymStateNotifier { iteration: state.iteration, ); final logNotifier = ref.read(gymLogProvider.notifier)..setLog(log); + if (!state.stickySetValues) { + return; + } - // Pre-fill with the values last logged for this exercise during this - // workout (e.g. when dialing in the weight over the first sets), if enabled - final lastValues = state.stickySetValues - ? state.lastLoggedValues[slotEntryPage.setConfigData!.exerciseId] - : null; - if (lastValues != null) { + // Pre-fill with the values last logged for this exercise, in this or any + // earlier workout. Read from the DB so they survive however gym mode was + // left, and a corrected earlier set keeps its date and doesn't win. + final seeded = ref.read(gymLogProvider); + final lastValues = await ref + .read(workoutLogRepositoryProvider) + .getLatestLogByExercise(slotEntryPage.setConfigData!.exerciseId); + + // Leave the form alone if the user already moved on or started typing + if (lastValues != null && ref.mounted && identical(ref.read(gymLogProvider), seeded)) { logNotifier.copyValuesFrom(lastValues); } } @@ -556,15 +556,6 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } - /// Remembers the values logged for the log's exercise so that the next - /// set of the exercise can be pre-filled with them, see - /// [GymModeState.stickySetValues]. - void recordLoggedValues(Log log) { - final updated = Map.of(state.lastLoggedValues); - updated[log.exerciseId] = log; - state = state.copyWith(lastLoggedValues: updated); - } - /// Applies [update] to the progress of the page with [key] void _updateProgress(String key, PageProgress Function(PageProgress) update) { state = state.copyWith(progress: {...state.progress, key: update(state.progressOf(key))}); @@ -688,7 +679,6 @@ class GymStateNotifier extends _$GymStateNotifier { isInitialized: false, pages: [], currentPage: 0, - lastLoggedValues: const {}, progress: const {}, addedExercises: const [], diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 9e8adfb2f..a4682dc24 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'6edef80da81e457a1d2b600dc205194d34adb407'; +String _$gymStateNotifierHash() => r'c03c5ee5ca6f1db5d63193e15744589f12486ea4'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/lib/features/routines/providers/workout_logs_repository.dart b/lib/features/routines/providers/workout_logs_repository.dart index 4346cc226..ce2294fe0 100644 --- a/lib/features/routines/providers/workout_logs_repository.dart +++ b/lib/features/routines/providers/workout_logs_repository.dart @@ -75,6 +75,17 @@ class WorkoutLogRepository { return query.watch().map((rows) => rows.map(_readWithUnits).toList()); } + /// The newest log of an exercise across all routines, with its units, or + /// null if the exercise was never logged + Future getLatestLogByExercise(int exerciseId) async { + final query = _selectWithUnits() + ..where(_db.workoutLogTable.exerciseId.equals(exerciseId)) + ..orderBy([OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc)]) + ..limit(1); + final row = await query.getSingleOrNull(); + return row == null ? null : _readWithUnits(row); + } + /// The logs with one of the [ids] that exist locally, with their units Future> getLogsByIds(List ids) async { final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids)); diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index f7d70ea8a..412b1b4e6 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -414,12 +414,6 @@ class _LogFormWidgetState extends ConsumerState { } gymProvider.markSlotPageAsDone(page.key, isDone: true, log: log); - - // Correcting an earlier set must not replace a later set's values - final lastLogged = gymState.lastLoggedValues[log.exerciseId]; - if (isNewEntry || lastLogged?.id == log.id) { - gymProvider.recordLoggedValues(log); - } showSnackbar( context, i18n.successfullySaved, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 5148a8e7b..98aedeaed 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1179,6 +1179,6 @@ "calculationHelpWindowDays": "{min} bis {max}. Wie weit zurück ein bester Satz zählt.", "useDynamicColor": "Dynamische Farben verwenden", "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", - "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du in diesem Training zuletzt dafür eingetragen hast", + "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du zuletzt dafür eingetragen hast", "upNext": "Als Nächstes" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7f1d75eca..8839af841 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -415,7 +415,7 @@ "@gymModeStickySetValues": { "description": "Label for a gym mode setting: when enabled, the next set of an exercise is pre-filled with the values last logged instead of the planned ones" }, - "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values you last logged for it during this workout", + "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values you last logged for it", "@gymModeStickySetValuesHelp": { "description": "Help text for the sticky set values setting in the gym mode" }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b6ee3eac..d8ea971bf 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1196,6 +1196,6 @@ "calculationHelpWindowDays": "De {min} a {max}. Hasta dónde cuenta la mejor serie.", "useDynamicColor": "Usar color dinámico", "gymModeStickySetValues": "Mantener los valores de la última serie", - "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez durante este entrenamiento", + "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez", "upNext": "A continuación" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index d15127b8a..47cd4c55c 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1188,6 +1188,6 @@ "calculationHelpWindowDays": "De {min} à {max}. Jusqu’où remonte la meilleure série.", "useDynamicColor": "Utiliser les couleurs dynamiques", "gymModeStickySetValues": "Reprendre les valeurs de la dernière série", - "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées pendant cet entraînement", + "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées", "upNext": "À suivre" } diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 8a4dd8817..03f503be2 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'package:clock/clock.dart'; @@ -735,9 +736,23 @@ void main() { // slot 1 (exercise 1): overview(1), log(2), timer(3), log(4), timer(5), log(6), timer(7) // slot 2 (exercise 6): overview(8), log(9), ... + late MockWorkoutLogRepository logRepo; + + setUp(() { + logRepo = MockWorkoutLogRepository(); + when(logRepo.getLatestLogByExercise(any)).thenAnswer((_) async => null); + + final initialState = notifier.state; + container = ProviderContainer.test( + overrides: [workoutLogRepositoryProvider.overrideWithValue(logRepo)], + ); + notifier = container.read(gymStateProvider.notifier)..state = initialState; + }); + Log buildLoggedValues() { final slotPage = notifier.state.pages[1].slotPages[1]; return Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1' ..repetitions = 7 ..weight = 42.5 ..rir = 1; @@ -753,106 +768,72 @@ void main() { expect(await PreferenceHelper.asyncPref.getBool(PREFS_STICKY_SET_VALUES), true); }); - test( - 'Pre-fills the next set of the exercise with the last logged values when enabled', - () async { - // Arrange - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act: navigate to the second set of the same exercise - notifier.setCurrentPage(4); - - // Assert - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 7); - expect(gymLog.weight, 42.5); - expect(gymLog.rir, 1); - expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); - }, - ); - - test('Pre-fills with the planned values when disabled', () { + test('Pre-fills the set with the last logged values of the exercise when enabled', () async { // Arrange - notifier.recordLoggedValues(buildLoggedValues()); + notifier.setStickySetValues(true); + await pumpEventQueue(); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); // Act notifier.setCurrentPage(4); - - // Assert: the values of the set configuration - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 3); - expect(gymLog.weight, 100); - }); - - test('Does not carry values over to a different exercise', () async { - // Arrange - notifier.setStickySetValues(true); await pumpEventQueue(); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act: navigate to the first set of the second exercise - notifier.setCurrentPage(9); - - // Assert: the values of that exercise's set configuration - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 12); - expect(gymLog.weight, 10); - }); - - test('A new workout forgets the values of an abandoned one', () async { - // Arrange: the summary page (and clear()) is never reached - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.state = notifier.state.copyWith( - isInitialized: true, - dayId: 1, - validUntil: DateTime(2024, 5, 1, 10, 0), - ); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act - withClock( - Clock.fixed(DateTime(2024, 5, 2, 18, 0)), - () => notifier.initData(getTestRoutine(), 1, 1), - ); - notifier.setCurrentPage(2); - - // Assert: the values of the set configuration - expect(notifier.state.lastLoggedValues, isEmpty); - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 3); - expect(gymLog.weight, 100); - }); - - test('Resuming the same workout keeps the logged values', () async { - // Arrange - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.state = notifier.state.copyWith(isInitialized: true, dayId: 1); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act - notifier.initData(getTestRoutine(), 1, 1); - notifier.setCurrentPage(4); // Assert final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 7); expect(gymLog.weight, 42.5); + expect(gymLog.rir, 1); + expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); }); - test('Clearing the state forgets the logged values', () { + test('Pre-fills with the planned values when disabled', () async { // Arrange - notifier.recordLoggedValues(buildLoggedValues()); - expect(notifier.state.lastLoggedValues, isNotEmpty); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); // Act - notifier.clear(); + notifier.setCurrentPage(4); + await pumpEventQueue(); + + // Assert: the values of the set configuration + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 3); + expect(gymLog.weight, 100); + verifyNever(logRepo.getLatestLogByExercise(any)); + }); + + test('Pre-fills with the planned values when the exercise was never logged', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + + // Act: the first set of the second exercise + notifier.setCurrentPage(9); + await pumpEventQueue(); + + // Assert: the values of that exercise's set configuration + verify(logRepo.getLatestLogByExercise(6)); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 12); + expect(gymLog.weight, 10); + }); + + test('Does not overwrite values entered while the lookup was running', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + final lookup = Completer(); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) => lookup.future); + + // Act + notifier.setCurrentPage(4); + container.read(gymLogProvider.notifier).setWeight(55); + lookup.complete(buildLoggedValues()); + await pumpEventQueue(); // Assert - expect(notifier.state.lastLoggedValues, isEmpty); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.weight, 55); + expect(gymLog.repetitions, 3); }); }); @@ -1115,11 +1096,6 @@ void main() { DateTime(2026, 7, 26, 18, 30), reason: 'the rest that started with the logged set keeps running', ); - expect( - restarted.state.lastLoggedValues[1]!.weight, - 80, - reason: 'the sticky values come from the restored logs', - ); }); test('Restores the rest of the progress when the logs can not be read', () async { diff --git a/test/features/routines/providers/gym_state_test.mocks.dart b/test/features/routines/providers/gym_state_test.mocks.dart index 9ffda94cb..536a2e2bc 100644 --- a/test/features/routines/providers/gym_state_test.mocks.dart +++ b/test/features/routines/providers/gym_state_test.mocks.dart @@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + @override _i3.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart index 614da26dc..ded5ef543 100644 --- a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart +++ b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart @@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + @override _i3.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/providers/workout_logs_repository_test.dart b/test/features/routines/providers/workout_logs_repository_test.dart index 3c8b43d78..4875b333b 100644 --- a/test/features/routines/providers/workout_logs_repository_test.dart +++ b/test/features/routines/providers/workout_logs_repository_test.dart @@ -267,6 +267,40 @@ void main() { }); }); + group('getLatestLogByExercise', () { + test('returns null when the exercise was never logged', () async { + await db.into(db.workoutLogTable).insert(makeLog(exerciseId: 2).toCompanion()); + + expect(await repo.getLatestLogByExercise(1), isNull); + }); + + test('returns the newest log of the exercise across routines', () async { + await seedUnits(); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 14), weight: 14).toCompanion()); + await db + .into(db.workoutLogTable) + .insert( + makeLog(routineId: 999, date: DateTime.utc(2026, 4, 16), weight: 16).toCompanion(), + ); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 15), weight: 15).toCompanion()); + // Newer, but a different exercise + await db + .into(db.workoutLogTable) + .insert( + makeLog(exerciseId: 2, date: DateTime.utc(2026, 4, 17), weight: 17).toCompanion(), + ); + + final log = await repo.getLatestLogByExercise(1); + + expect(log!.weight, 16); + expect(log.weightUnitObj?.name, 'kg'); + }); + }); + group('updateLocalDrift', () { test('overwrites the row with matching id', () async { final log = makeLog(sessionId: 'session-1', weight: 50); diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index 95fc3f0ab..ccf083404 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -553,6 +553,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i27.WorkoutLogReposi ) as _i10.Stream>); + @override + _i10.Future<_i28.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i10.Future<_i28.Log?>.value(), + ) + as _i10.Future<_i28.Log?>); + @override _i10.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/screens/routine_logs_screen_test.mocks.dart b/test/features/routines/screens/routine_logs_screen_test.mocks.dart index c2ab95ffc..e36f8f31e 100644 --- a/test/features/routines/screens/routine_logs_screen_test.mocks.dart +++ b/test/features/routines/screens/routine_logs_screen_test.mocks.dart @@ -156,6 +156,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit ) as _i5.Stream>); + @override + _i5.Future<_i10.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i5.Future<_i10.Log?>.value(), + ) + as _i5.Future<_i10.Log?>); + @override _i5.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index eaa41adc6..4d4a093a2 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -70,17 +70,39 @@ void main() { late ProviderContainer container; late MockWorkoutLogRepository mockWorkoutLogRepo; + /// What the mocked repository wrote, so the sticky values can be read back + late List storedLogs; + + void storeLog(Log log) { + storedLogs + ..removeWhere((l) => l.id == log.id) + ..add(log.copyWith()); + } + setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); testExercises = getTestExercises(); mockWorkoutLogRepo = MockWorkoutLogRepository(); + storedLogs = []; // Mimic the real insert: the freshly minted id is written back to the log when( mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), ).thenAnswer((invocation) async { - (invocation.positionalArguments[0] as Log).id = 'new-log-id'; + storeLog((invocation.positionalArguments[0] as Log)..id = 'new-log-id'); + }); + when(mockWorkoutLogRepo.updateLocalDrift(any)).thenAnswer((invocation) async { + storeLog(invocation.positionalArguments[0] as Log); + }); + // Newest first like the real query, on equal dates the later write wins + when(mockWorkoutLogRepo.getLatestLogByExercise(any)).thenAnswer((invocation) async { + final exerciseId = invocation.positionalArguments[0] as int; + return storedLogs + .where((l) => l.exerciseId == exerciseId) + .fold( + null, + (newest, l) => newest == null || !l.date.isBefore(newest.date) ? l : newest, + ); }); - when(mockWorkoutLogRepo.updateLocalDrift(any)).thenAnswer((_) async {}); // Past logs on the page come from this stream (per exercise); reuse the // test routine's logs so the previous-entries assertions keep working. when( @@ -311,7 +333,7 @@ void main() { when( mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), ).thenAnswer((invocation) async { - (invocation.positionalArguments[0] as Log).id = 'log-${++count}'; + storeLog((invocation.positionalArguments[0] as Log)..id = 'log-${++count}'); }); }); @@ -329,6 +351,7 @@ void main() { // Set 3 is pre-filled with the values of set 2 container.read(gymStateProvider.notifier).setCurrentPage(6); + await tester.pump(); final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 14); expect(gymLog.weight, 40); @@ -346,6 +369,7 @@ void main() { // Set 2 is pre-filled with the corrected values container.read(gymStateProvider.notifier).setCurrentPage(4); + await tester.pump(); final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 12); expect(gymLog.weight, 36); diff --git a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart index 3853e98bc..4340f2626 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart @@ -50,6 +50,22 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i4.Log>[]), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod(