Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Add auto progression, deload weeks, exercise alternatives and muscle tuning (#309)
InlitXefe99544f162
diff --git a/lib/models/live_session.dart b/lib/models/live_session.dartindex ad51d65..9e47eff 100644--- a/lib/models/live_session.dart+++ b/lib/models/live_session.dart@@ -80,6 +80,7 @@ class WorkoutSession {int currentIndex = 0;bool complete = false;bool manual = false;+ bool deload = false;String? routineId;String? name;DateTime? loggedAt;@@ -108,6 +109,7 @@ class WorkoutSession {'i': currentIndex,'c': complete,if (manual) 'm': true,+ if (deload) 'dl': true,if (routineId != null) 'r': routineId,if (name != null) 'n': name,'at': loggedAt?.toIso8601String(),@@ -124,6 +126,7 @@ class WorkoutSession {..currentIndex = (j['i'] as num?)?.toInt() ?? 0..complete = j['c'] as bool? ?? false..manual = j['m'] as bool? ?? false+ ..deload = j['dl'] as bool? ?? false..routineId = j['r'] as String?..name = j['n'] as String?..loggedAt = DateTime.tryParse((j['at'] as String?) ?? '')diff --git a/lib/models/workout.dart b/lib/models/workout.dartindex 5e66fc4..5c28d0c 100644--- a/lib/models/workout.dart+++ b/lib/models/workout.dart@@ -112,7 +112,7 @@ class LoggedExercise {}class LoggedSession {- LoggedSession(this.date, this.durationSec, this.exercises, {this.routineId, this.name, this.hrAvg, this.hrMax, this.sleep, this.energy});+ LoggedSession(this.date, this.durationSec, this.exercises, {this.routineId, this.name, this.hrAvg, this.hrMax, this.sleep, this.energy, this.deload = false});final DateTime date;int durationSec;final List<LoggedExercise> exercises;@@ -122,6 +122,7 @@ class LoggedSession {int? hrMax;int? sleep;int? energy;+ final bool deload;DateTime get day => date.subtract(Duration(seconds: durationSec));double get volume => exercises.fold(0.0, (s, e) => s + e.volume);@@ -137,6 +138,7 @@ class LoggedSession {if (hrMax != null) 'hrm': hrMax,if (sleep != null) 'sl': sleep,if (energy != null) 'en': energy,+ if (deload) 'dl': true,};factory LoggedSession.fromJson(Map<String, dynamic> j) => LoggedSession(DateTime.parse(j['d'] as String),@@ -148,6 +150,7 @@ class LoggedSession {hrMax: (j['hrm'] as num?)?.toInt(),sleep: (j['sl'] as num?)?.toInt().clamp(1, 5),energy: (j['en'] as num?)?.toInt().clamp(1, 5),+ deload: j['dl'] == true,);}@@ -249,6 +252,7 @@ class Routine {Map<String, List<PlannedSet>>? plan,Map<String, int>? rest,List<List<String>>? ladders,+ Map<String, List<String>>? alts,this.group = '',this.color = -1,this.archived = false})@@ -256,7 +260,8 @@ class Routine {chained = chained ?? {},plan = plan ?? {},rest = rest ?? {},- ladders = ladders ?? [];+ ladders = ladders ?? [],+ alts = alts ?? {};final String id;String name;String group;@@ -268,11 +273,13 @@ class Routine {final Map<String, List<PlannedSet>> plan;final Map<String, int> rest;final List<List<String>> ladders;+ final Map<String, List<String>> alts;Map<String, dynamic> toJson() => {'id': id,'n': name,if (ladders.isNotEmpty) 'lad': ladders,+ if (alts.isNotEmpty) 'alt': alts,'ex': exerciseIds,if (rest.isNotEmpty) 'r': rest,if (sets.isNotEmpty) 's': sets,@@ -300,8 +307,62 @@ class Routine {for (final l in (j['lad'] as List?) ?? const [])if (l is List && l.length > 1) l.cast<String>().toList(),],+ alts: {+ for (final e in ((j['alt'] as Map?) ?? const {}).entries)+ if (e.value is List && (e.value as List).isNotEmpty) e.key as String: (e.value as List).cast<String>().toList(),+ },group: (j['g'] as String?) ?? '',color: (j['k'] as num?)?.toInt() ?? -1,archived: j['a'] == true,);}++class MonthRecap {+ const MonthRecap({+ required this.month,+ required this.workouts,+ required this.days,+ required this.seconds,+ required this.longest,+ required this.sets,+ required this.volumeKg,+ required this.topExercise,+ required this.topExerciseKg,+ required this.heat,+ required this.topMuscle,+ required this.topMuscleSets,+ required this.records,+ required this.favDay,+ required this.usualStart,+ required this.weekdays,+ required this.lift,+ required this.sessionMinutes,+ required this.topLifts,+ required this.exerciseIds,+ });++ final DateTime month;+ final int workouts;+ final Set<int> days;+ final int seconds;+ final LoggedSession? longest;+ final int sets;+ final double volumeKg;+ final String? topExercise;+ final double topExerciseKg;+ final Map<String, double> heat;+ final String? topMuscle;+ final int topMuscleSets;+ final List<({String id, double kg})> records;+ final int? favDay;+ final int? usualStart;+ final List<int> weekdays;+ final ({String id, int sets, int times, double bestKg, double volumeKg})? lift;+ final List<int> sessionMinutes;+ final List<({String id, int sets})> topLifts;+ final List<String> exerciseIds;++ int get avgMinutes => workouts == 0 ? 0 : seconds ~/ 60 ~/ workouts;++ bool get empty => workouts == 0;+}diff --git a/lib/screens/exercise_detail_screen.dart b/lib/screens/exercise_detail_screen.dartindex b835eec..8367510 100644--- a/lib/screens/exercise_detail_screen.dart+++ b/lib/screens/exercise_detail_screen.dart@@ -211,15 +211,28 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {children: [_cardLabel(gc, t.personalRecord),const SizedBox(height: 8),- Text(fit.recordLabel(pr),- style: AppTheme.f(30,- weight: FontWeight.w800, color: gc.text, height: 1)),+ FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerStart,+ child: Text(fit.recordLabel(pr),+ maxLines: 1,+ style: AppTheme.f(30,+ weight: FontWeight.w800, color: gc.text, height: 1)),+ ),],),),- Text(fit.recordDetail(pr),- style: AppTheme.f(12,- weight: FontWeight.w500, color: gc.textSecondary)),+ const SizedBox(width: 10),+ Flexible(+ child: FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerEnd,+ child: Text(fit.recordDetail(pr),+ maxLines: 1,+ style: AppTheme.f(12,+ weight: FontWeight.w500, color: gc.textSecondary)),+ ),+ ),],),if (history.length > 1) _bests(gc, ex.id, pr.kind),@@ -391,7 +404,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {),const SizedBox(height: 4),Padding(- padding: const EdgeInsets.only(left: 26),+ padding: const EdgeInsetsDirectional.only(start: 26),child: Text(t.notHereWhy, style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),),const SizedBox(height: 14),@@ -865,7 +878,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {if (i < rows.length - 1)Container(height: 1,- margin: const EdgeInsets.only(left: 16),+ margin: const EdgeInsetsDirectional.only(start: 16),color: gc.border.withValues(alpha: 0.55),),],@@ -907,7 +920,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {}Widget _stackRow(BuildContext context, GymColors gc, String id) {- final stack = fit.stackFor(id);+ final stack = fit.ownStackFor(id);return GestureDetector(behavior: HitTestBehavior.opaque,onTap: () => showWeightStackSheet(context, id),@@ -1057,7 +1070,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {}Widget _rowIcon(GymColors gc, IconData icon, bool on) => Padding(- padding: const EdgeInsets.only(right: 14),+ padding: const EdgeInsetsDirectional.only(end: 14),child: SizedBox(width: 22,child: Icon(icon, size: 19, color: on ? gc.text : gc.textSecondary),@@ -1352,7 +1365,7 @@ class _ExerciseDetailScreenState extends State<ExerciseDetailScreen> {child: Row(children: [Padding(- padding: const EdgeInsets.only(right: 14),+ padding: const EdgeInsetsDirectional.only(end: 14),child: SizedBox(width: 22,child: SvgPathIcon(Ic.trendUp, size: 19, color: on ? gc.text : gc.textSecondary),diff --git a/lib/screens/progress_screen.dart b/lib/screens/progress_screen.dartindex 4cefa6c..6e3fd6a 100644--- a/lib/screens/progress_screen.dart+++ b/lib/screens/progress_screen.dart@@ -282,7 +282,7 @@ class ProgressScreen extends StatelessWidget {Container(width: 9,height: 9,- margin: const EdgeInsets.only(left: 3),+ margin: const EdgeInsetsDirectional.only(start: 3),decoration:BoxDecoration(color: c, borderRadius: BorderRadius.circular(3)),),@@ -312,11 +312,24 @@ class ProgressScreen extends StatelessWidget {Row(children: [Icon(PhosphorIconsFill.fire, size: 14, color: gc.accent),const SizedBox(width: 7),- Text(t.streakDays(fit.currentStreak),- style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.text)),+ Flexible(+ child: FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerStart,+ child: Text(t.streakDays(fit.currentStreak),+ maxLines: 1, style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.text)),+ ),+ ),+ const SizedBox(width: 12),const Spacer(),- Text(t.weekOfGoal(fit.daysDoneThisWeek, fit.weeklyTarget),- style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary)),+ Flexible(+ child: FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerEnd,+ child: Text(t.weekOfGoal(fit.daysDoneThisWeek, fit.weeklyTarget),+ maxLines: 1, style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary)),+ ),+ ),]),],),@@ -327,11 +340,11 @@ class ProgressScreen extends StatelessWidget {final hours = fit.totalTime.inHours;final lifted = fit.liftedSpanOf(fit.totalVolumeKg);final cells = <(String, String, String)>[- (t.allTimeSessions, '${fit.totalSessions}', ''),- (t.allTimeSets, '${fit.totalSets}', ''),+ (t.allTimeSessions, groupedInt(fit.totalSessions), ''),+ (t.allTimeSets, groupedInt(fit.totalSets), ''),(t.allTimeTime,- hours >= 1 ? '$hours' : '${fit.totalTime.inMinutes}',+ hours >= 1 ? groupedInt(hours) : '${fit.totalTime.inMinutes}',hours >= 1 ? t.unitHours : 'min'),(t.allTimeLifted, lifted.$1, lifted.$2),@@ -424,11 +437,47 @@ class ProgressScreen extends StatelessWidget {],],),+ for (final (i, note) in fit.weekInsights.indexed) ...[+ SizedBox(height: i == 0 ? 18 : 10),+ _insight(gc, note),+ ],],),);}+ Widget _insight(GymColors gc, ({String kind, String text, String? exerciseId}) note) {+ final id = note.exerciseId;+ final row = Row(children: [+ Container(+ width: 30,+ height: 30,+ decoration: BoxDecoration(color: gc.text.withValues(alpha: 0.07), shape: BoxShape.circle),+ child: Icon(+ switch (note.kind) {+ 'load' => PhosphorIconsRegular.gauge,+ 'muscle' => PhosphorIconsRegular.clockCounterClockwise,+ 'balance' => PhosphorIconsRegular.scales,+ _ => PhosphorIconsRegular.trendUp,+ },+ size: 15,+ color: note.kind == 'up' ? gc.sage : gc.textSecondary,+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Text(note.text,+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.text, height: 1.35)),+ ),+ if (id != null) ...[+ const SizedBox(width: 8),+ Icon(PhosphorIconsBold.caretRight, size: 12, color: gc.textTertiary),+ ],+ ]);+ if (id == null) return row;+ return GestureDetector(behavior: HitTestBehavior.opaque, onTap: () => fit.openExercise(id), child: row);+ }+List<({String label, bool done, String route})> _steps() => [(label: t.setupWorkout, done: fit.sessions.isNotEmpty, route: 'train'),(label: t.setupWeight, done: fit.bodyweight.isNotEmpty, route: 'weight'),@@ -2023,8 +2072,13 @@ class _PrCardState extends State<_PrCard> {overflow: TextOverflow.ellipsis,style: AppTheme.s(14, weight: FontWeight.w600, color: gc.text, height: 1.25)),const SizedBox(height: 3),- Text(fit.recordDetail(pr),- style: AppTheme.s(11.5, weight: FontWeight.w500, color: gc.textTertiary)),+ FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerStart,+ child: Text(fit.recordDetail(pr),+ maxLines: 1,+ style: AppTheme.s(11.5, weight: FontWeight.w500, color: gc.textTertiary)),+ ),],),),@@ -2838,7 +2892,7 @@ class _HeatToneSheetState extends State<_HeatToneSheet> {Container(width: 20,height: 20,- margin: const EdgeInsets.only(right: 6),+ margin: const EdgeInsetsDirectional.only(end: 6),decoration: BoxDecoration(color: c, borderRadius: BorderRadius.circular(6)),),const SizedBox(width: 8),diff --git a/lib/screens/routine_edit_screen.dart b/lib/screens/routine_edit_screen.dartindex 2982e2e..e56ae13 100644--- a/lib/screens/routine_edit_screen.dart+++ b/lib/screens/routine_edit_screen.dart@@ -314,7 +314,7 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {}Widget _label(GymColors gc, String text) => Padding(- padding: const EdgeInsets.only(left: 4),+ padding: const EdgeInsetsDirectional.only(start: 4),child: Text(text.toUpperCase(),style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),);@@ -351,7 +351,7 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {Widget _filterChips(GymColors gc) {Widget chip(String label, bool active, VoidCallback onTap) => Padding(- padding: const EdgeInsets.only(right: 8),+ padding: const EdgeInsetsDirectional.only(end: 8),child: Pill(label: label,bg: active ? gc.ember : gc.bgRaised2,@@ -575,7 +575,7 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {background: Container(margin: EdgeInsets.only(bottom: linksNext ? 4 : 0),alignment: Alignment.centerRight,- padding: const EdgeInsets.only(right: 22),+ padding: const EdgeInsetsDirectional.only(end: 22),decoration: BoxDecoration(color: gc.warn.withValues(alpha: 0.16), borderRadius: BorderRadius.circular(18)),child: Icon(PhosphorIconsFill.trash, size: 20, color: gc.warn),),@@ -883,6 +883,8 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {),const SizedBox(height: 10),_restRow(sheet, gc, routine, ex),+ const SizedBox(height: 8),+ _altsRow(sheet, gc, routine, ex),if (fit.modeOf(ex.id).isEmpty) ...[const SizedBox(height: 8),_ladderRow(sheet, gc, routine, ex),@@ -898,6 +900,74 @@ class _RoutineEditScreenState extends State<RoutineEditScreen> {);}+ Widget _altsRow(BuildContext sheet, GymColors gc, Routine routine, Exercise ex) {+ final alts = [for (final id in fit.routineAlts(routine.id, ex.id)) ?fit.exerciseById(id)];+ return Pressable(+ scale: 0.98,+ onTap: () => _pickAlts(sheet, routine.id, ex),+ child: Container(+ padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(18)),+ child: Row(children: [+ Icon(PhosphorIconsRegular.arrowsLeftRight, size: 19, color: alts.isNotEmpty ? gc.text : gc.textSecondary),+ const SizedBox(width: 12),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(t.altsTitle, style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),+ const SizedBox(height: 3),+ Text(alts.isEmpty ? t.altsHint : alts.map(exerciseName).join(' · '),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),+ ]),+ ),+ const SizedBox(width: 8),+ Icon(PhosphorIconsBold.caretRight, size: 13, color: gc.textTertiary),+ ]),+ ),+ );+ }++ void _pickAlts(BuildContext context, String routineId, Exercise ex) {+ showAppSheet<void>(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (sheet) => AnimatedBuilder(+ animation: fit,+ builder: (sheet, _) {+ final routine = fit.routines.where((r) => r.id == routineId).firstOrNull;+ if (routine == null) return const SizedBox.shrink();+ final chosen = fit.routineAlts(routineId, ex.id);+ final pool = [+ for (final id in chosen) ?fit.exerciseById(id),+ for (final e in fit.swapOptions(ex.id, n: 18))+ if (!chosen.contains(e.id) && !routine.exerciseIds.contains(e.id)) e,+ ];+ return AppSheet(children: [+ SheetTitle(t.altsTitle, subtitle: t.altsPickHint(RoutinesState.maxAlts)),+ const SizedBox(height: 16),+ OptionGroup([+ for (final e in pool)+ OptionItem(+ exerciseName(e),+ leading: SizedBox(width: 38, child: ExerciseMedia(ex: e, height: 38, radius: 10)),+ detail: t.equipment(e.equipment),+ selected: chosen.contains(e.id),+ onTap: () {+ HapticFeedback.selectionClick();+ fit.toggleRoutineAlt(routineId, ex.id, e.id);+ },+ ),+ ]),+ const SizedBox(height: 16),+ PrimaryButton(label: t.done, onTap: () => Navigator.of(sheet).pop()),+ ]);+ },+ ),+ );+ }+Widget _ladderRow(BuildContext sheet, GymColors gc, Routine routine, Exercise ex) {final own = fit.ladderIn(routine, ex.id);final next = fit.nextStepIn(routine, ex.id);diff --git a/lib/screens/session_screen.dart b/lib/screens/session_screen.dartindex 64ab999..c29a419 100644--- a/lib/screens/session_screen.dart+++ b/lib/screens/session_screen.dart@@ -50,6 +50,33 @@ class SessionScreen extends StatelessWidget {);}+ Widget _deloadNote(GymColors gc) => Container(+ padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(16)),+ child: Row(children: [+ Icon(PhosphorIconsRegular.feather, size: 17, color: gc.sage),+ const SizedBox(width: 10),+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(t.deloadNow,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(13.5, weight: FontWeight.w800, color: gc.text)),+ const SizedBox(height: 2),+ Text(t.deloadNowHint,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary, height: 1.3)),+ ]),+ ),+ if (fit.canSkipDeload)+ TextButton(+ onPressed: fit.skipDeload,+ child: Text(t.deloadSkip, style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.accent)),+ ),+ ]),+ );+Widget _active(BuildContext context, GymColors gc) {final s = fit.session!;final ex = fit.currentExercise;@@ -68,6 +95,10 @@ class SessionScreen extends StatelessWidget {const SizedBox(height: 14),_progressStrip(context, gc, s, locked),const SizedBox(height: 16),+ if (s.deload) ...[+ _deloadNote(gc),+ const SizedBox(height: 14),+ ],_ExerciseStage(index: exIdx,haptic: true,@@ -392,7 +423,7 @@ class SessionScreen extends StatelessWidget {),]),),- if (fit.workoutNotesFor(ex.id).isNotEmpty)+ if (WorkoutNoteStrip.offers(ex.id))Padding(padding: const EdgeInsets.fromLTRB(8, 10, 8, 0),child: _guard(locked, WorkoutNoteStrip(exerciseId: ex.id, onDark: true)),@@ -838,7 +869,7 @@ class SessionScreen extends StatelessWidget {),],]),- if (ex != null && fit.workoutNotesFor(ex.id).isNotEmpty) ...[+ if (ex != null && WorkoutNoteStrip.offers(ex.id)) ...[const SizedBox(height: 12),WorkoutNoteStrip(exerciseId: ex.id, onDark: true),],@@ -2063,6 +2094,10 @@ class SessionScreen extends StatelessWidget {const SizedBox(height: 10),Rise(index: 3, child: CheckInCard(fit.filedSession!)),],+ if (fit.tuneTargets.isNotEmpty) ...[+ const SizedBox(height: 10),+ Rise(index: 3, child: _TuneCard(fit.tuneTargets)),+ ],if (fit.sessionExtras.isNotEmpty || identical(_extrasFor, fit.session)) ...[const SizedBox(height: 10),const Rise(index: 3, child: _ExtrasCard()),@@ -2586,9 +2621,16 @@ void showSwapExerciseSheet(BuildContext context, int exIdx) {child: StatefulBuilder(builder: (sheetCtx, setSheet) {final q = search.text.trim();+ final alts = q.isEmpty ? fit.sessionAltsFor(exIdx) : const <Exercise>[];+ final skip = {for (final a in alts) a.id};final list = q.isEmpty- ? fit.swapOptions(from.id)+ ? fit.swapOptions(from.id).where((e) => !skip.contains(e.id)).toList(): fit.trainSearchResults(q).where((e) => !fit.inSession(e.id)).toList();+ Widget label(String text) => Padding(+ padding: const EdgeInsets.only(bottom: 10),+ child: Text(text.toUpperCase(),+ style: AppTheme.f(11, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.5)),+ );void pick(Exercise ex) {Navigator.pop(sheetCtx);fit.swapSessionExercise(exIdx, ex.id);@@ -2618,17 +2660,20 @@ void showSwapExerciseSheet(BuildContext context, int exIdx) {color: gc.bgRaised2,onChanged: (_) => setSheet(() {}),),- const SizedBox(height: 12),- Text(q.isEmpty ? t.swapSameMuscle(muscleLabel(from.primary)).toUpperCase() : t.results.toUpperCase(),- style: AppTheme.f(11, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.5)),],),),Flexible(child: ListView(- padding: const EdgeInsets.fromLTRB(20, 10, 20, 18),+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 18),shrinkWrap: true,children: [+ if (alts.isNotEmpty) ...[+ label(t.altsTitle),+ for (final ex in alts) _swapRow(sheetCtx, gc, ex, () => pick(ex)),+ const SizedBox(height: 12),+ ],+ label(q.isEmpty ? t.swapSameMuscle(muscleLabel(from.primary)) : t.results),if (list.isEmpty)Padding(padding: const EdgeInsets.symmetric(vertical: 18),@@ -3168,6 +3213,79 @@ class _CelebrateState extends State<_Celebrate> {Object? _extrasFor;+class _TuneCard extends StatelessWidget {+ const _TuneCard(this.targets);++ final List<({String muscle, String exId})> targets;++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ final routine = fit.sessionRoutine;+ if (routine == null) return const SizedBox.shrink();+ return SoftCard(+ radius: 22,+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 10),+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Text(t.tuneTitle.toUpperCase(),+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),+ const SizedBox(height: 4),+ Text(t.tuneHint,+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.35)),+ const SizedBox(height: 6),+ for (final m in targets) _row(gc, routine, m),+ ]),+ );+ }++ Widget _row(GymColors gc, Routine routine, ({String muscle, String exId}) m) {+ final vote = fit.muscleVote(m.muscle);+ final ex = fit.exerciseById(m.exId);+ final sets = fit.routineSets(routine, m.exId);+ void pick(int v) => fit.voteMuscle(m.muscle, vote == v ? null : v);+ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(children: [+ Expanded(+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(muscleLabel(m.muscle),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topLeft,+ child: vote == null || ex == null+ ? const SizedBox(width: double.infinity)+ : Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(vote == 0 ? t.tuneSame : t.tuneNext(t.setCount(sets), exerciseName(ex)),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(11.5,+ weight: FontWeight.w600, color: vote == 0 ? gc.textSecondary : gc.sage, height: 1.3)),+ ),+ ),+ ]),+ ),+ const SizedBox(width: 10),+ Flexible(+ child: FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerEnd,+ child: SegToggle([+ SegOption(t.tuneLess, vote == 1, () => pick(1)),+ SegOption(t.tuneRight, vote == 0, () => pick(0)),+ SegOption(t.tuneMore, vote == -1, () => pick(-1)),+ ], hPad: 10),+ ),+ ),+ ]),+ );+ }+}+class _ExtrasCard extends StatefulWidget {const _ExtrasCard();diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex 4d87dd4..a4b46b8 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -21,6 +21,7 @@ import '../services/auto_backup.dart';import '../services/backup_zip.dart';import '../services/fitnotes_backup.dart';import '../services/home_widget_bridge.dart';+import '../services/notif_sound.dart';import '../services/rest_alarm.dart';import '../services/sqlite_reader.dart';import '../services/workout_import.dart';@@ -33,23 +34,24 @@ import '../widgets/dialogs.dart';import '../widgets/entrance.dart';import '../widgets/file_thumb.dart';import '../widgets/glass.dart';+import '../widgets/health_cards.dart';+import '../widgets/home_cards_panel.dart';+import '../widgets/import_card.dart';import '../widgets/liquid_notch.dart';import '../widgets/photo_source_sheet.dart';-import '../widgets/widget_showcase.dart';-import '../widgets/home_cards_panel.dart';-import '../widgets/settings_showcase.dart';-import '../widgets/sheet_page.dart';import '../widgets/profile_avatar.dart';import '../widgets/report_sheet.dart';import '../widgets/ruler_picker.dart';-import '../widgets/timer_panel.dart';-import 'profile_screen.dart';-import 'strava_sheet.dart';-import '../widgets/health_cards.dart';+import '../widgets/settings_showcase.dart';+import '../widgets/sheet_page.dart';import '../widgets/steps_card.dart';import '../widgets/svg_icon.dart';-import '../widgets/import_card.dart';+import '../widgets/timer_panel.dart';import '../widgets/ui_kit.dart';+import '../widgets/voice_sheet.dart';+import '../widgets/widget_showcase.dart';+import 'profile_screen.dart';+import 'strava_sheet.dart';const _kRepoUrl = 'https://github.com/InlitX/GymMane';const _kBugUrl = '$_kRepoUrl/issues/new?labels=bug';@@ -166,9 +168,24 @@ class SettingsScreen extends StatelessWidget {GestureDetector(behavior: HitTestBehavior.opaque,- onTap: () => fit.setBlur(!fit.blurOn),- child: _prefRow(gc, PhosphorIconsRegular.drop, t.blurSetting, TinySwitch(on: fit.blurOn),- hint: t.blurSettingHint),+ onTap: () => _performanceSheet(context),+ child: _prefRow(+ gc,+ PhosphorIconsRegular.lightning,+ t.perfSetting,+ Row(mainAxisSize: MainAxisSize.min, children: [+ ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 128),+ child: Text(_perfName(fit.perfLevel),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.right,+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.textSecondary)),+ ),+ const SizedBox(width: 6),+ Icon(PhosphorIconsRegular.caretRight, size: 15, color: gc.textTertiary),+ ]),+ ),),_choiceRow(context,@@ -184,12 +201,6 @@ class SettingsScreen extends StatelessWidget {fit.setTextSize,hint: t.textSizeHint,),- GestureDetector(- behavior: HitTestBehavior.opaque,- onTap: () => fit.setCalmMotion(!fit.calmMotion),- child: _prefRow(gc, PhosphorIconsRegular.waveSine, t.calmMotionSetting, TinySwitch(on: fit.calmMotion),- hint: t.calmMotionHint),- ),]),const SizedBox(height: 22),const LookShowcase(),@@ -280,6 +291,37 @@ class SettingsScreen extends StatelessWidget {(v) => fit.setWeightStep(double.parse(v)),rowHint: t.weightStepHint,),+ _choiceRow(+ context,+ gc,+ PhosphorIconsRegular.trendUp,+ t.autoProgressSetting,+ [+ ('off', t.autoProgressOff, PhosphorIconsRegular.prohibit),+ ('weight', t.autoProgressWeight, PhosphorIconsRegular.barbell),+ ('reps', t.autoProgressReps, PhosphorIconsRegular.repeat),+ ],+ () => fit.autoProgress,+ fit.setAutoProgress,+ hint: t.autoProgressHint,+ rowHint: t.autoProgressRowHint,+ ),+ _choiceRow(+ context,+ gc,+ PhosphorIconsRegular.feather,+ t.deloadSetting,+ [+ ('0', t.deloadOff, PhosphorIconsRegular.prohibit),+ for (final w in [4, 5, 6, 8]) ('$w', t.deloadEvery(w), PhosphorIconsRegular.calendarBlank),+ ],+ () => '${fit.deloadEvery}',+ (v) => fit.setDeloadEvery(int.parse(v)),+ hint: t.deloadHint,+ rowHint: fit.deloadEvery == 0+ ? t.deloadRowHint+ : (fit.deloadWeek ? t.deloadNow : t.deloadIn(fit.weeksToDeload)),+ ),GestureDetector(behavior: HitTestBehavior.opaque,onTap: fit.toggleAutoAdvance,@@ -304,6 +346,23 @@ class SettingsScreen extends StatelessWidget {child: _prefRow(gc, PhosphorIconsRegular.moon, t.checkInSetting,TinySwitch(on: fit.askCheckIn), hint: t.checkInSettingHint),),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: fit.toggleMuscleTune,+ child: _prefRow(gc, PhosphorIconsRegular.equalizer, t.tuneSetting,+ TinySwitch(on: fit.muscleTune), hint: t.tuneSettingHint),+ ),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ fit.toggleVoiceCoach();+ if (fit.voiceCoach) showVoiceSheet(context);+ },+ child: _prefRow(gc, PhosphorIconsRegular.waveform, t.voiceSetting,+ TinySwitch(on: fit.voiceCoach),+ hint: t.voiceSettingHint,+ badge: BetaTag(t.sectionBeta, small: true)),+ ),]),_subhead(gc, t.routines),_card(gc, [@@ -404,6 +463,28 @@ class SettingsScreen extends StatelessWidget {hint: t.trainReminderRowHint,),),+ GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => showAppSheet<void>(+ context: context,+ backgroundColor: Colors.transparent,+ builder: (_) => const _NotifSoundSheet(),+ ),+ child: _prefRow(+ gc,+ PhosphorIconsRegular.musicNotes,+ t.notifSoundSetting,+ Row(mainAxisSize: MainAxisSize.min, children: [+ Text(+ NotifSound.uris.isEmpty ? t.notifSoundNormal : t.perfCustom,+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.textSecondary),+ ),+ const SizedBox(width: 6),+ Icon(PhosphorIconsRegular.caretRight, size: 15, color: gc.textTertiary),+ ]),+ hint: t.notifSoundRowHint,+ ),+ ),GestureDetector(behavior: HitTestBehavior.opaque,onTap: () => _editAlarmSound(context),@@ -476,8 +557,8 @@ class SettingsScreen extends StatelessWidget {PhosphorIconsRegular.heartbeat,t.healthSetting,Row(mainAxisSize: MainAxisSize.min, children: [- if (fit.healthShown.isNotEmpty)- Text('${fit.healthShown.length}',+ if (fit.healthShown.isNotEmpty || fit.stepsOn)+ Text('${fit.healthShown.length + (fit.stepsOn ? 1 : 0)}',style: AppTheme.f(13.5, weight: FontWeight.w700, color: gc.textSecondary)),const SizedBox(width: 6),Icon(PhosphorIconsBold.caretRight, size: 14, color: gc.textTertiary),@@ -650,19 +731,22 @@ class SettingsScreen extends StatelessWidget {(t.heatRangeSetting, PhosphorIconsRegular.calendarDots),(t.heatmapLabelsSetting, PhosphorIconsRegular.gridNine),(t.background, PhosphorIconsRegular.image),- (t.blurSetting, PhosphorIconsRegular.drop),+ (t.perfSetting, PhosphorIconsRegular.lightning),(t.textSizeSetting, PhosphorIconsRegular.textAa),- (t.calmMotionSetting, PhosphorIconsRegular.waveSine),]),_Category('training', PhosphorIconsRegular.barbell, _sectionTitle('training'), [(t.restTimer, PhosphorIconsRegular.timer),(t.miniRest, PhosphorIconsRegular.timer),(t.effortSetting, PhosphorIconsRegular.gauge),(t.weightStepSetting, PhosphorIconsRegular.barbell),+ (t.autoProgressSetting, PhosphorIconsRegular.trendUp),+ (t.deloadSetting, PhosphorIconsRegular.feather),+ (t.voiceSetting, PhosphorIconsRegular.waveform),(t.autoAdvance, PhosphorIconsRegular.skipForward),(t.countdownSetting, PhosphorIconsRegular.timer),(t.keepScreenOn, PhosphorIconsRegular.sun),(t.checkInSetting, PhosphorIconsRegular.moon),+ (t.tuneSetting, PhosphorIconsRegular.equalizer),(t.miniBodySetting, PhosphorIconsRegular.person),(t.multiPlanSetting, PhosphorIconsRegular.stack),(t.levelHintsSetting, PhosphorIconsRegular.stairs),@@ -673,6 +757,7 @@ class SettingsScreen extends StatelessWidget {]),_Category('alerts', PhosphorIconsRegular.bellSimple, _sectionTitle('alerts'), [(t.trainReminder, PhosphorIconsRegular.bellSimple),+ (t.notifSoundSetting, PhosphorIconsRegular.musicNotes),(t.alarmSound, PhosphorIconsRegular.speakerHigh),(t.alarmStyleTitle, PhosphorIconsRegular.vibrate),(t.toastSoundSetting, PhosphorIconsRegular.bellSimple),@@ -863,8 +948,82 @@ class SettingsScreen extends StatelessWidget {);}+ static String _perfName(String level) => switch (level) {+ 'lite' => t.perfLite,+ 'balanced' => t.perfBalanced,+ 'max' => t.perfMax,+ _ => t.perfCustom,+ };++ void _performanceSheet(BuildContext context) {+ fit.readDisplay();+ showAppSheet<void>(+ context: context,+ backgroundColor: Colors.transparent,+ isScrollControlled: true,+ builder: (sheet) => AnimatedBuilder(+ animation: fit,+ builder: (sheet, _) {+ final gc = sheet.gc;+ final level = fit.perfLevel;+ final hz = fit.maxRefresh.round();+ Widget toggle(IconData icon, String label, String hint, bool on, VoidCallback flip) => GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () {+ HapticFeedback.selectionClick();+ flip();+ },+ child: _prefRow(gc, icon, label, TinySwitch(on: on), hint: hint),+ );+ return AppSheet(children: [+ SheetTitle(t.perfSetting, subtitle: t.perfSheetHint),+ const SizedBox(height: 16),+ OptionGroup([+ for (final l in SettingsState.perfLevels)+ OptionItem(+ _perfName(l),+ icon: switch (l) {+ 'lite' => PhosphorIconsRegular.leaf,+ 'balanced' => PhosphorIconsRegular.scales,+ _ => PhosphorIconsRegular.lightning,+ },+ detail: switch (l) {+ 'lite' => t.perfLiteHint,+ 'balanced' => t.perfBalancedHint,+ _ => fit.canHighRefresh ? t.perfMaxHint(hz) : t.perfMaxHintNoHz,+ },+ selected: level == l,+ onTap: () {+ HapticFeedback.selectionClick();+ fit.setPerfLevel(l);+ },+ ),+ ]),+ _subhead(gc, t.perfTweak, top: 22),+ Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(22)),+ child: Column(children: [+ toggle(PhosphorIconsRegular.drop, t.blurSetting, t.blurSettingHint, fit.blurOn,+ () => fit.setBlur(!fit.blurOn)),+ if (fit.blurOn)+ toggle(PhosphorIconsRegular.dropHalf, t.perfFine, t.perfFineHint, fit.fineOn,+ () => fit.setFine(!fit.fineOn)),+ if (fit.canHighRefresh)+ toggle(PhosphorIconsRegular.deviceMobile, t.perfHz(hz), t.perfHzHint, fit.highRefresh,+ () => fit.setHighRefresh(!fit.highRefresh)),+ toggle(PhosphorIconsRegular.waveSine, t.calmMotionSetting, t.calmMotionHint, fit.calmMotion,+ () => fit.setCalmMotion(!fit.calmMotion)),+ ]),+ ),+ ]);+ },+ ),+ );+ }+Widget _rowIcon(GymColors gc, IconData icon, {Color? color}) => Padding(- padding: const EdgeInsets.only(right: 14),+ padding: const EdgeInsetsDirectional.only(end: 14),child: Container(width: 34,height: 34,@@ -1629,6 +1788,174 @@ class SettingsScreen extends StatelessWidget {}}+class _NotifSoundSheet extends StatelessWidget {+ const _NotifSoundSheet();++ Future<void> _phone(BuildContext context, SoundGroup g) async {+ final sounds = await NotifSound.phoneSounds();+ if (!context.mounted) return;+ if (sounds.isEmpty) return _system(g);+ await showAppSheet<void>(+ context: context,+ backgroundColor: Colors.transparent,+ builder: (_) => _PhoneSoundSheet(group: g, sounds: sounds, onMore: () => _system(g)),+ );+ await NotifSound.stopPreview();+ }++ Future<void> _system(SoundGroup g) async {+ final picked = await NotifSound.pick(NotifSound.uriOf(g));+ if (picked == null) return;+ await fit.setNotifSound(g, picked.uri, name: picked.name);+ }++ Widget _group(BuildContext context, GymColors gc, SoundGroup g, IconData icon, String title) {+ final uri = NotifSound.uriOf(g);+ final phone = uri.isNotEmpty && uri != NotifSound.silent;+ final name = fit.notifSoundNames[g] ?? '';+ return Container(+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(22)),+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Row(children: [+ Icon(icon, size: 19, color: gc.textSecondary),+ const SizedBox(width: 12),+ Expanded(+ child: Text(title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(15, weight: FontWeight.w800, color: gc.text)),+ ),+ ]),+ const SizedBox(height: 12),+ SegToggle([+ SegOption(t.notifSoundNormal, uri.isEmpty, () => fit.setNotifSound(g, '')),+ SegOption(t.notifSoundPhone, phone, () => _phone(context, g)),+ SegOption(t.notifSoundSilent, uri == NotifSound.silent, () => fit.setNotifSound(g, NotifSound.silent)),+ ]),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: !phone+ ? const SizedBox(width: double.infinity)+ : Padding(+ padding: const EdgeInsets.only(top: 10),+ child: Pressable(+ onTap: () => _phone(context, g),+ child: Container(+ constraints: const BoxConstraints(minHeight: 44),+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(16)),+ child: Row(children: [+ Icon(PhosphorIconsRegular.musicNote, size: 16, color: gc.accent),+ const SizedBox(width: 10),+ Expanded(+ child: Text(name.isEmpty ? t.notifSoundPhone : name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: AppTheme.f(13.5, weight: FontWeight.w700, color: gc.text)),+ ),+ Text(t.notifSoundChange, style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.accent)),+ ]),+ ),+ ),+ ),+ ),+ ]),+ );+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return AnimatedBuilder(+ animation: fit,+ builder: (context, _) => Container(+ padding: sheetPad(context),+ decoration: sheetDecoration(gc),+ child: SingleChildScrollView(+ child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ const SheetHandle(),+ const SizedBox(height: 16),+ SheetTitle(t.notifSoundSetting, subtitle: t.notifSoundHint),+ const SizedBox(height: 16),+ _group(context, gc, SoundGroup.train, PhosphorIconsRegular.barbell, t.notifSoundTrain),+ if (fit.nutritionBeta) ...[+ const SizedBox(height: 10),+ _group(context, gc, SoundGroup.food, PhosphorIconsRegular.forkKnife, t.notifSoundFood),+ ],+ const SizedBox(height: 10),+ _group(context, gc, SoundGroup.other, PhosphorIconsRegular.camera, t.notifSoundOther),+ ]),+ ),+ ),+ );+ }+}++class _PhoneSoundSheet extends StatefulWidget {+ const _PhoneSoundSheet({required this.group, required this.sounds, required this.onMore});++ final SoundGroup group;+ final List<({String uri, String name})> sounds;+ final Future<void> Function() onMore;++ @override+ State<_PhoneSoundSheet> createState() => _PhoneSoundSheetState();+}++class _PhoneSoundSheetState extends State<_PhoneSoundSheet> {+ late String _uri = NotifSound.uriOf(widget.group);++ void _choose(({String uri, String name}) s) {+ setState(() => _uri = s.uri);+ NotifSound.preview(s.uri);+ fit.setNotifSound(widget.group, s.uri, name: s.name);+ }++ Future<void> _more() async {+ await NotifSound.stopPreview();+ await widget.onMore();+ if (mounted) Navigator.of(context).pop();+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return Container(+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.72),+ padding: sheetPad(context),+ decoration: sheetDecoration(gc),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SheetHandle(),+ const SizedBox(height: 16),+ SheetTitle(t.notifSoundPhone, subtitle: t.notifSoundPhoneHint),+ const SizedBox(height: 14),+ Flexible(+ child: OptionGroup(+ scroll: true,+ [+ for (final s in widget.sounds)+ OptionItem(+ s.name,+ icon: s.uri == _uri ? PhosphorIconsRegular.speakerHigh : PhosphorIconsRegular.musicNote,+ selected: s.uri == _uri,+ onTap: () => _choose(s),+ ),+ OptionItem(t.notifSoundMore, icon: PhosphorIconsRegular.folderOpen, onTap: _more),+ ],+ ),+ ),+ ],+ ),+ );+ }+}+class _LanguageSheet extends StatelessWidget {@overrideWidget build(BuildContext context) {@@ -1795,7 +2122,7 @@ class _ProfileSheetState extends State<_ProfileSheet> {_stepRow(gc, t.weeklyGoal, '${p.weeklyGoal}×', () => _up(() => fit.updateProfile(weeklyGoalDelta: -1)), () => _up(() => fit.updateProfile(weeklyGoalDelta: 1))),]),const SizedBox(height: 18),- Padding(padding: const EdgeInsets.only(left: 4), child: _label(gc, t.activityLabel)),+ Padding(padding: const EdgeInsetsDirectional.only(start: 4), child: _label(gc, t.activityLabel)),const SizedBox(height: 10),Wrap(spacing: 8, runSpacing: 8, children: [_act(gc, t.activityName('Sedentary'), 1.2),diff --git a/lib/state/fit_core.dart b/lib/state/fit_core.dartindex d7f165c..420833f 100644--- a/lib/state/fit_core.dart+++ b/lib/state/fit_core.dart@@ -51,9 +51,11 @@ abstract class FitCore extends ChangeNotifier {final List<LoggedSession> sessions = [];final List<BodyweightEntry> bodyweight = [];final List<GymNote> notes = [];+ final List<NoteFolder> noteFolders = [];final List<BodyMeasure> measures = [];final List<ProgressEntry> shots = [];final Set<String> checkins = {};+ final Map<String, String> daysOff = {};final List<Routine> routines = [];final Map<int, String> weeklyPlan = {};final Map<int, List<String>> planExtras = {};@@ -106,6 +108,13 @@ abstract class FitCore extends ChangeNotifier {final Map<String, List<double>> weightStacks = {};List<double>? stackFor(String id) {+ final s = weightStacks[id];+ return s == null || s.isEmpty ? dumbbellStockFor(id) : s;+ }++ List<double>? dumbbellStockFor(String id) => null;++ List<double>? ownStackFor(String id) {final s = weightStacks[id];return s == null || s.isEmpty ? null : s;}@@ -157,6 +166,8 @@ abstract class FitCore extends ChangeNotifier {void syncTrainReminder() {}+ bool get rotating => false;+bool hasPlanOn(DateTime day) => false;Map<double, int>? get plateStockKg => null;@@ -184,6 +195,7 @@ abstract class FitCore extends ChangeNotifier {sessions.isEmpty ? 0 : identityHashCode(sessions.first),sessions.isEmpty ? 0 : identityHashCode(sessions.last),checkins.length,+ daysOff.length,extra,);final hit = _memo[key];@@ -344,7 +356,10 @@ abstract class FitCore extends ChangeNotifier {}String get volumeUnit => isLb ? 'k lb' : 't';- String volumeValue(double kg) => fmt(_round1(toDisplayWeight(kg) / 1000));+ String volumeValue(double kg) {+ final v = _round1(toDisplayWeight(kg) / 1000);+ return v >= 1000 ? groupedInt(v.round()) : fmt(v);+ }String volumeLabel(double kg) => '${volumeValue(kg)} $volumeUnit';diff --git a/lib/state/fit_state.dart b/lib/state/fit_state.dartindex 8bf2a6a..4690a65 100644--- a/lib/state/fit_state.dart+++ b/lib/state/fit_state.dart@@ -26,6 +26,7 @@ import '../models/progress_shot.dart';import '../models/workout.dart';import '../services/alarm_store.dart';import '../services/beeper.dart';+import '../services/device_kind.dart';import '../services/exercise_match.dart';import '../services/food_library.dart';import '../services/health_metrics.dart';@@ -33,11 +34,13 @@ import '../services/health_steps.dart';import '../services/local_store.dart';import '../services/media_store.dart';import '../services/merged_ids.dart';+import '../services/notif_sound.dart';import '../services/progress_reminder.dart';import '../services/plan_share.dart';import '../services/rest_alarm.dart';import '../services/supplement_reminder.dart';import '../services/train_reminder.dart';+import '../services/voice_coach.dart';import '../services/workout_import.dart';part 'awards_state.dart';@@ -62,6 +65,52 @@ part 'workout_state.dart';class FitState extends FitCorewith ToolsState, LibraryState, SettingsState, NotesState, PlacesState, GymPassState, MeasuresState, MomentsState, TimelineState, StatsState, StepsState, HealthState, CircuitState, NutritionState, ReportState, AwardsState, RoutinesState, WorkoutState {+ final Map<SoundGroup, String> notifSoundNames = {};++ void _loadNotifSounds(Object? raw) {+ NotifSound.uris.clear();+ notifSoundNames.clear();+ if (raw is! Map) return;+ for (final g in SoundGroup.values) {+ final v = raw[g.name];+ if (v is! List || v.isEmpty || v.first is! String || (v.first as String).isEmpty) continue;+ NotifSound.uris[g] = v.first as String;+ notifSoundNames[g] = v.length > 1 && v[1] is String ? v[1] as String : '';+ }+ }++ static const _soundChannels = ['train_reminder', 'supplement_reminder', 'fasting', 'progress_photo', 'measures'];++ Future<void> setNotifSound(SoundGroup g, String uri, {String name = ''}) async {+ if (uri.isEmpty) {+ NotifSound.uris.remove(g);+ notifSoundNames.remove(g);+ } else {+ NotifSound.uris[g] = uri;+ notifSoundNames[g] = name;+ }+ _persist();+ notifyListeners();+ await NotifSound.dropOld(_soundChannels, {+ NotifSound.channelOf('train_reminder', SoundGroup.train),+ NotifSound.channelOf('supplement_reminder', SoundGroup.food),+ NotifSound.channelOf('fasting', SoundGroup.food),+ NotifSound.channelOf('progress_photo', SoundGroup.other),+ NotifSound.channelOf('measures', SoundGroup.other),+ 'fasting_live',+ });+ switch (g) {+ case SoundGroup.train:+ syncTrainReminder();+ case SoundGroup.food:+ syncSupplementReminder();+ _syncFast();+ case SoundGroup.other:+ syncPhotoReminder();+ syncMeasureReminder();+ }+ }+void loadFromStore() {final data = withMergedExercises(Store.instance.load());_loading = true;@@ -81,6 +130,7 @@ class FitState extends FitCorealarmSound = data['alarmSound'] as String?;alarmSoundName = data['alarmSoundName'] as String?;RestAlarm.instance.customSoundPath = alarmSoundPath;+ _loadNotifSounds(data['notifSounds']);if (alarmSoundPath == null) {alarmSound = null;@@ -100,6 +150,9 @@ class FitState extends FitCorecheckins..clear()..addAll(((data['checkins'] as List?) ?? []).cast<String>());+ daysOff+ ..clear()+ ..addAll(((data['daysOff'] as Map?) ?? const {}).map((k, v) => MapEntry(k as String, v as String)));routines..clear()..addAll(((data['routines'] as List?) ?? [])@@ -241,6 +294,8 @@ class FitState extends FitCoreshowRoutineRow = data['showRoutineRow'] as bool? ?? true;levelHints = data['levelHints'] as bool? ?? true;toastSound = data['toastSound'] as bool? ?? true;+ final auto = data['autoProgress'] as String? ?? 'off';+ autoProgress = SettingsState.autoProgressModes.contains(auto) ? auto : 'off';Beeper.instance.chimeOn = toastSound;heatmapLabels = data['heatLabels'] as bool? ?? true;hideShots = data['hideShots'] as bool? ?? false;@@ -259,8 +314,17 @@ class FitState extends FitCorefinal size = data['textSize'];textSize = SettingsState.textSizes.contains(size) ? size as String : 'normal';calmMotion = data['calm'] as bool? ?? false;+ fineOn = data['fine'] as bool? ?? false;+ fineEffects = fineOn;+ highRefresh = data['hz'] as bool? ?? false;+ if (highRefresh) DeviceKind.setHighRefresh(true);showMiniBody = data['miniBody'] as bool? ?? true;askCheckIn = data['checkIn'] as bool? ?? true;+ muscleTune = data['mTune'] as bool? ?? true;+ voiceCoach = data['voice'] as bool? ?? false;+ final every = (data['deload'] as num?)?.toInt() ?? 0;+ deloadEvery = SettingsState.deloadChoices.contains(every) ? every : 0;+ deloadFrom = deloadEvery > 0 ? DateTime.tryParse((data['deloadFrom'] as String?) ?? '') ?? DateTime.now() : null;blurEffects = blurOn;lowEndAsked = data['lowEndAsked'] as bool? ?? false;startCountdown = data['countdown'] as bool? ?? true;@@ -423,6 +487,12 @@ class FitState extends FitCorevoid _loadNotes(Map<String, dynamic> data) {notes.clear();+ noteFolders+ ..clear()+ ..addAll([+ for (final f in (data['noteFolders'] as List?) ?? const [])+ if (f is Map) NoteFolder.fromJson(f.cast<String, dynamic>()),+ ]);final raw = data['notes'];if (raw is List) {notes.addAll(raw.map((e) => GymNote.fromJson((e as Map).cast<String, dynamic>())));@@ -467,6 +537,10 @@ class FitState extends FitCore'miniRest': miniRestSeconds,'alarmSound': alarmSound,'alarmSoundName': alarmSoundName,+ if (NotifSound.uris.isNotEmpty)+ 'notifSounds': {+ for (final g in NotifSound.uris.keys) g.name: [NotifSound.uris[g], notifSoundNames[g] ?? ''],+ },'bg': bgPattern,'heatTone': heatTone,'bgDim': bgDim,@@ -476,6 +550,7 @@ class FitState extends FitCore'showRoutineRow': showRoutineRow,'levelHints': levelHints,'toastSound': toastSound,+ if (autoProgress != 'off') 'autoProgress': autoProgress,'heatLabels': heatmapLabels,if (hideShots) 'hideShots': true,'weekStart': weekStartDay,@@ -484,8 +559,14 @@ class FitState extends FitCoreif (!blurOn) 'blur': false,if (textSize != 'normal') 'textSize': textSize,if (calmMotion) 'calm': true,+ if (fineOn) 'fine': true,+ if (highRefresh) 'hz': true,if (!showMiniBody) 'miniBody': false,if (!askCheckIn) 'checkIn': false,+ if (!muscleTune) 'mTune': false,+ if (voiceCoach) 'voice': true,+ if (deloadEvery > 0) 'deload': deloadEvery,+ if (deloadFrom != null) 'deloadFrom': deloadFrom!.toIso8601String(),if (lowEndAsked) 'lowEndAsked': true,'countdown': startCountdown,'gamify': gamification,@@ -518,11 +599,13 @@ class FitState extends FitCore'onboarded': onboarded,'favorites': favorites,'notes': notes.map((n) => n.toJson()).toList(),+ if (noteFolders.isNotEmpty) 'noteFolders': noteFolders.map((f) => f.toJson()).toList(),'places': places.map((p) => p.toJson()).toList(),'place': activePlaceId,if (gymPasses.isNotEmpty) 'passes': gymPasses.map((p) => p.toJson()).toList(),if (lastPassId.isNotEmpty) 'lastPass': lastPassId,'checkins': checkins.toList(),+ if (daysOff.isNotEmpty) 'daysOff': daysOff,'routines': routines.map((r) => r.toJson()).toList(),'weeklyPlan': weeklyPlan.map((k, v) => MapEntry(k.toString(), v)),'planExtras': planExtras.map((k, v) => MapEntry(k.toString(), v)),@@ -617,6 +700,7 @@ class FitState extends FitCorecompareFromId = null;compareToId = null;notes.clear();+ noteFolders.clear();moments.clear();loadNutrition(null);loadSteps(null);@@ -631,6 +715,7 @@ class FitState extends FitCoregymPasses.clear();lastPassId = '';checkins.clear();+ daysOff.clear();routines.clear();weeklyPlan.clear();planExtras.clear();@@ -682,10 +767,15 @@ class FitState extends FitCoreshowRecommended = true;textSize = 'normal';calmMotion = false;+ fineOn = false;+ fineEffects = false;+ if (highRefresh) DeviceKind.setHighRefresh(false);+ highRefresh = false;showWeekStats = true;showRoutineRow = true;levelHints = true;toastSound = true;+ autoProgress = 'off';Beeper.instance.chimeOn = true;heatmapLabels = true;hideShots = false;@@ -780,6 +870,9 @@ class FitState extends FitCorecheckins..clear()..addAll(((map['checkins'] as List?) ?? []).cast<String>());+ daysOff+ ..clear()+ ..addAll(((map['daysOff'] as Map?) ?? const {}).map((k, v) => MapEntry(k as String, v as String)));routines..clear()..addAll(((map['routines'] as List?) ?? [])@@ -873,7 +966,7 @@ class FitState extends FitCoreweekdays: reminderWeekdays,skipToday: trainedToday,againMinutes: trainAgainMin,- restOn: rotating ? rotationRestOn : null,+ restOn: (day) => daysOff.containsKey(dayIdOf(day)) || (rotating && rotationRestOn(day)),);}diff --git a/lib/state/routines_state.dart b/lib/state/routines_state.dartindex fc46ff8..8be68c2 100644--- a/lib/state/routines_state.dart+++ b/lib/state/routines_state.dart@@ -197,6 +197,7 @@ mixin RoutinesState on FitCore, LibraryState {Routine? routineById(String id) => _routine(id);+ @overridebool get rotating => rotation && rotationRoutines.isNotEmpty;List<Routine> get rotationRoutines => [for (final id in rotationIds) ?_routine(id)];@@ -547,6 +548,7 @@ mixin RoutinesState on FitCore, LibraryState {made.ladders.addAll([for (final l in source.ladders) [...l]]);made.plan.addAll({for (final e in source.plan.entries) e.key: [...e.value]});made.rest.addAll(source.rest);+ made.alts.addAll({for (final e in source.alts.entries) e.key: [...e.value]});made.group = source.group;made.color = source.color;_persist();@@ -618,6 +620,7 @@ mixin RoutinesState on FitCore, LibraryState {r.plan.remove(exId);r.rest.remove(exId);r.chained.remove(exId);+ r.alts.remove(exId);} else {r.exerciseIds.add(exId);}@@ -675,6 +678,32 @@ mixin RoutinesState on FitCore, LibraryState {final rest = r.rest.remove(from);if (rest != null) r.rest[to] = rest;if (r.chained.remove(from)) r.chained.add(to);+ final alts = r.alts.remove(from);+ if (alts != null) {+ final kept = [for (final a in alts) if (a != to) a];+ if (kept.isNotEmpty) r.alts[to] = kept;+ }+ _persist();+ notifyListeners();+ }++ static const maxAlts = 3;++ List<String> routineAlts(String routineId, String exId) => _routine(routineId)?.alts[exId] ?? const [];++ void toggleRoutineAlt(String routineId, String exId, String altId) {+ final r = _routine(routineId);+ if (r == null || altId == exId) return;+ final list = [...?r.alts[exId]];+ if (!list.remove(altId)) {+ if (list.length >= maxAlts) list.removeAt(0);+ list.add(altId);+ }+ if (list.isEmpty) {+ r.alts.remove(exId);+ } else {+ r.alts[exId] = list;+ }_persist();notifyListeners();}@@ -688,6 +717,7 @@ mixin RoutinesState on FitCore, LibraryState {final plan = r.plan[exId];final rest = r.rest[exId];final chained = r.chained.contains(exId);+ final alts = r.alts[exId];toggleRoutineExercise(routineId, exId);return () {final back = _routine(routineId);@@ -697,6 +727,7 @@ mixin RoutinesState on FitCore, LibraryState {if (plan != null) back.plan[exId] = plan;if (rest != null) back.rest[exId] = rest;if (chained) back.chained.add(exId);+ if (alts != null) back.alts[exId] = alts;_persist();notifyListeners();};diff --git a/lib/state/settings_state.dart b/lib/state/settings_state.dartindex 21ff190..fd29f6f 100644--- a/lib/state/settings_state.dart+++ b/lib/state/settings_state.dart@@ -37,6 +37,8 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {bool showRoutineRow = true;bool levelHints = true;bool toastSound = true;+ String autoProgress = 'off';+ static const autoProgressModes = ['off', 'weight', 'reps'];bool heatmapLabels = true;bool hideShots = false;bool autoAdvance = true;@@ -44,8 +46,55 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {bool blurOn = true;String textSize = 'normal';bool calmMotion = false;+ bool fineOn = false;+ bool highRefresh = false;+ double maxRefresh = 60;bool showMiniBody = true;bool askCheckIn = true;+ bool muscleTune = true;++ bool voiceCoach = false;+ int deloadEvery = 0;+ DateTime? deloadFrom;+ static const deloadChoices = [0, 4, 5, 6, 8];++ int get deloadWeekIndex {+ final from = deloadFrom;+ if (deloadEvery <= 0 || from == null) return -1;+ final start = DateTime(from.year, from.month, from.day - (from.weekday - 1));+ final now = DateTime.now();+ final today = DateTime(now.year, now.month, now.day);+ return (today.difference(start).inDays / 7).floor();+ }++ bool get deloadWeek => deloadEvery > 0 && deloadWeekIndex >= 0 && deloadWeekIndex % deloadEvery == deloadEvery - 1;++ int get weeksToDeload {+ final i = deloadWeekIndex;+ if (i < 0) return -1;+ return (deloadEvery - 1 - i % deloadEvery) % deloadEvery;+ }++ void setDeloadEvery(int weeks) {+ if (!deloadChoices.contains(weeks) || weeks == deloadEvery) return;+ deloadEvery = weeks;+ deloadFrom = weeks > 0 ? DateTime.now() : null;+ _persist();+ notifyListeners();+ }++ void toggleVoiceCoach() {+ voiceCoach = !voiceCoach;+ if (!voiceCoach) VoiceCoach.stop();+ _persist();+ notifyListeners();+ }++ void toggleMuscleTune() {+ muscleTune = !muscleTune;+ _persist();+ notifyListeners();+ }void toggleMiniBody() {showMiniBody = !showMiniBody;@@ -417,12 +466,67 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {notifyListeners();}+ static const perfLevels = ['lite', 'balanced', 'max'];++ bool get canHighRefresh => maxRefresh > 61;++ String get perfLevel {+ final refresh = highRefresh && canHighRefresh;+ if (!blurOn && !fineOn && !refresh && calmMotion) return 'lite';+ if (blurOn && !fineOn && !refresh && !calmMotion) return 'balanced';+ if (blurOn && fineOn && (refresh || !canHighRefresh) && !calmMotion) return 'max';+ return 'custom';+ }++ void setPerfLevel(String level) {+ if (!perfLevels.contains(level)) return;+ final max = level == 'max';+ blurOn = level != 'lite';+ blurEffects = blurOn;+ calmMotion = level == 'lite';+ fineOn = max;+ fineEffects = max;+ highRefresh = max;+ DeviceKind.setHighRefresh(highRefresh);+ _persist();+ notifyListeners();+ }++ void setFine(bool on) {+ fineOn = on;+ fineEffects = on;+ _persist();+ notifyListeners();+ }++ void setHighRefresh(bool on) {+ highRefresh = on;+ DeviceKind.setHighRefresh(on);+ _persist();+ notifyListeners();+ }++ Future<void> readDisplay() async {+ final hz = await DeviceKind.maxRefresh();+ if (hz == maxRefresh) return;+ maxRefresh = hz;+ notifyListeners();+ }+void markLowEndAsked() {lowEndAsked = true;_persist();}- double? progressFor(String exerciseId) => progressStep[exerciseId];+ double? progressFor(String exerciseId) =>+ progressStep[exerciseId] ?? (autoProgress == 'off' ? null : fromDisplayWeight(weightStep));++ void setAutoProgress(String mode) {+ if (!autoProgressModes.contains(mode) || mode == autoProgress) return;+ autoProgress = mode;+ _persist();+ notifyListeners();+ }void setWeightStack(String id, List<double> kg) {final clean = <double>{for (final v in kg) if (v.isFinite && v > 0 && v < 1000) (v * 1000).round() / 1000}.toList()@@ -452,10 +556,15 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {notifyListeners();}- bool hasProgress(String exerciseId) =>- (progressStep[exerciseId] ?? 0) > 0 && progressRule(exerciseId).kind != ProgressKind.manual;+ bool hasProgress(String exerciseId) {+ final step = progressStep[exerciseId];+ if (step == null && autoProgress == 'off') return false;+ return (step ?? 1) > 0 && progressRule(exerciseId).kind != ProgressKind.manual;+ }- ProgressRule progressRule(String exerciseId) => progressRules[exerciseId] ?? const ProgressRule();+ ProgressRule progressRule(String exerciseId) =>+ progressRules[exerciseId] ??+ (autoProgress == 'reps' ? const ProgressRule(kind: ProgressKind.double) : const ProgressRule());void setProgressRule(String exerciseId, ProgressRule rule) {final was = progressRule(exerciseId).kind;@@ -472,7 +581,11 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {void toggleProgress(String exerciseId) {if (hasProgress(exerciseId)) {- progressStep.remove(exerciseId);+ if (autoProgress == 'off') {+ progressStep.remove(exerciseId);+ } else {+ progressStep[exerciseId] = 0;+ }} else {progressStep[exerciseId] = fromDisplayWeight(weightStep);if (progressRule(exerciseId).kind == ProgressKind.manual) progressRules.remove(exerciseId);@@ -482,7 +595,7 @@ mixin SettingsState on FitCore, ToolsState, LibraryState {}void bumpProgressStep(String exerciseId, int dir) {- final current = toDisplayWeight(progressStep[exerciseId] ?? 0);+ final current = toDisplayWeight(progressFor(exerciseId) ?? 0);final next = (current + dir * weightStep / 2).clamp(weightStep / 2, weightStep * 8);progressStep[exerciseId] = fromDisplayWeight(next);_persist();diff --git a/lib/state/stats_state.dart b/lib/state/stats_state.dartindex d1640ea..c9ee144 100644--- a/lib/state/stats_state.dart+++ b/lib/state/stats_state.dart@@ -98,7 +98,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStfinal shown = toDisplayWeight(kg);if (shown < 1000) return (shown.round().toString(), units);final k = shown / 1000;- return (k >= 10 ? k.round().toString() : decimalText(k.toStringAsFixed(1)), units == 'kg' ? 't' : 'k $units');+ return (k >= 10 ? groupedInt(k.round()) : decimalText(k.toStringAsFixed(1)), units == 'kg' ? 't' : 'k $units');}(String, String) get liftedSpan => liftedSpanOf(totalVolumeKg);@@ -617,18 +617,23 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStreturn _remember('streak', _streak, today);}+ static const looseRestDays = 2;+int _streak() {final days = {..._byDay.keys, ..._checkinDays};if (days.isEmpty) return 0;final first = days.reduce((a, b) => a.isBefore(b) ? a : b);- bool rest(DateTime d) => weeklyPlan.isNotEmpty && !weeklyPlan.containsKey(d.weekday);+ final loose = rotating;+ bool rest(DateTime d) =>+ daysOff.containsKey(_dayId(d)) || (!loose && weeklyPlan.isNotEmpty && !weeklyPlan.containsKey(d.weekday));var cursor = _dayKey(DateTime.now());if (!days.contains(cursor)) cursor = shiftDays(cursor, -1);- var n = 0;+ var n = 0, gap = 0;while (!cursor.isBefore(first)) {if (days.contains(cursor)) {n++;- } else if (!rest(cursor)) {+ gap = 0;+ } else if (!rest(cursor) && ++gap > (loose ? looseRestDays : 0)) {break;}cursor = shiftDays(cursor, -1);@@ -636,6 +641,44 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStreturn n;}+ static const dayOffReasons = ['sick', 'travel', 'injury', 'rest'];++ String dayIdOf(DateTime d) => _dayId(d);++ String? dayOffOn(DateTime d) => daysOff[_dayId(d)];++ bool isCheckedIn(DateTime d) => checkins.contains(_dayId(d));++ void setDayOff(DateTime d, String? reason) {+ final id = _dayId(d);+ if (reason == null || !dayOffReasons.contains(reason)) {+ if (daysOff.remove(id) == null) return;+ } else {+ daysOff[id] = reason;+ checkins.remove(id);+ }+ _persist();+ _refreshWidgets();+ syncTrainReminder();+ refreshAwards();+ notifyListeners();+ }++ void setCheckedIn(DateTime d, bool on) {+ final id = _dayId(d);+ if (_hasSessionOn(d) || on == checkins.contains(id)) return;+ if (on) {+ checkins.add(id);+ daysOff.remove(id);+ } else {+ checkins.remove(id);+ }+ _persist();+ _refreshWidgets();+ refreshAwards();+ notifyListeners();+ }+List<bool> get weekMask {final start = _weekStart;final days = _byDay;@@ -668,6 +711,7 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStcheckins.remove(id);} else {checkins.add(id);+ daysOff.remove(id);}_persist();_refreshWidgets();@@ -1086,7 +1130,13 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineStList<LoggedSet> lastSetsFor(String id) {final h = exerciseHistory(id);- return h.isEmpty ? const [] : h.first.ex.sets;+ if (h.isEmpty) return const [];+ final light = _remember('lightEx', () => Set<LoggedExercise>.identity()+ ..addAll([for (final s in sessions) if (s.deload) ...s.exercises]));+ for (final e in h) {+ if (!light.contains(e.ex)) return e.ex.sets;+ }+ return h.first.ex.sets;}String? lastSummaryFor(String id) {@@ -1128,6 +1178,239 @@ mixin StatsState on FitCore, ToolsState, LibraryState, SettingsState, TimelineSt('Kyd9Rz5', 0.45, ['Kyd9Rz5', 'kTbSH9h']),];+ DateTime get recapMonth {+ final now = DateTime.now();+ final last = DateTime(now.year, now.month - 1);+ final early = now.day <= 7 && sessions.any((s) => s.day.year == last.year && s.day.month == last.month);+ return early ? last : DateTime(now.year, now.month);+ }++ MonthRecap recapFor(DateTime month) => _remember(('recap', month.year, month.month), () => _recap(month));++ MonthRecap _recap(DateTime month) {+ final from = DateTime(month.year, month.month);+ final to = DateTime(month.year, month.month + 1);+ final inMonth = [for (final s in sessions) if (!s.day.isBefore(from) && s.day.isBefore(to)) s];+ final days = <int>{for (final s in inMonth) s.day.day};+ var seconds = 0, sets = 0;+ var volume = 0.0;+ LoggedSession? longest;+ final byExercise = <String, double>{};+ final setsOf = <String, int>{};+ final timesOf = <String, int>{};+ final bestOf = <String, double>{};+ final weekdays = <int, int>{};+ final starts = <int>[];+ for (final s in inMonth) {+ seconds += s.durationSec;+ sets += s.setCount;+ volume += s.volume;+ if (longest == null || s.durationSec > longest.durationSec) longest = s;+ weekdays[s.day.weekday] = (weekdays[s.day.weekday] ?? 0) + 1;+ starts.add(s.day.hour * 60 + s.day.minute);+ for (final e in s.exercises) {+ if (e.volume > 0) byExercise[e.id] = (byExercise[e.id] ?? 0) + e.volume;+ final n = e.workingSets.length;+ if (n == 0) continue;+ setsOf[e.id] = (setsOf[e.id] ?? 0) + n;+ timesOf[e.id] = (timesOf[e.id] ?? 0) + 1;+ if (e.topWeight > (bestOf[e.id] ?? 0)) bestOf[e.id] = e.topWeight;+ }+ }+ String? topExercise;+ var topVolume = 0.0;+ for (final e in byExercise.entries) {+ if (e.value > topVolume) {+ topVolume = e.value;+ topExercise = e.key;+ }+ }+ final muscles = muscleSetsBetween(from, shiftDays(to, -1));+ String? topMuscle;+ var topSets = 0.0;+ for (final e in muscles.entries) {+ if (e.value > topSets) {+ topSets = e.value;+ topMuscle = e.key;+ }+ }+ final records = <({String id, double kg})>[];+ final seen = <String>{};+ for (final s in inMonth) {+ for (final e in s.exercises) {+ if (!seen.add(e.id) || modeOf(e.id).isNotEmpty || isAssisted(e.id) || isRepsOnly(e.id)) continue;+ var before = 0.0, now = 0.0, kg = 0.0;+ for (final h in exerciseHistory(e.id)) {+ final day = h.date;+ if (day.isBefore(from)) {+ if (h.ex.bestOneRm > before) before = h.ex.bestOneRm;+ } else if (day.isBefore(to) && h.ex.bestOneRm > now) {+ now = h.ex.bestOneRm;+ kg = h.ex.topWeight;+ }+ }+ if (before > 0 && now > before) records.add((id: e.id, kg: kg));+ }+ }+ records.sort((a, b) => b.kg.compareTo(a.kg));+ int? favDay;+ var favCount = 0;+ for (final e in weekdays.entries) {+ if (e.value > favCount) {+ favCount = e.value;+ favDay = e.key;+ }+ }+ starts.sort();+ String? liftId;+ for (final e in setsOf.entries) {+ if (exerciseById(e.key) == null) continue;+ if (liftId == null || e.value > setsOf[liftId]! ||+ (e.value == setsOf[liftId]! && (byExercise[e.key] ?? 0) > (byExercise[liftId] ?? 0))) {+ liftId = e.key;+ }+ }+ return MonthRecap(+ month: from,+ workouts: inMonth.length,+ days: days,+ seconds: seconds,+ longest: longest,+ sets: sets,+ volumeKg: volume,+ topExercise: topExercise,+ topExerciseKg: topVolume,+ heat: muscleHeatBetween(from, shiftDays(to, -1)),+ topMuscle: topMuscle,+ topMuscleSets: topSets.round(),+ records: records,+ favDay: favCount >= 2 ? favDay : null,+ usualStart: starts.length >= 3 ? (starts[starts.length ~/ 2] ~/ 15) * 15 : null,+ weekdays: [for (var d = 1; d <= 7; d++) weekdays[d] ?? 0],+ lift: liftId == null+ ? null+ : (+ id: liftId,+ sets: setsOf[liftId]!,+ times: timesOf[liftId]!,+ bestKg: bestOf[liftId] ?? 0,+ volumeKg: byExercise[liftId] ?? 0,+ ),+ sessionMinutes: [for (final s in inMonth) s.durationSec ~/ 60],+ topLifts: ([+ for (final e in setsOf.entries)+ if (exerciseById(e.key) != null && !isCardio(e.key)) (id: e.key, sets: e.value),+ ]..sort((a, b) => b.sets.compareTo(a.sets)))+ .take(5)+ .toList(),+ exerciseIds: (setsOf.keys.where((id) => exerciseById(id) != null).toList()+ ..sort((a, b) => setsOf[b]!.compareTo(setsOf[a]!))),+ );+ }++ static const _pushMuscles = {'chest', 'shoulders', 'triceps'};+ static const _pullMuscles = {'back', 'biceps', 'trapezius'};++ List<({String kind, String text, String? exerciseId})> get weekInsights =>+ _remember('insights', _weekInsights, (_dayKey(DateTime.now()), weekStartDay, t.localeName));++ List<({String kind, String text, String? exerciseId})> _weekInsights() {+ final today = _dayKey(DateTime.now());+ final lastHit = <String, DateTime>{};+ final visits = <String, int>{};+ final recent = <String>{};+ var push = 0, pull = 0;+ for (final s in sessions) {+ final day = _dayKey(s.day);+ final age = today.difference(day).inDays;+ if (age < 0 || age > 56) continue;+ final seen = <String>{};+ for (final e in s.exercises) {+ final n = e.workingSets.length;+ if (n == 0 || !countsForMuscles(e.id)) continue;+ seen.add(e.primary);+ final was = lastHit[e.primary];+ if (was == null || day.isAfter(was)) lastHit[e.primary] = day;+ if (age <= 28) {+ if (_pushMuscles.contains(e.primary)) push += n;+ if (_pullMuscles.contains(e.primary)) pull += n;+ if (modeOf(e.id).isEmpty && !isAssisted(e.id) && !isRepsOnly(e.id)) recent.add(e.id);+ }+ }+ for (final m in seen) {+ visits[m] = (visits[m] ?? 0) + 1;+ }+ }+ final out = <({String kind, String text, String? exerciseId})>[];++ final start = _weekStart;+ final weeks = List<int>.filled(5, 0);+ for (final s in sessions) {+ final day = _dayKey(s.day);+ if (day.isAfter(today)) continue;+ final back = start.difference(day).inDays;+ final i = back <= 0 ? 0 : 1 + (back - 1) ~/ 7;+ if (i < weeks.length) weeks[i] += s.setCount;+ }+ final before = weeks.sublist(1).where((w) => w > 0).toList();+ if (before.length >= 3 && weeks[0] >= 12) {+ final avg = before.fold(0, (a, b) => a + b) / before.length;+ if (weeks[0] >= avg * 1.5) {+ out.add((kind: 'load', text: t.insightLoad(((weeks[0] / avg - 1) * 100).round()), exerciseId: null));+ }+ }++ String? forgotten;+ var gap = 13;+ for (final e in lastHit.entries) {+ final days = today.difference(e.value).inDays;+ if ((visits[e.key] ?? 0) >= 2 && days > gap) {+ gap = days;+ forgotten = e.key;+ }+ }+ if (forgotten != null) {+ out.add((kind: 'muscle', text: t.insightMuscle(muscleLabel(forgotten), gap), exerciseId: null));+ }++ if (push + pull >= 20) {+ if (push >= pull * 1.6) {+ out.add((kind: 'balance', text: t.insightPushHeavy(push, pull), exerciseId: null));+ } else if (pull >= push * 1.6) {+ out.add((kind: 'balance', text: t.insightPullHeavy(pull, push), exerciseId: null));+ }+ }++ String? best;+ var gain = 0.03;+ for (final id in recent) {+ var now = 0.0, then = 0.0;+ for (final h in exerciseHistory(id)) {+ final age = today.difference(_dayKey(h.date)).inDays;+ if (age > 90) break;+ final rm = h.ex.bestOneRm;+ if (age <= 28) {+ if (rm > now) now = rm;+ } else if (rm > then) {+ then = rm;+ }+ }+ if (then <= 0 || now <= 0) continue;+ final g = now / then - 1;+ if (g > gain) {+ gain = g;+ best = id;+ }+ }+ if (best != null) {+ final ex = exerciseById(best);+ if (ex != null) {+ out.add((kind: 'up', text: t.insightStronger(exerciseName(ex), (gain * 100).round()), exerciseId: best));+ }+ }+ return out.take(3).toList();+ }+({List<({String id, double kg, double target, double score})> lifts, String? behind})? get structuralBalance =>_remember('balance', _structuralBalance, _dayKey(DateTime.now()));diff --git a/lib/state/workout_state.dart b/lib/state/workout_state.dartindex b59ab7e..ce54f62 100644--- a/lib/state/workout_state.dart+++ b/lib/state/workout_state.dart@@ -505,6 +505,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStlinkedNext: chained.contains(ex.id),)).toList();+ if (deloadWeek && !s.manual) _lighten(s);_restTimer?.cancel();_elapsedBefore = 0;sessionPaused = false;@@ -517,6 +518,42 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ void _lighten(WorkoutSession s) {+ s.deload = true;+ for (final e in s.exercises) {+ final working = e.sets.where((st) => st.kind != SetKind.warmup).toList();+ if (working.isEmpty) continue;+ final keep = (working.length / 2).ceil();+ final drop = working.sublist(keep).toSet();+ e.sets.removeWhere(drop.contains);+ if (modeOf(e.id).isNotEmpty || isRepsOnly(e.id)) continue;+ for (final st in e.sets) {+ if (st.kind == SetKind.warmup || st.weight <= 0) continue;+ st.weight = fromDisplayWeight(_roundTo(toDisplayWeight(st.weight * 0.9), plateStep));+ }+ }+ }++ bool get canSkipDeload {+ final s = session;+ return s != null && s.deload && s.routineId != null && !s.exercises.any((e) => e.sets.any((st) => st.done));+ }++ void skipDeload() {+ final s = session;+ final r = routineById(s?.routineId ?? '');+ if (s == null || r == null || !canSkipDeload) return;+ for (final e in s.exercises) {+ final fresh = _openingSets(e.id, count: routineSets(r, e.id), planned: hasPlan(r, e.id) ? plannedSets(r, e.id) : null);+ e.sets+ ..clear()+ ..addAll(fresh);+ }+ s.deload = false;+ persistNow();+ notifyListeners();+ }+void _startTicking({DateTime? from}) {_sessionTimer?.cancel();_runningSince = from ?? DateTime.now();@@ -943,10 +980,50 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStrestTotal = seconds;_armRest(seconds);+ if (voiceCoach) {+ final next = voiceNext();+ VoiceCoach.say(next == null ? t.voiceRest(voiceDuration(seconds)) : '${t.voiceRest(voiceDuration(seconds))} $next', intlLocale);+ }askAlarmPermission();notifyListeners();}+ String voiceDuration(int sec) {+ final m = sec ~/ 60;+ final s = sec % 60;+ if (m == 0) return t.voiceSeconds(s);+ if (s == 0) return t.voiceMinutes(m);+ return '${t.voiceMinutes(m)} ${t.voiceAnd} ${t.voiceSeconds(s)}';+ }++ String? voiceNext() {+ final s = session;+ if (s == null || s.exercises.isEmpty) return null;+ var i = s.currentIndex.clamp(0, s.exercises.length - 1);+ var pending = s.exercises[i].sets.indexWhere((st) => !st.done);+ if (pending < 0) {+ final after = pendingAfter(i);+ if (after == null) return null;+ i = after;+ pending = s.exercises[i].sets.indexWhere((st) => !st.done);+ if (pending < 0) return null;+ }+ final ex = s.exercises[i];+ final st = ex.sets[pending];+ final name = t.catalogName(ex.id, ex.name);+ final String load;+ if (st.sec != null) {+ load = voiceDuration(st.sec!);+ } else if (st.km != null) {+ load = fit.loggedSetLabel(st.logged);+ } else if (isRepsOnly(ex.id) || st.weight <= 0) {+ load = t.voiceReps(st.reps);+ } else {+ load = t.voiceLoad(st.reps, weightLabel(st.weight));+ }+ return t.voiceNext(name, load);+ }+void _armRest(int seconds) {final s = session;if (s == null) return;@@ -960,10 +1037,12 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStt.cancel();return;}- if (live.restRemaining == null) {+ final left = live.restRemaining;+ if (left == null) {restElapsed();return;}+ if (voiceCoach && left <= 3) VoiceCoach.say('$left', intlLocale);clock.value++;});}@@ -974,6 +1053,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsSt_restTimer?.cancel();s.clearRest();restDoneTick++;+ if (voiceCoach) VoiceCoach.say(t.voiceGo, intlLocale);RestAlarm.instance.fireNow();notifyListeners();}@@ -1468,6 +1548,19 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ List<Exercise> sessionAltsFor(int exIdx) {+ final s = session;+ final r = sessionRoutine;+ if (s == null || r == null || exIdx < 0 || exIdx >= s.exercises.length) return const [];+ final slot = s.exercises[exIdx].swappedFrom ?? s.exercises[exIdx].id;+ final back = s.exercises[exIdx].swappedFrom;+ return [+ if (back != null && !inSession(back)) ?exerciseById(back),+ for (final id in r.alts[slot] ?? const <String>[])+ if (id != s.exercises[exIdx].id && !inSession(id)) ?exerciseById(id),+ ];+ }+List<Exercise> swapOptions(String exId, {int n = 15}) {final from = exerciseById(exId);if (from == null) return const [];@@ -1592,7 +1685,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStlogged.add(LoggedExercise(e.id, e.name, e.primary, doneSets, incline: lastIncline(e.id)));}}- final entry = LoggedSession(s.loggedAt ?? DateTime.now(), s.summaryDuration ?? 0, logged, routineId: s.routineId, name: s.name);+ final entry = LoggedSession(s.loggedAt ?? DateTime.now(), s.summaryDuration ?? 0, logged, routineId: s.routineId, name: s.name, deload: s.deload);sessions.add(entry);sessions.sort((a, b) => a.date.compareTo(b.date));_rotationBefore = (rotationNextId, rotationRestDay);@@ -1627,16 +1720,27 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal out = <String, String>{};for (final e in _savable) {final from = e.swappedFrom;- if (from != null && r.exerciseIds.contains(from) && !r.exerciseIds.contains(e.id)) out[from] = e.id;+ if (from == null || r.alts[from]?.contains(e.id) == true) continue;+ if (r.exerciseIds.contains(from) && !r.exerciseIds.contains(e.id)) out[from] = e.id;}return out;}+ bool _onAlt(SessionExercise e) {+ final from = e.swappedFrom;+ return from != null && sessionRoutine?.alts[from]?.contains(e.id) == true;+ }+List<SessionExercise> get _savableForRoutine {final swaps = _swaps;- return [for (final e in _savable) if (!swaps.containsKey(e.id)) e];+ return [for (final e in _savable) if (!swaps.containsKey(e.id) && !_onAlt(e)) e];}+ List<String> get _slotsForRoutine => [+ for (final e in _savable)+ if (_onAlt(e)) e.swappedFrom! else if (!_swaps.containsKey(e.id)) e.id,+ ];+void _planFromSession(String routineId, SessionExercise ex) {if (ex.sets.isEmpty) return;setPlannedSets(routineId, ex.id, [@@ -1659,7 +1763,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStbool get sessionEditedRoutine {final r = sessionRoutine;return r != null &&- (_savableForRoutine.map((e) => e.id).join('|') != routineExercises(r).map((e) => e.id).join('|') ||+ (_slotsForRoutine.join('|') != routineExercises(r).map((e) => e.id).join('|') ||_sessionSetChanges.isNotEmpty);}@@ -1667,8 +1771,9 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal r = sessionRoutine;if (r == null) return const [];final out = <({Exercise ex, int from, int to})>[];+ final tuned = {for (final v in _votes.values) v.exId};for (final e in _savableForRoutine) {- if (!r.exerciseIds.contains(e.id)) continue;+ if (!r.exerciseIds.contains(e.id) || tuned.contains(e.id)) continue;final to = e.sets.where((st) => st.kind != SetKind.warmup).length;final from = routineSets(r, e.id);if (to > 0 && to != from) out.add((ex: exerciseById(e.id)!, from: from, to: to));@@ -1680,7 +1785,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStget sessionRoutineChanges {final r = sessionRoutine;final before = r == null ? const <Exercise>[] : routineExercises(r);- final after = [for (final e in _savableForRoutine) exerciseById(e.id)!];+ final after = [for (final id in _slotsForRoutine) ?exerciseById(id)];final was = {for (final e in before) e.id};final now = {for (final e in after) e.id};return (@@ -1710,12 +1815,12 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal r = sessionRoutine;if (r == null) return;final swaps = _swaps;- final exs = [for (final e in _savable) if (!swaps.containsKey(e.id)) e];+ final exs = [for (final e in _savable) if (!swaps.containsKey(e.id) && !_onAlt(e)) e];final counts = _sessionSetChanges;+ final kept = {for (final id in _slotsForRoutine) id};for (final swap in swaps.entries) {replaceRoutineExercise(r.id, swap.key, swap.value);}- final kept = {for (final e in exs) e.id};for (final id in [...r.exerciseIds]) {if (!kept.contains(id)) toggleRoutineExercise(r.id, id);}@@ -1740,7 +1845,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStfinal swaps = _swaps;return [for (final e in _savable)- if (!r.exerciseIds.contains(e.id) && !swaps.containsKey(e.id) && e.sets.any((st) => st.done)) e,+ if (!r.exerciseIds.contains(e.id) && !swaps.containsKey(e.id) && !_onAlt(e) && e.sets.any((st) => st.done)) e,];}@@ -1932,9 +2037,61 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStnotifyListeners();}+ final Map<String, ({String exId, int vote})> _votes = {};++ List<({String muscle, String exId})> get tuneTargets {+ final r = sessionRoutine;+ final s = session;+ if (!muscleTune || r == null || s == null || _filed == null) return const [];+ final last = <String, String>{};+ final done = <String, int>{};+ for (final e in s.exercises) {+ final slot = _onAlt(e) ? e.swappedFrom! : e.id;+ if (!r.exerciseIds.contains(slot) || modeOf(e.id).isNotEmpty || _drivesSets(slot)) continue;+ final n = e.sets.where((st) => st.done && st.counts).length;+ if (n == 0) continue;+ done[e.primary] = (done[e.primary] ?? 0) + n;+ last[e.primary] = slot;+ }+ final ranked = done.entries.where((e) => e.value >= 2).toList()..sort((a, b) => b.value.compareTo(a.value));+ return [for (final m in ranked.take(3)) (muscle: m.key, exId: _votes[m.key]?.exId ?? last[m.key]!)];+ }++ int? muscleVote(String muscle) => _votes[muscle]?.vote;++ void voteMuscle(String muscle, int? vote) {+ final r = sessionRoutine;+ if (r == null) return;+ final target = tuneTargets.where((m) => m.muscle == muscle).firstOrNull;+ if (target == null) return;+ final old = muscleVote(muscle) ?? 0;+ final next = vote?.clamp(-1, 1);+ final delta = (next ?? 0) - old;+ if (routineSets(r, target.exId) + delta < 1) return;+ if (delta != 0) bumpRoutineSets(r.id, target.exId, delta);+ if (next == null) {+ _votes.remove(muscle);+ } else {+ _votes[muscle] = (exId: target.exId, vote: next);+ }+ persistNow();+ notifyListeners();+ }++ void _undoVotes() {+ final r = sessionRoutine;+ if (r != null) {+ for (final v in _votes.values) {+ bumpRoutineSets(r.id, v.exId, -v.vote);+ }+ }+ _votes.clear();+ }+void continueSession() {final s = session;if (s == null || !s.complete) return;+ _undoVotes();final level = summaryLevelUp;if (level != null) {final before = _levelQuietBefore;@@ -2022,6 +2179,7 @@ mixin WorkoutState on FitCore, SettingsState, LibraryState, PlacesState, StatsStsessionLocked = false;session = null;_filed = null;+ _votes.clear();selectedMuscles.clear();sessionPicks.clear();pickSeed.clear();diff --git a/lib/widgets/dialogs.dart b/lib/widgets/dialogs.dartindex 2b0e93c..efdb9a0 100644--- a/lib/widgets/dialogs.dart+++ b/lib/widgets/dialogs.dart@@ -97,7 +97,7 @@ Future<String?> askText(],),);- controller.dispose();+ Future<void>.delayed(const Duration(milliseconds: 600), controller.dispose);final text = raw?.trim() ?? '';return text.isEmpty ? null : text;}@@ -138,7 +138,7 @@ Future<double?> askNumber(],),);- controller.dispose();+ Future<void>.delayed(const Duration(milliseconds: 600), controller.dispose);return double.tryParse((raw ?? '').trim().replaceAll(',', '.'));}diff --git a/lib/widgets/settings_showcase.dart b/lib/widgets/settings_showcase.dartindex 7771e94..dac6148 100644--- a/lib/widgets/settings_showcase.dart+++ b/lib/widgets/settings_showcase.dart@@ -107,7 +107,7 @@ class _Tile extends StatelessWidget {height: h,padding: EdgeInsets.all(pad),decoration: BoxDecoration(color: context.gc.bgRaised2, borderRadius: BorderRadius.circular(24)),- child: child,+ child: MediaQuery.withNoTextScaling(child: child),));}@@ -257,11 +257,15 @@ class AlertsShowcase extends StatelessWidget {when: t.liveChannel,extra: Padding(padding: const EdgeInsets.only(top: 12),- child: Row(children: [- _pill(gc, t.liveDoneSet, strong: true),- const SizedBox(width: 8),- _pill(gc, t.liveSkipRest),- ]),+ child: FittedBox(+ fit: BoxFit.scaleDown,+ alignment: AlignmentDirectional.centerStart,+ child: Row(children: [+ _pill(gc, t.liveDoneSet, strong: true),+ const SizedBox(width: 8),+ _pill(gc, t.liveSkipRest),+ ]),+ ),),);final restNote = _note(gc,diff --git a/lib/widgets/widget_showcase.dart b/lib/widgets/widget_showcase.dartindex 8aea770..fa7c09d 100644--- a/lib/widgets/widget_showcase.dart+++ b/lib/widgets/widget_showcase.dart@@ -201,6 +201,7 @@ class WidgetShowcase extends StatelessWidget {return ShowcaseFrame(height: height,child: ExcludeSemantics(+ child: MediaQuery.withNoTextScaling(child: IgnorePointer(child: SizedBox(height: height,@@ -245,6 +246,7 @@ class WidgetShowcase extends StatelessWidget {),),),+ ),);}}diff --git a/test/progression_test.dart b/test/progression_test.dartindex 69fbfeb..2d3a6f6 100644--- a/test/progression_test.dart+++ b/test/progression_test.dart@@ -412,4 +412,91 @@ void main() {});});});++ group('#309 progresión por defecto', () {+ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ await Store.instance.init();+ fit.resetAllData();+ fit.setUnits('kg');+ });++ DateTime ago(int days) {+ final n = DateTime.now();+ return DateTime(n.year, n.month, n.day - days, 18);+ }++ String bench() => fit.matchExerciseByName('Barbell Bench Press')!.id;++ test('apagada no propone nada en un ejercicio sin configurar', () {+ final id = bench();+ fit.sessions.add(LoggedSession(ago(3), 1200, [LoggedExercise(id, id, 'chest', [LoggedSet(10, 60), LoggedSet(10, 60)])]));+ expect(fit.hasProgress(id), isFalse);+ });++ test('subir repeticiones suma una por serie y al llegar a 12 sube el peso', () {+ final id = bench();+ fit.setAutoProgress('reps');+ fit.sessions.add(LoggedSession(ago(6), 1200, [LoggedExercise(id, id, 'chest', [LoggedSet(10, 60), LoggedSet(10, 60)])]));+ var next = fit.nextTarget(id)!;+ expect(next.move, NextMove.reps);+ expect(next.reps, 11);+ expect(next.weightKg, 60);++ fit.sessions.add(LoggedSession(ago(3), 1200, [LoggedExercise(id, id, 'chest', [LoggedSet(12, 60), LoggedSet(12, 60)])]));+ next = fit.nextTarget(id)!;+ expect(next.move, NextMove.up);+ expect(next.reps, 8);+ expect(next.weightKg, greaterThan(60));+ });++ test('un ejercicio apagado a mano sigue apagado con la progresión por defecto', () {+ final id = bench();+ fit.setAutoProgress('weight');+ expect(fit.hasProgress(id), isTrue);+ fit.toggleProgress(id);+ expect(fit.hasProgress(id), isFalse);+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.autoProgress, 'weight');+ expect(fit.hasProgress(id), isFalse);+ fit.toggleProgress(id);+ expect(fit.hasProgress(id), isTrue);+ });+ });++ group('semana de descarga', () {+ tearDown(() {+ fit.setDeloadEvery(0);+ fit.saveAndExit();+ });++ test('toca la última semana del ciclo y la siguiente se cuenta bien', () {+ fit.setDeloadEvery(4);+ fit.deloadFrom = DateTime.now().subtract(const Duration(days: 21));+ expect(fit.deloadWeek, isTrue);+ fit.deloadFrom = DateTime.now();+ expect(fit.deloadWeek, isFalse);+ expect(fit.weeksToDeload, 3);+ });++ test('en descarga la sesión lleva la mitad de series, y entrenar normal las devuelve', () {+ final id = fit.createRoutine('Descarga');+ fit.toggleRoutineExercise(id, 'EIeI8Vf');+ final r = fit.routines.firstWhere((x) => x.id == id);+ fit.startRoutine(r);+ final normal = fit.session!.exercises.first.sets.where((s) => s.kind != SetKind.warmup).length;+ fit.saveAndExit();+ fit.setDeloadEvery(4);+ fit.deloadFrom = DateTime.now().subtract(const Duration(days: 21));+ fit.startRoutine(r);+ final s = fit.session!;+ expect(s.deload, isTrue);+ expect(s.exercises.first.sets.where((x) => x.kind != SetKind.warmup).length, (normal / 2).ceil());+ expect(fit.canSkipDeload, isTrue);+ fit.skipDeload();+ expect(s.deload, isFalse);+ expect(s.exercises.first.sets.where((x) => x.kind != SetKind.warmup).length, normal);+ });+ });}diff --git a/test/routine_session_edit_test.dart b/test/routine_session_edit_test.dartindex 1236605..288aade 100644--- a/test/routine_session_edit_test.dart+++ b/test/routine_session_edit_test.dart@@ -238,4 +238,70 @@ void main() {fit.saveAndExit();});});++ group('ajustar series por músculo', () {+ late String chest, legs, r;++ setUp(() {+ fit.muscleTune = true;+ final free = fit.allExercises.where((e) => fit.modeOf(e.id).isEmpty && !fit.isAssisted(e.id));+ chest = free.firstWhere((e) => e.primary == 'chest').id;+ legs = free.firstWhere((e) => e.primary == 'quads').id;+ r = fit.createRoutine('Torso');+ fit.toggleRoutineExercise(r, chest);+ fit.toggleRoutineExercise(r, legs);+ });++ tearDown(fit.saveAndExit);++ void trainChest(int sets) {+ fit.startRoutine(fit.routines.single);+ fit.endCountdown();+ final ex = fit.session!.exercises.first;+ var done = 0;+ for (var i = 0; i < ex.sets.length && done < sets; i++) {+ if (!ex.sets[i].counts) continue;+ fit.toggleSet(0, i);+ done++;+ }+ fit.finishSession();+ }++ test('solo pregunta por los músculos con al menos dos series', () {+ trainChest(2);+ expect(fit.tuneTargets.map((m) => m.muscle), ['chest']);+ });++ test('me faltó suma una serie, me pasé la quita y cambiar de idea lo deshace', () {+ final routine = fit.routines.single;+ final before = fit.routineSets(routine, chest);+ trainChest(2);+ fit.voteMuscle('chest', 1);+ expect(fit.routineSets(routine, chest), before + 1);+ expect(fit.sessionEditedRoutine, isFalse, reason: 'no propone deshacerlo al guardar');+ fit.voteMuscle('chest', -1);+ expect(fit.routineSets(routine, chest), before - 1);+ fit.voteMuscle('chest', 0);+ expect(fit.routineSets(routine, chest), before);+ expect(fit.muscleVote('chest'), 0);+ fit.voteMuscle('chest', null);+ expect(fit.muscleVote('chest'), isNull);+ });++ test('seguir entrenando deshace lo votado', () {+ final routine = fit.routines.single;+ final before = fit.routineSets(routine, chest);+ trainChest(2);+ fit.voteMuscle('chest', 1);+ fit.continueSession();+ expect(fit.routineSets(routine, chest), before);+ });++ test('apagado, no pregunta', () {+ fit.muscleTune = false;+ trainChest(2);+ expect(fit.tuneTargets, isEmpty);+ fit.muscleTune = true;+ });+ });}diff --git a/test/session_test.dart b/test/session_test.dartindex ccbb50e..3798502 100644--- a/test/session_test.dart+++ b/test/session_test.dart@@ -1,3 +1,4 @@+import 'package:gymmane/l10n/l10n.dart';import 'package:flutter_test/flutter_test.dart';import 'package:gymmane/models/workout.dart';import 'package:gymmane/state/fit_state.dart';@@ -245,4 +246,20 @@ void strengthTests() {expect(fit.activeStrengthId, 'a1');_reset();});++ test('la voz del entreno dice el ejercicio y la carga de la serie que toca', () {+ setAppLanguage('es');+ final id = fit.createRoutine('Voz');+ fit.toggleRoutineExercise(id, 'EIeI8Vf');+ fit.startRoutine(fit.routines.firstWhere((r) => r.id == id));+ fit.endCountdown();+ final ex = fit.session!.exercises.first;+ ex.sets.first+ ..reps = 8+ ..weight = 60;+ final text = fit.voiceNext()!;+ expect(text, contains(t.catalogName(ex.id, ex.name)));+ expect(text, contains('8 repeticiones'));+ setAppLanguage('en');+ });}diff --git a/test/settings_test.dart b/test/settings_test.dartindex aaf925c..761eaf8 100644--- a/test/settings_test.dart+++ b/test/settings_test.dart@@ -107,6 +107,27 @@ void main() {expect(fit.textFactor, greaterThan(1));expect(fit.calmMotion, isTrue);});++ test('#307 los niveles de rendimiento mueven cada parte y tocar una lo deja personalizado', () {+ fit.maxRefresh = 120;+ fit.setPerfLevel('max');+ expect((fit.blurOn, fit.fineOn, fit.highRefresh, fit.calmMotion), (true, true, true, false));+ expect(fit.perfLevel, 'max');+ fit.persistNow();+ fit.loadFromStore();+ expect(fit.perfLevel, 'max');+ fit.setFine(false);+ expect(fit.perfLevel, 'custom');+ fit.setPerfLevel('lite');+ expect((fit.blurOn, fit.fineOn, fit.highRefresh, fit.calmMotion), (false, false, false, true));+ expect(fit.perfLevel, 'lite');+ fit.maxRefresh = 60;+ fit.setPerfLevel('max');+ fit.setHighRefresh(false);+ expect(fit.perfLevel, 'max', reason: 'sin pantalla rápida, Máximo no depende de los Hz');+ fit.setPerfLevel('balanced');+ expect(fit.perfLevel, 'balanced');+ });});group('#92 inicio de semana', () {diff --git a/test/stats_totals_test.dart b/test/stats_totals_test.dartindex bead4fc..050208d 100644--- a/test/stats_totals_test.dart+++ b/test/stats_totals_test.dart@@ -169,4 +169,50 @@ void main() {expect(fit.heatmapDate(levels.length - 1), shiftDays(DateTime.now(), 0));});});++ group('lecturas de la semana', () {+ String idFor(String muscle) =>+ fit.allExercises.firstWhere((e) => e.primary == muscle && fit.modeOf(e.id).isEmpty && !fit.isAssisted(e.id)).id;++ void log(int daysAgo, String muscle, double kg, {int sets = 3}) {+ final now = DateTime.now();+ final at = DateTime(now.year, now.month, now.day - daysAgo, 12);+ fit.sessions.add(LoggedSession(at, 600, [+ LoggedExercise(idFor(muscle), muscle, muscle, [for (var i = 0; i < sets; i++) LoggedSet(5, kg)]),+ ]));+ fit.sessions.sort((a, b) => a.date.compareTo(b.date));+ }++ test('sin historial no dice nada', () {+ expect(fit.weekInsights, isEmpty);+ });++ test('avisa del músculo olvidado y de quien se ha hecho más fuerte', () {+ log(40, 'quads', 100);+ log(30, 'quads', 100);+ log(50, 'chest', 60);+ log(3, 'chest', 70);+ final notes = fit.weekInsights;+ expect(notes.map((n) => n.kind), containsAll(['muscle', 'up']));+ expect(notes.firstWhere((n) => n.kind == 'up').exerciseId, idFor('chest'));+ });++ test('nota el desequilibrio entre empujar y tirar', () {+ for (var d = 1; d <= 20; d += 4) {+ log(d, 'chest', 60, sets: 5);+ }+ log(2, 'back', 60, sets: 3);+ expect(fit.weekInsights.map((n) => n.kind), contains('balance'));+ });++ test('nunca da más de tres', () {+ for (var d = 1; d <= 20; d += 4) {+ log(d, 'chest', 60, sets: 6);+ }+ log(40, 'quads', 100);+ log(30, 'quads', 100);+ log(50, 'chest', 40);+ expect(fit.weekInsights.length, lessThanOrEqualTo(3));+ });+ });}diff --git a/test/swap_exercise_test.dart b/test/swap_exercise_test.dartindex 093570c..b0c7e84 100644--- a/test/swap_exercise_test.dart+++ b/test/swap_exercise_test.dart@@ -1,5 +1,6 @@import 'package:flutter_test/flutter_test.dart';import 'package:gymmane/models/live_session.dart';+import 'package:gymmane/models/workout.dart';import 'package:gymmane/services/local_store.dart';import 'package:gymmane/state/fit_state.dart';import 'package:shared_preferences/shared_preferences.dart';@@ -90,4 +91,38 @@ void main() {final back = SessionExercise.fromJson(fit.session!.exercises.first.toJson());expect(back.swappedFrom, bench);});++ group('reservas', () {+ test('se guardan en la rutina, como mucho tres, y la cuarta cambia la más antigua', () {+ final pool = fit.swapOptions(bench, n: 6).map((e) => e.id).toList();+ for (final id in pool.take(4)) {+ fit.toggleRoutineAlt(r, bench, id);+ }+ expect(fit.routineAlts(r, bench), pool.sublist(1, 4));+ fit.toggleRoutineAlt(r, bench, pool[2]);+ expect(fit.routineAlts(r, bench), [pool[1], pool[3]]);+ final back = Routine.fromJson(fit.routines.single.toJson());+ expect(back.alts[bench], [pool[1], pool[3]]);+ });++ test('salen primero al cambiar y usar una no cambia la rutina', () {+ fit.toggleRoutineAlt(r, bench, other);+ fit.startRoutine(fit.routines.single);+ expect(fit.sessionAltsFor(0).map((e) => e.id), [other]);+ fit.swapSessionExercise(0, other);+ expect(fit.sessionAltsFor(0).map((e) => e.id), [bench]);+ expect(fit.sessionEditedRoutine, isFalse);+ fit.toggleSet(0, fit.session!.exercises.first.sets.indexWhere((st) => st.counts));+ fit.finishSession();+ expect(fit.sessionExtras, isEmpty);+ expect(fit.sessionEditedRoutine, isFalse);+ expect(fit.routines.single.exerciseIds, [bench, legs]);+ });++ test('quitar el ejercicio de la rutina se lleva sus reservas', () {+ fit.toggleRoutineAlt(r, bench, other);+ fit.toggleRoutineExercise(r, bench);+ expect(fit.routines.single.alts, isEmpty);+ });+ });}