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 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 f6e3f4502..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. @@ -15,8 +19,8 @@ class PreferenceHelper { static final PreferenceHelper _instance = PreferenceHelper._instantiate(); - /// Bound to the current `SharedPreferencesAsyncPlatform.instance` on every - /// read, so a platform swapped in later (e.g. per test) takes effect. + /// 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; 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/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/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/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/routine.dart b/lib/features/routines/models/routine.dart index eeb5edb5b..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,43 +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) { - 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) { - for (final config in slot.setConfigs) { - if (config.exerciseId == oldExerciseId) { - config.exerciseId = newExercise.id; - config.exercise = newExercise; - } - } - } - } - return updatedRoutine; } } 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/models/workout_progress.dart b/lib/features/routines/models/workout_progress.dart new file mode 100644 index 000000000..174cf4442 --- /dev/null +++ b/lib/features/routines/models/workout_progress.dart @@ -0,0 +1,51 @@ +/* + * 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'; + +part 'workout_progress.freezed.dart'; +part 'workout_progress.g.dart'; + +/// 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({ + required int dayId, + required int iteration, + required String currentPageKey, + required DateTime workoutStart, + required DateTime validUntil, + @Default({}) Map pages, + }) = _WorkoutProgress; + + 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/notifications/workout_notification_content.dart b/lib/features/routines/notifications/workout_notification_content.dart index d849dca94..23057f151 100644 --- a/lib/features/routines/notifications/workout_notification_content.dart +++ b/lib/features/routines/notifications/workout_notification_content.dart @@ -39,18 +39,18 @@ class WorkoutNotificationPayload extends Equatable { final DateTime workoutStart; /// The log page the "log set" action logs - final String? logSlotUuid; + final String? logSlotKey; /// The timer page the "skip rest" action leaves - final String? restSlotUuid; + final String? restSlotKey; const WorkoutNotificationPayload({ required this.routineId, required this.dayId, required this.iteration, required this.workoutStart, - this.logSlotUuid, - this.restSlotUuid, + this.logSlotKey, + this.restSlotKey, }); /// Whether this belongs to the session [state] is running @@ -66,8 +66,8 @@ class WorkoutNotificationPayload extends Equatable { 'dayId': dayId, 'iteration': iteration, 'workoutStart': workoutStart.toUtc().toIso8601String(), - 'logSlotUuid': logSlotUuid, - 'restSlotUuid': restSlotUuid, + 'logSlotKey': logSlotKey, + 'restSlotKey': restSlotKey, }); /// Null if [payload] is missing or not one of ours @@ -82,8 +82,8 @@ class WorkoutNotificationPayload extends Equatable { dayId: json['dayId'] as int, iteration: json['iteration'] as int, workoutStart: DateTime.parse(json['workoutStart'] as String), - logSlotUuid: json['logSlotUuid'] as String?, - restSlotUuid: json['restSlotUuid'] as String?, + logSlotKey: json['logSlotKey'] as String?, + restSlotKey: json['restSlotKey'] as String?, ); } on Object { return null; @@ -91,7 +91,7 @@ class WorkoutNotificationPayload extends Equatable { } @override - List get props => [routineId, dayId, iteration, workoutStart, logSlotUuid, restSlotUuid]; + List get props => [routineId, dayId, iteration, workoutStart, logSlotKey, restSlotKey]; } /// The ongoing notification while a workout runs (Android) @@ -332,7 +332,7 @@ WorkoutNotificationTarget buildWorkoutNotification( } bool canLog(SlotPageEntry page) => - !page.logDone && + !state.progressOf(page.key).done && isWorkoutLogComplete( repetitions: page.setConfigData!.repetitions, weight: page.setConfigData!.weight, @@ -344,14 +344,14 @@ WorkoutNotificationTarget buildWorkoutNotification( Uri? image(SlotPageEntry? page) => page == null ? null : mediaUrl?.call(page.setConfigData!.exercise.getMainImage?.image); - WorkoutNotificationPayload payload({String? logSlotUuid, String? restSlotUuid}) => + WorkoutNotificationPayload payload({String? logSlotKey, String? restSlotKey}) => WorkoutNotificationPayload( routineId: state.routine.id!, dayId: state.dayId, iteration: state.iteration, workoutStart: state.workoutStart, - logSlotUuid: logSlotUuid, - restSlotUuid: restSlotUuid, + logSlotKey: logSlotKey, + restSlotKey: restSlotKey, ); if (current?.type == SlotPageType.timer) { @@ -360,7 +360,7 @@ WorkoutNotificationTarget buildWorkoutNotification( ); // The set right after the rest, the one the rest end is about final next = following?.pageIndex == current!.pageIndex + 1 ? following : null; - final actionPayload = payload(logSlotUuid: next?.uuid, restSlotUuid: current.uuid); + final actionPayload = payload(logSlotKey: next?.key, restSlotKey: current.key); final nextText = following == null ? '' : i18n.workoutNotificationNext(setText(following)); final endsAt = state.restEndsAt; @@ -423,7 +423,7 @@ WorkoutNotificationTarget buildWorkoutNotification( title: exerciseName(current!), body: setOf(current), canLogSet: canLog(current), - payload: payload(logSlotUuid: current.uuid), + payload: payload(logSlotKey: current.key), quickLogs: quickLogs(current), image: image(current), ), diff --git a/lib/features/routines/notifications/workout_notification_controller.dart b/lib/features/routines/notifications/workout_notification_controller.dart index 4feac7af7..cc1ab02cc 100644 --- a/lib/features/routines/notifications/workout_notification_controller.dart +++ b/lib/features/routines/notifications/workout_notification_controller.dart @@ -119,10 +119,8 @@ class WorkoutNotificationController { /// Follows the earlier logs of the set the notification can log void _watchRecentLogs(GymModeState state, WorkoutNotificationTarget target) { - final uuid = target.controls?.payload.logSlotUuid; - final exerciseId = uuid == null - ? null - : state.getSlotPageByUUID(uuid)?.setConfigData?.exerciseId; + final key = target.controls?.payload.logSlotKey; + final exerciseId = key == null ? null : state.getSlotPageByKey(key)?.setConfigData?.exerciseId; if (exerciseId == _recentLogsExerciseId) { return; } @@ -205,26 +203,26 @@ class WorkoutNotificationController { try { switch (actionId) { case WORKOUT_NOTIFICATION_ACTION_LOG_SET: - final uuid = payload.logSlotUuid; - final config = uuid == null ? null : state.getSlotPageByUUID(uuid)?.setConfigData; + final key = payload.logSlotKey; + final config = key == null ? null : state.getSlotPageByKey(key)?.setConfigData; if (config == null) { break; } if (input == null) { - await notifier.logPlannedSet(uuid!); + await notifier.logPlannedSet(key!); } else { // An unknown label is from an outdated notification final valuesFrom = quickLogChoices(config, _recentLogs)[input]; if (valuesFrom != null) { - await notifier.logPlannedSet(uuid!, valuesFrom: valuesFrom); + await notifier.logPlannedSet(key!, valuesFrom: valuesFrom); } } case WORKOUT_NOTIFICATION_ACTION_SKIP_REST: - if (state.getSlotEntryPageByIndex()?.uuid == payload.restSlotUuid) { + if (state.getSlotEntryPageByIndex()?.key == payload.restSlotKey) { notifier.skipRest(); } case WORKOUT_NOTIFICATION_ACTION_EXTEND_REST: - if (state.getSlotEntryPageByIndex()?.uuid == payload.restSlotUuid) { + if (state.getSlotEntryPageByIndex()?.key == payload.restSlotKey) { notifier.extendRest(REST_EXTENSION); } } diff --git a/lib/features/routines/providers/gym_log_notifier.dart b/lib/features/routines/providers/gym_log_notifier.dart index a8979437c..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. @@ -56,6 +61,14 @@ class GymLogNotifier extends _$GymLogNotifier { ..rir = pastLog.rir; } + /// 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. [log] itself + /// is not modified by the edits. + void editLog(Log log) { + state = log.copyWith(); + } + void setWeight(num weight) { state = state?.copyWith(weight: weight); } 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.dart b/lib/features/routines/providers/gym_state.dart index 5b3dac3ce..8c6766f7c 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -18,9 +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/added_exercise.dart'; import 'package:wger/features/routines/models/day_data.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'; @@ -35,6 +36,7 @@ const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs'; const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs'; const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs'; const PREFS_WORKOUT_NOTIFICATION = 'workoutNotificationPrefs'; +const PREFS_STICKY_SET_VALUES = 'stickySetValuesPrefs'; /// In seconds const DEFAULT_COUNTDOWN_DURATION = 180; @@ -55,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; @@ -67,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, @@ -97,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; @@ -116,9 +115,6 @@ class SlotPageEntry { /// Absolute page index final int pageIndex; - /// Whether the log page has been marked as done - final bool logDone; - /// The associated SetConfigData final SetConfigData? setConfigData; @@ -126,42 +122,37 @@ class SlotPageEntry { required this.type, required this.pageIndex, required this.setIndex, + required this.key, this.setConfigData, - this.logDone = false, - 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, }) { 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, ); } @override String toString() => 'SlotPageEntry(' - 'uuid: $uuid, ' + 'key: $key, ' 'type: $type, ' 'setIndex: $setIndex, ' - 'pageIndex: $pageIndex, ' - 'logDone: $logDone' + 'pageIndex: $pageIndex' ')'; } @@ -177,12 +168,6 @@ class GymModeState { final DateTime workoutStart; final DateTime validUntil; - /// When the rest on the current timer page started, null on other pages - final DateTime? restStartedAt; - - /// When the countdown on the current timer page ends, null if it counts up - final DateTime? restEndsAt; - // User settings final bool showExercisePages; final bool showTimerPages; @@ -199,6 +184,18 @@ class GymModeState { /// Ongoing notification with the rest and the next set (Android) final bool showWorkoutNotification; + /// Whether the log form of a set is pre-filled with the values last + /// logged for the same exercise, in this or an earlier workout, instead + /// of the planned ones. Disabled by default. + final bool stickySetValues; + + /// 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; + + /// Exercises added during the workout, in the order they were added + final List addedExercises; + // Routine data late final int dayId; late final int iteration; @@ -208,8 +205,6 @@ class GymModeState { this.isInitialized = false, this.pages = const [], this.currentPage = 0, - this.restStartedAt, - this.restEndsAt, this.showExercisePages = true, this.showTimerPages = true, @@ -220,6 +215,9 @@ class GymModeState { this.showDistinctLogs = true, this.showWorkoutDuration = true, this.showWorkoutNotification = true, + this.stickySetValues = false, + this.progress = const {}, + this.addedExercises = const [], int? dayId, int? iteration, Routine? routine, @@ -247,11 +245,6 @@ class GymModeState { List? pages, int? currentPage, - // Rest data. clearRest drops both rest fields before the passed ones apply - DateTime? restStartedAt, - DateTime? restEndsAt, - bool clearRest = false, - // Routine data int? dayId, int? iteration, @@ -270,13 +263,14 @@ class GymModeState { bool? showDistinctLogs, bool? showWorkoutDuration, bool? showWorkoutNotification, + bool? stickySetValues, + Map? progress, + List? addedExercises, }) { return GymModeState( isInitialized: isInitialized ?? this.isInitialized, pages: pages ?? this.pages, currentPage: currentPage ?? this.currentPage, - restStartedAt: restStartedAt ?? (clearRest ? null : this.restStartedAt), - restEndsAt: restEndsAt ?? (clearRest ? null : this.restEndsAt), dayId: dayId ?? this.dayId, iteration: iteration ?? this.iteration, @@ -295,9 +289,19 @@ class GymModeState { showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, showWorkoutNotification: showWorkoutNotification ?? this.showWorkoutNotification, + stickySetValues: stickySetValues ?? this.stickySetValues, + progress: progress ?? this.progress, + addedExercises: addedExercises ?? this.addedExercises, ); } + 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); @@ -310,6 +314,22 @@ class GymModeState { return useCountdownBetweenSets ? countdownDuration : null; } + /// When the rest on the current timer page started, null on other pages + DateTime? get restStartedAt { + final slotPage = getSlotEntryPageByIndex(); + return slotPage?.type == SlotPageType.timer ? progressOf(slotPage!.key).timerStartedAt : null; + } + + /// When the countdown on the current timer page ends, null if it counts up + DateTime? get restEndsAt { + final startedAt = restStartedAt; + if (startedAt == null) { + return null; + } + final duration = restDurationFor(getSlotEntryPageByIndex()!); + return duration == null ? null : startedAt.add(duration); + } + int get totalPages { // Main pages (start, session, etc.) var count = pages.where((p) => p.type != PageType.set).length; @@ -351,9 +371,49 @@ class GymModeState { return null; } - SlotPageEntry? getSlotPageByUUID(String uuid) { + /// 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.uuid == uuid) { + if (slotPage.key == key) { + return slotPage; + } + } + 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; } } diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index f9b50112a..a45348275 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'; @@ -24,14 +26,18 @@ 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'; import 'package:wger/features/routines/models/set_config_data.dart'; import 'package:wger/features/routines/models/weight_unit.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'; import 'package:wger/features/routines/providers/routines_notifier.dart'; import 'package:wger/features/routines/providers/workout_logs_notifier.dart'; +import 'package:wger/features/routines/providers/workout_logs_repository.dart'; import 'package:wger/features/routines/validators.dart'; part 'gym_state_notifier.g.dart'; @@ -93,6 +99,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); + } + final workoutNotification = await prefs.getBool(PREFS_WORKOUT_NOTIFICATION); if (workoutNotification != null && workoutNotification != state.showWorkoutNotification) { state = state.copyWith(showWorkoutNotification: workoutNotification); @@ -129,6 +140,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); await prefs.setBool(PREFS_WORKOUT_NOTIFICATION, state.showWorkoutNotification); _logger.finer( @@ -145,21 +157,186 @@ class GymStateNotifier extends _$GymStateNotifier { ); } + /// 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) { + return; + } + + final progress = WorkoutProgress( + dayId: state.dayId, + iteration: state.iteration, + currentPageKey: state.keyOfPage(state.currentPage) ?? 'start', + workoutStart: state.workoutStart, + validUntil: state.validUntil, + 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( + 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'); + } + + /// 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); + await loadPrefs(); + + if (resume && state.pages.isNotEmpty) { + return initialPage; + } + + 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; + } + + final WorkoutProgress saved; + try { + 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, 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; + } + + // 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(); + 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 + 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: state.pageIndexOf(saved.currentPageKey) ?? 0, + workoutStart: saved.workoutStart, + validUntil: saved.validUntil, + progress: progress, + ); + + _logger.fine('Restored workout progress on page ${state.currentPage}'); + + return state.currentPage; + } + /// 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}'; + + // 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 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) @@ -175,6 +352,7 @@ class GymStateNotifier extends _$GymStateNotifier { type: SlotPageType.exerciseOverview, setIndex: setIndex, pageIndex: pageIndex, + key: 'overview:${nextSet(setConfig.slotEntryId)}', setConfigData: setConfig, ), ); @@ -183,12 +361,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, ), ); @@ -202,6 +384,7 @@ class GymStateNotifier extends _$GymStateNotifier { type: SlotPageType.timer, setIndex: setIndex, pageIndex: pageIndex, + key: 'timer:$setKey', setConfigData: config, ), ); @@ -213,58 +396,24 @@ class GymStateNotifier extends _$GymStateNotifier { PageEntry( type: PageType.set, pageIndex: slotPageIndex, + key: slotKey, slotPages: slotEntries, ), ); + addAddedPages(slotKey); } // 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()); _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 = []; @@ -281,13 +430,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.'); } @@ -300,9 +450,11 @@ class GymStateNotifier extends _$GymStateNotifier { routine: routine, iteration: iteration, currentPage: initialPage, - clearRest: shouldReset, - // 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, + progress: shouldReset ? const {} : null, + addedExercises: shouldReset ? const [] : null, ); // Calculate the pages. @@ -317,17 +469,55 @@ class GymStateNotifier extends _$GymStateNotifier { } void setCurrentPage(int page) { - final pageChanged = page != state.currentPage; state = state.copyWith(currentPage: page); - _updateRest(restart: pageChanged); + _saveProgress(); + // 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 slotPage = state.getSlotEntryPageByIndex(); + + // Not only from the timer widget, the notifications need the rest while + // the app draws no frames in the background + if (slotPage?.type == SlotPageType.timer) { + startTimerIfNeeded(slotPage!.key); + } + + final loggedEntry = slotPage == null ? null : state.progressOf(slotPage.key).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. + 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) { return; } - ref.read(gymLogProvider.notifier).setLog(_draftFor(slotEntryPage)); + final logNotifier = ref.read(gymLogProvider.notifier)..setLog(_draftFor(slotEntryPage)); + if (!state.stickySetValues) { + return; + } + + // 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); + } } /// The log draft a slot page starts with, prefilled with the planned values @@ -348,16 +538,21 @@ class GymStateNotifier extends _$GymStateNotifier { /// Adds [extra] to the running countdown, counted from now if the rest is /// already over. No-op without a countdown (other pages, count-up rest). void extendRest(Duration extra) { + final slotPage = state.getSlotEntryPageByIndex(); final endsAt = state.restEndsAt; - if (endsAt == null) { + if (slotPage == null || endsAt == null) { return; } final now = clock.now(); - state = state.copyWith(restEndsAt: (endsAt.isAfter(now) ? endsAt : now).add(extra)); + final newEnd = (endsAt.isAfter(now) ? endsAt : now).add(extra); + + // The rest is stored by its start, so the start moves along with the end + final startedAt = newEnd.subtract(state.restDurationFor(slotPage)!); + _updateProgress(slotPage.key, (p) => p.copyWith(timerStartedAt: startedAt)); } - /// Saves the log draft of the current log page, marks the page as done and - /// moves on to the next page. A failed write propagates to the caller. + /// Saves the log draft of the current log page, a new set or a correction, + /// and moves on to the next page. A failed write propagates to the caller. Future logCurrentSet() async { final slotPage = state.getSlotEntryPageByIndex(); final log = ref.read(gymLogProvider); @@ -367,13 +562,20 @@ class GymStateNotifier extends _$GymStateNotifier { } // Done before the write, so a repeated logPlannedSet is rejected meanwhile - markSlotPageAsDone(slotPage.uuid, isDone: true); + final wasDone = state.progressOf(slotPage.key).done; + _updateProgress(slotPage.key, (p) => p.copyWith(done: true)); try { - await ref.read(workoutLogProvider).addEntry(log, dayId: state.dayId); + final logs = ref.read(workoutLogProvider); + if (log.id == null) { + await logs.addEntry(log, dayId: state.dayId); + } else { + await logs.updateEntry(log); + } } catch (_) { - markSlotPageAsDone(slotPage.uuid, isDone: false); + _updateProgress(slotPage.key, (p) => p.copyWith(done: wasDone)); rethrow; } + markSlotPageAsDone(slotPage.key, isDone: true, log: log); // The user may have moved on or left gym mode during the write if (state.currentPage == slotPage.pageIndex) { @@ -381,13 +583,13 @@ class GymStateNotifier extends _$GymStateNotifier { } } - /// Logs the set of the log page [slotPageUuid] without the UI, e.g. from a + /// Logs the set of the log page [slotPageKey] without the UI, e.g. from a /// notification. From the rest right before it the planned values are logged, /// on the page itself the current draft, in both cases the values of /// [valuesFrom] if given. False if stale, done or incomplete. - Future logPlannedSet(String slotPageUuid, {Log? valuesFrom}) async { - final target = state.getSlotPageByUUID(slotPageUuid); - if (target == null || target.type != SlotPageType.log || target.logDone) { + Future logPlannedSet(String slotPageKey, {Log? valuesFrom}) async { + final target = state.getSlotPageByKey(slotPageKey); + if (target == null || target.type != SlotPageType.log || state.progressOf(target.key).done) { return false; } @@ -414,27 +616,6 @@ class GymStateNotifier extends _$GymStateNotifier { return true; } - /// Starts the rest when on a timer page, ends it everywhere else. A rest - /// that is already running on the current page keeps going unless [restart]. - void _updateRest({required bool restart}) { - final slotPage = state.getSlotEntryPageByIndex(); - if (slotPage?.type != SlotPageType.timer) { - state = state.copyWith(clearRest: true); - return; - } - if (!restart && state.restStartedAt != null) { - return; - } - - final now = clock.now(); - final duration = state.restDurationFor(slotPage!); - state = state.copyWith( - clearRest: true, - restStartedAt: now, - restEndsAt: duration == null ? null : now.add(duration), - ); - } - void setShowExercisePages(bool value) { state = state.copyWith(showExercisePages: value); calculatePages(); @@ -478,81 +659,104 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } + void setStickySetValues(bool value) { + state = state.copyWith(stickySetValues: value); + _savePrefs(); + } + void setShowWorkoutNotification(bool value) { state = state.copyWith(showWorkoutNotification: value); _savePrefs(); } - void markSlotPageAsDone(String uuid, {required bool isDone}) { - final slotPage = state.getSlotPageByUUID(uuid); + /// 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 + /// 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 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 (state.progressOf(key).timerStartedAt != null) { return; } - final updatedSlotPage = slotPage.copyWith(logDone: isDone); - - 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); - _logger.fine('Set logDone=$isDone 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 + /// 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. + void markSlotPageAsDone(String key, {required bool isDone, Log? log}) { + final slotPage = state.getSlotPageByKey(key); + if (slotPage == null) { + _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 + _updateProgress( + key, + (p) => p.copyWith(done: isDone, loggedEntry: log?.copyWith() ?? p.loggedEntry), + ); + _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 = previousEntry?.id != log?.id; + if (isNewEntry && timerPage?.type == SlotPageType.timer) { + _updateProgress(timerPage!.key, (p) => p.copyWith(timerStartedAt: clock.now())); + } + } + + /// Replaces the exercise everywhere in the workout, also where it was added void replaceExercises( - String pageEntryUUID, { + String pageEntryKey, { required int originalExerciseId, required Exercise newExercise, }) { - final updatedPages = state.pages.map((page) { - if (page.type != PageType.set) { - return page; - } - - if (page.uuid != pageEntryUUID) { - 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}'); } void addExerciseAfterPage( - String pageEntryUUID, { + 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. @@ -561,48 +765,25 @@ class GymStateNotifier extends _$GymStateNotifier { final defaultWeightUnitId = profile?.defaultWeightUnitId ?? WEIGHT_UNIT_KG; final defaultWeightUnit = weightUnits.firstWhereOrNull((u) => u.id == defaultWeightUnitId); - final List pages = []; - for (final page in state.pages) { - pages.add(page); - - if (page.uuid == pageEntryUUID) { - 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, - setConfigData: SetConfigData( - textRepr: '-/-', - exerciseId: newExercise.id, - exercise: newExercise, - slotEntryId: setConfigData.slotEntryId, - weightUnit: defaultWeightUnit, - ), - ), - ); - } - - final newPage = PageEntry(type: PageType.set, pageIndex: 1, 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" void startWorkout() { _logger.fine('Setting workout start time'); state = state.copyWith(workoutStart: clock.now()); + _saveProgress(); } void clear() { @@ -611,10 +792,12 @@ class GymStateNotifier extends _$GymStateNotifier { isInitialized: false, pages: [], currentPage: 0, - clearRest: true, + progress: const {}, + addedExercises: const [], validUntil: clock.now().add(DEFAULT_DURATION), workoutStart: clock.now(), ); + _clearProgress(); } } diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 691ca7d7f..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'be5943c4201793dc053ef44a4a243226e6d38526'; +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 318ab65bb..ce2294fe0 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,50 @@ 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 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)); + 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/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 3a9b60880..908c72e0d 100644 --- a/lib/features/routines/widgets/gym_mode/gym_mode.dart +++ b/lib/features/routines/widgets/gym_mode/gym_mode.dart @@ -109,14 +109,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(); + final initialPage = await ref + .read(gymStateProvider.notifier) + .open(routine, widget._args.dayId, widget._args.iteration); _requestNotificationPermissions(); return initialPage; @@ -147,19 +142,19 @@ 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)); } if (slotPage.type == SlotPageType.timer) { final rest = gymState.restDurationFor(slotPage); out.add( rest != null - ? TimerCountdownWidget(_controller, slotPage.uuid) - : TimerWidget(_controller, slotPage.uuid), + ? TimerCountdownWidget(_controller, rest.inSeconds, slotPage.key) + : 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 9d691c089..1e1f344df 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -47,9 +47,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) { @@ -57,9 +57,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(); } @@ -84,7 +84,7 @@ class LogPage extends ConsumerWidget { ); // Mark done sets - final decorationStyle = slotEntryPage.logDone + final decorationStyle = gymState.progressOf(slotEntryPage.key).done ? TextDecoration.lineThrough : TextDecoration.none; @@ -153,7 +153,7 @@ class LogPage extends ConsumerWidget { child: LogFormWidget( controller: _controller, configData: setConfigData, - key: ValueKey('log-form-${slotEntryPage.uuid}'), + key: ValueKey('log-form-${slotEntryPage.key}'), ), ), ), @@ -302,13 +302,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, ), @@ -360,41 +363,56 @@ 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; + } - // A failed write is intentionally left to propagate to the global - // error handler; the success path below is then skipped. The - // PageView follows the page change from the gym state. - await ref.read(gymStateProvider.notifier).logCurrentSet(); - if (!context.mounted) { - return; - } + // A failed write is intentionally left to propagate to the global + // error handler; the success path below is then skipped. A page + // logged before updates its row, and the PageView follows the + // page change from the gym state. + await ref.read(gymStateProvider.notifier).logCurrentSet(); + if (!context.mounted) { + return; + } - showSnackbar( - context, - i18n.successfullySaved, - center: true, - duration: const Duration(seconds: 2), - ); - }, - child: Text(i18n.save), + showSnackbar( + context, + i18n.successfullySaved, + center: true, + duration: const Duration(seconds: 2), + ); + }, + child: Text(i18n.save), + ), + ], ), ], ), diff --git a/lib/features/routines/widgets/gym_mode/start_page.dart b/lib/features/routines/widgets/gym_mode/start_page.dart index 988aa5e0d..7cc5fe926 100644 --- a/lib/features/routines/widgets/gym_mode/start_page.dart +++ b/lib/features/routines/widgets/gym_mode/start_page.dart @@ -238,6 +238,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/features/routines/widgets/gym_mode/timer.dart b/lib/features/routines/widgets/gym_mode/timer.dart index 0aefed621..5b834de16 100644 --- a/lib/features/routines/widgets/gym_mode/timer.dart +++ b/lib/features/routines/widgets/gym_mode/timer.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2026 wger Team + * Copyright (C) 2020, 2025 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, + * 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. @@ -16,25 +16,26 @@ * along with this program. If not, see . */ import 'dart:async'; -import 'dart:math'; import 'package:clock/clock.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; import 'package:material_ui/material_ui.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'; -/// Rest that counts up, from the rest start in the gym state class TimerWidget extends ConsumerStatefulWidget { final PageController _controller; - /// The timer page this widget renders - final String slotUuid; + /// 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 slotKey; - const TimerWidget(this._controller, this.slotUuid); + const TimerWidget(this._controller, this.slotKey); @override _TimerWidgetState createState() => _TimerWidgetState(); @@ -48,6 +49,15 @@ class _TimerWidgetState extends ConsumerState { void initState() { super.initState(); + // 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.slotKey); + } + }); + _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate if (mounted) { @@ -64,15 +74,8 @@ class _TimerWidgetState extends ConsumerState { @override Widget build(BuildContext context) { - final gymState = ref.watch(gymStateProvider); - final slotPage = gymState.getSlotPageByUUID(widget.slotUuid); - if (slotPage == null) { - return Container(); - } - - // The rest only runs while this is the current page - final startedAt = gymState.currentPage == slotPage.pageIndex ? gymState.restStartedAt : null; - final elapsed = startedAt == null ? 0 : clock.now().difference(startedAt).inSeconds; + 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)); @@ -83,13 +86,18 @@ class _TimerWidgetState extends ConsumerState { 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.slotKey), + ], ), ), NavigationFooter(widget._controller), @@ -98,14 +106,20 @@ class _TimerWidgetState extends ConsumerState { } } -/// Rest that counts down to the rest end in the gym state class TimerCountdownWidget extends ConsumerStatefulWidget { final PageController _controller; + final int _seconds; - /// The timer page this widget renders - final String slotUuid; + /// 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 slotKey; - const TimerCountdownWidget(this._controller, this.slotUuid); + const TimerCountdownWidget( + this._controller, + this._seconds, + this.slotKey, + ); @override _TimerCountdownWidgetState createState() => _TimerCountdownWidgetState(); @@ -114,13 +128,35 @@ class TimerCountdownWidget extends ConsumerStatefulWidget { class _TimerCountdownWidgetState extends ConsumerState { late Timer _uiTimer; - /// The rest end the alert was played for, so each rest alerts once + /// The end the alert was played for, so each rest (also an extended one) + /// alerts once DateTime? _alertedFor; + /// 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.progressOf(widget.slotKey).timerStartedAt; + return (startedAt ?? clock.now()).add(Duration(seconds: widget._seconds)); + } + @override 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. + final endTime = _endTime(ref.read(gymStateProvider)); + _alertedFor = endTime.isBefore(clock.now()) ? endTime : null; + + // Deferred because a provider can't be modified during the widget + // life-cycle. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) { + ref.read(gymStateProvider.notifier).startTimerIfNeeded(widget.slotKey); + } + }); + _uiTimer = Timer.periodic(const Duration(seconds: 1), (_) { // ignore: no-empty-block, avoid-empty-setstate if (mounted) { @@ -138,22 +174,14 @@ class _TimerCountdownWidgetState extends ConsumerState { @override Widget build(BuildContext context) { final gymState = ref.watch(gymStateProvider); - final slotPage = gymState.getSlotPageByUUID(widget.slotUuid); - if (slotPage == null) { - return Container(); - } - - // The rest only runs while this is the current page, the neighbours show - // their full length - final endsAt = gymState.currentPage == slotPage.pageIndex ? gymState.restEndsAt : null; - final remaining = endsAt == null - ? gymState.restDurationFor(slotPage)! - : endsAt.difference(clock.now()); - final remainingSeconds = max(0, remaining.inSeconds); + final endTime = _endTime(gymState); + final remaining = endTime.difference(clock.now()); + final remainingSeconds = remaining.inSeconds <= 0 ? 0 : remaining.inSeconds; final displayTime = DateTime(2000, 1, 1, 0, 0, 0).add(Duration(seconds: remainingSeconds)); - if (endsAt != null && remainingSeconds == 0 && _alertedFor != endsAt) { - _alertedFor = endsAt; + // When countdown finishes, notify ONCE, and respect settings + if (remainingSeconds == 0 && _alertedFor != endTime) { + _alertedFor = endTime; if (gymState.alertOnCountdownEnd) { // Strongest built-in haptic on both platforms (iOS: full vibration, // Android: LONG_PRESS). heavyImpact maps to a weak tick on Android. @@ -181,6 +209,7 @@ class _TimerCountdownWidgetState extends ConsumerState { ).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary), ), const SizedBox(height: 16), + UpNextWidget(widget.slotKey), ], ), ), @@ -189,3 +218,61 @@ class _TimerCountdownWidgetState extends ConsumerState { ); } } + +/// Shows the set that will be performed once the rest timer on the slot page +/// 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 slotKey; + + 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.getSlotPageByKey(slotKey); + 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/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/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 98094dc07..2453a5e92 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1193,5 +1193,8 @@ "workoutNotificationNotLoggedTitle": "Satz nicht eingetragen", "workoutNotificationNotLoggedBody": "Öffne den Studiomodus, um das Training fortzusetzen", "workoutNotificationAlarmChannel": "Pausenalarm", - "workoutNotificationChannel": "Training" + "workoutNotificationChannel": "Training", + "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", + "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 7fbbcd337..284e9a4db 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -461,6 +461,18 @@ "@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" + }, + "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 you last logged for it", + "@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/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 800eb7074..b5cbb6b75 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1211,5 +1211,8 @@ "workoutNotificationNotLoggedBody": "Abre el modo gimnasio para continuar el entrenamiento", "workoutNotificationAlarmChannel": "Alarma de descanso", "workoutNotificationChannel": "Entrenamiento", - "authorHelpText": "Se muestra como autor del ejercicio (CC BY-SA 4.0). Cámbialo solo si no eres el autor." + "authorHelpText": "Se muestra como autor del ejercicio (CC BY-SA 4.0). Cámbialo solo si no eres el autor.", + "gymModeStickySetValues": "Mantener los valores de la última serie", + "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 52e8190f5..adae245c6 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1202,5 +1202,8 @@ "workoutNotificationNotLoggedTitle": "Série non enregistrée", "workoutNotificationNotLoggedBody": "Ouvrez le mode entraînement pour poursuivre la séance", "workoutNotificationAlarmChannel": "Alarme de repos", - "workoutNotificationChannel": "Entraînement" + "workoutNotificationChannel": "Entraînement", + "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", + "upNext": "À suivre" } 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.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 { 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 a14405407..7b552f83d 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; @@ -1691,6 +1692,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( 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/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/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.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 { 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/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); + }); }); } diff --git a/test/features/routines/notifications/workout_notification_content_test.dart b/test/features/routines/notifications/workout_notification_content_test.dart index 3453860fb..0f064049d 100644 --- a/test/features/routines/notifications/workout_notification_content_test.dart +++ b/test/features/routines/notifications/workout_notification_content_test.dart @@ -24,6 +24,7 @@ import 'package:shared_preferences_platform_interface/shared_preferences_async_p import 'package:wger/core/consts.dart'; import 'package:wger/features/exercises/models/image.dart'; import 'package:wger/features/routines/models/log.dart'; +import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/notifications/workout_notification_content.dart'; import 'package:wger/features/routines/providers/gym_state.dart'; import 'package:wger/features/routines/providers/gym_state_notifier.dart'; @@ -65,12 +66,18 @@ void main() { mediaUrl: mediaUrl, ); + /// The state keeps a rest by its start, the end of a countdown follows from + /// the rest length of [page] void onPage(SlotPageEntry page, {DateTime? restStartedAt, DateTime? restEndsAt}) { + final startedAt = restEndsAt == null + ? restStartedAt + : restEndsAt.subtract(notifier.state.restDurationFor(page)!); notifier.state = notifier.state.copyWith( currentPage: page.pageIndex, - clearRest: true, - restStartedAt: restStartedAt, - restEndsAt: restEndsAt, + progress: { + ...notifier.state.progress, + if (startedAt != null) page.key: PageProgress(timerStartedAt: startedAt), + }, ); } @@ -94,13 +101,13 @@ void main() { expect(target.alarm!.subtitle, 'Rest is over'); expect(target.alarm!.body, 'Set 2 of 3 · 3x100kg'); expect(target.alarm!.canLogSet, isTrue); - expect(target.alarm!.payload.logSlotUuid, logs()[1].uuid); + expect(target.alarm!.payload.logSlotKey, logs()[1].key); expect(target.controls!.title, 'Pause'); expect(target.controls!.body, 'Next: Bench press 3x100kg'); expect(target.controls!.chronometerAt, endsAt); expect(target.controls!.chronometerCountsDown, isTrue); expect(target.controls!.canSkipRest, isTrue); - expect(target.controls!.payload.restSlotUuid, timer.uuid); + expect(target.controls!.payload.restSlotKey, timer.key); }); test('No alarm when the setting is off', () { @@ -184,7 +191,7 @@ void main() { expect(controls.body, 'Set 2 of 3 · 3x100kg'); expect(controls.canLogSet, isTrue); expect(controls.canSkipRest, isFalse); - expect(controls.payload.logSlotUuid, logs()[1].uuid); + expect(controls.payload.logSlotKey, logs()[1].key); }); test('The short server text when there is one, without the rest time', () { @@ -197,7 +204,7 @@ void main() { }); test('A logged set cannot be logged again', () { - notifier.markSlotPageAsDone(logs()[1].uuid, isDone: true); + notifier.markSlotPageAsDone(logs()[1].key, isDone: true); onPage(logs()[1]); expect(build().controls!.canLogSet, isFalse); @@ -223,7 +230,8 @@ void main() { onPage(timer, restStartedAt: now, restEndsAt: now.subtract(const Duration(seconds: 1))); expect(build().controls!.canExtendRest, isTrue); - onPage(timer, restStartedAt: now); + // The other exercise has no rest time and the countdown setting is off + onPage(timers().last, restStartedAt: now); expect(build().controls!.canExtendRest, isFalse); onPage(logs()[1]); @@ -311,7 +319,7 @@ void main() { target = build(recentLogs: recent); expect(target.controls!.quickLogs, ['9 × 60 kg']); - notifier.markSlotPageAsDone(logs()[1].uuid, isDone: true); + notifier.markSlotPageAsDone(logs()[1].key, isDone: true); expect(build(recentLogs: recent).controls!.quickLogs, isEmpty); }); @@ -357,8 +365,8 @@ void main() { dayId: 2, iteration: 3, workoutStart: DateTime.utc(2025, 3, 29, 14, 33), - logSlotUuid: 'log', - restSlotUuid: 'rest', + logSlotKey: 'log', + restSlotKey: 'rest', ); expect(WorkoutNotificationPayload.decode(payload.encode()), payload); diff --git a/test/features/routines/notifications/workout_notification_controller_test.dart b/test/features/routines/notifications/workout_notification_controller_test.dart index c2ee5fe20..a762f2062 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.dart @@ -246,14 +246,14 @@ void main() { SlotPageEntry slotPage(int index) => gymState.state.getSlotEntryPageByIndex(index)!; /// The payload the notification on the current page carries - String payloadFor({String? logSlotUuid, String? restSlotUuid, DateTime? workoutStart}) => + String payloadFor({String? logSlotKey, String? restSlotKey, DateTime? workoutStart}) => WorkoutNotificationPayload( routineId: gymState.state.routine.id!, dayId: gymState.state.dayId, iteration: gymState.state.iteration, workoutStart: workoutStart ?? gymState.state.workoutStart, - logSlotUuid: logSlotUuid, - restSlotUuid: restSlotUuid, + logSlotKey: logSlotKey, + restSlotKey: restSlotKey, ).encode(); test('"Log set" from the rest logs the next set and shows the next rest', () async { @@ -266,7 +266,7 @@ void main() { .read(workoutNotificationControllerProvider) .handleAction( WORKOUT_NOTIFICATION_ACTION_LOG_SET, - payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + payloadFor(logSlotKey: slotPage(rest + 1).key), ); await settle(); }); @@ -276,7 +276,7 @@ void main() { // Only once the notification shows the new rest may iOS suspend the app verifyInOrder([service.showControls(any, any), service.actionHandled()]); final alarms = verify(service.scheduleRestAlarm(captureAny, any)).captured; - expect((alarms.last as RestAlarm).payload.restSlotUuid, slotPage(rest + 2).uuid); + expect((alarms.last as RestAlarm).payload.restSlotKey, slotPage(rest + 2).key); }); test('Actions arrive through the port from the background isolate', () async { @@ -285,7 +285,7 @@ void main() { IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ WORKOUT_NOTIFICATION_ACTION_SKIP_REST, - payloadFor(restSlotUuid: slotPage(rest).uuid), + payloadFor(restSlotKey: slotPage(rest).key), null, ]); await settle(); @@ -353,7 +353,7 @@ void main() { IsolateNameServer.lookupPortByName(WORKOUT_NOTIFICATION_PORT)!.send([ WORKOUT_NOTIFICATION_ACTION_LOG_SET, - payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + payloadFor(logSlotKey: slotPage(rest + 1).key), '9 × 60 kg', ]); await settle(); @@ -372,7 +372,7 @@ void main() { .read(workoutNotificationControllerProvider) .handleAction( WORKOUT_NOTIFICATION_ACTION_LOG_SET, - payloadFor(logSlotUuid: slotPage(rest + 1).uuid), + payloadFor(logSlotKey: slotPage(rest + 1).key), '7 × 50 kg', ); await settle(); @@ -393,7 +393,7 @@ void main() { .read(workoutNotificationControllerProvider) .handleAction( WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, - payloadFor(restSlotUuid: slotPage(rest).uuid), + payloadFor(restSlotKey: slotPage(rest).key), ); await settle(); }); @@ -411,7 +411,7 @@ void main() { .read(workoutNotificationControllerProvider) .handleAction( WORKOUT_NOTIFICATION_ACTION_EXTEND_REST, - payloadFor(restSlotUuid: 'another rest'), + payloadFor(restSlotKey: 'another rest'), ); await settle(); @@ -429,14 +429,14 @@ void main() { await controller.handleAction( WORKOUT_NOTIFICATION_ACTION_LOG_SET, payloadFor( - logSlotUuid: slotPage(rest + 1).uuid, + logSlotKey: slotPage(rest + 1).key, workoutStart: DateTime.utc(2020), ), ); // For a rest the user already left await controller.handleAction( WORKOUT_NOTIFICATION_ACTION_SKIP_REST, - payloadFor(restSlotUuid: slotPage(rest - 2).uuid), + payloadFor(restSlotKey: slotPage(rest - 2).key), ); await settle(); }); diff --git a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart index 9deba8fe8..99453be3e 100644 --- a/test/features/routines/notifications/workout_notification_controller_test.mocks.dart +++ b/test/features/routines/notifications/workout_notification_controller_test.mocks.dart @@ -155,6 +155,22 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i5.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i6.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i6.Log?>.value(), + ) + as _i3.Future<_i6.Log?>); + + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i6.Log>[]), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod( diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index b6eb6f4ed..ea5441106 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -17,6 +17,7 @@ */ import 'dart:async'; +import 'dart:convert'; import 'package:clock/clock.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -31,9 +32,11 @@ 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'; +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'; @@ -80,103 +83,176 @@ 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); } } } }); - }); - group('GymStateNotifier.recalculateIndices', () { - test('Correctly recalculates indices if new pages are added', () { + test('Stores the logged entry in the page progress', () { // Arrange - final newPages = [ - ...notifier.state.pages.sublist(0, 2), - PageEntry( - type: PageType.set, - pageIndex: 1111, - uuid: 'new-page-1', - ), - PageEntry( - type: PageType.set, - pageIndex: 9, - uuid: 'new-page-2', - ), - ...notifier.state.pages.sublist(2), - PageEntry( - type: PageType.set, - pageIndex: 0, - uuid: 'new-page-3', - slotPages: [ - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 10, - setIndex: 9, - uuid: 'new-slot-1', - ), - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 10, - setIndex: 6, - uuid: 'new-slot-2', - ), - SlotPageEntry( - type: SlotPageType.timer, - pageIndex: 100, - setIndex: 100, - uuid: 'new-slot-3', - ), - ], - ), - ]; - notifier.state = notifier.state.copyWith(pages: newPages); + 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.recalculateIndices(); + notifier.markSlotPageAsDone(slotPage.key, isDone: true, log: log); // Assert - final pages = notifier.state.pages; - expect(pages[0].pageIndex, 0); - expect(pages[1].pageIndex, 1); + final loggedEntry = notifier.state.progressOf(slotPage.key).loggedEntry!; + expect(loggedEntry.id, 'log-1'); + expect(loggedEntry, isNot(same(log))); - // 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); + // 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'); + }); + }); - expect(pages[5].pageIndex, 15); - expect(pages[6].pageIndex, 16); - expect(pages[7].pageIndex, 17); + 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.key, isDone: true, log: log); - // Preserve the order of new pages - expect(pages[7].uuid, 'new-page-3'); + // Act + notifier.setCurrentPage(slotPage.pageIndex); - // 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].pageIndex, 17); - expect(slotPages[0].setIndex, 0); - expect(slotPages[1].uuid, 'new-slot-2'); - expect(slotPages[1].pageIndex, 18); - expect(slotPages[1].setIndex, 1); - expect(slotPages[2].uuid, 'new-slot-3'); - expect(slotPages[2].pageIndex, 19); - expect(slotPages[2].setIndex, 2); + // Assert: the id and session are kept so saving updates the row + // instead of inserting a duplicate + final gymLog = container.read(gymLogProvider); + 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.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.key, 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.progressOf(slotPage.key).loggedEntry!.id, 'log-1'); + }); + }); + + 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.key); + }); + + // Assert + expect( + 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.key); + }); + + // Assert + expect( + notifier.state.progressOf(timerPage.key).timerStartedAt, + DateTime(2024, 5, 2, 12), + ); + }); + + 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]; + expect(logPage.type, SlotPageType.log); + expect(timerPage.type, SlotPageType.timer); + withClock(Clock.fixed(DateTime(2024, 5, 2, 12)), () { + notifier.startTimerIfNeeded(timerPage.key); + }); + // 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)), () { + notifier.markSlotPageAsDone(logPage.key, isDone: true, log: log); + }); + + // Assert + expect( + 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.key, isDone: true, log: log); + }); + + // Assert + expect( + 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.key, isDone: true, log: extraLog); + }); + + // Assert + expect( + notifier.state.progressOf(timerPage.key).timerStartedAt, + DateTime(2024, 5, 2, 12, 15), + ); }); }); @@ -185,6 +261,7 @@ void main() { // 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)), @@ -193,11 +270,16 @@ 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) 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) @@ -217,9 +299,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(), @@ -246,19 +327,79 @@ 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.uuid, newExercise: testSquats); + imperialNotifier.addExerciseAfterPage(setPage.key, newExercise: testSquats); - // recalculateIndices copies the page objects, so look the page up by uuid. + // The pages are recalculated, 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', + ]); + }); + + 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); }); }); @@ -369,9 +510,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', () { @@ -600,7 +814,7 @@ void main() { expect(notifier.state.restEndsAt, isNull); }); - test('Leaving the timer page clears the rest', () { + test('Other pages have no rest', () { final timer = timerWithRestTime(); goTo(timer); @@ -621,15 +835,16 @@ void main() { expect(notifier.state.restStartedAt, start); }); - test('Coming back to a timer page restarts the rest', () { + test('Coming back to a timer page continues its rest', () { + // E.g. after going back to correct the set during the rest final timer = timerWithRestTime(); goTo(timer); goTo(timer + 1); goTo(timer, at: later); - expect(notifier.state.restStartedAt, later); - expect(notifier.state.restEndsAt, later.add(const Duration(seconds: 120))); + expect(notifier.state.restStartedAt, start); + expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 120))); }); test('clear() ends the rest', () { @@ -677,7 +892,7 @@ void main() { ).captured; expect((captured[0] as Log).repetitions, 12); expect(captured[1], 1); - expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue); + expect(notifier.state.progressOf(log.key).done, isTrue); expect(notifier.state.currentPage, log.pageIndex + 1); expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 120))); }); @@ -689,10 +904,32 @@ void main() { await expectLater(notifier.logCurrentSet(), throwsException); - expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isFalse); + expect(notifier.state.progressOf(log.key).done, isFalse); expect(notifier.state.currentPage, log.pageIndex); }); + test('logCurrentSet updates a corrected set and keeps its rest running', () async { + when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((invocation) async { + (invocation.positionalArguments.first as Log).id = 'log-1'; + }); + when(mockLogRepo.updateLocalDrift(any)).thenAnswer((_) async {}); + final log = firstLog(); + notifier.setCurrentPage(log.pageIndex); + await withClock(Clock.fixed(start), notifier.logCurrentSet); + + // Back to the set during the rest, the form holds the saved entry + notifier.setCurrentPage(log.pageIndex); + container.read(gymLogProvider.notifier).setRepetitions(5); + await withClock(Clock.fixed(start.add(const Duration(seconds: 40))), notifier.logCurrentSet); + + final updated = verify(mockLogRepo.updateLocalDrift(captureAny)).captured.single as Log; + expect(updated.id, 'log-1'); + expect(updated.repetitions, 5); + verify(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1); + expect(notifier.state.currentPage, log.pageIndex + 1); + expect(notifier.state.restStartedAt, start); + }); + test('logCurrentSet does not move on when the user left the page meanwhile', () async { final write = Completer(); when( @@ -714,14 +951,14 @@ void main() { final logged = await withClock( Clock.fixed(start), - () => notifier.logPlannedSet(log.uuid), + () => notifier.logPlannedSet(log.key), ); expect(logged, isTrue); final saved = capturedLog(); expect(saved.repetitions, log.setConfigData!.repetitions); expect(saved.weight, log.setConfigData!.weight); - expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue); + expect(notifier.state.progressOf(log.key).done, isTrue); expect(notifier.state.currentPage, log.pageIndex + 1); expect(notifier.state.restStartedAt, start); }); @@ -731,7 +968,7 @@ void main() { notifier.setCurrentPage(log.pageIndex); container.read(gymLogProvider.notifier).setRepetitions(7); - expect(await notifier.logPlannedSet(log.uuid), isTrue); + expect(await notifier.logPlannedSet(log.key), isTrue); expect(capturedLog().repetitions, 7); }); @@ -747,7 +984,6 @@ void main() { final later = endsAt.add(const Duration(minutes: 5)); withClock(Clock.fixed(later), () => notifier.extendRest(const Duration(seconds: 30))); expect(notifier.state.restEndsAt, later.add(const Duration(seconds: 30))); - expect(notifier.state.restStartedAt, start); }); test('extendRest does nothing outside a countdown', () { @@ -764,7 +1000,7 @@ void main() { final earlier = Log(exerciseId: log.setConfigData!.exerciseId, repetitions: 8, weight: 62.5); earlier.weightUnit = testWeightUnit2; - expect(await notifier.logPlannedSet(log.uuid, valuesFrom: earlier), isTrue); + expect(await notifier.logPlannedSet(log.key, valuesFrom: earlier), isTrue); final saved = capturedLog(); expect(saved.repetitions, 8); @@ -782,7 +1018,7 @@ void main() { container.read(gymLogProvider.notifier).setRepetitions(7); final earlier = Log(exerciseId: log.setConfigData!.exerciseId, repetitions: 9, weight: 60); - expect(await notifier.logPlannedSet(log.uuid, valuesFrom: earlier), isTrue); + expect(await notifier.logPlannedSet(log.key, valuesFrom: earlier), isTrue); expect(capturedLog().repetitions, 9); }); @@ -792,7 +1028,7 @@ void main() { final log = secondLog(); notifier.state = notifier.state.copyWith(currentPage: log.pageIndex); - expect(await notifier.logPlannedSet(log.uuid), isFalse); + expect(await notifier.logPlannedSet(log.key), isFalse); verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); @@ -804,8 +1040,8 @@ void main() { final log = secondLog(); notifier.setCurrentPage(log.pageIndex - 1); - final first = notifier.logPlannedSet(log.uuid); - final second = await notifier.logPlannedSet(log.uuid); + final first = notifier.logPlannedSet(log.key); + final second = await notifier.logPlannedSet(log.key); write.complete(); expect(second, isFalse); @@ -816,14 +1052,14 @@ void main() { test('logPlannedSet ignores stale actions', () async { final log = secondLog(); notifier.setCurrentPage(log.pageIndex - 1); - final timerUuid = notifier.state.getSlotEntryPageByIndex()!.uuid; + final timerKey = notifier.state.getSlotEntryPageByIndex()!.key; expect(await notifier.logPlannedSet('unknown'), isFalse, reason: 'unknown page'); - expect(await notifier.logPlannedSet(timerUuid), isFalse, reason: 'not a log page'); - expect(await notifier.logPlannedSet(firstLog().uuid), isFalse, reason: 'not the next set'); + expect(await notifier.logPlannedSet(timerKey), isFalse, reason: 'not a log page'); + expect(await notifier.logPlannedSet(firstLog().key), isFalse, reason: 'not the next set'); - notifier.markSlotPageAsDone(log.uuid, isDone: true); - expect(await notifier.logPlannedSet(log.uuid), isFalse, reason: 'already logged'); + notifier.markSlotPageAsDone(log.key, isDone: true); + expect(await notifier.logPlannedSet(log.key), isFalse, reason: 'already logged'); verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); expect(notifier.state.currentPage, log.pageIndex - 1); @@ -834,7 +1070,7 @@ void main() { notifier.setCurrentPage(log.pageIndex - 1); expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.exerciseOverview); - expect(await notifier.logPlannedSet(log.uuid), isFalse); + expect(await notifier.logPlannedSet(log.key), isFalse); verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); }); @@ -865,7 +1101,7 @@ void main() { final log = secondLog(); notifier.setCurrentPage(log.pageIndex - 1); - expect(await notifier.logPlannedSet(log.uuid), isFalse); + expect(await notifier.logPlannedSet(log.key), isFalse); verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))); expect(notifier.state.currentPage, log.pageIndex - 1, reason: 'stays on the rest'); @@ -891,6 +1127,113 @@ 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), ... + + 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; + } + + 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 set with the last logged values of the exercise when enabled', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); + + // Act + notifier.setCurrentPage(4); + await pumpEventQueue(); + + // 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', () async { + // Arrange + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); + + // Act + 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 + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.weight, 55); + expect(gymLog.repetitions, 3); + }); + }); + group('GymStateNotifier.startWorkout', () { test('Resets the workout start time to now', () { // Arrange @@ -908,9 +1251,15 @@ 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)}, + addedExercises: [ + AddedExercise(afterPageKey: 'slot:1:1', exercise: testSquats, slotEntryId: 1), + ], + ); // Act withClock(Clock.fixed(DateTime(2024, 5, 2, 9, 15)), () { @@ -919,6 +1268,8 @@ void main() { // Assert expect(notifier.state.workoutStart, DateTime(2024, 5, 2, 9, 15)); + expect(notifier.state.progress, isEmpty); + expect(notifier.state.addedExercises, isEmpty); }); }); @@ -970,10 +1321,16 @@ void main() { isInitialized: true, 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', () { @@ -992,6 +1349,242 @@ 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); + }); + }); + + group('GymStateNotifier workout progress', () { + /// 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 [], Object? lookupError}) { + final logRepo = MockWorkoutLogRepository(); + 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); + } + + 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 { + await openDay1(notifier); + notifier.markSlotPageAsDone(notifier.state.pages[1].slotPages[1].key, 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 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.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 keeps running', + ); + }); + + test('Continues an interrupted workout where it stopped', () async { + await runWorkout(); + + final restarted = restartedNotifier(); + + expect(await openDay1(restarted), 2); + expect(restarted.state.currentPage, 2); + expect( + restarted.state.progressOf(restarted.state.pages[1].slotPages[1].key).done, + 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 = restartedNotifier(); + await openDay1(restarted); + + expect(restarted.state.workoutStart, DateTime(2026, 7, 26, 18, 30)); + }); + }); + + test('Does not continue the workout of another day', () async { + await runWorkout(); + await editStoredProgress('dayId', 2); + + final restarted = restartedNotifier(); + + expect(await openDay1(restarted), 0); + 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 = restartedNotifier(); + + expect(await openDay1(restarted), 0); + expect(restarted.state.currentPage, 0); + }); + }); + + 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', + ); + }); + + 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; + + // 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, 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 { + await runWorkout(); + + notifier.clear(); + await pumpEventQueue(); + + expect(await openDay1(restartedNotifier()), 0); + }); + + test('Ignores stored progress that can not be read', () async { + await PreferenceHelper.asyncPref.setString(PREFS_WORKOUT_PROGRESS, 'not json'); + + expect(await openDay1(restartedNotifier()), 0); + expect( + await PreferenceHelper.asyncPref.getString(PREFS_WORKOUT_PROGRESS), + isNull, + reason: 'the unreadable value is cleared instead of failing again later', + ); }); }); @@ -1007,32 +1600,33 @@ void main() { expect(state.copyWith(clearLogScopeWeeks: true).logScopeWeeks, isNull); }); + }); - test('Keeps the rest when it is not passed', () { - final state = notifier.state.copyWith( - restStartedAt: DateTime.utc(2024, 5, 1, 17, 30), - restEndsAt: DateTime.utc(2024, 5, 1, 17, 32), - ); + 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) - final copy = state.copyWith(currentPage: 3); + test('Returns the next set of the same exercise for a rest between sets', () { + final next = notifier.state.getNextLogPage(3); - expect(copy.restStartedAt, DateTime.utc(2024, 5, 1, 17, 30)); - expect(copy.restEndsAt, DateTime.utc(2024, 5, 1, 17, 32)); + expect(next!.type, SlotPageType.log); + expect(next.pageIndex, 4); + expect(next.setConfigData!.exerciseId, getTestExercises()[0].id); }); - test('clearRest drops both rest fields before applying the passed ones', () { - final state = notifier.state.copyWith( - restStartedAt: DateTime.utc(2024, 5, 1, 17, 30), - restEndsAt: DateTime.utc(2024, 5, 1, 17, 32), - ); + test('Returns the first set of the next exercise after the final rest of an exercise', () { + final next = notifier.state.getNextLogPage(7); - final cleared = state.copyWith(clearRest: true); - expect(cleared.restStartedAt, isNull); - expect(cleared.restEndsAt, isNull); + expect(next!.type, SlotPageType.log); + expect(next.pageIndex, 9); + expect(next.setConfigData!.exerciseId, getTestExercises()[5].id); + }); - final countUp = state.copyWith(clearRest: true, restStartedAt: DateTime.utc(2024, 5, 1, 18)); - expect(countUp.restStartedAt, DateTime.utc(2024, 5, 1, 18)); - expect(countUp.restEndsAt, isNull); + test('Returns null after the last set of the day', () { + expect(notifier.state.getNextLogPage(14), isNull); }); }); } diff --git a/test/features/routines/providers/gym_state_test.mocks.dart b/test/features/routines/providers/gym_state_test.mocks.dart index 60a3dfa88..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,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( 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..ded5ef543 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,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( diff --git a/test/features/routines/providers/workout_logs_repository_test.dart b/test/features/routines/providers/workout_logs_repository_test.dart index 0e3bd4945..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); @@ -464,4 +498,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 8e4d85fb1..68113e753 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -555,6 +555,22 @@ 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( + 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_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..e36f8f31e 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,22 @@ 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( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i5.Future>.value(<_i10.Log>[]), + ) + as _i5.Future>); + @override _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( 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.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index 070ec8e02..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,11 +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(); - when(mockWorkoutLogRepo.addLocalDrift(any)).thenAnswer((_) async {}); + 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 { + 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, + ); + }); // 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( @@ -103,9 +131,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, @@ -120,7 +148,7 @@ void main() { final controller = PageController(); return PageView( controller: controller, - children: [LogPage(controller, slotUuid)], + children: [LogPage(controller, slotKey)], ); }, ), @@ -254,6 +282,215 @@ void main() { expect(captured[1], gymState.dayId); }); + 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'); + }); + + 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 { + storeLog((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); + await tester.pump(); + 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); + await tester.pump(); + 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 { + 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(any, dayId: anyNamed('dayId'))).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, 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 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', ( + 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 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 + 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).progressOf(logPageKey).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; 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..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 @@ -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,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( 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/gym_mode/start_page_test.dart b/test/features/routines/widgets/gym_mode/start_page_test.dart index d1b397ce9..39151fa66 100644 --- a/test/features/routines/widgets/gym_mode/start_page_test.dart +++ b/test/features/routines/widgets/gym_mode/start_page_test.dart @@ -134,12 +134,20 @@ 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, isFalse); expect(notifier.state.showWorkoutDuration, isFalse); expect(notifier.state.showWorkoutNotification, isFalse); + expect(notifier.state.stickySetValues, isTrue); }); testWidgets('The rest end alert works without the default countdown', (tester) async { diff --git a/test/features/routines/widgets/gym_mode/timer_test.dart b/test/features/routines/widgets/gym_mode/timer_test.dart index 226542caa..f3f23849a 100644 --- a/test/features/routines/widgets/gym_mode/timer_test.dart +++ b/test/features/routines/widgets/gym_mode/timer_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2026 wger Team + * 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, + * 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. @@ -23,125 +23,204 @@ 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/models/page_progress.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 'package:wger/l10n/localizations_delegates.dart'; -import '../../../../../test_data/routines.dart'; +import '../../../../../test_data/routines.dart' as testdata; void main() { - final now = DateTime.utc(2025, 3, 29, 14, 33); - late ProviderContainer container; - late GymStateNotifier notifier; + TestWidgetsFlutterBinding.ensureInitialized(); - setUp(() { - SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); - container = ProviderContainer.test(); - notifier = container.read(gymStateProvider.notifier); - final routine = getTestRoutine(); - notifier.initData(routine, routine.days.first.id!, 1); - }); + group('Timer up-next', () { + late ProviderContainer container; - // In the fixture the first slot rests 120 s, the second has no rest time - SlotPageEntry timerPage({required bool withRestTime}) => notifier.state.pages - .expand((p) => p.slotPages) - .firstWhere( - (p) => p.type == SlotPageType.timer && (p.setConfigData!.restTime != null) == withRestTime, - ); + // 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, Widget timer) async { - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: MaterialApp( - locale: const Locale('en'), - localizationsDelegates: appLocalizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: Builder( - builder: (context) { - final controller = PageController(); - return PageView(controller: controller, children: [timer]); - }, + Future pumpTimer(WidgetTester tester, int timerPageIndex, {bool countsUp = false}) 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: [ + if (countsUp) + TimerWidget(controller, slotPage.key) + else + TimerCountdownWidget(controller, 90, slotPage.key), + ], + ); + }, + ), ), ), ), - ), - ); - } - - group('TimerCountdownWidget', () { - testWidgets('counts down to the rest end of the gym state', (tester) async { - final page = timerPage(withRestTime: true); - notifier.state = notifier.state.copyWith( - currentPage: page.pageIndex, - restStartedAt: now.subtract(const Duration(seconds: 75)), - restEndsAt: now.add(const Duration(seconds: 45)), ); + await tester.pump(); + } - await withClock(Clock.fixed(now), () async { - await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); - }); + testWidgets('shows the next set of the same exercise for a rest between sets', (tester) async { + await pumpTimer(tester, 3); - expect(find.text('0:45'), findsOneWidget); + expect(find.text('Up next'), findsOneWidget); + expect(find.text('Bench press'), findsOneWidget); + expect(find.text('3x100kg'), findsOneWidget); + expect(find.text('2 / 3'), findsOneWidget); }); - testWidgets('a timer page that is not current shows its full rest', (tester) async { - // The rest end in the state belongs to the current page only - final page = timerPage(withRestTime: true); - notifier.state = notifier.state.copyWith( - currentPage: page.pageIndex + 1, - restEndsAt: now.add(const Duration(seconds: 45)), - ); + testWidgets('shows the next exercise after the final rest of an exercise', (tester) async { + await pumpTimer(tester, 7); - await withClock(Clock.fixed(now), () async { - await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); - }); - - expect(find.text('2:00'), findsOneWidget); + expect(find.text('Up next'), findsOneWidget); + expect(find.text('Side raises'), findsOneWidget); + expect(find.text('12x10kg'), findsOneWidget); + expect(find.text('1 / 3'), findsOneWidget); }); - testWidgets('alerts once when the rest is over', (tester) async { - final calls = []; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - SystemChannels.platform, - (call) async { - calls.add(call.method); - return null; - }, - ); + testWidgets('shows nothing after the last set of the day', (tester) async { + await pumpTimer(tester, 14); + + 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); + }); + }); + + 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 page = timerPage(withRestTime: true); - notifier.state = notifier.state.copyWith(currentPage: page.pageIndex, restEndsAt: now); + final t0 = DateTime(2024, 5, 2, 12); - await withClock(Clock.fixed(now), () async { - await pumpTimer(tester, TimerCountdownWidget(PageController(), page.uuid)); - // The widget repaints every second and keeps seeing the end - await tester.pump(const Duration(seconds: 3)); + 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(calls.where((m) => m == 'HapticFeedback.vibrate'), hasLength(1)); + expect(haptics, hasLength(1)); }); - }); - group('TimerWidget', () { - testWidgets('counts up from the rest start of the gym state', (tester) async { - final page = timerPage(withRestTime: false); + testWidgets('alerts again when the rest is extended after its end', (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); + final key = container.read(gymStateProvider).getSlotEntryPageByIndex(3)!.key; + + await withClock(Clock.fixed(t0), () => pumpTimer(tester, 3)); + await withClock(Clock.fixed(t0.add(const Duration(seconds: 95))), () => pumpTimer(tester, 3)); + expect(haptics, hasLength(1)); + expect(haptics.single.arguments, isNull, reason: 'the full vibration, not a light impact'); + + // Extending moves the start, so the countdown ends 30 s later + final notifier = container.read(gymStateProvider.notifier); notifier.state = notifier.state.copyWith( - currentPage: page.pageIndex, - restStartedAt: now.subtract(const Duration(seconds: 30)), + progress: {key: PageProgress(timerStartedAt: t0.add(const Duration(seconds: 30)))}, + ); + await withClock( + Clock.fixed(t0.add(const Duration(seconds: 100))), + () => pumpTimer(tester, 3), + ); + expect(find.text('0:20'), findsOneWidget); + expect(haptics, hasLength(1)); + + await withClock( + Clock.fixed(t0.add(const Duration(seconds: 125))), + () => pumpTimer(tester, 3), + ); + expect(haptics, hasLength(2)); + }); + + testWidgets('counts up from the start in the gym state', (tester) async { + final t0 = DateTime(2024, 5, 2, 12); + final key = container.read(gymStateProvider).getSlotEntryPageByIndex(3)!.key; + final notifier = container.read(gymStateProvider.notifier); + notifier.state = notifier.state.copyWith( + progress: {key: PageProgress(timerStartedAt: t0.subtract(const Duration(seconds: 30)))}, ); - await withClock(Clock.fixed(now), () async { - await pumpTimer(tester, TimerWidget(PageController(), page.uuid)); - }); + await withClock(Clock.fixed(t0), () => pumpTimer(tester, 3, countsUp: true)); expect(find.text('0:30'), findsOneWidget); }); 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); }); 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;