Read the sticky set values from the logs in the database

This commit is contained in:
Roland Geider
2026-10-29 20:03:02 +01:00
parent 64c3c46e53
commit f6ee298a12
17 changed files with 205 additions and 136 deletions

View File

@@ -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<int, Log> 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<String, PageProgress> 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<int, Log>? lastLoggedValues,
Map<String, PageProgress>? progress,
List<AddedExercise>? 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,
);

View File

@@ -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<void> 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<int, Log>.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 [],

View File

@@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider<GymStateNotifier,
}
}
String _$gymStateNotifierHash() => r'6edef80da81e457a1d2b600dc205194d34adb407';
String _$gymStateNotifierHash() => r'c03c5ee5ca6f1db5d63193e15744589f12486ea4';
abstract class _$GymStateNotifier extends $Notifier<GymModeState> {
GymModeState build();

View File

@@ -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<Log?> 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<List<Log>> getLogsByIds(List<String> ids) async {
final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids));

View File

@@ -414,12 +414,6 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
}
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,

View File

@@ -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"
}

View File

@@ -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"
},

View File

@@ -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"
}

View File

@@ -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"
}

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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<Log?>();
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 {

View File

@@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit
)
as _i3.Stream<List<_i4.Log>>);
@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<List<_i4.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(

View File

@@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit
)
as _i3.Stream<List<_i4.Log>>);
@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<List<_i4.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(

View File

@@ -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);

View File

@@ -553,6 +553,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i27.WorkoutLogReposi
)
as _i10.Stream<List<_i28.Log>>);
@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<List<_i28.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(

View File

@@ -156,6 +156,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit
)
as _i5.Stream<List<_i10.Log>>);
@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<List<_i10.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(

View File

@@ -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<Log> 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<Log?>(
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);

View File

@@ -50,6 +50,22 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit
)
as _i3.Stream<List<_i4.Log>>);
@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<List<_i4.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(
Invocation.method(#getLogsByIds, [ids]),
returnValue: _i3.Future<List<_i4.Log>>.value(<_i4.Log>[]),
)
as _i3.Future<List<_i4.Log>>);
@override
_i3.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(