mirror of
https://github.com/wger-project/flutter.git
synced 2026-12-05 23:44:02 +01:00
Merge master into feature/gym-notifications
This commit is contained in:
2
.github/workflows/analyze.yml
vendored
2
.github/workflows/analyze.yml
vendored
@@ -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
|
||||
|
||||
2
.github/workflows/build-android.yml
vendored
2
.github/workflows/build-android.yml
vendored
@@ -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
|
||||
|
||||
3
.github/workflows/build-apple.yml
vendored
3
.github/workflows/build-apple.yml
vendored
@@ -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
|
||||
|
||||
1
.github/workflows/build-linux.yml
vendored
1
.github/workflows/build-linux.yml
vendored
@@ -46,6 +46,7 @@ jobs:
|
||||
- name: Checkout application
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
- name: Read Flutter SDK version
|
||||
|
||||
1
.github/workflows/build-web.yml
vendored
1
.github/workflows/build-web.yml
vendored
@@ -24,6 +24,7 @@ jobs:
|
||||
- name: Checkout application
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
- name: Common flutter setup
|
||||
|
||||
1
.github/workflows/build-windows.yml
vendored
1
.github/workflows/build-windows.yml
vendored
@@ -26,6 +26,7 @@ jobs:
|
||||
- name: Checkout application
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.ref }}
|
||||
|
||||
- name: Common flutter setup
|
||||
|
||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -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
|
||||
|
||||
2
.github/workflows/codeql-analysis.yml
vendored
2
.github/workflows/codeql-analysis.yml
vendored
@@ -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
|
||||
|
||||
1
.github/workflows/make-release.yml
vendored
1
.github/workflows/make-release.yml
vendored
@@ -75,6 +75,7 @@ jobs:
|
||||
- name: Checkout application
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
lfs: true
|
||||
ref: ${{ github.event.inputs.version }}
|
||||
|
||||
|
||||
4
.github/workflows/screenshots.yml
vendored
4
.github/workflows/screenshots.yml
vendored
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -10,7 +10,7 @@ GalleryImage _$GalleryImageFromJson(Map<String, dynamic> 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? ?? '',
|
||||
);
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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
|
||||
|
||||
@@ -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());
|
||||
|
||||
|
||||
44
lib/features/routines/models/added_exercise.dart
Normal file
44
lib/features/routines/models/added_exercise.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
208
lib/features/routines/models/added_exercise.freezed.dart
Normal file
208
lib/features/routines/models/added_exercise.freezed.dart
Normal file
@@ -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>(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<AddedExercise> get copyWith => _$AddedExerciseCopyWithImpl<AddedExercise>(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<TResult extends Object?>({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<TResult extends Object?>(){
|
||||
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<TResult extends Object?>(){
|
||||
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<TResult extends Object?>({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<TResult extends Object?>() {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<TResult extends Object?>() {final _that = this;
|
||||
switch (_that) {
|
||||
case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
39
lib/features/routines/models/page_progress.dart
Normal file
39
lib/features/routines/models/page_progress.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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});
|
||||
}
|
||||
207
lib/features/routines/models/page_progress.freezed.dart
Normal file
207
lib/features/routines/models/page_progress.freezed.dart
Normal file
@@ -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>(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<PageProgress> get copyWith => _$PageProgressCopyWithImpl<PageProgress>(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<TResult extends Object?>({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<TResult extends Object?>(){
|
||||
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<TResult extends Object?>(){
|
||||
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<TResult extends Object?>({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<TResult extends Object?>() {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<TResult extends Object?>() {final _that = this;
|
||||
switch (_that) {
|
||||
case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
@@ -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<WorkoutSession>.from(sessions),
|
||||
dayData: List<DayData>.from(dayData),
|
||||
dayDataGym: List<DayData>.from(dayDataGym),
|
||||
List<DayData> replaceInDays(List<DayData> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ Routine _$RoutineFromJson(Map<String, dynamic> 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),
|
||||
|
||||
51
lib/features/routines/models/workout_progress.dart
Normal file
51
lib/features/routines/models/workout_progress.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'workout_progress.freezed.dart';
|
||||
part 'workout_progress.g.dart';
|
||||
|
||||
/// The progress through a running workout, as stored in the preferences. 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<String, StoredPageProgress> pages,
|
||||
}) = _WorkoutProgress;
|
||||
|
||||
factory WorkoutProgress.fromJson(Map<String, dynamic> json) => _$WorkoutProgressFromJson(json);
|
||||
}
|
||||
|
||||
/// The stored part of a page's progress, the logged entry only by its ID
|
||||
@freezed
|
||||
sealed class StoredPageProgress with _$StoredPageProgress {
|
||||
const factory StoredPageProgress({
|
||||
@Default(false) bool done,
|
||||
String? logId,
|
||||
DateTime? timerStartedAt,
|
||||
}) = _StoredPageProgress;
|
||||
|
||||
factory StoredPageProgress.fromJson(Map<String, dynamic> json) =>
|
||||
_$StoredPageProgressFromJson(json);
|
||||
}
|
||||
570
lib/features/routines/models/workout_progress.freezed.dart
Normal file
570
lib/features/routines/models/workout_progress.freezed.dart
Normal file
@@ -0,0 +1,570 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'workout_progress.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// dart format off
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$WorkoutProgress {
|
||||
|
||||
int get dayId; int get iteration; String get currentPageKey; DateTime get workoutStart; DateTime get validUntil; Map<String, StoredPageProgress> get pages;
|
||||
/// Create a copy of WorkoutProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$WorkoutProgressCopyWith<WorkoutProgress> get copyWith => _$WorkoutProgressCopyWithImpl<WorkoutProgress>(this as WorkoutProgress, _$identity);
|
||||
|
||||
/// Serializes this WorkoutProgress to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as WorkoutProgress;
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is WorkoutProgress&&(identical(other.dayId, _this.dayId) || other.dayId == _this.dayId)&&(identical(other.iteration, _this.iteration) || other.iteration == _this.iteration)&&(identical(other.currentPageKey, _this.currentPageKey) || other.currentPageKey == _this.currentPageKey)&&(identical(other.workoutStart, _this.workoutStart) || other.workoutStart == _this.workoutStart)&&(identical(other.validUntil, _this.validUntil) || other.validUntil == _this.validUntil)&&const DeepCollectionEquality().equals(other.pages, _this.pages));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as WorkoutProgress;
|
||||
return Object.hash(runtimeType,_this.dayId,_this.iteration,_this.currentPageKey,_this.workoutStart,_this.validUntil,const DeepCollectionEquality().hash(_this.pages));
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as WorkoutProgress;
|
||||
return 'WorkoutProgress(dayId: ${_this.dayId}, iteration: ${_this.iteration}, currentPageKey: ${_this.currentPageKey}, workoutStart: ${_this.workoutStart}, validUntil: ${_this.validUntil}, pages: ${_this.pages})';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $WorkoutProgressCopyWith<$Res> {
|
||||
factory $WorkoutProgressCopyWith(WorkoutProgress value, $Res Function(WorkoutProgress) _then) = _$WorkoutProgressCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> pages
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$WorkoutProgressCopyWithImpl<$Res>
|
||||
implements $WorkoutProgressCopyWith<$Res> {
|
||||
_$WorkoutProgressCopyWithImpl(this._self, this._then);
|
||||
|
||||
final WorkoutProgress _self;
|
||||
final $Res Function(WorkoutProgress) _then;
|
||||
|
||||
/// Create a copy of WorkoutProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? dayId = null,Object? iteration = null,Object? currentPageKey = null,Object? workoutStart = null,Object? validUntil = null,Object? pages = null,}) {
|
||||
return _then(WorkoutProgress(
|
||||
dayId: null == dayId ? _self.dayId : dayId // ignore: cast_nullable_to_non_nullable
|
||||
as int,iteration: null == iteration ? _self.iteration : iteration // ignore: cast_nullable_to_non_nullable
|
||||
as int,currentPageKey: null == currentPageKey ? _self.currentPageKey : currentPageKey // ignore: cast_nullable_to_non_nullable
|
||||
as String,workoutStart: null == workoutStart ? _self.workoutStart : workoutStart // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,validUntil: null == validUntil ? _self.validUntil : validUntil // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,pages: null == pages ? _self.pages : pages // ignore: cast_nullable_to_non_nullable
|
||||
as Map<String, StoredPageProgress>,
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [WorkoutProgress].
|
||||
extension WorkoutProgressPatterns on WorkoutProgress {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _WorkoutProgress value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _WorkoutProgress value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress():
|
||||
return $default(_that);}
|
||||
}
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _WorkoutProgress value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> pages)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress() when $default != null:
|
||||
return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> pages) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress():
|
||||
return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> pages)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _WorkoutProgress() when $default != null:
|
||||
return $default(_that.dayId,_that.iteration,_that.currentPageKey,_that.workoutStart,_that.validUntil,_that.pages);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
|
||||
class _WorkoutProgress implements WorkoutProgress {
|
||||
const _WorkoutProgress({required this.dayId, required this.iteration, required this.currentPageKey, required this.workoutStart, required this.validUntil, Map<String, StoredPageProgress> pages = const {}}): _pages = pages;
|
||||
factory _WorkoutProgress.fromJson(Map<String, dynamic> json) => _$WorkoutProgressFromJson(json);
|
||||
|
||||
@override final int dayId;
|
||||
@override final int iteration;
|
||||
@override final String currentPageKey;
|
||||
@override final DateTime workoutStart;
|
||||
@override final DateTime validUntil;
|
||||
final Map<String, StoredPageProgress> _pages;
|
||||
@override@JsonKey() Map<String, StoredPageProgress> get pages {
|
||||
if (_pages is EqualUnmodifiableMapView) return _pages;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableMapView(_pages);
|
||||
}
|
||||
|
||||
|
||||
/// Create a copy of WorkoutProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$WorkoutProgressCopyWith<_WorkoutProgress> get copyWith => __$WorkoutProgressCopyWithImpl<_WorkoutProgress>(this, _$identity);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$WorkoutProgressToJson(this, );
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _WorkoutProgress&&(identical(other.dayId, dayId) || other.dayId == dayId)&&(identical(other.iteration, iteration) || other.iteration == iteration)&&(identical(other.currentPageKey, currentPageKey) || other.currentPageKey == currentPageKey)&&(identical(other.workoutStart, workoutStart) || other.workoutStart == workoutStart)&&(identical(other.validUntil, validUntil) || other.validUntil == validUntil)&&const DeepCollectionEquality().equals(other.pages, _pages));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType,dayId,iteration,currentPageKey,workoutStart,validUntil,const DeepCollectionEquality().hash(_pages));
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'WorkoutProgress(dayId: $dayId, iteration: $iteration, currentPageKey: $currentPageKey, workoutStart: $workoutStart, validUntil: $validUntil, pages: $pages)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$WorkoutProgressCopyWith<$Res> implements $WorkoutProgressCopyWith<$Res> {
|
||||
factory _$WorkoutProgressCopyWith(_WorkoutProgress value, $Res Function(_WorkoutProgress) _then) = __$WorkoutProgressCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
int dayId, int iteration, String currentPageKey, DateTime workoutStart, DateTime validUntil, Map<String, StoredPageProgress> pages
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$WorkoutProgressCopyWithImpl<$Res>
|
||||
implements _$WorkoutProgressCopyWith<$Res> {
|
||||
__$WorkoutProgressCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _WorkoutProgress _self;
|
||||
final $Res Function(_WorkoutProgress) _then;
|
||||
|
||||
/// Create a copy of WorkoutProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? dayId = null,Object? iteration = null,Object? currentPageKey = null,Object? workoutStart = null,Object? validUntil = null,Object? pages = null,}) {
|
||||
return _then(_WorkoutProgress(
|
||||
dayId: null == dayId ? _self.dayId : dayId // ignore: cast_nullable_to_non_nullable
|
||||
as int,iteration: null == iteration ? _self.iteration : iteration // ignore: cast_nullable_to_non_nullable
|
||||
as int,currentPageKey: null == currentPageKey ? _self.currentPageKey : currentPageKey // ignore: cast_nullable_to_non_nullable
|
||||
as String,workoutStart: null == workoutStart ? _self.workoutStart : workoutStart // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,validUntil: null == validUntil ? _self.validUntil : validUntil // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,pages: null == pages ? _self._pages : pages // ignore: cast_nullable_to_non_nullable
|
||||
as Map<String, StoredPageProgress>,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// @nodoc
|
||||
mixin _$StoredPageProgress {
|
||||
|
||||
bool get done; String? get logId; DateTime? get timerStartedAt;
|
||||
/// Create a copy of StoredPageProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$StoredPageProgressCopyWith<StoredPageProgress> get copyWith => _$StoredPageProgressCopyWithImpl<StoredPageProgress>(this as StoredPageProgress, _$identity);
|
||||
|
||||
/// Serializes this StoredPageProgress to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as StoredPageProgress;
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is StoredPageProgress&&(identical(other.done, _this.done) || other.done == _this.done)&&(identical(other.logId, _this.logId) || other.logId == _this.logId)&&(identical(other.timerStartedAt, _this.timerStartedAt) || other.timerStartedAt == _this.timerStartedAt));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as StoredPageProgress;
|
||||
return Object.hash(runtimeType,_this.done,_this.logId,_this.timerStartedAt);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as StoredPageProgress;
|
||||
return 'StoredPageProgress(done: ${_this.done}, logId: ${_this.logId}, timerStartedAt: ${_this.timerStartedAt})';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $StoredPageProgressCopyWith<$Res> {
|
||||
factory $StoredPageProgressCopyWith(StoredPageProgress value, $Res Function(StoredPageProgress) _then) = _$StoredPageProgressCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
bool done, String? logId, DateTime? timerStartedAt
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$StoredPageProgressCopyWithImpl<$Res>
|
||||
implements $StoredPageProgressCopyWith<$Res> {
|
||||
_$StoredPageProgressCopyWithImpl(this._self, this._then);
|
||||
|
||||
final StoredPageProgress _self;
|
||||
final $Res Function(StoredPageProgress) _then;
|
||||
|
||||
/// Create a copy of StoredPageProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? done = null,Object? logId = freezed,Object? timerStartedAt = freezed,}) {
|
||||
return _then(StoredPageProgress(
|
||||
done: null == done ? _self.done : done // ignore: cast_nullable_to_non_nullable
|
||||
as bool,logId: freezed == logId ? _self.logId : logId // ignore: cast_nullable_to_non_nullable
|
||||
as String?,timerStartedAt: freezed == timerStartedAt ? _self.timerStartedAt : timerStartedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime?,
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [StoredPageProgress].
|
||||
extension StoredPageProgressPatterns on StoredPageProgress {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _StoredPageProgress value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _StoredPageProgress value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress():
|
||||
return $default(_that);}
|
||||
}
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _StoredPageProgress value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool done, String? logId, DateTime? timerStartedAt)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress() when $default != null:
|
||||
return $default(_that.done,_that.logId,_that.timerStartedAt);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool done, String? logId, DateTime? timerStartedAt) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress():
|
||||
return $default(_that.done,_that.logId,_that.timerStartedAt);}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool done, String? logId, DateTime? timerStartedAt)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _StoredPageProgress() when $default != null:
|
||||
return $default(_that.done,_that.logId,_that.timerStartedAt);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
|
||||
class _StoredPageProgress implements StoredPageProgress {
|
||||
const _StoredPageProgress({this.done = false, this.logId, this.timerStartedAt});
|
||||
factory _StoredPageProgress.fromJson(Map<String, dynamic> json) => _$StoredPageProgressFromJson(json);
|
||||
|
||||
@override@JsonKey() final bool done;
|
||||
@override final String? logId;
|
||||
@override final DateTime? timerStartedAt;
|
||||
|
||||
/// Create a copy of StoredPageProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$StoredPageProgressCopyWith<_StoredPageProgress> get copyWith => __$StoredPageProgressCopyWithImpl<_StoredPageProgress>(this, _$identity);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$StoredPageProgressToJson(this, );
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _StoredPageProgress&&(identical(other.done, done) || other.done == done)&&(identical(other.logId, logId) || other.logId == logId)&&(identical(other.timerStartedAt, timerStartedAt) || other.timerStartedAt == timerStartedAt));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType,done,logId,timerStartedAt);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'StoredPageProgress(done: $done, logId: $logId, timerStartedAt: $timerStartedAt)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$StoredPageProgressCopyWith<$Res> implements $StoredPageProgressCopyWith<$Res> {
|
||||
factory _$StoredPageProgressCopyWith(_StoredPageProgress value, $Res Function(_StoredPageProgress) _then) = __$StoredPageProgressCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
bool done, String? logId, DateTime? timerStartedAt
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$StoredPageProgressCopyWithImpl<$Res>
|
||||
implements _$StoredPageProgressCopyWith<$Res> {
|
||||
__$StoredPageProgressCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _StoredPageProgress _self;
|
||||
final $Res Function(_StoredPageProgress) _then;
|
||||
|
||||
/// Create a copy of StoredPageProgress
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? done = null,Object? logId = freezed,Object? timerStartedAt = freezed,}) {
|
||||
return _then(_StoredPageProgress(
|
||||
done: null == done ? _self.done : done // ignore: cast_nullable_to_non_nullable
|
||||
as bool,logId: freezed == logId ? _self.logId : logId // ignore: cast_nullable_to_non_nullable
|
||||
as String?,timerStartedAt: freezed == timerStartedAt ? _self.timerStartedAt : timerStartedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime?,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
46
lib/features/routines/models/workout_progress.g.dart
Normal file
46
lib/features/routines/models/workout_progress.g.dart
Normal file
@@ -0,0 +1,46 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'workout_progress.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_WorkoutProgress _$WorkoutProgressFromJson(Map<String, dynamic> json) => _WorkoutProgress(
|
||||
dayId: (json['dayId'] as num).toInt(),
|
||||
iteration: (json['iteration'] as num).toInt(),
|
||||
currentPageKey: json['currentPageKey'] as String,
|
||||
workoutStart: DateTime.parse(json['workoutStart'] as String),
|
||||
validUntil: DateTime.parse(json['validUntil'] as String),
|
||||
pages:
|
||||
(json['pages'] as Map<String, dynamic>?)?.map(
|
||||
(k, e) => MapEntry(
|
||||
k,
|
||||
StoredPageProgress.fromJson(e as Map<String, dynamic>),
|
||||
),
|
||||
) ??
|
||||
const {},
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$WorkoutProgressToJson(_WorkoutProgress instance) => <String, dynamic>{
|
||||
'dayId': instance.dayId,
|
||||
'iteration': instance.iteration,
|
||||
'currentPageKey': instance.currentPageKey,
|
||||
'workoutStart': instance.workoutStart.toIso8601String(),
|
||||
'validUntil': instance.validUntil.toIso8601String(),
|
||||
'pages': instance.pages,
|
||||
};
|
||||
|
||||
_StoredPageProgress _$StoredPageProgressFromJson(Map<String, dynamic> json) => _StoredPageProgress(
|
||||
done: json['done'] as bool? ?? false,
|
||||
logId: json['logId'] as String?,
|
||||
timerStartedAt: json['timerStartedAt'] == null
|
||||
? null
|
||||
: DateTime.parse(json['timerStartedAt'] as String),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$StoredPageProgressToJson(_StoredPageProgress instance) => <String, dynamic>{
|
||||
'done': instance.done,
|
||||
'logId': instance.logId,
|
||||
'timerStartedAt': instance.timerStartedAt?.toIso8601String(),
|
||||
};
|
||||
@@ -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<Object?> get props => [routineId, dayId, iteration, workoutStart, logSlotUuid, restSlotUuid];
|
||||
List<Object?> 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),
|
||||
),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ final class GymLogNotifierProvider extends $NotifierProvider<GymLogNotifier, Log
|
||||
}
|
||||
}
|
||||
|
||||
String _$gymLogNotifierHash() => r'f19f65118fc2746149178debd2f5fcb1cdfcab3c';
|
||||
String _$gymLogNotifierHash() => r'd50243d3e4a87c02812e15b3c5bb207a8ef2d1b6';
|
||||
|
||||
abstract class _$GymLogNotifier extends $Notifier<Log?> {
|
||||
Log? build();
|
||||
|
||||
@@ -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<SlotPageEntry>? 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<String, PageProgress> progress;
|
||||
|
||||
/// Exercises added during the workout, in the order they were added
|
||||
final List<AddedExercise> 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<PageEntry>? 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<String, PageProgress>? progress,
|
||||
List<AddedExercise>? 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<void> _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<void> _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<int> 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<int?> _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<String, dynamic>);
|
||||
} 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 = <String?, Log>{};
|
||||
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<PageEntry> 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 = <int, int>{};
|
||||
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 = <SlotPageEntry>[];
|
||||
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 = <PageEntry>[];
|
||||
|
||||
for (final page in state.pages) {
|
||||
final slotPageIndex = pageIndex;
|
||||
var setIndex = 0;
|
||||
final updatedSlotPages = <SlotPageEntry>[];
|
||||
|
||||
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<String> 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<void> startNewEntry() async {
|
||||
// Ensure that there is a log entry for the current slot entry
|
||||
final slotEntryPage = state.getSlotEntryPageByIndex();
|
||||
if (slotEntryPage == null || slotEntryPage.setConfigData == null) {
|
||||
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<void> 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<bool> logPlannedSet(String slotPageUuid, {Log? valuesFrom}) async {
|
||||
final target = state.getSlotPageByUUID(slotPageUuid);
|
||||
if (target == null || target.type != SlotPageType.log || target.logDone) {
|
||||
Future<bool> 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<PageEntry> pages = [];
|
||||
for (final page in state.pages) {
|
||||
pages.add(page);
|
||||
|
||||
if (page.uuid == pageEntryUUID) {
|
||||
final setConfigData = page.slotPages.first.setConfigData!;
|
||||
|
||||
final List<SlotPageEntry> 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider<GymStateNotifier,
|
||||
}
|
||||
}
|
||||
|
||||
String _$gymStateNotifierHash() => r'be5943c4201793dc053ef44a4a243226e6d38526';
|
||||
String _$gymStateNotifierHash() => r'c03c5ee5ca6f1db5d63193e15744589f12486ea4';
|
||||
|
||||
abstract class _$GymStateNotifier extends $Notifier<GymModeState> {
|
||||
GymModeState build();
|
||||
|
||||
@@ -34,8 +34,8 @@ final workoutLogRepositoryProvider = Provider<WorkoutLogRepository>((ref) {
|
||||
});
|
||||
|
||||
/// Local access to the `workout_log` table: writes (add/update/delete) plus a
|
||||
/// per-exercise read stream. Reading logs grouped under their parent session
|
||||
/// happens through `WorkoutSessionRepository.watchAllDrift`.
|
||||
/// per-exercise read stream and a lookup by ID. Reading logs grouped under
|
||||
/// their parent session happens through `WorkoutSessionRepository.watchAllDrift`.
|
||||
class WorkoutLogRepository {
|
||||
final _logger = Logger('WorkoutLogRepository');
|
||||
final DriftPowersyncDatabase _db;
|
||||
@@ -58,16 +58,7 @@ class WorkoutLogRepository {
|
||||
'routine ${routineId ?? 'any'}, since ${since ?? 'always'}',
|
||||
);
|
||||
|
||||
final query = _db.select(_db.workoutLogTable).join([
|
||||
leftOuterJoin(
|
||||
_db.routineRepetitionUnitTable,
|
||||
_db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId),
|
||||
),
|
||||
leftOuterJoin(
|
||||
_db.routineWeightUnitTable,
|
||||
_db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId),
|
||||
),
|
||||
]);
|
||||
final query = _selectWithUnits();
|
||||
|
||||
var whereCondition = _db.workoutLogTable.exerciseId.equals(exerciseId);
|
||||
if (routineId != null) {
|
||||
@@ -81,20 +72,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<Log?> getLatestLogByExercise(int exerciseId) async {
|
||||
final query = _selectWithUnits()
|
||||
..where(_db.workoutLogTable.exerciseId.equals(exerciseId))
|
||||
..orderBy([OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc)])
|
||||
..limit(1);
|
||||
final row = await query.getSingleOrNull();
|
||||
return row == null ? null : _readWithUnits(row);
|
||||
}
|
||||
|
||||
/// The logs with one of the [ids] that exist locally, with their units
|
||||
Future<List<Log>> getLogsByIds(List<String> ids) async {
|
||||
final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids));
|
||||
return (await query.get()).map(_readWithUnits).toList();
|
||||
}
|
||||
|
||||
JoinedSelectStatement<HasResultSet, dynamic> _selectWithUnits() {
|
||||
return _db.select(_db.workoutLogTable).join([
|
||||
leftOuterJoin(
|
||||
_db.routineRepetitionUnitTable,
|
||||
_db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId),
|
||||
),
|
||||
leftOuterJoin(
|
||||
_db.routineWeightUnitTable,
|
||||
_db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
Log _readWithUnits(TypedResult row) {
|
||||
final log = row.readTable(_db.workoutLogTable);
|
||||
final repetitionUnit = row.readTableOrNull(_db.routineRepetitionUnitTable);
|
||||
if (repetitionUnit != null) {
|
||||
log.repetitionUnit = repetitionUnit;
|
||||
}
|
||||
final weightUnit = row.readTableOrNull(_db.routineWeightUnitTable);
|
||||
if (weightUnit != null) {
|
||||
log.weightUnit = weightUnit;
|
||||
}
|
||||
return log;
|
||||
}
|
||||
|
||||
Future<void> deleteLocalDrift(String id) async {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -109,14 +109,9 @@ class _GymModeState extends ConsumerState<GymMode> {
|
||||
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<GymMode> {
|
||||
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),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<LogFormWidget> {
|
||||
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<LogFormWidget> {
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -238,6 +238,13 @@ class _GymModeOptionsState extends ConsumerState<GymModeOptions> {
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
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<TimerWidget> {
|
||||
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<TimerWidget> {
|
||||
|
||||
@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<TimerWidget> {
|
||||
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<TimerWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<TimerCountdownWidget> {
|
||||
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<TimerCountdownWidget> {
|
||||
@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<TimerCountdownWidget> {
|
||||
).textTheme.displayLarge!.copyWith(color: Theme.of(context).colorScheme.primary),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
UpNextWidget(widget.slotKey),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -189,3 +218,61 @@ class _TimerCountdownWidgetState extends ConsumerState<TimerCountdownWidget> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<ProgressionTab> {
|
||||
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<ProgressionTab> {
|
||||
}
|
||||
|
||||
// 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<ProgressionTab> {
|
||||
: 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<ProgressionTab> {
|
||||
//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<ProgressionTab> {
|
||||
),
|
||||
],
|
||||
),
|
||||
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<ProgressionTab> {
|
||||
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),
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>(
|
||||
this,
|
||||
Invocation.getter(#upNext),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get gymModeStickySetValues =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#gymModeStickySetValues),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#gymModeStickySetValues),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get gymModeStickySetValuesHelp =>
|
||||
(super.noSuchMethod(
|
||||
Invocation.getter(#gymModeStickySetValuesHelp),
|
||||
returnValue: _i3.dummyValue<String>(
|
||||
this,
|
||||
Invocation.getter(#gymModeStickySetValuesHelp),
|
||||
),
|
||||
)
|
||||
as String);
|
||||
|
||||
@override
|
||||
String get jumpTo =>
|
||||
(super.noSuchMethod(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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', () {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<SparkBarChart>(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<SparkBarChart>(find.byType(SparkBarChart));
|
||||
expect(chart.data.slotCount, 7);
|
||||
|
||||
await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastMonth));
|
||||
await tester.pumpAndSettle();
|
||||
chart = tester.widget<SparkBarChart>(find.byType(SparkBarChart));
|
||||
expect(chart.data.slotCount, 31);
|
||||
await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.lastMonth));
|
||||
await tester.pumpAndSettle();
|
||||
chart = tester.widget<SparkBarChart>(find.byType(SparkBarChart));
|
||||
expect(chart.data.slotCount, 31);
|
||||
|
||||
await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.last3Months));
|
||||
await tester.pumpAndSettle();
|
||||
chart = tester.widget<SparkBarChart>(find.byType(SparkBarChart));
|
||||
expect(chart.data.slotCount, 13);
|
||||
await tester.pumpWidget(_wrap(steps, entries: entries, range: ChartRange.last3Months));
|
||||
await tester.pumpAndSettle();
|
||||
chart = tester.widget<SparkBarChart>(find.byType(SparkBarChart));
|
||||
expect(chart.data.slotCount, 13);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('blood pressure tile: the reading quoted high over low', (tester) async {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user