Store the gym mode progress by page key

This commit is contained in:
Roland Geider
2026-10-26 22:34:35 +01:00
parent d7781845fd
commit 4522f018ad
13 changed files with 983 additions and 115 deletions

View File

@@ -16,55 +16,38 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
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<String, StoredPageProgress> pages,
}) = _WorkoutProgress;
/// Absolute page indices of the log pages already marked as done
final List<int> 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<String, dynamic> 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<dynamic>).cast<int>(),
);
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> json) =>
_$StoredPageProgressFromJson(json);
}

View File

@@ -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>(T value) => value;
/// @nodoc
mixin _$WorkoutProgress {
int get dayId; int get iteration; String get currentPageKey; DateTime get workoutStart; DateTime get validUntil; Map<String, StoredPageProgress> 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<WorkoutProgress> get copyWith => _$WorkoutProgressCopyWithImpl<WorkoutProgress>(this as WorkoutProgress, _$identity);
/// Serializes this WorkoutProgress to a JSON map.
Map<String, dynamic> 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<String, StoredPageProgress> 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<String, StoredPageProgress>,
));
}
}
/// 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 extends Object?>(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 extends Object?>(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 extends Object?>(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 extends Object?>(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> 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 extends Object?>(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> 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 extends Object?>(TResult? Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> 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<String, StoredPageProgress> pages = const {}}): _pages = pages;
factory _WorkoutProgress.fromJson(Map<String, dynamic> 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<String, StoredPageProgress> _pages;
@override@JsonKey() Map<String, StoredPageProgress> 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<String, dynamic> 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<String, StoredPageProgress> 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<String, StoredPageProgress>,
));
}
}
/// @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<StoredPageProgress> get copyWith => _$StoredPageProgressCopyWithImpl<StoredPageProgress>(this as StoredPageProgress, _$identity);
/// Serializes this StoredPageProgress to a JSON map.
Map<String, dynamic> 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 extends Object?>(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 extends Object?>(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 extends Object?>(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 extends Object?>(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 extends Object?>(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 extends Object?>(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<String, dynamic> 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<String, dynamic> 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

View File

@@ -0,0 +1,46 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'workout_progress.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_WorkoutProgress _$WorkoutProgressFromJson(Map<String, dynamic> 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<String, dynamic>?)?.map(
(k, e) => MapEntry(
k,
StoredPageProgress.fromJson(e as Map<String, dynamic>),
),
) ??
const {},
);
Map<String, dynamic> _$WorkoutProgressToJson(_WorkoutProgress instance) => <String, dynamic>{
'dayId': instance.dayId,
'iteration': instance.iteration,
'currentPageKey': instance.currentPageKey,
'workoutStart': instance.workoutStart.toIso8601String(),
'validUntil': instance.validUntil.toIso8601String(),
'pages': instance.pages,
};
_StoredPageProgress _$StoredPageProgressFromJson(Map<String, dynamic> 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<String, dynamic> _$StoredPageProgressToJson(_StoredPageProgress instance) => <String, dynamic>{
'done': instance.done,
'logId': instance.logId,
'timerStartedAt': instance.timerStartedAt?.toIso8601String(),
};

View File

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

View File

@@ -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<int> 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<void> _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<String, dynamic>);
} on Exception catch (e) {
saved = WorkoutProgress.fromJson(json.decode(stored) as Map<String, dynamic>);
} 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

View File

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

View File

@@ -34,8 +34,8 @@ final workoutLogRepositoryProvider = Provider<WorkoutLogRepository>((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<List<Log>> getLogsByIds(List<String> ids) async {
final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids));
return (await query.get()).map(_readWithUnits).toList();
}
JoinedSelectStatement<HasResultSet, dynamic> _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<void> deleteLocalDrift(String id) async {

View File

@@ -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<Log> logs = const []}) {
final logRepo = MockWorkoutLogRepository();
when(logRepo.getLogsByIds(any)).thenAnswer(
(invocation) async => [
for (final log in logs)
if ((invocation.positionalArguments.first as List<String>).contains(log.id)) log,
],
);
return ProviderContainer.test(
overrides: [workoutLogRepositoryProvider.overrideWithValue(logRepo)],
).read(gymStateProvider.notifier);
}
Future<int> 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<String, dynamic>;
await editStoredProgress('pages', {
...stored['pages'] as Map<String, dynamic>,
'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 {

View File

@@ -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<List<_i4.Log>> watchLogsByExerciseDrift({
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i3.Stream<List<_i4.Log>>.empty(),
)
as _i3.Stream<List<_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(
Invocation.method(#deleteLocalDrift, [id]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> updateLocalDrift(_i4.Log? log) =>
(super.noSuchMethod(
Invocation.method(#updateLocalDrift, [log]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDrift(_i4.Log? log, {int? dayId}) =>
(super.noSuchMethod(
Invocation.method(#addLocalDrift, [log], {#dayId: dayId}),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}

View File

@@ -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<List<_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(

View File

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

View File

@@ -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<List<_i28.Log>>);
@override
_i10.Future<List<_i28.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(
Invocation.method(#getLogsByIds, [ids]),
returnValue: _i10.Future<List<_i28.Log>>.value(<_i28.Log>[]),
)
as _i10.Future<List<_i28.Log>>);
@override
_i10.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(

View File

@@ -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<List<_i10.Log>>);
@override
_i5.Future<List<_i10.Log>> getLogsByIds(List<String>? ids) =>
(super.noSuchMethod(
Invocation.method(#getLogsByIds, [ids]),
returnValue: _i5.Future<List<_i10.Log>>.value(<_i10.Log>[]),
)
as _i5.Future<List<_i10.Log>>);
@override
_i5.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(